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
complete
Algorithm
Algorithm_22289_C
def reverse_number(n): """ Reverses the digits of a given number. """ return int(str(n)[::-1]) def is_palindrome(n): """ Checks if a given number is a palindrome. """ return str(n) == str(n)[::-1] def count_palindrome_numbers(max_start: int = 1000, max_iterations: int = 50) -> int: ...
def reverse_number(n): """ Reverses the digits of a given number. """ return int(str(n)[::-1]) def is_palindrome(n): """ Checks if a given number is a palindrome. """ return str(n) == str(n)[::-1] def count_palindrome_numbers(max_start: int = 1000, max_iterations: int = 50) -> int: ...
from solution import count_palindrome_numbers def test_within_one_thousand(): result = count_palindrome_numbers(1000, 50) assert result > 0, "Expected some count of palindromic sequences within 1000." def test_smaller_range(): result = count_palindrome_numbers(10, 50) assert result > 0, "Expected some...
[ { "docstring": "Reverses the digits of a given number.", "function_declaration": "def reverse_number(n):", "function_name": "reverse_number", "parameter_list": "(n)" }, { "docstring": "Checks if a given number is a palindrome.", "function_declaration": "def is_palindrome(n):", "funct...
[ 1, 0, 1, 0, 0, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def reverse_number(n: int) -> int:\n \"\"\"\n Returns the number obtained by reversing the digits of n.\n \"\"\"\n return int(str(n)[::-1])\n\ndef is...
trial_gpt4o_5
{ "original_instruction": "### Problem Statement\n\nConsider a series of numbers where the next number in the series is generated by reversing the order of the digits of the current number and then adding it to the original number. This series always ends in either:\n1. A palindrome (a number that reads the same back...
0.738005
Algorithm_22289
C
[ "reverse_number", "is_palindrome", "count_palindrome_numbers" ]
3
[ [ "count_palindrome_numbers", "is_palindrome" ], [ "count_palindrome_numbers", "reverse_number" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9614d81f683fecef0164c2dcadc01d60720de0b9
8f1a637f2703fe9d90c866bc1cc4443e416eb2a2
v1.0
complete
Algorithm
Algorithm_29552_C
from typing import List, Tuple def calculate_total_distance(path: List[Tuple[int, int]]) -> float: """ Calculate the total distance of a given path. """ def euclidean_distance(p1, p2): return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 total_distance = 0 for i in range(len...
from itertools import permutations from typing import List, Tuple def calculate_total_distance(path: List[Tuple[int, int]]) -> float: """ Calculate the total distance of a given path. """ def euclidean_distance(p1, p2): return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 total_...
from solution import find_optimal_path def test_single_path(): assert find_optimal_path([(0, 0), (1, 1)]) == [(0, 0), (1, 1), (0, 0)] def test_triangle_path(): points = [(0, 0), (0, 2), (2, 0)] path = find_optimal_path(points) assert path[-1] == path[0] assert set(path[:-1]) == set(points) def te...
[ { "docstring": "Calculate the total distance of a given path.", "function_declaration": "def calculate_total_distance(path):", "function_name": "calculate_total_distance", "parameter_list": "(path)" }, { "docstring": "Determines the optimal path to visit each point exactly once and return to...
[ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from itertools import permutations\nfrom typing import List, Tuple\n\ndef calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\...
trial_gpt4o_7
{ "original_instruction": "### Scenario\nYou are developing a navigation system for a marine vessel that needs to determine the optimal path through a set of waypoints. The goal is to visit each waypoint exactly once and return to the starting point, minimizing the total traveled distance. This is a classic Traveling...
0.655452
Algorithm_29552
C
[ "calculate_total_distance", "find_optimal_path" ]
2
[ [ "find_optimal_path", "calculate_total_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5a9baa18fa4b405ffc684158571cc5b2a7b31eaa
7fbf76417bc04210b48c003093617fa09912ddb8
v1.0
complete
Algorithm
Algorithm_35887_C
import numpy as np def scale_array(array: np.ndarray, factor: float) -> np.ndarray: """Scales a 1D numpy array by a given factor. Args: array (np.ndarray): The input array. factor (float): The scaling factor. Returns: np.ndarray: The scaled array. >>> scale_array(np.array([1, 2, 3]), 2) ...
import numpy as np def scale_array(array: np.ndarray, factor: float) -> np.ndarray: """ Scales the array by a given factor. """ return array * factor def exponential_transform(array: np.ndarray) -> np.ndarray: """ Applies exponential transformation to the array. """ return np.exp(array...
import numpy as np from solution import scale_array, exponential_transform, subtract_mean, smooth_array, compare_arrays, array_transformation_pipeline def test_scale_array(): array = np.array([1, 2, 3, 4, 5]) factor = 2 result = scale_array(array, factor) expected = np.array([2, 4, 6, 8, 10]) asser...
[ { "docstring": "Scales the array by a given factor.", "function_declaration": "def scale_array(array, factor):", "function_name": "scale_array", "parameter_list": "(array, factor)" }, { "docstring": "Applies exponential transformation to the array.", "function_declaration": "def exponent...
[ 1, 1, 0, 1, 0, 0, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\n# Function 1: Scaling Transformation\ndef scale_array(array: np.ndarray, factor: float) -> np.ndarray:\n return array * factor\n\n# Func...
trial_gpt4o_9
{ "original_instruction": "**Array Transformation and Analysis**\n\nYou are building a data processing tool that involves a series of transformations for numerical arrays. Your objective is to implement functions that perform four specific transformations and an evaluation step.\n\n**Objective:**\n\nComplete the miss...
0.636206
Algorithm_35887
C
[ "scale_array", "exponential_transform", "subtract_mean", "smooth_array", "compare_arrays", "array_transformation_pipeline" ]
6
[ [ "array_transformation_pipeline", "compare_arrays" ], [ "array_transformation_pipeline", "exponential_transform" ], [ "array_transformation_pipeline", "scale_array" ], [ "array_transformation_pipeline", "smooth_array" ], [ "array_transformation_pipeline", "su...
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
adac3e4db184653b46004f9d8b06240d1cb614c5
40103be33ff71a88e30f4d52c46010ccce0cf463
v1.0
complete
Algorithm
Algorithm_10291_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def delete_node(root: TreeNode, key: int) -> TreeNode: """ Deletes a specified value from a Binary Search Tree (BST) and maintains the BST properties after deletion....
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def find_minimum(node): """ Function to find the node with the minimum value in a BST. """ current = node while current.left is not None: current ...
import pytest def test_tree_structure_1(): root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(6) root.left.left = TreeNode(2) root.left.right = TreeNode(4) root.right.right = TreeNode(7) new_root = delete_node(root, 3) assert new_root.val == 5 assert new_root...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_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 delet...
trial_gpt4o_6
{ "original_instruction": "### Binary Search Tree (BST) Delete Operation\n\nImplement a function to delete a specified value from a Binary Search Tree (BST). The BST is given with its root node, and the function should maintain the BST properties after deletion. The function should return the root node of the updated...
0.502396
Algorithm_10291
C
[ "find_minimum", "delete_node" ]
2
[ [ "delete_node", "find_minimum" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
false
[]
true
5442be185db928c8dcfa301add5fe11af70843c2
0190e189305de81d8075fd25e804be43c7e06326
v1.0
complete
Algorithm
Algorithm_3244_C
from typing import List, Tuple def euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float: """ Returns the Euclidean distance between two points. >>> euclidean_distance((0, 0), (3, 4)) 5.0 >>> euclidean_distance((1, 1), (4, 5)) 5.0 >>> euclidean_distance((0, 0), (0, 0...
from typing import List, Tuple import math def euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float: """ Returns the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) def sort_points_by_distance(points: Lis...
from solution import euclidean_distance, sort_points_by_distance def test_euclidean_distance(): assert euclidean_distance((0, 0), (3, 4)) == 5.0 assert euclidean_distance((1, 1), (4, 5)) == 5.0 assert euclidean_distance((0, 0), (0, 0)) == 0.0 assert euclidean_distance((1, 1), (1, 1)) == 0.0 def test_s...
[ { "docstring": "Returns the Euclidean distance between two points.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Sorts a list of points by their Euclidean distance to the tar...
[ 1, 1, 1, 0, 1, 1, 1, 0, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport math\n\ndef sort_points_by_distance(points: List[Tuple[int, int]], target: Tuple[int, int]) -> List[Tuple[int, int]]:\n ...
trial_gpt4o_6
{ "original_instruction": "### Problem Statement\nIn a coordinate system, a point is defined by its \\(x\\) and \\(y\\) values. Given a list of points and the target point, calculate the Euclidean distance from each point to the target point and return a sorted list of points based on their distances from the target ...
0.720563
Algorithm_3244
C
[ "euclidean_distance", "sort_points_by_distance" ]
2
[ [ "sort_points_by_distance", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d84a3e7d2e3681ede20544af4fcb1a2a9545458a
915f8f8e39db88d254df074534bed931134d0308
v1.0
complete
Algorithm
Algorithm_13142_C
class AVLNode: def __init__(self, key): self.key = key self.height = 1 self.left = None self.right = None def insert(root: AVLNode, key: int) -> AVLNode: """ Insert a new key into the AVL Tree and ensure the tree remains balanced. >>> keys = [20, 4, 15, 10, 22, 18, 80] >...
class AVLNode: def __init__(self, key): self.key = key self.height = 1 self.left = None self.right = None def get_height(node): if not node: return 0 return node.height def update_height(node): if node: node.height = 1 + max(get_height(node.left)...
from solution import AVLNode, insert, range_sum def test_insert_and_balance(): keys = [20, 4, 15, 10, 22, 18, 80] root = None for key in keys: root = insert(root, key) # Check the AVL tree properties assert root.key == 15 # After balancing the tree def test_range_sum(): keys = [20, 4...
[]
[ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class AVLNode:\n def __init__(self, key):\n self.key = key\n self.height = 1\n self.left = None\n self.right = None\n \ndef...
trial_gpt4o_0
{ "original_instruction": "### AVL Tree Implementation and Range Sum Query\n\nYou are to implement an AVL Tree and perform a range sum query. AVL Trees are self-balancing binary search trees that maintain height balance for efficient querying.\n\n#### Task 1: AVL Tree Construction\nWrite a function, `insert(root: AVL...
0.504018
Algorithm_13142
C
[ "get_height", "update_height", "get_balance", "right_rotate", "left_rotate", "insert", "range_sum" ]
7
[ [ "get_balance", "get_height" ], [ "insert", "get_balance" ], [ "insert", "left_rotate" ], [ "insert", "right_rotate" ], [ "insert", "update_height" ], [ "left_rotate", "update_height" ], [ "right_rotate", "update_height" ], [ "...
8
[]
false
[ "AVLNode" ]
true
pytest
true
[]
true
a2ac0f181d8b949d6fd24330f108b9fde759a378
558a5a3d6d9e5e7fabb87fee980c206568065913
v1.0
complete
Algorithm
Algorithm_38392_C
def total_fuel_consumption(segments): """ Calculates the total fuel consumption for a given route. Args: segments (list of tuples): Each tuple contains a string (segment name) and a float (fuel consumption). Returns: float: Total fuel consumption. """ pass def max_fuel_consump...
def total_fuel_consumption(segments): """ Calculates the total fuel consumption for a given route. Args: segments (list of tuples): Each tuple contains a string (segment name) and a float (fuel consumption). Returns: float: Total fuel consumption. """ return sum(fuel for _, fue...
from solution import total_fuel_consumption, max_fuel_consumption_segment, average_fuel_consumption def test_total_fuel_consumption(): segments = [("A-B", 3.2), ("B-C", 4.5), ("C-D", 2.8), ("D-E", 5.0)] assert total_fuel_consumption(segments) == 15.5 def test_max_fuel_consumption_segment(): segments = [(...
[ { "docstring": "Calculates the total fuel consumption for a given route.\n\nArgs:\nsegments (list of tuples): Each tuple contains a string (segment name) and a float (fuel consumption).\n\nReturns:\nfloat: Total fuel consumption.", "function_declaration": "def total_fuel_consumption(segments):", "functi...
[ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def total_fuel_consumption(segments):\n \"\"\"\n Returns the total fuel consumption for the given route segments.\n \n Parameters:\n segments (lis...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n**Scenario**: You are a data analyst at a logistics company. Your team needs to analyze route data to determine the most fuel-efficient path for delivery trucks. The company measures fuel consumption per mile for each segment of the route.\n\nYou need to ca...
0.537718
Algorithm_38392
C
[ "total_fuel_consumption", "max_fuel_consumption_segment", "average_fuel_consumption" ]
3
[ [ "average_fuel_consumption", "total_fuel_consumption" ] ]
1
[]
false
[]
false
pytest
true
[]
true
150075dbbab59797d3d17a5d95b99f60bd356d10
c9550ce23009c6e67a5d4cb425604ba0f27f32cd
v1.0
complete
Algorithm
Algorithm_43340_C
from typing import List def find_isbns(records: List[str], isbns: List[str]) -> List[bool]: """ Takes a sorted list of records and a list of ISBNs, and returns a list of boolean values indicating if each ISBN in the list is found in the records. >>> records = ["0000000000", "1234567890", "23456789...
def binary_search(records, isbn): left, right = 0, len(records) - 1 while left <= right: mid = (left + right) // 2 if records[mid] == isbn: return True elif records[mid] < isbn: left = mid + 1 else: right = mid - 1 return False def find_is...
from solution import find_isbns def test_find_isbns_with_existing_isbns(): records = ["0000000000", "1234567890", "2345678901", "3456789012", "4567890123", "5678901234"] isbns = ["1234567890", "3456789012", "9876543210"] assert find_isbns(records, isbns) == [True, True, False] def test_find_isbns_with_all...
[ { "docstring": null, "function_declaration": "def binary_search(records, isbn):", "function_name": "binary_search", "parameter_list": "(records, isbn)" }, { "docstring": "Takes a sorted list of records and a list of ISBNs, and returns a list of boolean values\nindicating if each ISBN in the ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def binary_search(records, isbn):\n left, right = 0, len(records) - 1\n while left <= right:\n mid = (left + right) // 2\n if records[mid] ==...
trial_gpt4o_9
{ "original_instruction": "### Scenario:\nYou are developing a feature for a library management system that helps librarians quickly identify books based on their unique ISBN numbers. Your task is to implement an algorithm that efficiently checks if a given list of ISBN numbers exists within a sorted list of records....
0.531542
Algorithm_43340
C
[ "binary_search", "find_isbns" ]
2
[ [ "find_isbns", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a8d03b9574e9fa4b1ca1962c464a6c07be69b86e
4bd474d1b65da61297dc36beec3a437e92a3582f
v1.0
complete
Algorithm
Algorithm_2724_C
def validate_mac(mac: str) -> bool: """ Validates if the input string is a valid MAC address. Args: mac (str): The string representing the MAC address. Returns: bool: True if valid, False otherwise. >>> validate_mac("00:1A:2B:3C:4D:5E") == True >>> validate_mac("00-1A-2B-3C-4D...
import re def validate_mac(mac: str) -> bool: """ Validates if the input string is a valid MAC address. Args: mac (str): The string representing the MAC address. Returns: bool: True if valid, False otherwise. """ # MAC address regex patterns for different formats patterns ...
from solution import validate_mac, normalize_mac def test_validate_mac(): assert validate_mac("00:1A:2B:3C:4D:5E") == True assert validate_mac("00-1A-2B-3C-4D-5E") == True assert validate_mac("001A.2B3C.4D5E") == True assert validate_mac("00:1A:2B:3C:4D:5Z") == False assert validate_mac("00-1A-2B-3...
[ { "docstring": "Validates if the input string is a valid MAC address.\n\nArgs:\nmac (str): The string representing the MAC address.\n\nReturns:\nbool: True if valid, False otherwise.", "function_declaration": "def validate_mac(mac):", "function_name": "validate_mac", "parameter_list": "(mac)" }, ...
[ 1, 1, 0, 0, 1, 1, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef validate_mac(mac: str) -> bool:\n \"\"\"\n Validates if the input string is a valid MAC address.\n \"\"\"\n # Regular expression for...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement: Validate and Normalize MAC Addresses\n\nYou are working for a networking company that needs a utility to validate and normalize MAC (Media Access Control) addresses. MAC addresses are unique identifiers assigned to network interfaces for communications on the physical...
0.509431
Algorithm_2724
C
[ "validate_mac", "normalize_mac" ]
2
[ [ "normalize_mac", "validate_mac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3bba6e0e4b06daf59c5b32e5476e10a3d631504
10edc4e7aa64f839f53396cd810784408ae468ce
v1.0
complete
Algorithm
Algorithm_37736_C
def minimum_steps_to_balance(bitr: List[int], action: int) -> Tuple[int, int]: """ Determines the minimum number of steps required to balance a binary indexed tree and indicates which node should be added, removed, or adjusted to achieve the balance. Args: bitr (List[int]): A list of integers repr...
import math from typing import List, Tuple def height_of_tree(n: int) -> int: if n == 0: return 0 return math.ceil(math.log2(n + 1)) def is_balanced(height: int, low: int, high: int) -> bool: return height >= low and height <= high def minimum_steps_to_balance(bitr: List[int], action: int) -> Tup...
from solution import minimum_steps_to_balance def test_minimum_steps_to_balance(): assert minimum_steps_to_balance([10, 12, 8, 15, 6, 9], 1) == (1, 6) assert minimum_steps_to_balance([10, 12, 8, 15, 6, 9], -1) == (1, 5) assert minimum_steps_to_balance([10, 12, 8, 15, 6], 0) == (0, -1) assert minimum_st...
[ { "docstring": null, "function_declaration": "def height_of_tree(n):", "function_name": "height_of_tree", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_balanced(height, low, high):", "function_name": "is_balanced", "parameter_list": "(height, low...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef minimum_steps_to_balance(bitr: List[int], action: int) -> Tuple[int, int]:\n def height(node_index: int) -> int:\n ...
trial_gpt4o_4
{ "original_instruction": "### Problem Statement\n\nYou are tasked with developing a function that determines the minimum number of steps required to convert a given binary indexed tree into a balanced binary indexed tree. A binary indexed tree is used in various algorithm problems to query and update elements of an ...
0.712574
Algorithm_37736
C
[ "height_of_tree", "is_balanced", "minimum_steps_to_balance" ]
3
[ [ "minimum_steps_to_balance", "height_of_tree" ], [ "minimum_steps_to_balance", "is_balanced" ] ]
2
[]
false
[]
false
pytest
true
[]
true
33b8df022fd1996458118205fc28fee449ff0f87
abba0349f5f38bc60953f91e7341953e83f85b8d
v1.0
complete
Algorithm
Algorithm_9296_C
[Completion Task in Python] def get_neighbors(x: int, y: int, grid: List[List[str]]) -> List[Tuple[int, int]]: """ Function to get the valid neighboring cells for the cell at position (x, y). Parameters: - x: int, row index of the current cell - y: int, column index of the current cell ...
from typing import List, Tuple, Set def get_neighbors(x: int, y: int, grid: List[List[str]]) -> List[Tuple[int, int]]: neighbors = [] directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] rows, cols = len(grid), len(grid[0]) for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < ...
from solution import get_neighbors, longest_word_from, longest_snake_word def test_get_neighbors(): assert get_neighbors(1, 1, [['a', 'b'], ['c', 'd']]) == [(0, 1), (1, 0)] def test_longest_word_from(): assert longest_word_from(0, 0, [['a', 'b'], ['c', 'd']], set()) == 4 assert longest_word_from(1, 1, [['...
[ { "docstring": null, "function_declaration": "def get_neighbors(x, y, grid):", "function_name": "get_neighbors", "parameter_list": "(x, y, grid)" }, { "docstring": null, "function_declaration": "def longest_word_from(x, y, grid, visited):", "function_name": "longest_word_from", "...
[ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple, Set\n\ndef get_neighbors(x: int, y: int, grid: List[List[str]]) -> List[Tuple[int, int]]:\n neighbors = []\n rows, cols = l...
trial_gpt4o_4
{ "original_instruction": "#### Coding Assessment Question\n\nYou are given a problem where you need to analyze a grid of characters and identify the length of the longest word that can be constructed by moving to adjacent (horizontally or vertically) characters. Words are formed in a \"snake-like\" manner, where you...
0.63614
Algorithm_9296
C
[ "get_neighbors", "longest_word_from", "longest_snake_word" ]
3
[ [ "longest_snake_word", "longest_word_from" ], [ "longest_word_from", "get_neighbors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f38e0c61f685633439d6a06bd720b8cee7efa4c2
54721e7e8fd7c188a1619d30fe804440ce55e25a
v1.0
complete
Algorithm
Algorithm_24725_C
from typing import List, Tuple from math import sqrt def dbscan(points: List[Tuple[float, float]], eps: float, min_points: int) -> List[int]: """Clusters geographical points based on DBSCAN algorithm. Args: points (List[Tuple[float, float]]): A list of tuples representing the (latitude, longitude) of a po...
from typing import List, Tuple from math import sqrt def euclidean_distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float: return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def dbscan(points: List[Tuple[float, float]], eps: float, min_points: int) -> List[int]: labels = [-1] * len(points) ...
def test_single_point(): points = [(0, 0)] eps = 0.1 min_points = 1 assert dbscan(points, eps, min_points) == [0] def test_no_neighbors(): points = [(0, 0), (10, 10)] eps = 1 min_points = 2 assert dbscan(points, eps, min_points) == [-1, -1] def test_all_points_in_one_cluster(): poi...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def dbscan(points, eps, min_points):", "function_name": "dbscan", "parameter_list":...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport math\n\ndef haversine_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:\n R = 6371.0 # Radi...
trial_gpt4o_4
{ "original_instruction": "### Scenario\nYou are working with a system that processes large datasets containing geographical coordinates. Your task is to identify clusters of points that are geographically close to one another. The clustering algorithm you need to implement uses a form of Density-Based Spatial Cluste...
0.669393
Algorithm_24725
C
[ "euclidean_distance", "dbscan", "get_neighbors", "expand_cluster" ]
4
[ [ "dbscan", "expand_cluster" ], [ "dbscan", "get_neighbors" ], [ "expand_cluster", "get_neighbors" ], [ "get_neighbors", "euclidean_distance" ] ]
4
[]
false
[]
false
pytest
false
[]
true
f6224538031716e99eedb17c27b62284f9b93a9a
278bde1daf2f07a57a4ac49e865a72f8360574ff
v1.0
complete
Algorithm
Algorithm_5885_C
from typing import List, Tuple, Dict def generate_truth_table(expression: str) -> List[Tuple[Dict[str, bool], bool]]: """ Generate a truth table for a given logical expression. The expression is composed of the following logical operators: - AND (&) - OR (|) - NOT (!) Variables in the expressio...
from typing import List, Tuple, Dict import itertools def evaluate_expression(variables: Dict[str, bool], expression: str) -> bool: # Replace variable names with their boolean values in the expression for var, val in variables.items(): expression = expression.replace(var, str(val)) # Replace l...
from solution import generate_truth_table def test_generate_truth_table_basic_and(): assert generate_truth_table("a&b") == [({'a': False, 'b': False}, False), ({'a': False, 'b': True}, False), ({'a': True, 'b': False}, False), ...
[ { "docstring": null, "function_declaration": "def evaluate_expression(variables, expression):", "function_name": "evaluate_expression", "parameter_list": "(variables, expression)" }, { "docstring": null, "function_declaration": "def generate_truth_table(expression):", "function_name"...
[ 1, 0, 1, 0, 0, 1, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple, Dict\n\ndef generate_truth_table(expression: str) -> List[Tuple[Dict[str, bool], bool]]:\n import re\n from itertools impor...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement\nWrite a function that takes a string representing a formula for a truth table and generates the corresponding truth table. \n\n### Task Description\n1. **Function: `generate_truth_table(expression: str) -> List[Tuple[Dict[str, bool], bool]]`**\n - The function shou...
0.515202
Algorithm_5885
C
[ "evaluate_expression", "generate_truth_table" ]
2
[ [ "generate_truth_table", "evaluate_expression" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0e52045393135a39292305ada07018b295af419b
16ea9b8725ae61b997eeb2ab709f19bb492aee51
v1.0
complete
Algorithm
Algorithm_21208_C
def is_prime(n: int) -> bool: """Check whether a number is prime. >>> is_prime(2) == True >>> is_prime(3) == True >>> is_prime(4) == False >>> is_prime(29) == True >>> is_prime(1) == False >>> is_prime(0) == False >>> is_prime(-5) == False >>> is_prime(999983) == True """ pas...
def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def is_anagram(n1, n2): return sorted(str(n1)) == sorted(str(n2)) def are_prime_...
from solution import are_prime_anagrams, is_prime, is_anagram def test_are_prime_anagrams(): assert are_prime_anagrams(13, 31) == True assert are_prime_anagrams(13, 37) == False assert are_prime_anagrams(17, 71) == True assert are_prime_anagrams(23, 32) == False assert are_prime_anagrams(113, 131) ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_anagram(n1, n2):", "function_name": "is_anagram", "parameter_list": "(n1, n2)" }, { "docstring": n...
[ 1, 0, 1, 0, 0, 1, 1, 0, 0 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise returns False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:...
trial_gpt4o_7
{ "original_instruction": "### Prime Anagrams\n\n#### Scenario:\nYou are working as a software developer at a cybersecurity firm. One of your tasks is to implement a function to determine special properties of numbers, which can aid in cryptographic algorithms. A particular property of interest is identifying prime a...
0.68705
Algorithm_21208
C
[ "is_prime", "is_anagram", "are_prime_anagrams" ]
3
[ [ "are_prime_anagrams", "is_anagram" ], [ "are_prime_anagrams", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
080abc552b288339f5a6ef36f2acd2670ab0e352
c02449c8d10acf16c7e3ecfe2622aafbf5a8ba56
v1.0
complete
Algorithm
Algorithm_40339_C
def roman_to_int(roman: str) -> int: """ Converts a Roman numeral string to an integer. :param roman: A string representing a Roman numeral. :return: An integer equivalent of the Roman numeral. :raises ValueError: If the input string is not a valid Roman numeral. :raises TypeError: If the i...
def roman_to_int(roman: str) -> int: """ Converts a Roman numeral string to an integer. :param roman: A string representing a Roman numeral. :return: An integer equivalent of the Roman numeral. """ if not isinstance(roman, str): raise TypeError("input must be a string") rom...
import pytest from solution import roman_to_int def test_roman_to_int_basic(): assert roman_to_int("I") == 1 assert roman_to_int("III") == 3 assert roman_to_int("IV") == 4 assert roman_to_int("IX") == 9 assert roman_to_int("LVIII") == 58 assert roman_to_int("MCMXCIV") == 1994 def test_roman_to...
[ { "docstring": "Converts a Roman numeral string to an integer.\n\n:param roman: A string representing a Roman numeral.\n:return: An integer equivalent of the Roman numeral.", "function_declaration": "def roman_to_int(roman):", "function_name": "roman_to_int", "parameter_list": "(roman)" }, { ...
[ 0, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def roman_to_int(roman: str) -> int:\n \"\"\"\n Converts a Roman numeral string to an integer.\n \n Args:\n roman (str): A string representing a R...
trial_gpt4o_8
{ "original_instruction": "### Coding Question: Convert Roman Numerals to Integers\n\n#### Context\nIn various applications, historical data is often represented in Roman numerals. Your task is to create a function that converts Roman numerals into their corresponding integer values. This can be particularly useful i...
0.701145
Algorithm_40339
C
[ "roman_to_int", "int_to_roman" ]
2
[ [ "roman_to_int", "int_to_roman" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3d16d40bef2ad493ac6152b3dbe8d4e2dbc1af62
72ff49f875474d910cba0b524be2d0da7b8c1778
v1.0
complete
Algorithm
Algorithm_20012_C
def merge_sort(arr): """ Given a list of integers `arr`, returns a new list that contains all the elements, sorted in non-decreasing order. Parameters: arr (list): The list of integers to be sorted. Returns: list: A new list containing all the elements from `arr` in sorted order. """ ...
def merge_sort(arr): """ Given a list of integers `arr`, returns a new list that contains all the elements, sorted in non-decreasing order. Parameters: arr (list): The list of integers to be sorted. Returns: list: A new list containing all the elements from `arr` in sorted order. """ ...
from solution import merge_sort def test_merge_sort_with_unsorted_list(): assert merge_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_merge_sort_with_unsorted_list_two(): assert merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13] def test_merge_sort_with_empty_li...
[ { "docstring": "Given a list of integers `arr`, returns a new list that contains all the elements,\nsorted in non-decreasing order.\n\nParameters:\narr (list): The list of integers to be sorted.\n\nReturns:\nlist: A new list containing all the elements from `arr` in sorted order.", "function_declaration": "...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Given a list of integers `arr`, returns a new list that contains all the elements,\n sorted in non-decreasing order.\n\n...
trial_gpt4o_9
{ "original_instruction": "### Coding Challenge: Implementing a Sorting Algorithm\n\nYou have been provided a partially implemented function to sort a list of integers using the Merge Sort algorithm. Your task is to complete the implementation to ensure the function sorts the list correctly.\n\n### Task\n\n**Function...
0.601388
Algorithm_20012
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fe7b9730b49eda88ca1b990375f3c77674d11e30
f372f708fb539a2e9993a3048b51d7c627b2cbf0
v1.0
complete
Algorithm
Algorithm_24708_C
def optimized_matrix_multiplication(A: list[list[float]], B: list[list[float]]) -> list[list[float]]: """ Implement an optimized matrix multiplication algorithm that leverages Strassen's algorithm for large matrices but defaults to the classical approach for small matrices. >>> A = [[1.0, 2.0], [3.0, 4.0]] ...
def add_matrix(A, B): """ Add two matrices element-wise. """ n = len(A) return [[A[i][j] + B[i][j] for j in range(n)] for i in range(n)] def sub_matrix(A, B): """ Subtract matrix B from matrix A element-wise. """ n = len(A) return [[A[i][j] - B[i][j] for j in range(n)] for i in ...
from solution import optimized_matrix_multiplication def test_optimized_matrix_multiplication_small_matrices(): A = [[1.0, 2.0], [3.0, 4.0]] B = [[5.0, 6.0], [7.0, 8.0]] expected_result = [[19.0, 22.0], [43.0, 50.0]] result = optimized_matrix_multiplication(A, B) assert result == expected_result d...
[ { "docstring": "Add two matrices element-wise.", "function_declaration": "def add_matrix(A, B):", "function_name": "add_matrix", "parameter_list": "(A, B)" }, { "docstring": "Subtract matrix B from matrix A element-wise.", "function_declaration": "def sub_matrix(A, B):", "function_na...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def optimized_matrix_multiplication(A, B):\n def classical_multiplication(A, B):\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i i...
trial_gpt4o_4
{ "original_instruction": "### Question: Implement an Optimized Matrix Multiplication Algorithm\n\n#### Context\nYou are developing a mathematical library that requires efficient matrix operations. Matrix multiplication is a fundamental operation frequently used in various applications, from graphics transformations ...
0.52046
Algorithm_24708
C
[ "add_matrix", "sub_matrix", "matrix_mult", "optimized_matrix_multiplication" ]
4
[ [ "matrix_mult", "add_matrix" ], [ "matrix_mult", "sub_matrix" ], [ "optimized_matrix_multiplication", "matrix_mult" ] ]
3
[]
false
[]
false
pytest
true
[]
true
ae98404c1c6579dde88ecc657229130b68ad2e9b
ce02d1fb1c1b202388135829a42ab00202969913
v1.0
complete
Algorithm
Algorithm_36798_C
from typing import List def digit_sum(n: int) -> int: return sum(int(d) for d in str(abs(n))) def custom_sort(arr: List[int]) -> List[int]: pass """ Sorts a list of integers based on the sum of their digits. In case of a tie, sorts by natural order. Args: arr List[int]: A list of integers to sort. Retu...
from typing import List def digit_sum(n: int) -> int: return sum(int(d) for d in str(abs(n))) def custom_sort(arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (digit_sum(x), x))
from solution import custom_sort def test_example_cases(): assert custom_sort([56, 74, 35, 213, 92, 110]) == [110, 213, 35, 56, 74, 92] assert custom_sort([6, 21, 30, 111, 100]) == [100, 21, 30, 111, 6] def test_single_element(): assert custom_sort([5]) == [5] assert custom_sort([0]) == [0] def test_...
[ { "docstring": null, "function_declaration": "def digit_sum(n):", "function_name": "digit_sum", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def custom_sort(arr):", "function_name": "custom_sort", "parameter_list": "(arr)" } ]
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef digit_sum(n: int) -> int:\n \"\"\"\n Calculate the sum of digits of the given number.\n \"\"\"\n return sum(int(digit)...
trial_gpt4o_1
{ "original_instruction": "### Question: Sorting Integers with Custom Comparator\n\nYou are required to implement a custom sorting function for a list of integers. Your task is to sort the integers based on the sum of their digits. In case of a tie (i.e., two integers have the same sum of digits), the integers should...
0.740407
Algorithm_36798
C
[ "digit_sum", "custom_sort" ]
2
[ [ "custom_sort", "digit_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2cdad234ef4594bcf8e118d02404d648736a1949
67b8420f8b7ee8f458de64991c3816165563dd30
v1.0
complete
Algorithm
Algorithm_39919_C
from typing import List def rotate_90_clockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotate the matrix 90 degrees clockwise """ pass def reflect_horizontally(matrix: List[List[int]]) -> List[List[int]]: """ Reflect the matrix horizontally """ pass def process_queries(matrix: List[List[int...
def rotate_90_clockwise(matrix): n = len(matrix) new_matrix = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): new_matrix[j][n-i-1] = matrix[i][j] return new_matrix def reflect_horizontally(matrix): n = len(matrix) new_matrix = [[0]*n for _ in range(n)] fo...
from solution import matrix_transform_sum def test_single_rotation_and_query(): n = 3 matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] t = 1 transformations = ['R'] q = 1 queries = ['R 1'] result = matrix_transform_sum(n, matrix, t, transformations, q, queries) a...
[ { "docstring": null, "function_declaration": "def rotate_90_clockwise(matrix):", "function_name": "rotate_90_clockwise", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def reflect_horizontally(matrix):", "function_name": "reflect_horizontally", "par...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rotate_90_clockwise(matrix):\n return [list(x)[::-1] for x in zip(*matrix)]\n\ndef reflect_horizontally(matrix):\n return matrix[::-1]\n\ndef matrix_tr...
trial_gpt4o_6
{ "original_instruction": "### Matrix Transform Sum\n\n**Context**:\nMatrix manipulation is a key aspect of various algorithmic challenges. This problem involves performing a series of transformations on a matrix, followed by operations that sum specific elements based on given queries.\n\n**Task**:\nWrite a program ...
0.602617
Algorithm_39919
C
[ "rotate_90_clockwise", "reflect_horizontally", "process_queries", "matrix_transform_sum" ]
4
[ [ "matrix_transform_sum", "process_queries" ], [ "matrix_transform_sum", "reflect_horizontally" ], [ "matrix_transform_sum", "rotate_90_clockwise" ] ]
3
[ "process_queries" ]
false
[]
false
pytest
true
[]
true
c261f3aff996c92dd40a7454c85f3559843b691a
e1ff359ff7246577d1415748d0e3f33ae3699f06
v1.0
complete
Algorithm
Algorithm_16368_C
def shortest_delivery_route(grid: list, warehouse: tuple, customers: list) -> int: """ Calculate the shortest total path length to deliver from the warehouse to all customer locations in the shortest possible order. >>> shortest_delivery_route( ... [ ... [0, 0, 0, 0], ... [0, 1, ...
from collections import deque def bfs(grid, start): rows, cols = len(grid), len(grid[0]) distances = [[float('inf')] * cols for _ in range(rows)] distances[start[0]][start[1]] = 0 queue = deque([start]) while queue: x, y = queue.popleft() for dx, dy in [(-1, 0), (1, 0), (0, -1)...
from solution import shortest_delivery_route def test_shortest_delivery_route_example1(): grid = [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0], [0, 1, 0, 0] ] warehouse = (0, 0) customers = [(2, 3), (3, 2)] assert shortest_delivery_route(grid, warehouse, customers) == 1...
[ { "docstring": null, "function_declaration": "def bfs(grid, start):", "function_name": "bfs", "parameter_list": "(grid, start)" }, { "docstring": null, "function_declaration": "def shortest_delivery_route(grid, warehouse, customers):", "function_name": "shortest_delivery_route", ...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef bfs(grid, start):\n rows, cols = len(grid), len(grid[0])\n distances = [[float('inf')] * cols for _ in range(rows)]\n ...
trial_gpt4o_0
{ "original_instruction": "### Coding Assessment Task:\n\n#### Context:\nYou are working on a logistics software system and need to design a function that can calculate the optimal route for package delivery in a city. The city is modeled as a grid, and you need to find the shortest path from a warehouse to multiple ...
0.584671
Algorithm_16368
C
[ "bfs", "shortest_delivery_route" ]
2
[ [ "shortest_delivery_route", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
19592af4d16bffe1b544cde6a988788743cc770e
fb7026e0dfaa5ab1fe4d878e21e6184467c57326
v1.0
complete
Algorithm
Algorithm_19432_C
def dual_pivot_quicksort(arr: List[int], low: int, high: int) -> List[int]: """ Implements the Quicksort algorithm using a dual pivot partitioning method. This function sorts an array of integers from index low to index high in place. >>> arr = [24, -34, 5, 0, 17, -5, 10, 23] >>> dual_pivot_quickso...
def dual_pivot_quicksort(arr, low, high): if low < high: # partition the array and get the indices of the pivots lp, rp = dual_pivot_partition(arr, low, high) # recursively sort the subarrays dual_pivot_quicksort(arr, low, lp - 1) dual_pivot_quicksort(arr, lp + 1, rp - 1) ...
from solution import dual_pivot_quicksort def test_small_array(): arr = [24, -34, 5, 0, 17, -5, 10, 23] sorted_arr = [-34, -5, 0, 5, 10, 17, 23, 24] assert dual_pivot_quicksort(arr, 0, len(arr) - 1) == sorted_arr def test_large_array(): arr = [34, 7, 23, 32, 5, 62, 32, 7, 5, 32, 23, 7, 34] sorted_...
[ { "docstring": null, "function_declaration": "def dual_pivot_quicksort(arr, low, high):", "function_name": "dual_pivot_quicksort", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def dual_pivot_partition(arr, low, high):", "function_name": "dual_...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef dual_pivot_quicksort(arr: List[int], low: int, high: int) -> List[int]:\n if low < high:\n # lp is the index of the lowe...
trial_gpt4o_9
{ "original_instruction": "### Quicksort with Dual Pivot Partitioning\n\nYou are required to implement the Quicksort algorithm using a dual pivot partitioning method. This variation of Quicksort uses two pivots and can offer improved performance over the classic single pivot Quicksort.\n\n### Function Signature\n```p...
0.605772
Algorithm_19432
C
[ "dual_pivot_quicksort", "dual_pivot_partition" ]
2
[ [ "dual_pivot_quicksort", "dual_pivot_partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b1d6b8fe4d5d2aefcba99a459731b9543debb36
31ebcf5906b3f338ed430cab83ddb8a594d8d37b
v1.0
complete
Algorithm
Algorithm_16710_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorder_traversal(root): """ Helper function for in-order traversal of BST and returns elements in sorted order. >>> root = TreeNode(1, None, TreeNode(2, None, Tr...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorder_traversal(root): """Helper function for in-order traversal of BST and returns elements in sorted order.""" return inorder_traversal(root.left) + [root.val...
import pytest def test_inorder_traversal(): root = TreeNode(1, None, TreeNode(2, None, TreeNode(3))) assert inorder_traversal(root) == [1, 2, 3] root = TreeNode(3, TreeNode(2, TreeNode(1)), None) assert inorder_traversal(root) == [1, 2, 3] def test_sorted_array_to_bst(): nums = [1, 2, 3] root...
[]
[ 0, 1, 0, 1, 1, 0, 0, 1, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_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 balan...
trial_gpt4o_9
{ "original_instruction": "### Binary Search Tree Balancing\n\n#### Context:\nA Binary Search Tree (BST) is a node-based binary tree data structure that has the following properties: the left subtree of a node contains only nodes with values less than the node's key, the right subtree of a node contains only nodes wi...
0.631008
Algorithm_16710
C
[ "inorder_traversal", "sorted_array_to_bst", "balance_bst" ]
3
[ [ "balance_bst", "inorder_traversal" ], [ "balance_bst", "sorted_array_to_bst" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
f6782210f8a2621eff1f1413efadb268f65f2915
06d65d15c689077ed157651ed25ac486cf84b7ca
v1.0
complete
Algorithm
Algorithm_24165_C
def get_stock_price(url: str) -> float: """ Fetch the current stock price from a given URL. Args: - url (str): The URL from which to fetch the stock price. Returns: - float: The current stock price. >>> import requests >>> from unittest.mock import patch, MagicMock >>>...
import requests def get_stock_price(url): """ Fetch the current stock price from a given URL. Args: - url (str): The URL from which to fetch the stock price. Returns: - float: The current stock price. """ try: response = requests.get(url, timeout=10) response.r...
from solution import get_stock_price, check_stock_price from unittest.mock import patch, MagicMock def test_get_stock_price_success(): with patch('solution.requests.get') as mock_get: mock_response = MagicMock() mock_response.json.return_value = {'price': '200.0'} mock_get.return_value = mo...
[ { "docstring": "Fetch the current stock price from a given URL.\n\nArgs:\n- url (str): The URL from which to fetch the stock price.\n\nReturns:\n- float: The current stock price.", "function_declaration": "def get_stock_price(url):", "function_name": "get_stock_price", "parameter_list": "(url)" },...
[ 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nfrom requests.exceptions import Timeout, RequestException\n\ndef get_stock_price(url):\n \"\"\"\n Fetch the current price of a stock from ...
trial_gpt4o_9
{ "original_instruction": "### Stock Price Alert System\n\nYou are tasked with creating a system that monitors stock prices and sends an alert when the price of a specified stock crosses a certain threshold. The system will have to retrieve the current stock price from a provided URL and compare it to a given target ...
0.737
Algorithm_24165
C
[ "get_stock_price", "check_stock_price" ]
2
[ [ "check_stock_price", "get_stock_price" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
bbe28b4cf269227d221e5514f1474467a28d348e
06d652c780312f02e8bdb7f909d6f9ad49011510
v1.0
complete
Algorithm
Algorithm_14753_C
import requests def calculate_feels_like(temp_f, humidity): """ Calculate the 'feels like' temperature using a basic heat index formula. This is simplified and for more accurate results, more complex equations can be used. """ feels_like = temp_f + 0.33 * humidity - 0.7 return feels_like def e...
import requests def calculate_feels_like(temp_f, humidity): """ Calculate the 'feels like' temperature using a basic heat index formula. This is simplified and for more accurate results, more complex equations can be used. """ feels_like = temp_f + 0.33 * humidity - 0.7 return feels_like def e...
import pytest import requests from unittest.mock import patch from solution import enhanced_weather_report def test_success_response(): # Mock response data mock_response = { "current": { "temp_f": 75, "humidity": 50, "wind_mph": 10.0, "condition": { ...
[ { "docstring": "Calculate the 'feels like' temperature using a basic heat index formula.\nThis is simplified and for more accurate results, more complex equations can be used.", "function_declaration": "def calculate_feels_like(temp_f, humidity):", "function_name": "calculate_feels_like", "parameter...
[ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\n\ndef enhanced_weather_report(location, api_key):\n \"\"\"\n Fetches weather data for the given location and returns a detailed report.\n ...
trial_gpt4o_7
{ "original_instruction": "### Problem: Weather Data Analyzer\n\nYou are provided with a function that retrieves weather data from an API. The API returns a JSON object that includes various data points such as temperature, humidity, wind speed, and a weather description. Your task is to enhance this function in the ...
0.524107
Algorithm_14753
C
[ "calculate_feels_like", "enhanced_weather_report" ]
2
[ [ "enhanced_weather_report", "calculate_feels_like" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
466a27c6464dda694c9a888761a5a798a59a97de
2f2be8ed05184985afa8e723266056791dbb86e5
v1.0
complete
Algorithm
Algorithm_30482_C
import numpy as np from typing import List, Tuple def damerau_levenshtein_distance(s1: str, s2: str) -> int: """ Calculate the Damerau-Levenshtein distance between two strings s1 and s2. """ pass # implementation here def spell_check(file_path: str, dictionary_path: str) -> List[Tuple[str, str]]: ...
import numpy as np def damerau_levenshtein_distance(s1, s2): """ Calculate the Damerau-Levenshtein distance between two strings s1 and s2. """ d = np.zeros((len(s1) + 1, len(s2) + 1), dtype=int) d[0] = np.arange(len(s2) + 1) d[:, 0] = np.arange(len(s1) + 1) for i in range(1, len(s...
def test_damerau_levenshtein_distance(): assert damerau_levenshtein_distance("helo", "hello") == 1 assert damerau_levenshtein_distance("helo", "world") == 4 assert damerau_levenshtein_distance("helo", "helo") == 0 assert damerau_levenshtein_distance("abcd", "acbd") == 1 def test_spell_check(tmp_path): ...
[ { "docstring": "Calculate the Damerau-Levenshtein distance between two strings s1 and s2.", "function_declaration": "def damerau_levenshtein_distance(s1, s2):", "function_name": "damerau_levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": "Checks and corrects the spelling o...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import os\nfrom collections import defaultdict\nfrom Levenshtein import damerau_levenshtein_distance as dld\n\ndef spell_check(file_path, dictionary_path):\n ...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement**:\nYou are required to implement a simple spell checker for an English language file using the Damerau-Levenshtein distance algorithm. This algorithm calculates the minimum number of operations (insertions, deletions, substitutions, and transpositions) needed to transfo...
0.609822
Algorithm_30482
C
[ "damerau_levenshtein_distance", "spell_check" ]
2
[ [ "spell_check", "damerau_levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
false
[ "numpy" ]
false
cb41071fd2fc6db65918f7c5941981e071c56a55
0b002da2ebd4fc52d7b8a098a12a7e94d5e0d65b
v1.0
complete
Algorithm
Algorithm_35328_C
from typing import List, Tuple def find_path(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]: """ Uses the A* algorithm to find the shortest path from start to goal, allowing diagonal movements. Args: grid: A 2D list of integers, where 0 indicate...
import heapq from typing import List, Tuple import math def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> float: return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) def find_path(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]: def neighbors(n): ...
from solution import find_path def test_find_path_empty_grid(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] start = (0, 0) goal = (2, 2) path = find_path(grid, start, goal) assert len(path) > 0 assert path[0] == start assert path[-1] == goal def test_find_path_wi...
[ { "docstring": null, "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def find_path(grid, start, goal):", "function_name": "find_path", "parameter_list": "(grid, start, goal)"...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nfrom typing import List, Tuple\nimport math\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> float:\n return math.sqrt((a[0] - b[0]) ...
trial_gpt4o_0
{ "original_instruction": "### Pathfinding Algorithm with Diagonal Movements\n\nIn this coding challenge, you are asked to extend the traditional A* pathfinding algorithm to support diagonal movements in addition to the standard horizontal and vertical movements.\n\nA* is a popular heuristic search algorithm for find...
0.704086
Algorithm_35328
C
[ "heuristic", "find_path" ]
2
[ [ "find_path", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8ea725f302cfb23b37034a470c020112621d06f9
f460965ddee32e47fede765127a4b1498a166fe7
v1.0
complete
Algorithm
Algorithm_44450_C
Implement a Simple Neural Network from Scratch --- In this task, you will build a simple feedforward neural network with a single hidden layer from scratch using only numpy. This will help you understand the basics of neural networks, including forward pass, loss calculations, and backward pass for parameter updates....
import numpy as np def initialize_parameters(input_dim: int, hidden_dim: int, output_dim: int) -> dict: """ Initializes weights and biases of the neural network. """ np.random.seed(42) W1 = np.random.randn(input_dim, hidden_dim) * 0.01 b1 = np.zeros((1, hidden_dim)) W2 = np.random.randn(hid...
import numpy as np from solution import initialize_parameters, forward_pass, compute_loss, backward_pass, update_parameters def test_initialize_parameters(): params = initialize_parameters(2, 3, 1) assert params["W1"].shape == (2, 3) assert params["b1"].shape == (1, 3) assert params["W2"].shape == (3, ...
[ { "docstring": "Initializes weights and biases of the neural network.", "function_declaration": "def initialize_parameters(input_dim, hidden_dim, output_dim):", "function_name": "initialize_parameters", "parameter_list": "(input_dim, hidden_dim, output_dim)" }, { "docstring": null, "func...
[ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef initialize_parameters(input_dim: int, hidden_dim: int, output_dim: int) -> dict:\n np.random.seed(42) # Ensure reproducibility\n ...
trial_gpt4o_7
{ "original_instruction": "### Question: Implement a Simple Neural Network from Scratch\n\nIn this task, you will build a simple feedforward neural network with a single hidden layer from scratch using only numpy. This will help you understand the basics of neural networks, including forward pass, loss calculations, ...
0.546918
Algorithm_44450
C
[ "initialize_parameters", "sigmoid", "forward_pass", "compute_loss", "backward_pass", "update_parameters" ]
6
[ [ "forward_pass", "sigmoid" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
bbf6809ea6120977adf26bad464eb4b4eea91714
76c5732c05066465a26e34ae8df80d26ccb7137f
v1.0
complete
Algorithm
Algorithm_6972_C
def count_live_neighbors(board: list[list[int]], row: int, col: int) -> int: directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] live_neighbors = 0 for dr, dc in directions: rr = (row + dr) % len(board) cc = (col + dc) % len(board[0]) live_neighbors +=...
def count_live_neighbors(board: list[list[int]], row: int, col: int) -> int: directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] live_neighbors = 0 for dr, dc in directions: rr = (row + dr) % len(board) cc = (col + dc) % len(board[0]) live_neighbors +=...
def test_next_generation(): # Block pattern (still life) initial_state = [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0] ] expected_next_state = [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0] ] assert next_generat...
[ { "docstring": null, "function_declaration": "def count_live_neighbors(board, row, col):", "function_name": "count_live_neighbors", "parameter_list": "(board, row, col)" }, { "docstring": null, "function_declaration": "def next_generation(board):", "function_name": "next_generation",...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def count_live_neighbors(board, row, col):\n directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n live_neighbors = 0\n ...
trial_gpt4o_8
{ "original_instruction": "### Conway's Game of Life with Custom Initial State\n\nYou are given a skeleton code to simulate Conway's Game of Life, which is a cellular automaton where cells evolve based on their neighbors' states. The board is represented as a 2D grid of cells that are either alive (1) or dead (0). Ce...
0.556369
Algorithm_6972
C
[ "count_live_neighbors", "next_generation", "initialize_board" ]
3
[ [ "next_generation", "count_live_neighbors" ] ]
1
[]
false
[]
false
pytest
false
[]
true
ec707ba9b4efc07bcc3df39ce1032de475d320cd
efd1fb54657f0d48deb74fa1e1b53e98fc619dc3
v1.0
complete
Algorithm
Algorithm_10715_C
def reverse_words(sentence: str) -> str: """ Reverses the words in a sentence. >>> reverse_words("hello world") "world hello" >>> reverse_words("The quick brown fox") "fox brown quick The" >>> reverse_words("single") "single" """ pass def count_words(sentence: str) -> int: """ C...
def reverse_words(sentence: str) -> str: """ Reverses the words in a sentence. """ return ' '.join(sentence.split()[::-1]) def count_words(sentence: str) -> int: """ Counts the words in a sentence. """ return len(sentence.split()) def analyze_sentence(sentence: str) -> tuple: """ ...
from solution import reverse_words, count_words, analyze_sentence def test_reverse_words(): assert reverse_words("hello world") == "world hello" assert reverse_words("The quick brown fox") == "fox brown quick The" assert reverse_words("single") == "single" assert reverse_words("a b c d") == "d c b a" ...
[ { "docstring": "Reverses the words in a sentence.", "function_declaration": "def reverse_words(sentence):", "function_name": "reverse_words", "parameter_list": "(sentence)" }, { "docstring": "Counts the words in a sentence.", "function_declaration": "def count_words(sentence):", "fun...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def reverse_words(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a sentence.\n \"\"\"\n return ' '.join(sentence.split()[::-1])\n\n...
trial_gpt4o_9
{ "original_instruction": "### Coding Question: Sentence Reversal and Word Count Analysis\n\n#### Objective:\nYou are given a function that reverses words in a sentence and another function that counts the words. Your task is to enhance these functions and write a new function that works with both to solve a given pr...
0.65625
Algorithm_10715
C
[ "reverse_words", "count_words", "analyze_sentence" ]
3
[ [ "analyze_sentence", "count_words" ], [ "analyze_sentence", "reverse_words" ] ]
2
[]
false
[]
false
pytest
true
[]
true
75bcbe57efb22604ae1013267a9725f60c547c80
11fcabe3e418d826ddc5a80bbe33564f5adced42
v1.0
complete
Algorithm
Algorithm_12470_C
class SegmentTreeNode: def __init__(self, start, end, count): self.start = start self.end = end self.count = count # Dictionary to store frequency of elements self.left = None self.right = None def build_segment_tree(arr): def build(start, end): if start == end:...
class SegmentTreeNode: def __init__(self, start, end, count): self.start = start self.end = end self.count = count # Dictionary to store frequency of elements self.left = None self.right = None def build_segment_tree(arr): def build(start, end): if start == end:...
import pytest def test_range_kth_smallest(): arr = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] root = build_segment_tree(arr) assert range_kth_smallest(root, 0, 4, 3) == 4 assert range_kth_smallest(root, 6, 10, 2) == 1 assert range_kth_smallest(root, 13, 18, 4) == 3 assert...
[]
[ 0, 1, 0, 0, 0, 0, 0, 1, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class SegmentTreeNode:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.min_vals = []\n self.left = ...
trial_gpt4o_1
{ "original_instruction": "### Question:\n\nYou have been given an implementation of the Segment Tree data structure that supports point updates and range sum queries. Your task is to extend this data structure by introducing a new method to determine and return the k-th smallest element in a specified subarray range...
0.559216
Algorithm_12470
C
[ "build_segment_tree", "query", "range_kth_smallest" ]
3
[ [ "range_kth_smallest", "query" ] ]
1
[]
false
[ "SegmentTreeNode" ]
true
pytest
false
[]
true
fc2291ed68ae8d8d3b8b9bdeaf157c4373e1f511
be22b2dd3433cc2b8a9164355d8ce9da90a5e440
v1.0
complete
Algorithm
Algorithm_7752_C
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): """ Helper function to compute nth Fibonacci number with caching """ if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) def cached_fibonacci(n: int) -> list[int]: """ Generates a list of the first `n` Fibona...
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) def cached_fibonacci(n: int) -> list[int]: if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer") result = [] ...
from solution import cached_fibonacci import pytest def test_cached_fibonacci_general_cases(): assert cached_fibonacci(5) == [0, 1, 1, 2, 3] assert cached_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] def test_cached_fibonacci_edge_cases(): assert cached_fibonacci(0) == [] assert cached_fibonacci...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def cached_fibonacci(n):", "function_name": "cached_fibonacci", "parameter_list": "(n)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from functools import lru_cache\n\ndef cached_fibonacci(n: int) -> list[int]:\n # Check for invalid input\n if not isinstance(n, int) or n < 0:\n ra...
trial_gpt4o_9
{ "original_instruction": "### Fibonacci Sequence Generator with Caching\nYou are tasked with creating a function that efficiently generates a list of the first `n` Fibonacci numbers using caching to improve performance. The function must utilize a caching mechanism (such as `functools.lru_cache` or a dictionary) to ...
0.739973
Algorithm_7752
C
[ "fibonacci", "cached_fibonacci" ]
2
[ [ "cached_fibonacci", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a218353c42b70589b815cb7c358f5532ef9d056
04f117101776a629b583f3bb23f0274a086f7cee
v1.0
complete
Algorithm
Algorithm_2158_C
def is_valid(board: list[list[int]], row: int, col: int, num: int) -> bool: """ Check if it's valid to place the `num` at `board[row][col]` """ # Check current row for i in range(9): if board[row][i] == num: return False # Check current column for i in range(9): ...
def is_valid(board, row, col, num): """ Check if it's valid to place the `num` at `board[row][col]` """ for i in range(9): if board[row][i] == num: return False if board[i][col] == num: return False start_row, start_col = 3 * (row // 3), 3 * (col // 3) ...
import pytest from solution import solve_sudoku def test_sudoku_solver_complete(): board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], ...
[ { "docstring": "Check if it's valid to place the `num` at `board[row][col]`", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Implement a backtracking algorithm to solve the Sudoku puzzl...
[ 1, 0, 1, 0, 1, 1, 0, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if it's valid to place the `num` at `board[row][col]`\n \"\"\"\n # Check current row\n for i ...
trial_gpt4o_2
{ "original_instruction": "**[Question 2]: Sudoku Solver**\n\nYou are tasked with creating a solver for a standard 9x9 Sudoku puzzle. A Sudoku puzzle consists of a 9x9 grid of cells, which are subdivided into 3x3 subgrids. The puzzle starts with some cells already filled with digits from 1 to 9. Your objective is to ...
0.606438
Algorithm_2158
C
[ "is_valid", "sudoku_solver", "solve_sudoku" ]
3
[ [ "solve_sudoku", "sudoku_solver" ], [ "sudoku_solver", "is_valid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ad5bd5d7c144d6ac3fa0ae4514630bd6b8d40b90
594ae3df68d7938d0a3fd8c294802336ae13a05c
v1.0
complete
Algorithm
Algorithm_29304_C
import numpy as np def k_means_plus_plus(data, K): """ Initialize centroids using the K-Means++ algorithm. Args: data (np.ndarray): The input dataset of shape (N, D). K (int): The number of clusters. Returns: np.ndarray: The initialized centroids of shape (K, D). """ p...
import numpy as np def k_means_plus_plus(data, K): n_samples, n_features = data.shape centroids = np.empty((K, n_features)) # Choose the first centroid randomly from the data points centroids[0] = data[np.random.choice(n_samples)] for k in range(1, K): # Compute the distance from ...
import numpy as np from solution import k_means, k_means_plus_plus def test_k_means_plus_plus_initialization(): data = np.array([ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0] ]) K = 2 centroids = k_means_plus_plus(data, K) a...
[ { "docstring": null, "function_declaration": "def k_means_plus_plus(data, K):", "function_name": "k_means_plus_plus", "parameter_list": "(data, K)" }, { "docstring": null, "function_declaration": "def k_means(data, K, max_iters=300, tol=0.0001):", "function_name": "k_means", "par...
[ 0, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.spatial.distance import cdist, euclidean\n\ndef k_means_plus_plus(data, K):\n \"\"\" Initialize centroids using the K-Means++ a...
trial_gpt4o_9
{ "original_instruction": "### Advanced Coding Challenge: Implementing K-Means Clustering with Optimizations\n\n#### Background\nK-Means clustering is a widely-used algorithm for partitioning a dataset into K clusters, where each data point belongs to the cluster with the nearest mean. The algorithm works iteratively...
0.790149
Algorithm_29304
C
[ "k_means_plus_plus", "k_means" ]
2
[ [ "k_means", "k_means_plus_plus" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
498463f1d70b5f48d3199fb1bb4e43c7d05c1a7a
b0452e75f8c0c1be860552d6d80f3dd802e60954
v1.0
complete
Algorithm
Algorithm_9633_C
def calculate_entropy(labels): """ Calculate the entropy of a dataset. :param labels: List of labels (int) :return: Entropy value (float) """ pass def calculate_information_gain(original_labels, split_labels): """ Calculate the information gain of a split dataset. :param original_la...
import math from collections import Counter def calculate_entropy(labels): """ Calculate the entropy of a dataset. :param labels: List of labels (int) :return: Entropy value (float) """ total_count = len(labels) label_counts = Counter(labels) entropy = 0.0 for count in lab...
from solution import calculate_entropy, calculate_information_gain, split_dataset, build_tree, predict, accuracy def test_calculate_entropy(): assert math.isclose(calculate_entropy([1, 0, 1, 1, 0, 0]), 1.0) assert math.isclose(calculate_entropy([1, 1, 1, 1]), 0.0) assert math.isclose(calculate_entropy([0, ...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom collections import Counter\n\ndef calculate_entropy(labels):\n \"\"\"\n Calculate the entropy of a list of labels.\n \n Args:\n ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: Implement a Decision Tree Classifier\n\nYou are required to implement a simple Decision Tree Classifier from scratch. The model should be able to train on a given dataset and predict the class of new instances. Your implementation should follow the basic prin...
0.609692
Algorithm_9633
C
[ "calculate_entropy", "calculate_information_gain", "split_dataset", "build_tree", "predict", "accuracy" ]
6
[ [ "build_tree", "calculate_entropy" ], [ "build_tree", "calculate_information_gain" ], [ "build_tree", "split_dataset" ], [ "calculate_information_gain", "calculate_entropy" ] ]
4
[]
false
[]
false
pytest
true
[]
true
6d8763b1bb84dcc1f8cf3b6bfe22eafd6277fc96
96d027b00509366248666455887df6f10336715f
v1.0
complete
Algorithm
Algorithm_14281_C
import requests EXCHANGERATE_API_KEY = "your_exchangerate_api_key" CURRENCY_LAYER_API_KEY = "your_currency_layer_api_key" EXCHANGERATE_URL_BASE = "https://v6.exchangerate-api.com/v6/{key}/latest/{from_currency}" CURRENCY_LAYER_URL_BASE = "http://api.currencylayer.com/live?access_key={key}&currencies={to_currency}&sour...
import requests EXCHANGERATE_API_KEY = "your_exchangerate_api_key" CURRENCY_LAYER_API_KEY = "your_currency_layer_api_key" EXCHANGERATE_URL_BASE = "https://v6.exchangerate-api.com/v6/{key}/latest/{from_currency}" CURRENCY_LAYER_URL_BASE = "http://api.currencylayer.com/live?access_key={key}&currencies={to_currency}&sour...
import pytest from unittest.mock import patch from solution import convert_currency, fetch_exchange_rate_exchangerate_api, fetch_exchange_rate_currency_layer @patch('solution.requests.get') def test_fetch_exchange_rate_exchangerate_api(mock_get): mock_response_data = { 'conversion_rates': { 'EU...
[ { "docstring": null, "function_declaration": "def fetch_exchange_rate_exchangerate_api(from_currency, to_currency):", "function_name": "fetch_exchange_rate_exchangerate_api", "parameter_list": "(from_currency, to_currency)" }, { "docstring": null, "function_declaration": "def fetch_excha...
[ 0, 1, 1, 0, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\n\nEXCHANGERATE_API_KEY = \"YOUR_EXCHANGERATE_API_KEY\"\nCURRENCY_LAYER_API_KEY = \"YOUR_CURRENCY_LAYER_API_KEY\"\nEXCHANGERATE_URL_BASE = \"http...
trial_gpt4o_8
{ "original_instruction": "### Question: Currency Converter\n\nYou are required to create a function that converts an amount of money from one currency to another using exchange rates from two different APIs: ExchangeRate-API and CurrencyLayer. The function should handle cases where no valid API keys are provided, or...
0.54723
Algorithm_14281
C
[ "fetch_exchange_rate_exchangerate_api", "fetch_exchange_rate_currency_layer", "convert_currency" ]
3
[ [ "convert_currency", "fetch_exchange_rate_currency_layer" ], [ "convert_currency", "fetch_exchange_rate_exchangerate_api" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
6b149e3a8feb04fe8d4250c69d5fe039fe5f69c4
8b8a8d955dede60db16ae96b116eb07245caf5e4
v1.0
complete
Data_Structure
Data_Structure_10_C
def enhanced_encode_rle(input: str) -> str: """ Encodes the input string using Run-Length Encoding (RLE). :param input: A string containing the data to be encoded. :return: A string that represents the encoded data. >>> enhanced_encode_rle("aaabbbcccaaa") "3a3b3c3a" >>> enhanced_encode...
def enhanced_encode_rle(input: str) -> str: if not input: return "" encoded_str = [] i = 0 while i < len(input): count = 1 while i + 1 < len(input) and input[i] == input[i + 1]: i += 1 count += 1 encoded_str.append(f"{count}{input[i]}") ...
from solution import enhanced_encode_rle, enhanced_decode_rle, validate_encoded_rle def test_enhanced_encode_rle(): assert enhanced_encode_rle("aaabbbcccaaa") == "3a3b3c3a" assert enhanced_encode_rle("hhhhhaaann") == "5h3a2n" assert enhanced_encode_rle("") == "" assert enhanced_encode_rle("a") == "1a" ...
[ { "docstring": null, "function_declaration": "def enhanced_encode_rle(input):", "function_name": "enhanced_encode_rle", "parameter_list": "(input)" }, { "docstring": null, "function_declaration": "def enhanced_decode_rle(input):", "function_name": "enhanced_decode_rle", "paramete...
[ 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 enhanced_encode_rle(input: str) -> str:\n if not input:\n return \"\"\n \n encoded_str = []\n i = 0\n\n while i < len(input):\n ...
trial_gpt4o_0
{ "original_instruction": "### Question Title: Advanced Run-Length Encoding and Decoding with Validations\n\n#### Description:\nImplement an enhanced version of the Run-Length Encoding (RLE) and Decoding functions. In addition to encoding and decoding, your implementation needs to handle edge cases gracefully and inc...
0.671127
Data_Structure_10
C
[ "enhanced_encode_rle", "enhanced_decode_rle", "validate_encoded_rle" ]
3
[ [ "enhanced_decode_rle", "validate_encoded_rle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5957820320e9adc8e4c80ef3a8382699fd793ab4
1d437b8fc38fcabd662a928772286929f7e5018a
v1.0
complete
Data_Structure
Data_Structure_14_C
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def create_bst(nums: List[int]) -> TreeNode: """ Create a Binary Search Tree (BST) from a list of integers. """ pass def inorder_tra...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_bst(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert_into_bst(root.left, val) elif val > ro...
from solution import create_bst, inorder_traversal def test_example_1(): nums = [8, 3, 10, 1, 6, 14, 4, 7, 13] root = create_bst(nums) assert inorder_traversal(root) == [1, 3, 4, 6, 7, 8, 10, 13, 14] def test_example_2(): nums = [20, 5, 25, 3, 8, 30] root = create_bst(nums) assert inorder_trav...
[]
[ 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, Optional\n\nclass TreeNode:\n def __init__(self, val: int):\n self.val = val\n self.left = None\n self.right ...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement:**\n\nYou are given a list of integers. Your task is to construct a Binary Search Tree (BST) from the integers and implement a function to perform an in-order traversal of the BST. The traversal should be printed as a list of integers in ascending order.\n\n**Function Si...
0.550629
Data_Structure_14
C
[ "insert_into_bst", "create_bst", "inorder_traversal" ]
3
[ [ "create_bst", "insert_into_bst" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
8e6c6acc180fd7cddd51a9d7284003bd79ad6f95
baf1b603363f88e3b5e79cc62295eac67b7e0544
v1.0
complete
Data_Structure
Data_Structure_26_C
from typing import Dict, List def generate_sequence(chain: Dict[str, Dict[str, float]], start_state: str, iterations: int) -> List[str]: """ Generates a sequence of states in a Markov Chain. :param chain: Dictionary representing the Markov Chain. :param start_state: String, the starting state. :param i...
import random def generate_sequence(chain, start_state, iterations): """ Generates a sequence of states in a Markov Chain. :param chain: Dictionary, the Markov chain. :param start_state: The starting state. :param iterations: Number of transitions to generate. :return: List of states visit...
from solution import generate_sequence, is_valid_chain def test_generate_sequence(): chain = { 'A': {'A': 0.6, 'B': 0.4}, 'B': {'A': 0.7, 'B': 0.3} } sequence = generate_sequence(chain, 'A', 5) assert len(sequence) == 6 # The initial state + 5 iterations assert all(state in chain f...
[ { "docstring": "Generates a sequence of states in a Markov Chain.\n\n:param chain: Dictionary, the Markov chain.\n:param start_state: The starting state.\n:param iterations: Number of transitions to generate.\n:return: List of states visited in sequence.", "function_declaration": "def generate_sequence(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 generate_sequence(chain, start_state, iterations):\n \"\"\"\n Generates a sequence of states in a Markov chain.\n \n Paramete...
trial_gpt4o_2
{ "original_instruction": "You are given a Markov Chain defined as described below. Implement two functions:\n1. `generate_sequence(chain, start_state, iterations)`:\n - **Input**: \n - `chain`: A dictionary representing the Markov chain where keys are states and values are dictionaries of next state probabilit...
0.559305
Data_Structure_26
C
[ "generate_sequence", "_get_next_state", "is_valid_chain" ]
3
[ [ "generate_sequence", "_get_next_state" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f65e098be748394fc18aa3c784e08049445453bb
bb755d449164e2f115fafea982b6d5fcd3617d48
v1.0
complete
Data_Structure
Data_Structure_66_C
def is_prime_miller_rabin(n, k=5): """ Determine if n is prime using the Miller-Rabin test with k iterations. >>> is_prime_miller_rabin(23) True >>> is_prime_miller_rabin(24) False """ def euler_totient_optimized(n): """ Computes the count of coprime integers to n. >>> euler_totient...
import random def is_prime_miller_rabin(n, k=5): """Determine if n is a prime using Miller-Rabin Primality Test.""" if n in (2, 3): return True if n <= 1 or n % 2 == 0: return False # Write n-1 as 2^r * d r, d = 0, n - 1 while d % 2 == 0: r += 1 d //= 2 def...
from solution import ( is_prime_miller_rabin, euler_totient_optimized, find_order_optimized, find_primitive_root_optimized, diffie_hellman_key_exchange_optimized ) def test_is_prime_miller_rabin(): assert is_prime_miller_rabin(23) == True assert is_prime_miller_rabin(24) == False assert...
[ { "docstring": "Determine if n is a prime using Miller-Rabin Primality Test.", "function_declaration": "def is_prime_miller_rabin(n, k=5):", "function_name": "is_prime_miller_rabin", "parameter_list": "(n, k=5)" }, { "docstring": "Calculate Euler's Totient function using optimized approach."...
[ 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_prime_miller_rabin(n, k=5):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0:\n re...
trial_gpt4o_2
{ "original_instruction": "### Question: Implement and Analyze Diffie-Hellman Key Exchange with Optimized Primality Testing\n\n#### Description\nAlice and Bob want to securely share data over an insecure channel using the Diffie-Hellman key exchange algorithm. Your task is to implement this key exchange mechanism, in...
0.555506
Data_Structure_66
C
[ "is_prime_miller_rabin", "euler_totient_optimized", "find_order_optimized", "gcd", "find_primitive_root_optimized", "prime_factors", "diffie_hellman_key_exchange_optimized" ]
7
[ [ "diffie_hellman_key_exchange_optimized", "find_primitive_root_optimized" ], [ "diffie_hellman_key_exchange_optimized", "is_prime_miller_rabin" ], [ "find_order_optimized", "gcd" ], [ "find_primitive_root_optimized", "euler_totient_optimized" ], [ "find_primitive...
6
[]
false
[]
false
pytest
true
[]
true
73f736fa179238fed74c6d457f476639053a8def
b8b2315774232c6da0f79d27d601997c082c3017
v1.0
complete
Data_Structure
Data_Structure_56_C
def bucket_sort(arr: List[int], bucket_size: int = 10) -> List[int]: """ Implement Bucket Sort with Enhanced Insertion Sort. Given a list of integers, implement the bucket sort algorithm. Your implementation should handle edge cases effectively and optimize for performance by incorporating any improvements you ...
def insertion_sort(arr): """ A simple insertion sort. Effective for 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 arr[j + 1] = key return arr def bucket_sort(arr...
from solution import bucket_sort def test_bucket_sort_normal_case(): arr = [19, 3, 15, 4, 6, 1, 13, 122, 47, 91] expected = [1, 3, 4, 6, 13, 15, 19, 47, 91, 122] assert bucket_sort(arr) == expected def test_bucket_sort_single_element(): arr = [5] expected = [5] assert bucket_sort(arr) == expec...
[ { "docstring": "A simple insertion sort. Effective for small arrays.", "function_declaration": "def insertion_sort(arr):", "function_name": "insertion_sort", "parameter_list": "(arr)" }, { "docstring": "Bucket sort function which distributes elements into buckets,\nsorts each bucket with a p...
[ 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 insertion_sort(arr):\n \"\"\"\n Helper function to perform insertion sort on an array.\n \"\"\"\n for i in range(1, len(arr)):\n key = ...
trial_gpt4o_2
{ "original_instruction": "Implement Bucket Sort with Enhanced Insertion Sort\n\nGiven a list of integers, implement the bucket sort algorithm. Your implementation should handle edge cases effectively and optimize for performance by incorporating any improvements you consider necessary.\n\n### Input\n- A list of inte...
0.56699
Data_Structure_56
C
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
92cc2817b892af8a64dc1e712c34c920ba6f2170
2d81aabb161e915723e46f751fcc9902468dba2e
v1.0
complete
Data_Structure
Data_Structure_58_C
class Node: def __init__(self, val): self.val = val self.next = None def get_length(head: Node) -> int: """ Get the length of the linked list starting from the head node. >>> get_length(Node(1)) # Assuming it links to other nodes 1 """ pass def find_intersection(head1: Node, h...
class Node: def __init__(self, val): self.val = val self.next = None def get_length(head): length = 0 current = head while current: length += 1 current = current.next return length def find_intersection(head1, head2): # Get lengths of both lists len1 = get_l...
from solution import Node, find_intersection def test_intersection_node(): # Creating linked lists # List 1: 1 -> 3 -> 5 -> 7 -> 9 -> 11 n1 = Node(1) n3 = Node(3) n5 = Node(5) n7 = Node(7) n9 = Node(9) n11 = Node(11) n1.next = n3 n3.next = n5 n5.next = n7 n7.next = n9 ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, val):\n self.val = val\n self.next = None\n\ndef get_length(head: Node) -> int:\n length = 0\n while h...
trial_gpt4o_2
{ "original_instruction": "### Intersection of Two Linked Lists\n\nYou are tasked with finding the intersection node of two singly linked lists. The intersection is defined based on reference, not value. Create a function `find_intersection` which takes the heads of two such linked lists and returns the intersecting ...
0.554326
Data_Structure_58
C
[ "get_length", "find_intersection" ]
2
[ [ "find_intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
5fddd66a85e95fc11791a21520429f13b424bc82
6cd247a0c371f613cd093f096964a223736e9523
v1.0
complete
Data_Structure
Data_Structure_127_C
from typing import List def insertion_sort(array: List[int]) -> List[int]: """ Sort an array of integers using an improved insertion sort algorithm that leverages binary search. >>> insertion_sort([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5] >>> insertion_sort([]) == [] >>> insertion_sort([5, -1, 3]) == [-1, 3,...
from typing import List def binary_search_insert_position(arr: List[int], key: int, start: int, end: int) -> int: while start < end: mid = (start + end) // 2 if arr[mid] < key: start = mid + 1 else: end = mid return start def insertion_sort(array: List[int]) -> ...
from solution import insertion_sort def test_insertion_sort_empty(): assert insertion_sort([]) == [] def test_insertion_sort_single_element(): assert insertion_sort([1]) == [1] def test_insertion_sort_sorted_array(): assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_insertion_sort_rever...
[ { "docstring": null, "function_declaration": "def binary_search_insert_position(arr, key, start, end):", "function_name": "binary_search_insert_position", "parameter_list": "(arr, key, start, end)" }, { "docstring": null, "function_declaration": "def insertion_sort(array):", "functio...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n A helper function to perform binary sear...
trial_gpt4o_2
{ "original_instruction": "### Description\nYou are tasked with implementing a function `insertion_sort` that sorts an array of integers using an improved insertion sort algorithm that leverages binary search for finding the insertion point swiftly. The aim is to combine the simplicity of insertion sort with the effi...
0.650973
Data_Structure_127
C
[ "binary_search_insert_position", "insertion_sort" ]
2
[ [ "insertion_sort", "binary_search_insert_position" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9df30803f51ef8fdb4821c900565ea39d85752af
2fd742104754fccdaf5aa8b00f2f55340767addb
v1.0
complete
Data_Structure
Data_Structure_142_C
def bogo_sort_improved(arr: list, max_iterations: int = 100000) -> (list, int): """ Sorts the array using Bogo Sort with an iteration limit :param arr: List of integers to be sorted :param max_iterations: Maximum number of iterations allowed to prevent infinite loops :return: Tuple containing the so...
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_improved(arr, max_iterations=100000): """ Sorts the array using Bogo Sort with an iteration limit. :param arr: List of inte...
from solution import bogo_sort_improved def test_empty_list(): assert bogo_sort_improved([]) == ([], 0) def test_single_element(): assert bogo_sort_improved([1]) == ([1], 0) def test_sorted_list(): assert bogo_sort_improved([1, 2, 3], max_iterations=10) == ([1, 2, 3], 0) def test_reverse_sorted_list...
[ { "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 Bogo Sort with an iteration limit.\n:param arr: List of integers to be sorted\n:p...
[ 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 the array is sorted.\n \"\"\"\n return all(arr[i] <= arr[i + 1] for i ...
trial_gpt4o_0
{ "original_instruction": "### Bogo Sort Implementation and Analysis\n\n#### Context:\n\nBogo Sort is often considered a joke among computer scientists due to its exceptionally poor performance characteristics and is rarely used in practice. However, it serves as an excellent didactic tool to highlight the importance...
0.601553
Data_Structure_142
C
[ "is_sorted", "bogo_sort_improved" ]
2
[ [ "bogo_sort_improved", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4cb47c9b092a11d421ac5604965be7f7c7f97df7
a3f36c31afe6a127f8b3e40d75cec7734044f342
v1.0
complete
Data_Structure
Data_Structure_168_C
from typing import List def radix_sort(arr: List[int]) -> List[int]: """Sort a list of non-negative integers using the Radix Sort algorithm. Args: arr (List[int]): A list of non-negative integers to be sorted. Returns: List[int]: A sorted list of integers in ascending order. ...
from typing import List def counting_sort(arr: List[int], exp: int) -> List[int]: n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >...
from solution import radix_sort def test_radix_sort_basic(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_single_element(): assert radix_sort([5]) == [5] def test_radix_sort_sorted_array(): assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4,...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_sort", "parameter_list": "(arr)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A helper function to perform a counting sort based on the digit represented by exp.\n \"\"\"\n n = len(arr...
trial_gpt4o_2
{ "original_instruction": "### Question\nYou are tasked to implement a function that sorts a list of non-negative integers using the Radix Sort algorithm. Your implementation should maintain stability and efficiently handle lists with varying integer sizes.\n\n#### Description\nWrite a function `radix_sort(arr)` that...
0.72378
Data_Structure_168
C
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3ec5ba7f4ad60ce209e1ac489a45c3948b8e4a3
bc07b0c22acb48d3f8bad4bc500f1678ae5a3fa3
v1.0
complete
Data_Structure
Data_Structure_313_C
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted in ascending order. >>> is_sorted([1, 2, 3]) True >>> is_sorted([3, 2, 1]) False """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: ...
import random from typing import List def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted in ascending order. """ for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True def custom_bogo_sort(arr: List[int]) -> None: ...
from solution import custom_bogo_sort def test_empty_array(): arr = [] custom_bogo_sort(arr) assert arr == [] def test_single_element_array(): arr = [1] custom_bogo_sort(arr) assert arr == [1] def test_sorted_array(): arr = [1, 2, 3] custom_bogo_sort(arr) assert arr == [1, 2, 3] ...
[ { "docstring": "Helper function to check if the array is sorted in ascending order.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Sorts the array `arr` in-place using the Bogo Sort algorithm.", "function_declar...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted in ascending...
trial_gpt4o_2
{ "original_instruction": "### Scenario\nIn this question, you will implement a version of Bogo Sort, notoriously known for its inefficiency. While this algorithm is not suitable for actual sorting tasks, it serves as an excellent exercise to demonstrate understanding of random permutations and algorithm design.\n\n#...
0.66688
Data_Structure_313
C
[ "is_sorted", "custom_bogo_sort" ]
2
[ [ "custom_bogo_sort", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6e6036c9da846f27fa9971dc5dcdc98224adeb70
fe3cf6459a9051ef2498b23b962181d37ddfca25
v1.0
complete
Data_Structure
Data_Structure_620_C
class ListNode: def __init__(self, val=0, next=None, sublist=None): self.val = val self.next = next self.sublist = sublist def reverse_hybrid_list(head: ListNode) -> ListNode: """ Reverse the main list and each of the sub-linked lists. >>> head = ListNode(1, ListNode(2, ListNode(3))...
class ListNode: def __init__(self, val=0, next=None, sublist=None): self.val = val self.next = next self.sublist = sublist def reverse_linked_list(head: ListNode) -> ListNode: prev = None current = head while current: next_node = current.next current.next = prev ...
from solution import ListNode, reverse_hybrid_list def list_to_string(head: ListNode) -> str: result = [] while head: sublist_as_string = '->'.join( str(node.val) for node in iterate_list(head.sublist)) if head.sublist else "" result.append(f"{head.val}:[{sublist_as_string}]") ...
[]
[ 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, sublist=None):\n self.val = val\n self.next = next\n self.sublist = sublist\n\n...
trial_gpt4o_2
{ "original_instruction": "### Reversing a Hybrid Linked List\n\nYou are given a singly linked list where each node might contain a primary value and a pointer to a sub-linked list. Your task is to reverse the main list and each of the sub-linked lists. For instance:\n\n```\n 1 --> 2 --> 3\n ↓ ↓ ↓\n ...
0.520338
Data_Structure_620
C
[ "reverse_linked_list", "reverse_sublist", "reverse_hybrid_list" ]
3
[ [ "reverse_hybrid_list", "reverse_linked_list" ], [ "reverse_hybrid_list", "reverse_sublist" ], [ "reverse_sublist", "reverse_linked_list" ] ]
3
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
3fff6fb5af4dcb012292b3b78d3c8dfc976ddced
f03d61ca275473e8e49be50b4e033769b7a45e79
v1.0
complete
Data_Structure
Data_Structure_481_C
from typing import List def compute_matrix_inverse(matrix: List[List[float]]) -> List[List[float]]: """ Given an n x n matrix represented as a 2D list, compute its inverse. Your function should account for edge cases such as non-square matrices and singular matrices (matrices with a determinant of zero)....
from typing import List def determinant(matrix: List[List[float]]) -> float: n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for c in range(n): det += ((-1) ** c) * matrix[0][c] * determi...
from solution import compute_matrix_inverse def test_non_matrix_input(): assert compute_matrix_inverse("not a matrix") == [[-1]] assert compute_matrix_inverse(12345) == [[-1]] def test_non_square_matrix(): assert compute_matrix_inverse([[1, 2], [3, 4], [5, 6]]) == [[-2]] assert compute_matrix_inverse(...
[ { "docstring": null, "function_declaration": "def determinant(matrix):", "function_name": "determinant", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def minor(matrix, i, j):", "function_name": "minor", "parameter_list": "(matrix, i, j)" }, { ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_determinant(matrix: List[List[float]]) -> float:\n \"\"\"Computes the determinant of an n x n matrix.\"\"\"\n n =...
trial_gpt4o_2
{ "original_instruction": "Given an n x n matrix represented as a 2D list, write a function that computes its inverse. Your function should account for edge cases, such as non-square matrices and singular matrices (matrices with a determinant of zero). If such cases are encountered, your function should handle it gra...
0.564241
Data_Structure_481
C
[ "determinant", "minor", "cofactor", "transpose", "inverse", "compute_matrix_inverse" ]
6
[ [ "cofactor", "determinant" ], [ "cofactor", "minor" ], [ "compute_matrix_inverse", "inverse" ], [ "determinant", "minor" ], [ "inverse", "cofactor" ], [ "inverse", "determinant" ], [ "inverse", "transpose" ] ]
7
[]
false
[]
false
pytest
true
[]
true
0b99d606350e66be5e8d6aaec1d3983cd2a45ab2
134796a0e7a112dff1b50524a6fe4d0c70b66997
v1.0
complete
Data_Structure
Data_Structure_583_C
import random def prime_check(num: int) -> bool: """ Returns True if num is a prime number. """ pass def find_order(a: int, n: int) -> int: """ Returns the order of a modulo n, or -1 if no order exists """ pass def euler_totient(n: int) -> int: """ Returns the Euler's totient ...
import random def prime_check(num: int) -> bool: """ Returns True if num is a prime number. """ if num <= 1: return False for i in range(2, int(num**0.5)+1): if num % i == 0: return False return True def find_order(a: int, n: int) -> int: """ Returns the ord...
from solution import prime_check, find_order, euler_totient, find_primitive_root, perform_diffie_hellman_key_exchange import pytest def test_prime_check(): assert prime_check(2) == True assert prime_check(4) == False assert prime_check(23) == True assert prime_check(1) == False assert prime_check(0...
[ { "docstring": "Returns True if num is a prime number.", "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": "Returns the order of a modulo n, or -1 if no order exists", "function_declaration": "def find_order(a, n)...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Returns True if num is a prime number.\n \"\"\"\n if num <= 1:\n return Fals...
trial_gpt4o_0
{ "original_instruction": "**Problem Statement: Secure Communication with Diffie-Hellman Key Exchange**\n\nAlice and Bob want to establish a secure communication channel by using the Diffie-Hellman key exchange algorithm. Your task is to implement the functions needed to carry out this cryptographic key exchange secu...
0.567913
Data_Structure_583
C
[ "prime_check", "find_order", "euler_totient", "find_primitive_root", "perform_diffie_hellman_key_exchange" ]
5
[ [ "find_primitive_root", "euler_totient" ], [ "find_primitive_root", "prime_check" ], [ "perform_diffie_hellman_key_exchange", "find_primitive_root" ], [ "perform_diffie_hellman_key_exchange", "prime_check" ] ]
4
[]
false
[]
false
pytest
true
[]
true
cd39c2a37875277a298c10676b4fc9b60f1c333d
127bb395b81b28dbfa1c4df550d8513863f22231
v1.0
complete
Data_Structure
Data_Structure_597_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def deserialize(data: str) -> TreeNode: def helper(nodes): val = next(nodes) if val == "#": return None node = TreeNode(int(val)) ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def deserialize(data: str) -> TreeNode: def helper(nodes): val = next(nodes) if val == "#": return None node = TreeNode(int(val)) ...
from solution import tree_path_sum def test_tree_path_sum_simple(): serialized = "1 2 # # 3 4 # # 5 # #" assert tree_path_sum(serialized) == 281 def test_tree_path_sum_single_node(): serialized = "1 # #" assert tree_path_sum(serialized) == 1 def test_tree_path_sum_left_skewed(): serialized = "1 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 TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef de...
trial_gpt4o_0
{ "original_instruction": "Binary Tree Path Sum Calculator\n\n**Context**:\nYou have a binary tree and need to work with its structure by serializing it to a string and deserializing it back to a tree form. After reconstructing the tree, you need to implement a function that calculates the sum of all root-to-leaf pat...
0.524051
Data_Structure_597
C
[ "deserialize", "tree_path_sum" ]
2
[ [ "tree_path_sum", "deserialize" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
351de2b652618d67c407a28d3659cb755ca926d1
3ad8cfc0c4c418522945cae8056668c8e6d99194
v1.0
complete
Data_Structure
Data_Structure_199_C
from typing import List def construct(freq: List[int]) -> List[int]: """ Initializes a Fenwick Tree (Binary Indexed Tree) based on input frequency array. Parameters: freq (List[int]): The input list of integers representing the frequency array. Returns: List[int]: The BIT (Fenwick Tre...
from typing import List def construct(freq: List[int]) -> List[int]: """ Initializes a Fenwick Tree (Binary Indexed Tree) based on input frequency array. Parameters: freq (List[int]): The input list of integers representing the frequency array. Returns: List[int]: The BIT (Fenwick Tre...
from solution import construct, get_sum, update_bit def test_construct_and_get_sum(): freq = [1, 2, 3, 4, 5] bit_tree = construct(freq) assert get_sum(bit_tree, 0) == 1 # sum of first element assert get_sum(bit_tree, 1) == 3 # sum of first two elements assert get_sum(bit_tree, 2) == 6 # sum of f...
[ { "docstring": "Initializes a Fenwick Tree (Binary Indexed Tree) based on input frequency array.\n\nParameters:\nfreq (List[int]): The input list of integers representing the frequency array.\n\nReturns:\nList[int]: The BIT (Fenwick Tree) represented as a list.", "function_declaration": "def construct(freq)...
[ 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 construct(freq: List[int]) -> List[int]:\n \"\"\"\n Constructs a Fenwick Tree (Binary Indexed Tree) from the given freque...
trial_gpt4o_2
{ "original_instruction": "### Fenwick Tree / Binary Indexed Tree Implementation\n\n#### Problem Statement\n\nYou are required to implement a Fenwick Tree (Binary Indexed Tree) for an integer array to efficiently perform the following operations:\n1. Compute prefix sum up to a given index.\n2. Update an element in th...
0.540047
Data_Structure_199
C
[ "construct", "get_sum", "update_bit" ]
3
[ [ "construct", "update_bit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd853b5c3b017da3b014916685a77f98c7953557
d31f0488fe878ebc1ea15de9cc62004a40ce1060
v1.0
complete
Data_Structure
Data_Structure_117_C
import random def weather_simulation(chain: dict, start_state: str, steps: int) -> list: """ Simulates the weather based on a Markov Chain model. Parameters: - chain (dict): Dictionary representing the transition probabilities. - start_state (str): Initial weather condition. - steps (int): Num...
import random def __choose_state(state_map): choice = random.random() probability_reached = 0 for state, probability in state_map.items(): probability_reached += probability if probability_reached > choice: return state return None def next_state(chain, current_state): ...
from solution import weather_simulation def test_weather_simulation_single_step(): chain = { 'Sunny': {'Sunny': 0.7, 'Rainy': 0.2, 'Cloudy': 0.1}, 'Rainy': {'Sunny': 0.3, 'Rainy': 0.4, 'Cloudy': 0.3}, 'Cloudy': {'Sunny': 0.4, 'Rainy': 0.4, 'Cloudy': 0.2} } start_state = 'Sunny' ...
[ { "docstring": null, "function_declaration": "def __choose_state(state_map):", "function_name": "__choose_state", "parameter_list": "(state_map)" }, { "docstring": null, "function_declaration": "def next_state(chain, current_state):", "function_name": "next_state", "parameter_lis...
[ 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 __choose_state(state_map):\n choice = random.random()\n probability_reached = 0\n for state, probability in state_map.items():\n...
trial_gpt4o_0
{ "original_instruction": "### Markov Chain Simulator\n\n**Scenario**:\nYou have been hired to build a simulation tool for weather prediction based on a Markov Chain model. The states in this model represent different weather conditions (e.g., Sunny, Rainy, Cloudy), with predefined transition probabilities for moving...
0.533933
Data_Structure_117
C
[ "__choose_state", "next_state", "weather_simulation" ]
3
[ [ "next_state", "__choose_state" ], [ "weather_simulation", "next_state" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d60b6e6ae15e9ec489d9333abaf9a9519d550aca
015c725bb71c5614a6919085f5771b59a033b38f
v1.0
complete
Data_Structure
Data_Structure_485_C
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def construct_tree_from_pre_post(pre, post): """ Construct tree from preorder and postorder traversals. """ # Implementation here def inorder_traversal(root): """ Return inorder traversal of ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def construct_tree_from_pre_post(pre, post): if not pre or not post: return None root = TreeNode(pre[0]) if len(pre) == 1: return root left_root_val = pre[1] L = post.i...
from solution import construct_tree def test_construct_tree_example(): pre = [1, 2, 4, 8, 9, 5, 3, 6, 7] post = [8, 9, 4, 5, 2, 6, 7, 3, 1] assert construct_tree(pre, post) == [8, 4, 9, 2, 5, 1, 6, 3, 7] def test_construct_tree_single_node(): pre = [1] post = [1] assert construct_tree(pre, pos...
[]
[ 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 TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n sel...
trial_gpt4o_2
{ "original_instruction": "Given the preorder and postorder traversal arrays of a full binary tree, write a Python function `construct_tree(pre, post)` that reconstructs the binary tree and returns its inorder traversal as a list.\n\n### Input\n- `pre`: A list of integers representing the preorder traversal of a full...
0.551115
Data_Structure_485
C
[ "construct_tree_from_pre_post", "inorder_traversal", "construct_tree" ]
3
[ [ "construct_tree", "construct_tree_from_pre_post" ], [ "construct_tree", "inorder_traversal" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
e4a3db83f7bc66f6cbdc6758aa4b722176dc0d32
e8e8a82baa81fb269f3b1a059c3a87d35e2db6a8
v1.0
complete
Data_Structure
Data_Structure_690_C
import random def custom_quick_sort(arr, pivot_strategy='last'): """ Sorts the array using Quick Sort with a custom pivot selection strategy. Parameters: arr (list of int): The array to be sorted. pivot_strategy (str): The pivot selection strategy. It can be 'first', ...
import random def custom_quick_sort(arr, pivot_strategy='last'): """ Sorts the array using Quick Sort with a custom pivot selection strategy. Parameters: arr (list of int): The array to be sorted. pivot_strategy (str): The pivot selection strategy. It can be 'first', ...
from solution import custom_quick_sort def test_quick_sort_empty_array(): assert custom_quick_sort([], 'first') == [] assert custom_quick_sort([], 'last') == [] assert custom_quick_sort([], 'median') == [] assert custom_quick_sort([], 'random') == [] def test_quick_sort_single_element(): assert cu...
[ { "docstring": "Sorts the array using Quick Sort with a custom pivot selection strategy.\n\nParameters:\narr (list of int): The array to be sorted.\npivot_strategy (str): The pivot selection strategy.\n It can be 'first', 'last', 'median', or 'random'.\nReturns:\nlist of int: The sorted arr...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def custom_quick_sort(arr, pivot_strategy='last'):\n import random\n \n def partition(arr, low, high):\n if pivot_strategy == 'first':\n ...
trial_gpt4o_1
{ "original_instruction": "### Quick Sort Implementation with Custom Pivot Selection\n\n#### Context\nQuick Sort is a popular and efficient sorting algorithm. However, its performance relies heavily on the choice of the pivot element. The provided implementation always selects the last element as the pivot, which can...
0.596024
Data_Structure_690
C
[ "custom_quick_sort", "select_pivot" ]
2
[ [ "custom_quick_sort", "select_pivot" ] ]
1
[]
false
[]
false
pytest
true
[]
true
853ceaeb409c069e90fe870b2c4008955c8a47e3
7cdd0d0581ee63997c802d655c43c4ed4edba62e
v1.0
complete
Data_Structure
Data_Structure_651_C
class Node: def __init__(self, value=None): self.value = value self.next = None def intersection(head1: Node, head2: Node) -> Node: """ Determines the node at which the intersection of two singly linked lists begins. If the linked lists do not intersect, return None. >>> h1 = ...
class Node: def __init__(self, value=None): self.value = value self.next = None def get_length(head: Node) -> int: length = 0 current = head while current: length += 1 current = current.next return length def intersection(head1: Node, head2: Node) -> Node: if no...
from solution import Node, intersection def test_no_intersection(): h1 = Node(1) h1.next = Node(2) h1.next.next = Node(3) h2 = Node(4) h2.next = Node(5) h2.next.next = Node(6) assert intersection(h1, h2) is None def test_intersection(): h1 = Node(1) h1.next = Node(2) h1.next....
[]
[ 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 Node:\n def __init__(self, value=None):\n self.value = value\n self.next = None\n\ndef get_length(head: Node) -> int:\n length = 0\n...
trial_gpt4o_0
{ "original_instruction": "You are given two singly linked lists that may or may not intersect at some node. Your task is to implement a function that determines the node at which the intersection of two linked lists begins.\n\n**Function Signature**\n```python\ndef intersection(head1: Node, head2: Node) -> Node:\n ...
0.523956
Data_Structure_651
C
[ "get_length", "intersection" ]
2
[ [ "intersection", "get_length" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
79c45760e967e6a845f868ae71bd4cd685266edf
d11cb9e1c0d4fd0d77e3f7065ea28109bf712939
v1.0
complete
Data_Structure
Data_Structure_772_C
def flip(arr: list[int], k: int) -> list[int]: """ Helper function to reverse the first k elements of array arr. >>> flip([3, 2, 4, 1], 3) [4, 2, 3, 1] """ def find_max_index(arr: list[int], n: int) -> int: """ Helper function to find the index of the maximum element in arr upto index n. >>...
def flip(arr, k): """Helper function to reverse the first k elements of array arr.""" return arr[:k][::-1] + arr[k:] def find_max_index(arr, n): """Helper function to find the index of the maximum element in arr upto index n.""" return max(range(n), key=arr.__getitem__) def limited_pancake_sort(arr, m...
def test_flip(): assert flip([3, 2, 4, 1], 3) == [4, 2, 3, 1] def test_select_max(): assert find_max_index([1, 5, 4, 3, 2], 5) == 1 def test_limited_pancake_sort(): # Case where max_flips is enough to fully sort the array assert limited_pancake_sort([3, 2, 4, 1], max_flips=10) == [1, 2, 3, 4] ...
[ { "docstring": "Helper function to reverse the first k elements of array arr.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Helper function to find the index of the maximum element in arr upto index n.", "function_...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def flip(arr, k):\n \"\"\"Helper function to perform flip up to index k (inclusive)\"\"\"\n return arr[:k+1][::-1] + arr[k+1:]\n\ndef limited_pancake_so...
trial_gpt4o_3
{ "original_instruction": "### Pancake Sort with Enhanced Constraints\n\nImagine that you are a chef who loves sorting tasks as much as cooking delectable dishes. However, your sorting spatula (used to flip pancakes) is fragile and you can only use it a limited number of times. This introduces an additional constrain...
0.652783
Data_Structure_772
C
[ "flip", "find_max_index", "limited_pancake_sort" ]
3
[ [ "limited_pancake_sort", "find_max_index" ], [ "limited_pancake_sort", "flip" ] ]
2
[]
false
[]
false
pytest
false
[]
true
621a720c55e7ce86a8fb0083102de570f830d0e1
cd5a99333d80fbedb848ba38712c5e0df26186f0
v1.0
complete
Data_Structure
Data_Structure_346_C
from typing import Tuple import math def enhanced_gcd(a: int, b: int) -> int: """Calculate the greatest common divisor (GCD) of two non-negative integers a and b. Args: a (int): First non-negative integer. b (int): Second non-negative integer. Returns: int: GCD of a and b. >>> e...
import math def enhanced_gcd(a: int, b: int) -> int: """ Calculate the greatest common divisor (GCD) of two non-negative integers a and b. """ if a == 0: return b if b == 0: return a return math.gcd(a, b) def enhanced_lcm(a: int, b: int) -> int: """ Calculate the least ...
from solution import enhanced_gcd, enhanced_lcm def test_gcd_with_zeros(): assert enhanced_gcd(0, 0) == 0 assert enhanced_gcd(10, 0) == 10 assert enhanced_gcd(0, 10) == 10 def test_lcm_with_zeros(): assert enhanced_lcm(0, 0) == 0 assert enhanced_lcm(10, 0) == 0 assert enhanced_lcm(0, 10) == 0 ...
[ { "docstring": "Calculate the greatest common divisor (GCD) of two non-negative integers a and b.", "function_declaration": "def enhanced_gcd(a, b):", "function_name": "enhanced_gcd", "parameter_list": "(a, b)" }, { "docstring": "Calculate the least common multiple (LCM) of two non-negative ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def enhanced_gcd(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two non-negative integers.\n Uses the Euclidean al...
trial_gpt4o_2
{ "original_instruction": "### Coding Challenge: Enhanced GCD and LCM with Edge Case Handling\n\n#### Objective\nWrite a Python function to calculate both the GCD and the LCM of two non-negative integers with enhanced edge case handling and optimized performance.\n\n#### Problem Statement\nGiven two non-negative inte...
0.721706
Data_Structure_346
C
[ "enhanced_gcd", "enhanced_lcm" ]
2
[ [ "enhanced_lcm", "enhanced_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4679289f9b1733027164698ae5f8d798db01114d
cb8d228a0e99a83e59d05eb475e9cc8230706287
v1.0
complete
Data_Structure
Data_Structure_1180_C
def magic_number(n: int) -> bool: """ Determine whether a given number is a magic number. A magic number is defined as a number that, when summing its digits repeatedly, eventually reduces to the number 1. >>> magic_number(50113) True >>> magic_number(1234) True >>> magic_number...
def sum_of_digits(n): """ Helper function to calculate the sum of the digits of n. """ total = 0 while n > 0: total += n % 10 n //= 10 return total def magic_number(n): """ Determine whether a given number is a magic number. A magic number is defined as a number that...
from solution import magic_number def test_example_cases(): assert magic_number(50113) == True # 5+0+1+1+3=10 -> 1+0=1 assert magic_number(1234) == True # 1+2+3+4=10 -> 1+0=1 assert magic_number(199) == True # 1+9+9=19 -> 1+9=10 -> 1+0=1 assert magic_number(111) == False # 1+1+1=3 assert ma...
[ { "docstring": "Helper function to calculate the sum of the digits of n.", "function_declaration": "def sum_of_digits(n):", "function_name": "sum_of_digits", "parameter_list": "(n)" }, { "docstring": "Determine whether a given number is a magic number.\nA magic number is defined as a number ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def magic_number(n):\n \"\"\"\n Determines if a given number is a magic number, which repeatedly sums its digits to eventually become 1.\n \n Para...
trial_gpt4o_8
{ "original_instruction": "Magic Number Check\n\n**Context**: In mystical number theory, some numbers are considered special or \"magic\" based on specific properties. One such property is when the sum of a number's digits repeatedly reduces to 1.\n\n**Objective**: Write a function to determine whether a given number...
0.625156
Data_Structure_1180
C
[ "sum_of_digits", "magic_number" ]
2
[ [ "magic_number", "sum_of_digits" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd9285381e43ecf6982c1c6817e4b507d4b00187
0964365c7bc804e979354ed12b74b94b4fd19d26
v1.0
complete
Data_Structure
Data_Structure_1043_C
from typing import List def search_insert(arr: List[int], value: int) -> int: left, right = 0, len(arr) while left < right: mid = (left + right) // 2 if arr[mid] < value: left = mid + 1 else: right = mid return left def binary_insertion_sort(arr: List[int]) ...
from typing import List def search_insert(arr: List[int], value: int) -> int: left, right = 0, len(arr) while left < right: mid = (left + right) // 2 if arr[mid] < value: left = mid + 1 else: right = mid return left def binary_insertion_sort(arr: List[int]) ...
import pytest from solution import binary_insertion_sort def test_empty_list(): assert binary_insertion_sort([]) == [] def test_single_element(): assert binary_insertion_sort([1]) == [1] def test_sorted_list(): assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list...
[ { "docstring": null, "function_declaration": "def search_insert(arr, value):", "function_name": "search_insert", "parameter_list": "(arr, value)" }, { "docstring": null, "function_declaration": "def binary_insertion_sort(arr):", "function_name": "binary_insertion_sort", "paramete...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef search_insert(arr: List[int], left: int, right: int, target: int) -> int:\n \"\"\"\n Use binary search to find the index ...
trial_gpt4o_2
{ "original_instruction": "### Question: Insertion Sort with Binary Search\n\nTo assess your understanding of the insertion sort algorithm and binary search, your task is to implement the insertion sort algorithm with a twist. Use the `search_insert` helper method provided to find the correct position for each elemen...
0.668742
Data_Structure_1043
C
[ "search_insert", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a71c8be83c667cf5cf8487bc44b302a756cc8298
5051ffcbfc24dccf62687368bd4193cad5f54170
v1.0
complete
Data_Structure
Data_Structure_407_C
from typing import List def maximum_flow(capacity: List[List[int]], source: int, sink: int) -> int: """ Compute the maximum flow from the source to the sink using the Edmonds-Karp algorithm. Args: capacity: A 2D list representing the capacity matrix of the graph. source: An integer representin...
from collections import deque from typing import List def bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: visited = [False] * len(capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for v in range(len(capacity)): ...
from solution import maximum_flow def test_maximum_flow_example(): capacity = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert maximum_flow(capa...
[ { "docstring": null, "function_declaration": "def bfs(capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def maximum_flow(capacity, source, sink):", "function_name": "maximum...
[ 0, 0, 0, 1, 1, 0, 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": "from collections import deque\nfrom typing import List\n\ndef bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"\"\"\n...
trial_gpt4o_7
{ "original_instruction": "You are given a flow network represented by a capacity matrix, a source vertex, and a sink vertex. Your task is to implement a function to compute the maximum flow from the source to the sink using the **Edmonds-Karp** algorithm, which is an implementation of the Ford-Fulkerson method using...
0.581087
Data_Structure_407
C
[ "bfs", "maximum_flow" ]
2
[ [ "maximum_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
06b21d62eda73a9563a60d8d2156395b749e0578
ad7decf67751b418ee2f8f8b85321b3c2412754e
v1.0
complete
Data_Structure
Data_Structure_1188_C
import math def cosine_similarity_matrix(matrix1: list[list[float]], matrix2: list[list[float]]) -> list[list[float]]: """ Compute the cosine similarity matrix between two matrices. Parameters: - matrix1: A list of lists, where each inner list represents a vector. - matrix2: A list of lists, where eac...
import math def cosine_similarity(v1, v2): """ Helper function to calculate cosine similarity between two vectors. """ sumxx, sumxy, sumyy = 0, 0, 0 for i in range(len(v1)): x = v1[i] y = v2[i] sumxx += x * x sumyy += y * y sumxy += x * y if sumxx == 0 or...
from solution import cosine_similarity_matrix def test_cosine_similarity_basic(): matrix1 = [ [1, 1, 1], [2, 2, 2] ] matrix2 = [ [1, 2, -1], [3, 0, 0] ] expected_output = [ [0.47140452079103173, 0.5773502691896257], [0.47140452079103173, 0.57735026918...
[ { "docstring": "Helper function to calculate cosine similarity between two vectors.", "function_declaration": "def cosine_similarity(v1, v2):", "function_name": "cosine_similarity", "parameter_list": "(v1, v2)" }, { "docstring": "Compute the cosine similarity matrix between two matrices.\n\n...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef cosine_similarity(v1, v2):\n \"\"\"\n Helper function to calculate cosine similarity between two vectors.\n \"\"\"\n sumxx, sum...
trial_gpt4o_0
{ "original_instruction": "Cosine Similarity Enhancement\n\nSuppose you are working on a recommendation system and need to adjust the existing implementation for cosine similarity to handle more complex scenarios efficiently. You are provided the initial implementation of the cosine similarity calculation and are req...
0.589798
Data_Structure_1188
C
[ "cosine_similarity", "cosine_similarity_matrix" ]
2
[ [ "cosine_similarity_matrix", "cosine_similarity" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dbfa16ff54a16fa95e52c92d7db1405c13844504
e646c352729fbfdd989f606338097d9151f8ef14
v1.0
complete
Data_Structure
Data_Structure_1234_C
from typing import List def matrix_power(mat: List[List[int]], n: int) -> List[List[int]]: """Computes the n-th power of the matrix using the strategy of repeated squaring. >>> mat = [ >>> [2, 3], >>> [4, 5] >>> ] >>> matrix_power(mat, 0) [[1, 0], [0, 1]] >>> matrix_power(mat,...
from typing import List def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: d = len(A) result = [[0] * d for _ in range(d)] for i in range(d): for j in range(d): for k in range(d): result[i][j] += A[i][k] * B[k][j] return result def ident...
from solution import matrix_power def test_matrix_power_exponent_0(): mat = [ [2, 3], [4, 5] ] result = matrix_power(mat, 0) expected = [ [1, 0], [0, 1] ] assert result == expected def test_matrix_power_exponent_1(): mat = [ [2, 3], [4, 5] ...
[ { "docstring": null, "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def identity_matrix(size):", "function_name": "identity_matrix", "parameter_list": "(size)" ...
[ 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 matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two matrices A and B.\n...
trial_gpt4o_1
{ "original_instruction": "### Problem Description\n\nYou are given a square matrix `mat` of dimension `d` and an integer `n`. Write a function `matrix_power(mat: List[List[int]], n: int) -> List[List[int]]` that computes the `n`-th power of the matrix using the strategy of repeated squaring. The function should use ...
0.537513
Data_Structure_1234
C
[ "matrix_multiply", "identity_matrix", "matrix_power" ]
3
[ [ "matrix_power", "identity_matrix" ], [ "matrix_power", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bda7054a6377a05f567989de1cd1f7cbbe5711b9
d1552a4e5618c649bee98f142a140e701cb091f7
v1.0
complete
Data_Structure
Data_Structure_1113_C
from typing import List def ford_fulkerson(custom_capacity: List[List[int]], custom_source: int, custom_sink: int) -> int: """ Design an algorithm to determine the maximum flow from a specified source to a sink in a given flow network using the Ford-Fulkerson method. >>> custom_capacity = [ ... [0, 16,...
from collections import deque from typing import List def bfs(residual_capacity, source, sink, parent): visited = [False] * len(residual_capacity) queue = deque([source]) visited[source] = True while queue: u = queue.popleft() for ind, val in enumerate(residual_capacity[u]): ...
from solution import ford_fulkerson def test_small_graph(): custom_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] ] custom_source = 0 custom_sink = 5 assert for...
[ { "docstring": null, "function_declaration": "def bfs(residual_capacity, source, sink, parent):", "function_name": "bfs", "parameter_list": "(residual_capacity, source, sink, parent)" }, { "docstring": null, "function_declaration": "def ford_fulkerson(custom_capacity, custom_source, cust...
[ 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 collections import deque\n\ndef bfs(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n ...
trial_gpt4o_1
{ "original_instruction": "**Question**: Design an algorithm to determine the maximum flow from a specified source to a sink in a given flow network. Implement the algorithm using the Ford-Fulkerson method. The function signature should be:\n\n```python\ndef ford_fulkerson(custom_capacity: List[List[int]], custom_sou...
0.557504
Data_Structure_1113
C
[ "bfs", "ford_fulkerson" ]
2
[ [ "ford_fulkerson", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb5aa718c224d20aa9e92d677ca5e961b4dc5824
8a05d89bbcfd77e4e469533bc69e466e5c932924
v1.0
complete
Data_Structure
Data_Structure_1125_C
def secure_key_exchange(prime: int, root: int, print_steps: bool = False) -> bool: """ Simulates the Diffie-Hellman key exchange and returns True if both Alice and Bob derive the same shared secret key; otherwise, False. :param prime: A large prime number `p` :param root: A primitive root of the pr...
import random def is_prime(n): """Check if n is a prime number""" if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5)+1, 2): if n % i == 0: return False return True def find_primitive_root(p): ...
from solution import secure_key_exchange def test_secure_key_exchange_matching_keys(): assert secure_key_exchange(23, 5, print_steps=True) == True def test_secure_key_exchange_invalid_prime(): try: secure_key_exchange(24, 5, print_steps=False) except ValueError as e: assert str(e) == "The ...
[ { "docstring": "Check if n is a prime number", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find a primitive root for prime p", "function_declaration": "def find_primitive_root(p):", "function_name": "find_primiti...
[ 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_prime(n):\n \"\"\"Check if n is a prime number\"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n ...
trial_gpt4o_0
{ "original_instruction": "You are implementing a secure communication channel using the Diffie-Hellman Key Exchange method. You must write a function that simulates the key exchange process and verifies if both parties derive the same shared secret key. \n\n#### Function Signature\n```python\ndef secure_key_exchange...
0.514379
Data_Structure_1125
C
[ "is_prime", "find_primitive_root", "gcd", "secure_key_exchange" ]
4
[ [ "find_primitive_root", "gcd" ], [ "find_primitive_root", "is_prime" ], [ "secure_key_exchange", "find_primitive_root" ], [ "secure_key_exchange", "is_prime" ] ]
4
[]
false
[]
false
pytest
true
[]
true
63dccacc4e1ea8fd16d7772df4a36362a0538186
00ac0f277b0a5c8e20ddacc64e8445691249ddad
v1.0
complete
Data_Structure
Data_Structure_1363_C
def gcd(x, y): while y: x, y = y, x % y return x def find_order_with_print_steps(a: int, n: int) -> int: """ Finds the order of a modulo n and prints each step. Parameters: a (int): The base number. n (int): The modulus. Returns: int: The smallest positive integer ...
def gcd(x, y): while y: x, y = y, x % y return x def find_order_with_print_steps(a, n): """ Finds the order of a modulo n and prints each step. Parameters: a (int): The base number. n (int): The modulus. Returns: int: The smallest positive integer k such that a^k ≡...
from solution import find_order_with_print_steps def test_find_order_with_print_steps_basic(): assert find_order_with_print_steps(2, 5) == 4 # Should print out steps and return 4 assert find_order_with_print_steps(3, 11) == 5 # Should print out steps and return 5 def test_find_order_with_print_steps_error()...
[ { "docstring": null, "function_declaration": "def gcd(x, y):", "function_name": "gcd", "parameter_list": "(x, y)" }, { "docstring": "Finds the order of a modulo n and prints each step.\n\nParameters:\na (int): The base number.\nn (int): The modulus.\n\nReturns:\nint: The smallest positive in...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef find_order_with_print_steps(a: int, n: int) -> int:\n \"\"\"\n Finds the order of a positive integer a modulo n.\n \n Parameter...
trial_gpt4o_3
{ "original_instruction": "### Question:\n\nWrite a function `find_order_with_print_steps(a, n)` that finds the order of a positive integer a modulo n as follows:\n\n1. The function takes in two positive integers `a` and `n`.\n2. The function should return the smallest positive integer k such that \\(a^k ≡ 1 \\mod n\...
0.697368
Data_Structure_1363
C
[ "gcd", "find_order_with_print_steps" ]
2
[ [ "find_order_with_print_steps", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b1a8021ece19438ba9d1f24560a8550bf0b5cb57
c8fa7046e0061926dbcb3523bcc2202fbea60cb7
v1.0
complete
Data_Structure
Data_Structure_1079_C
from typing import List, Dict def compose_traversal_route(graph: Dict[int, List[int]], start: int, method: str) -> List[int]: """ Perform graph traversal starting from a specified node using the selected method ('dfs', 'bfs') and return the ordered list of nodes as they are visited. >>> compose_trave...
from typing import List, Dict def compose_traversal_route(graph: Dict[int, List[int]], start: int, method: str) -> List[int]: if method == 'dfs': return dfs_traversal(graph, start) elif method == 'bfs': return bfs_traversal(graph, start) else: raise ValueError("Method should be eith...
from solution import compose_traversal_route def test_dfs_simple(): graph = { 1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: [] } assert compose_traversal_route(graph, 1, 'dfs') == [1, 2, 4, 5, 3] def test_bfs_simple(): graph = { 1: [2, 3], 2: [4, 5], ...
[ { "docstring": null, "function_declaration": "def compose_traversal_route(graph, start, method):", "function_name": "compose_traversal_route", "parameter_list": "(graph, start, method)" }, { "docstring": null, "function_declaration": "def dfs_traversal(graph, start):", "function_name...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom typing import Dict, List\n\ndef compose_traversal_route(graph: Dict[int, List[int]], start: int, method: str) -> List[int]...
trial_gpt4o_2
{ "original_instruction": "You are given a graph represented as an adjacency list where each node has a list of its neighbors. Implement a function `compose_traversal_route(graph, start, method)` which performs graph traversal starting from a specified node using the selected method (`'dfs'`, `'bfs'`) and returns the...
0.49897
Data_Structure_1079
C
[ "compose_traversal_route", "dfs_traversal", "bfs_traversal" ]
3
[ [ "compose_traversal_route", "bfs_traversal" ], [ "compose_traversal_route", "dfs_traversal" ] ]
2
[]
false
[]
false
pytest
true
[]
true
866b8d1d995cf2b991139e5f9f88205b099f973f
350c3662e2c374de49ef053fae59eb18ff56e5cb
v1.0
complete
Data_Structure
Data_Structure_819_C
def generate_key(k, seed=None): """ Generate RSA key components. >>> n, e, d = generate_key(16, seed=42) >>> n > 0, e > 0, d > 0 (True, True, True) """ pass def encrypt(data, e, n): """ Encrypt data using RSA encryption. >>> n, e, d = generate_key(16, seed=42) >>> data = 20 >>> ...
import random from sympy import isprime, mod_inverse, nextprime def generate_key(k, seed=None): if seed is not None: random.seed(seed) # Generate two distinct prime numbers p and q p = nextprime(random.getrandbits(k // 2)) q = nextprime(random.getrandbits(k // 2)) while p == q: ...
from solution import generate_key, encrypt, decrypt def test_generate_key(): n, e, d = generate_key(16, seed=42) assert n > 0 assert e > 0 assert d > 0 def test_encrypt_decrypt(): n, e, d = generate_key(16, seed=42) data = 20 encrypted = encrypt(data, e, n) decrypted = decrypt(encrypte...
[ { "docstring": null, "function_declaration": "def generate_key(k, seed=None):", "function_name": "generate_key", "parameter_list": "(k, seed=None)" }, { "docstring": null, "function_declaration": "def encrypt(data, e, n):", "function_name": "encrypt", "parameter_list": "(data, e,...
[ 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_large_prime(bits):\n \"\"\"\n Generates a large prime number with the specified nu...
trial_gpt4o_2
{ "original_instruction": "You are tasked to implement a simplified version of the RSA encryption algorithm. Only key generation and encryption/decryption functionalities are needed. Specifically, you will write functions: `generate_key()`, `encrypt()`, and `decrypt()`.\n\n### Function Descriptions\n\n1. **generate_k...
0.687852
Data_Structure_819
C
[ "generate_key", "encrypt", "decrypt", "gcd" ]
4
[ [ "generate_key", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
f7ecb270d03d15aaf9420cf9922da750b6d7f34a
57511ec95e5f4c6516271238e203204cd4bbbaf5
v1.0
complete
Data_Structure
Data_Structure_1430_C
def pancake_sort(arr: List[int]) -> List[int]: """ Pancake sorting is a technique of sorting a sequence using only the prefix reversal operation. Write a function `pancake_sort` that sorts a given list of integers using the pancake sorting algorithm. Args: arr (List[int]): A list of integers, which can...
def flip(arr, k): """ Helper function to reverse the first k elements of the array. """ arr[:k] = arr[:k][::-1] def pancake_sort(arr): """ Pancake sorting function to sort the input list using pancake sorting algorithm. """ n = len(arr) for size in range(n, 1, -1): # Find th...
from solution import pancake_sort def test_pancake_sort_example_cases(): assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4] assert pancake_sort([5, 1, 2]) == [1, 2, 5] assert pancake_sort([1]) == [1] assert pancake_sort([]) == [] def test_pancake_sort_already_sorted(): assert pancake_sort([1, 2, 3,...
[ { "docstring": "Helper function to reverse the first k elements of the array.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Pancake sorting function to sort the input list using pancake sorting algorithm.", "functi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def flip(arr, k):\n \"\"\"\n Reverses the order of the first k elements of the list arr.\n \"\"\"\n arr[:k] = arr[:k][::-1]\n\ndef pancake_sort(ar...
trial_gpt4o_2
{ "original_instruction": "Pancake Sort Implementation\n\n**Context**: \nPancake sorting is a technique of sorting a sequence using only the prefix reversal operation, similar to flipping pancakes in a pan. Although it is not the most efficient sorting method by modern standards, it is a fascinating problem to unders...
0.800933
Data_Structure_1430
C
[ "flip", "pancake_sort" ]
2
[ [ "pancake_sort", "flip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5bf9131abe9d1a0e2b50ae32a2db0e9ce4e58305
8140b07f47b908dc8c738ba4d371e2475c6ac092
v1.0
complete
Data_Structure
Data_Structure_1078_C
from typing import List, Union def invert_matrix(matrix: List[List[Union[int, float]]]) -> List[List[float]]: """ Returns the inverse of the input n x n matrix if it is invertible. If the matrix is not square, returns [[-2]]. If the matrix is too small to invert (less than 2x2), returns [[-3]]. If...
from typing import List, Union def get_determinant(matrix: List[List[Union[int, float]]]) -> Union[float, int]: """Helper function to calculate the determinant of a matrix.""" n = len(matrix) if n == 1: return matrix[0][0] if n == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matri...
from solution import invert_matrix def test_square_invertible_matrix_2x2(): assert invert_matrix([[1, 2], [3, 4]]) == [[-2.0, 1.0], [1.5, -0.5]] def test_square_invertible_matrix_3x3(): assert invert_matrix([[3, 0, 2], [2, 0, -2], [0, 1, 1]]) == [ [0.2, 0.2, 0.0], [-0.2, 0.3, 1.0], [0....
[ { "docstring": "Helper function to calculate the determinant of a matrix.", "function_declaration": "def get_determinant(matrix):", "function_name": "get_determinant", "parameter_list": "(matrix)" }, { "docstring": "Helper function to get the minor matrix after removing the i-th row and j-th...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Union\n\ndef get_determinant(matrix: List[List[Union[int, float]]]) -> Union[float, int]:\n # Base case for 2x2 matrix:\n if le...
trial_gpt4o_5
{ "original_instruction": "**Context**:\nSuppose you are a software engineer developing a system that requires matrix operations to solve linear equations. Your task is to write a function that can efficiently compute the inverse of a given \\(n \\times n\\) matrix if it is invertible.\n\n### Problem Statement:\nYou ...
0.540013
Data_Structure_1078
C
[ "get_determinant", "get_matrix_minor", "get_matrix_of_minors", "transpose_matrix", "invert_matrix" ]
5
[ [ "get_determinant", "get_matrix_minor" ], [ "get_matrix_of_minors", "get_determinant" ], [ "get_matrix_of_minors", "get_matrix_minor" ], [ "invert_matrix", "get_determinant" ], [ "invert_matrix", "get_matrix_of_minors" ], [ "invert_matrix", "trans...
6
[]
false
[]
false
pytest
true
[]
true
0443cc71192c2b901e695c1485f105a5d4114c3b
ffa84d4d3d28749793d2237f1ac11aa6029cb693
v1.0
complete
Data_Structure
Data_Structure_1094_C
def bitonic_sort_general(arr): """ Sort an array of integers using the bitonic sort algorithm, adapted to handle arrays of arbitrary sizes by padding with sentinel values where necessary. >>> bitonic_sort_general([5, 3, 1, 2, 6, 4, 7]) [1, 2, 3, 4, 5, 6, 7] >>> bitonic_sort_general([10]) ...
import math def bitonic_sort_up(arr, start, length): if length > 1: k = length // 2 for i in range(start, start + k): if arr[i] > arr[i + k]: arr[i], arr[i + k] = arr[i + k], arr[i] bitonic_sort_up(arr, start, k) bitonic_sort_up(arr, start + k, k) def bi...
from solution import bitonic_sort_general def test_bitonic_sort_general_basic(): assert bitonic_sort_general([5, 3, 1, 2, 6, 4, 7]) == [1, 2, 3, 4, 5, 6, 7] assert bitonic_sort_general([10]) == [10] assert bitonic_sort_general([]) == [] assert bitonic_sort_general([9, 13, 3, 7]) == [3, 7, 9, 13] def t...
[ { "docstring": null, "function_declaration": "def bitonic_sort_up(arr, start, length):", "function_name": "bitonic_sort_up", "parameter_list": "(arr, start, length)" }, { "docstring": null, "function_declaration": "def bitonic_sort_down(arr, start, length):", "function_name": "bitoni...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef bitonic_sort_up(arr, start, length):\n if length > 1:\n k = length // 2\n for i in range(start, start + k):\n i...
trial_gpt4o_0
{ "original_instruction": "### Bitonic Sort for Non-Power-of-2 Size Arrays\n\n#### Objective:\nYou are required to implement a variant of the Bitonic Sort algorithm that can handle arrays of arbitrary sizes, not just powers of 2.\n\n#### Problem Statement:\nGiven an array `arr` containing `n` integers, you need to so...
0.734837
Data_Structure_1094
C
[ "bitonic_sort_up", "bitonic_sort_down", "bitonic_merge", "bitonic_sort", "bitonic_sort_general" ]
5
[ [ "bitonic_sort", "bitonic_merge" ], [ "bitonic_sort_general", "bitonic_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3d455d7f4ca0a5506e22ebac4f7e6d293c6fb5d4
682127bc8c529b6e30c36d3e8e232972b2e75397
v1.0
complete
Data_Structure
Data_Structure_1044_C
from typing import List def find_all_primitive_roots(n: int) -> List[int]: """Returns a list of all primitive roots of a given integer n. The function uses Euler's Totient function and order finding methodology to determine all the primitive roots of n. Primitive roots are crucial in cryptographic al...
from typing import List import math def gcd(a, b): """ Helper function to return the greatest common divisor of a and b. """ while b: a, b = b, a % b return a def euler_totient(n): """ Euler's Totient function to calculate the number of integers up to n that are coprime with n. ...
from solution import find_all_primitive_roots def test_find_all_primitive_roots_10(): assert find_all_primitive_roots(10) == [] def test_find_all_primitive_roots_17(): assert sorted(find_all_primitive_roots(17)) == [3, 5, 6, 7, 10, 11, 12, 14] def test_find_all_primitive_roots_2(): assert find_all_primit...
[ { "docstring": "Helper function to return the greatest common divisor of a and b.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Euler's Totient function to calculate the number of integers up to n that are coprime with n.", ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n: int) -> int:\n resu...
trial_gpt4o_2
{ "original_instruction": "### Question: Finding Primitive Roots for a Cryptographic Application\n\nYour task is to implement a function that finds the primitive roots of a given integer n. The function should use Euler's Totient function and the order finding methodology to determine all the primitive roots of n. Th...
0.512119
Data_Structure_1044
C
[ "gcd", "euler_totient", "is_primitive_root", "find_all_primitive_roots" ]
4
[ [ "find_all_primitive_roots", "is_primitive_root" ], [ "is_primitive_root", "euler_totient" ], [ "is_primitive_root", "gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
e470466471f984449707b2eb9fda8b1d820ce676
2426b3bdd8d8fe8136583d6ee733d33234f71b9d
v1.0
complete
Data_Structure
Data_Structure_695_C
def search_insert(sorted_subarray, val): """ Binary search helper function to find the insertion index for the value `val` in the sorted portion of array `sorted_subarray`. Args: sorted_subarray (list): The portion of the array that is already sorted. val (int): The value to be inserted. ...
def search_insert(sorted_subarray, val): """ Binary search helper function to find the insertion index for the value `val` in the sorted portion of array `sorted_subarray`. Args: sorted_subarray (list): The portion of the array that is already sorted. val (int): The value to be inserted. ...
from solution import insertion_sort def test_insertion_sort_with_unordered_elements(): assert insertion_sort([4, 2, 7, 1, 3]) == [1, 2, 3, 4, 7] def test_insertion_sort_with_sorted_elements(): assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_insertion_sort_with_reverse_sorted_elements(): ...
[ { "docstring": "Binary search helper function to find the insertion index for the value `val` \nin the sorted portion of array `sorted_subarray`.\n\nArgs:\nsorted_subarray (list): The portion of the array that is already sorted.\nval (int): The value to be inserted.\n\nReturns:\nint: The index where `val` shoul...
[ 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 search_insert(sorted_array, value):\n \"\"\"\n Helper function to find the index where `value` should be inserted in `sorted_array`.\n Uses binar...
trial_gpt4o_1
{ "original_instruction": "**Problem Statement:**\nWrite a function, `insertion_sort`, that sorts an array of integers using the insertion sort algorithm. To handle the insertion efficiently, utilize a helper function `search_insert` that determines the appropriate index to insert each element.\n\n**Function Signatur...
0.658511
Data_Structure_695
C
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e7c42f3b475e40ce2e5da8ff015890925d4daa3a
ecc4f98895fb148ab4c3b619aa2883577e8676cf
v1.0
complete
Data_Structure
Data_Structure_866_C
from typing import List def optimized_quick_sort(arr: List[int]) -> List[int]: """Sort a list of integers using the optimized Quick Sort algorithm. This implementation uses the median-of-three method for pivot selection. Args: arr (List[int]): A list of integers to be sorted. ...
from typing import List def median_of_three(arr: List[int], low: int, high: int) -> int: mid = (low + high) // 2 if arr[low] > arr[mid]: arr[low], arr[mid] = arr[mid], arr[low] if arr[mid] > arr[high]: arr[mid], arr[high] = arr[high], arr[mid] if arr[low] > arr[mid]: arr[low], a...
from solution import optimized_quick_sort def test_optimized_quick_sort_random_numbers(): assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] def test_optimized_quick_sort_single_element(): assert optimized_quick_sort([1]) == [1] def test_optimized_quick_sort_empty_list(): asser...
[ { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef optimized_quick_sort(arr: List[int]) -> List[int]:\n def median_of_three(a, b, c):\n if a > b:\n if a < c:...
trial_gpt4o_2
{ "original_instruction": "### Context\nYou are tasked with implementing a sorting functionality for a large dataset in a high-performance application. You decide to use the Quick Sort algorithm due to its average-case efficiency and in-place nature. However, you need to ensure your implementation can handle large in...
0.626194
Data_Structure_866
C
[ "median_of_three", "partition", "quick_sort_recursive", "optimized_quick_sort" ]
4
[ [ "optimized_quick_sort", "quick_sort_recursive" ], [ "partition", "median_of_three" ], [ "quick_sort_recursive", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2c06ca48646ec4b548e1986ef44ce6d8e716a013
3e290e2168998f23ff38dfb308a91e0434d39ec5
v1.0
complete
Data_Structure
Data_Structure_1663_C
def prime_check(n: int) -> bool: """ Given an integer n, return True if n is a prime number, else return False. """ # Implement this function pass def kth_prime(k: int) -> int: """ Returns the k-th prime number. >>> kth_prime(1) 2 >>> kth_prime(5) 11 >>> kth_prime(10) 29 """...
def prime_check(n): """ Checks whether a number n is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 ...
from solution import kth_prime, prime_check def test_kth_prime_first(): assert kth_prime(1) == 2 def test_kth_prime_fifth(): assert kth_prime(5) == 11 def test_kth_prime_tenth(): assert kth_prime(10) == 29 def test_prime_check_positive(): assert prime_check(2) is True assert prime_check(3) is Tr...
[ { "docstring": "Checks whether a number n is prime.", "function_declaration": "def prime_check(n):", "function_name": "prime_check", "parameter_list": "(n)" }, { "docstring": "Returns the k-th prime number.", "function_declaration": "def kth_prime(k):", "function_name": "kth_prime", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef prime_check(n):\n \"\"\"Returns True if n is a prime number, False otherwise.\"\"\"\n if n <= 1:\n return False\n if n <= 3...
trial_gpt4o_2
{ "original_instruction": "### Prime Detection Assessment\n\nGiven the function `prime_check(n)`, design and implement a function `kth_prime(k)` that returns the `k`-th prime number. Implement this in a way that efficiently finds primes as needed, making use of the provided `prime_check(n)` function.\n\n#### Input\n*...
0.746376
Data_Structure_1663
C
[ "prime_check", "kth_prime" ]
2
[ [ "kth_prime", "prime_check" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9b650dbf0913ab221fdcb02266c2e20cd8c5e638
4de457ff3a7ffc2cc9f638a82b4ded52cc355ed3
v1.0
complete
Data_Structure
Data_Structure_1752_C
import math def gcd(a, b): while b: a, b = b, a % b return a def find_order(a: int, n: int) -> int: """ Suppose you are building a cryptographic module that requires computing the order of a number modulo `n`. The order of `a` modulo `n` is defined as the smallest positive integer `k` suc...
import math def gcd(a, b): while b: a, b = b, a % b return a def find_order(a: int, n: int) -> int: """ Find the order of `a` modulo `n`. Parameters: a (int): The base integer. n (int): The modulus. Returns: int: The order of `a` modulo `n`, or -1 if n...
from solution import find_order def test_find_order_example_cases(): assert find_order(3, 7) == 6 assert find_order(2, 4) == -1 assert find_order(10, 17) == 16 def test_find_order_non_coprime(): assert find_order(6, 12) == -1 def test_find_order_prime_modulus(): assert find_order(2, 11) == 10 ...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Find the order of `a` modulo `n`.\n\nParameters:\n a (int): The base integer.\n n (int): The modulus.\n\nReturns:\n int: The order of `a` modulo `n`, ...
[ 0, 0, 0, 1, 0, 0, 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 find_order(a: int, n: int) -> int:\n \"\"\"\n Computes the order of a modulo n.\n\n Args:\n a: An integer whose order modulo n ...
trial_gpt4o_4
{ "original_instruction": "Suppose you are building a cryptographic module that requires computing the order of a number modulo `n`. The order of `a` modulo `n` is defined as the smallest positive integer `k` such that `a^k ≡ 1 (mod n)`, provided `gcd(a, n) = 1`. If no such integer exists, return -1.\n\n### Task\n\nW...
0.636733
Data_Structure_1752
C
[ "gcd", "find_order" ]
2
[ [ "find_order", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d9f01d9101a46c063abc880974585be30c03f061
a852cb74646fcb591dd357f07a4b91a74bdf6fd8
v1.0
complete
Data_Structure
Data_Structure_2304_C
def kmp_search(haystack: str, needle: str) -> int: """ Returns the index of the first occurrence of `needle` in `haystack`, or -1 if `needle` is not part of `haystack`. >>> kmp_search("hello", "ll") == 2 >>> kmp_search("aaaaa", "bba") == -1 >>> kmp_search("", "") == 0 """
def computeLPS(pattern): """ Computes the Longest Prefix Suffix (LPS) array for the given pattern. """ M = len(pattern) lps = [0] * M length = 0 i = 1 while i < M: if pattern[i] == pattern[length]: length += 1 lps[i] = length i += 1 el...
from solution import kmp_search def test_kmp_search_found(): """Test case where the needle is found in the haystack.""" assert kmp_search("hello", "ll") == 2 def test_kmp_search_not_found(): """Test case where the needle is not found in the haystack.""" assert kmp_search("aaaaa", "bba") == -1 def tes...
[ { "docstring": "Computes the Longest Prefix Suffix (LPS) array for the given pattern.", "function_declaration": "def computeLPS(pattern):", "function_name": "computeLPS", "parameter_list": "(pattern)" }, { "docstring": "Returns the index of the first occurrence of `needle` in `haystack`, or ...
[ 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 kmp_search(haystack: str, needle: str) -> int:\n # Edge case: if needle is an empty string\n if not needle:\n return 0\n\n # Function to c...
trial_gpt4o_2
{ "original_instruction": "### Longest Prefix Suffix (using KMP Algorithm)\n\nYou are given two strings, `haystack` and `needle`. Implement the `strStr()` function that returns the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`.\n\nTo solve this problem more eff...
0.514532
Data_Structure_2304
C
[ "computeLPS", "kmp_search" ]
2
[ [ "kmp_search", "computeLPS" ] ]
1
[]
false
[]
false
pytest
true
[]
true
62023ac28bf56248025c8ec86b5f2f374e686296
27e2be27d57ebdd08804cd765e642c9fb6eb899d
v1.0
complete
Data_Structure
Data_Structure_1110_C
from typing import List def prime_check(num: int) -> bool: """ Verify if the given number is prime. """ pass def find_primitive_root(n: int) -> List[int]: """ Find all primitive roots of the given prime number. """ pass def secure_diffie_hellman(a: int, p: int) -> bool: """ Im...
import random from sympy import isprime, primerange def prime_check(num): """ Verify if the given number is prime. """ return isprime(num) def find_primitive_root(p): """ Find all primitive roots of the given prime number p. """ required_set = {num for num in range(1, p) if gcd(num, p)...
from solution import secure_diffie_hellman, prime_check, find_primitive_root def test_prime_check(): assert prime_check(7) == True assert prime_check(4) == False assert prime_check(23) == True assert prime_check(24) == False def test_find_primitive_root(): assert find_primitive_root(7) == 3 ...
[ { "docstring": "Verify if the given number is prime.", "function_declaration": "def prime_check(num):", "function_name": "prime_check", "parameter_list": "(num)" }, { "docstring": "Find all primitive roots of the given prime number p.", "function_declaration": "def find_primitive_root(p)...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import isprime, primerange\n\ndef prime_check(num):\n \"\"\"\n Verify if the given number is prime.\n \"\"\"\n return is...
trial_gpt4o_0
{ "original_instruction": "### Question: Secure Communication with Diffie-Hellman\n\nYou are tasked with implementing an end-to-end Diffie-Hellman key exchange system, ensuring that Alice and Bob can securely establish a shared secret key over an unsecured network. Your implementation should involve the generation of...
0.585078
Data_Structure_1110
C
[ "prime_check", "find_primitive_root", "gcd", "generate_private_key", "generate_public_key", "compute_shared_key", "secure_diffie_hellman" ]
7
[ [ "find_primitive_root", "gcd" ], [ "secure_diffie_hellman", "compute_shared_key" ], [ "secure_diffie_hellman", "find_primitive_root" ], [ "secure_diffie_hellman", "generate_private_key" ], [ "secure_diffie_hellman", "generate_public_key" ], [ "secure_...
6
[]
false
[]
false
pytest
true
[ "sympy" ]
false
d00e9f742db36fa9b72ce57a0defc2f3c8eb3110
2924959cb0a1bc3aaff886d48f8dd51f29273a4c
v1.0
complete
Data_Structure
Data_Structure_1837_C
from typing import List def dna_pattern_search(dna_sequence: str, dna_pattern: str) -> List[int]: """ Given a DNA sequence and a DNA pattern, return the list of starting indices in the sequence where the pattern matches using KMP algorithm. Args: dna_sequence (str): The DNA sequence to search within. ...
from typing import List def compute_lps(pattern: str) -> List[int]: """ Helper function that computes the Longest Prefix Suffix (LPS) array for KMP algorithm. """ lps = [0] * len(pattern) length = 0 # length of the previous longest prefix suffix i = 1 while i < len(pattern): if pa...
from solution import dna_pattern_search def test_dna_pattern_search_simple(): assert dna_pattern_search('ACGTACGTGACG', 'ACGT') == [0, 4] def test_dna_pattern_search_no_match(): assert dna_pattern_search('ACGTACGTGACG', 'TGCA') == [] def test_dna_pattern_search_partial_match(): assert dna_pattern_search(...
[ { "docstring": "Helper function that computes the Longest Prefix Suffix (LPS) array for KMP algorithm.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "Implement the KMP algorithm to find all starting indi...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Computes the longest proper prefix which is also suffix array (lps) fo...
trial_gpt4o_2
{ "original_instruction": "### Scenario\nAlice loves solving problems involving DNA sequences. She has a collection of DNA sequences and wants to find out how often a smaller DNA pattern appears in these sequences. DNA sequences are essentially very large strings, and patterns can vary in length. Alice heard about th...
0.549694
Data_Structure_1837
C
[ "compute_lps", "dna_pattern_search" ]
2
[ [ "dna_pattern_search", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d064e239e510df9e16327813fcecd680e1afa3d3
700f875be0ad02002e29ace17dcf6e67eafdb195
v1.0
complete
Data_Structure
Data_Structure_1550_C
def bucket_sort(arr: List[int]) -> List[int]: """ Implement a bucket sort algorithm that sorts an array of integers. >>> bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) [3, 9, 21, 25, 29, 37, 43, 49] >>> bucket_sort([5, 1, 2, 2, 3, 5, 4]) [1, 2, 2, 3, 4, 5, 5] >>> bucket_sort([42]) [42] >>> ...
from typing import List def insertion_sort(bucket): """ Helper function to perform insertion sort on a single bucket/list. """ for i in range(1, len(bucket)): up = bucket[i] j = i - 1 while j >= 0 and bucket[j] > up: bucket[j + 1] = bucket[j] j -= 1 ...
from solution import bucket_sort def test_bucket_sort_standard_case(): assert bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) == [3, 9, 21, 25, 29, 37, 43, 49] def test_bucket_sort_with_duplicates(): assert bucket_sort([5, 1, 2, 2, 3, 5, 4]) == [1, 2, 2, 3, 4, 5, 5] def test_bucket_sort_single_element(): ass...
[ { "docstring": "Helper function to perform insertion sort on a single bucket/list.", "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" }, { "docstring": null, "function_declaration": "def bucket_sort(arr):", "functi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef insertion_sort(bucket: List[int]) -> List[int]:\n for i in range(1, len(bucket)):\n key = bucket[i]\n j = i - ...
trial_gpt4o_2
{ "original_instruction": "## Question: Implement a Bucket Sort Algorithm\n\nYou are required to implement a Bucket Sort algorithm that sorts an array of integers. The goal is to demonstrate your understanding of the bucket sort concept, distribution mechanism, and sorting within buckets.\n\n### Task:\n1. Implement a...
0.63091
Data_Structure_1550
C
[ "insertion_sort", "bucket_sort" ]
2
[ [ "bucket_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
36a81a90b75ba05fbf92ba073d871d0d1a35ecf4
32b2058536de18e00a5ac3b69dac775a9d43257e
v1.0
complete
Data_Structure
Data_Structure_1024_C
def efficient_sort(arr: List[int]) -> List[int]: """ Implement a more efficient sorting algorithm to replace the Bogo Sort algorithm for sorting a list of integers. The function should handle edge cases like empty arrays, arrays with identical elements, and already sorted arrays. The chosen algorithm s...
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left, right): sorted_list = [] left_pointer = right_pointer = 0 while left_pointer < len(...
from solution import efficient_sort def test_sorted_array(): assert efficient_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_array(): assert efficient_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_empty_array(): assert efficient_sort([]) == [] def test_single_element_array(): a...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docst...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in ascending order using merge sort.\n ...
trial_gpt4o_2
{ "original_instruction": "### Task\n\nYou are tasked with implementing a more efficient sorting algorithm to replace the Bogo Sort algorithm for sorting a list of integers.\n\n### Input and Output Formats\n\n**Input**:\n```python\n arr: List[int] \n```\n* A list of integers that needs to be sorted.\n\n**Output**:...
0.644144
Data_Structure_1024
C
[ "merge_sort", "merge", "efficient_sort" ]
3
[ [ "efficient_sort", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ffc58a5405a2e7803efbe6a7fb26e7f33a799309
13a490115d6491b6f79ba7da3b28f62576561b17
v1.0
complete
Data_Structure
Data_Structure_1324_C
def optimized_quick_sort(arr: List[int]) -> List[int]: """Sorts an array using an optimized version of quick sort. The function uses a randomized pivot to optimize performance on pre-sorted data and switches to insertion sort for small subarrays for better efficiency. >>> optimized_quick_sort([3, ...
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 arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def partition(arr, low, high): pivot_index = random.randint(low,...
from solution import optimized_quick_sort def test_optimized_quick_sort_regular_case(): assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] def test_optimized_quick_sort_all_identical_elements(): assert optimized_quick_sort([1, 1, 1, 1]) == [1, 1, 1, 1] def test_optimized_quick_sort...
[ { "docstring": null, "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "paramet...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1\n while j >= low ...
trial_gpt4o_2
{ "original_instruction": "## Quick Sort Implementation and Optimization\n\nIn this exercise, you need to implement the quick sort algorithm but with a focus on optimizing its performance and handling edge cases. Specifically, you are required to:\n\n1. Implement the quick sort algorithm with a randomized pivot selec...
0.574803
Data_Structure_1324
C
[ "insertion_sort", "partition", "quick_sort_recursive", "optimized_quick_sort" ]
4
[ [ "optimized_quick_sort", "quick_sort_recursive" ], [ "quick_sort_recursive", "insertion_sort" ], [ "quick_sort_recursive", "partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3e2ef40f480bf9ebb738e061e940b54a41b67bd0
b5eedc3f3a5cb3e634c6e5ac75738830095b03aa
v1.0
complete
Data_Structure
Data_Structure_2190_C
def matrix_power(mat: list, k: int) -> list: """ Computes the k-th power of a given matrix mat using matrix exponentiation by squaring. Parameters: - mat (list of list of int): A square matrix of integers. - k (int): The exponent to which the matrix is to be raised. Returns: - list of ...
def matrix_multiply(mat1, mat2): n = len(mat1) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += mat1[i][k] * mat2[k][j] return result def matrix_power(mat, k): """ Computes the k-th power of a given...
import pytest from solution import matrix_power def test_matrix_power_identity(): mat = [ [1, 2], [3, 4] ] k = 0 expected = [ [1, 0], [0, 1] ] assert matrix_power(mat, k) == expected def test_matrix_power_one(): mat = [ [1, 2], [3, 4] ] ...
[ { "docstring": null, "function_declaration": "def matrix_multiply(mat1, mat2):", "function_name": "matrix_multiply", "parameter_list": "(mat1, mat2)" }, { "docstring": "Computes the k-th power of a given matrix mat using matrix exponentiation by squaring.\n\nParameters:\n- mat (list of list ...
[ 0, 0, 0, 1, 1, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_mult(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in range(...
trial_gpt4o_9
{ "original_instruction": "## Problem Statement\nYou are given a matrix `mat` of size `n x n` and an integer `k`. Your task is to implement a function that computes the `k`-th power of the matrix `mat`, denoted as `mat^k`. To achieve this, you should leverage matrix exponentiation by repeated squaring for efficiency....
0.500567
Data_Structure_2190
C
[ "matrix_multiply", "matrix_power" ]
2
[ [ "matrix_power", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
true
[]
true
103b96f118c4a58a0fcd956cf8c6e0c857743688
2e74320c22cb15ab0c89b084e24e701476eb3bd5
v1.0
complete
Data_Structure
Data_Structure_1684_C
def enhanced_radix_sort(arr): """ Implement Enhanced Radix Sort with Support for Negative Numbers. Sort an array of integers in non-descending order using radix sort, modified to support negative numbers. >>> enhanced_radix_sort([170, 45, 75, -90, -802, 24, 2, 66]) [-802, -90, 2, 24, 45, 66, 75, 1...
def counting_sort(arr, exp): n = len(arr) output = [0] * n # output array that will have sorted arr count = [0] * 10 # count array to store count of occurrences # Store count of occurrences in count[] for i in range(n): index = abs(arr[i]) // exp count[index % 10] += 1 # Chan...
from solution import enhanced_radix_sort def test_enhanced_radix_sort_mixed_numbers(): assert enhanced_radix_sort([170, 45, 75, -90, -802, 24, 2, 66]) == [-802, -90, 2, 24, 45, 66, 75, 170] def test_enhanced_radix_sort_negative_and_zero(): assert enhanced_radix_sort([-5, -10, 0, -3, 8, 5, 4, -1]) == [-10, -5,...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort_non_negative(arr):", "function_name": "radix_sort_non_negative", "paramete...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def enhanced_radix_sort(arr):\n \"\"\"\n Function to perform radix sort on a list of integers\n including negative numbers.\n \"\"\"\n \n de...
trial_gpt4o_8
{ "original_instruction": "## Problem: Implement Enhanced Radix Sort with Support for Negative Numbers\n\n### Scenario\nYou have been contracted by a software company to improve their sorting functionality within their data processing pipeline. The company's data consists of integers that could be either positive or ...
0.689615
Data_Structure_1684
C
[ "counting_sort", "radix_sort_non_negative", "enhanced_radix_sort" ]
3
[ [ "enhanced_radix_sort", "radix_sort_non_negative" ], [ "radix_sort_non_negative", "counting_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4730ded4939d2383e6fc4a315f58fa1d615438fb
bfa9f7cdfd4bc68b6467b226659e3b4c2b3b07c3
v1.0
complete
Data_Structure
Data_Structure_1720_C
from typing import List def pancake_sort(arr: List[int]) -> List[int]: """ Sorts the given list of integers using the pancake sort technique. Parameters: arr (List[int]): A list of integers representing the sizes of pancakes. Returns: List[int]: A sorted list of integers in ascending order. ...
from typing import List def flip(arr: List[int], k: int) -> None: """ Reverses the order of the first k elements in arr. """ arr[:k] = arr[:k][::-1] def pancake_sort(arr: List[int]) -> List[int]: """ Sorts the given list of integers using the pancake sort technique. Parameters: ar...
from solution import pancake_sort def test_pancake_sort_empty(): assert pancake_sort([]) == [] def test_pancake_sort_single_element(): assert pancake_sort([1]) == [1] def test_pancake_sort_sorted_array(): assert pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_pancake_sort_reverse_sorted_array(...
[ { "docstring": "Reverses the order of the first k elements in arr.", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Sorts the given list of integers using the pancake sort technique.\n\nParameters:\narr (List[int]): A lis...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n A helper function that reverses the order of the first k elements in the...
trial_gpt4o_2
{ "original_instruction": "### Pancake Birthday Party\n\n#### Context\nYou are organizing a birthday party and want to serve the pancakes in a neat, sorted stack based on their size. Given a stack of pancakes, your task is to sort them so that the smallest pancake is on top and the largest pancake is at the bottom us...
0.72555
Data_Structure_1720
C
[ "flip", "pancake_sort" ]
2
[ [ "pancake_sort", "flip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
31ab7e8ab3f32b02a7a9c36fe1ec8cf72163412a
991b341e6672e87b274c15c74d0fa42c9220e1a0
v1.0
complete
Data_Structure
Data_Structure_1996_C
from typing import List def pancake_sort(arr: List[int]) -> List[int]: """ Perform pancake sorting on the input array `arr` and return the sorted array. >>> pancake_sort([3, 2, 4, 1]) [1, 2, 3, 4] >>> pancake_sort([1, 2, 3, 4]) [1, 2, 3, 4] >>> pancake_sort([4, 3, 2, 1]) [1, 2, 3, 4] ...
from typing import List def flip(arr: List[int], k: int) -> None: """ Flip function to reverse the order of the first k elements of the array """ arr[:k] = arr[:k][::-1] def pancake_sort(arr: List[int]) -> List[int]: """ Perform pancake sorting on the input array `arr` and return the sorted ar...
from solution import pancake_sort def test_pancake_sort_normal_case(): assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4] def test_pancake_sort_already_sorted(): assert pancake_sort([1, 2, 3, 4]) == [1, 2, 3, 4] def test_pancake_sort_reverse_sorted(): assert pancake_sort([4, 3, 2, 1]) == [1, 2, 3, 4] def...
[ { "docstring": "Flip function to reverse the order of the first k elements of the array", "function_declaration": "def flip(arr, k):", "function_name": "flip", "parameter_list": "(arr, k)" }, { "docstring": "Perform pancake sorting on the input array `arr` and return the sorted array.", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def flip(arr, k):\n \"\"\"\n Flips the first k elements of the array.\n \"\"\"\n return arr[:k][::-1] + arr[k:]\n\ndef find_max(arr, n):\n \"\"...
trial_gpt4o_2
{ "original_instruction": "### Pancake Sorting Challenge\n\nPancake sorting is a fascinating algorithm that operates similarly to the game of sorting pancakes on a grill by flipping them with a spatula. The goal is to sort an array of numbers using only a series of flips.\n\nA flip reverses the order of the elements ...
0.772985
Data_Structure_1996
C
[ "flip", "pancake_sort" ]
2
[ [ "pancake_sort", "flip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
41240d8a2f7db231abafe064a7430d002f69a2a0
4e32c3db6212aaef1129ce91a390e6db57cd14fc
v1.0
complete
Data_Structure
Data_Structure_2004_C
from typing import List def find_krishnamurthy_numbers_in_range(start: int, end: int) -> List[int]: """ Identify all Krishnamurthy numbers within a specified inclusive range [start, end]. A Krishnamurthy number is a number whose sum of the factorial of its digits equals the number itself. Args: ...
from typing import List def find_factorial(n: int) -> int: if n == 0 or n == 1: return 1 result = 1 for i in range(2, n + 1): result *= i return result # Precompute the factorials of digits 0-9 factorials = {i: find_factorial(i) for i in range(10)} def is_krishnamurthy_number(n: int) ...
from solution import find_krishnamurthy_numbers_in_range def test_find_krishnamurthy_numbers_in_range_1_to_150(): assert find_krishnamurthy_numbers_in_range(1, 150) == [1, 2, 145] def test_find_krishnamurthy_numbers_in_range_100_to_50000(): assert find_krishnamurthy_numbers_in_range(100, 50000) == [145, 40585...
[ { "docstring": null, "function_declaration": "def find_factorial(n):", "function_name": "find_factorial", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_krishnamurthy_number(n):", "function_name": "is_krishnamurthy_number", "parameter_list": "(n)"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\n# Precompute factorial values for digits 0-9\nfactorials = [1] * 10\nfor i in range(2, 10):\n factorials[i] = factorials[i-1] * ...
trial_gpt4o_2
{ "original_instruction": "### Question\n\n#### Scenario\nYou are working on a problem that requires you to identify Krishnamurthy numbers within a given range. Your task is to write a function that can efficiently determine if numbers in that range are Krishnamurthy numbers.\n\n#### Task\nWrite a function `find_kris...
0.561392
Data_Structure_2004
C
[ "find_factorial", "is_krishnamurthy_number", "find_krishnamurthy_numbers_in_range" ]
3
[ [ "find_krishnamurthy_numbers_in_range", "is_krishnamurthy_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb26b73f498689d71987b9114b9fc036b46eec32
a54dcdb1e0b5bef95bfed3e7c77ffb6f09308946
v1.0
complete
Data_Structure
Data_Structure_2567_C
class AvlTree: def __init__(self): self.root = None def insert(self, key: int) -> None: """Inserts a new key into the AVL tree and rebalances if necessary. Args: key (int): The key to be inserted into the AVL tree. """ def in_order_traverse(self): """Pe...
class Node: def __init__(self, key): self.key = key self.left = None self.right = None self.height = 1 def get_height(node): return node.height if node else 0 def update_height(node): node.height = 1 + max(get_height(node.left), get_height(node.right)) def get_balance(node...
import pytest from solution import AvlTree def test_insert_single_element(): tree = AvlTree() tree.insert(10) assert tree.in_order_traverse() == [10] def test_insert_multiple_elements(): tree = AvlTree() tree.insert(10) tree.insert(20) tree.insert(15) assert tree.in_order_traverse() ==...
[]
[ 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 AvlTree:\n class Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n ...
trial_gpt4o_1
{ "original_instruction": "### Question: Implement AVL Tree Insert Operation with Rebalancing\n\n#### Scenario:\nYou are tasked with implementing the insert operation for an AVL tree that automatically maintains balance after any insertion. Your goal is to ensure that the AVL tree remains height-balanced.\n\n#### Fun...
0.416787
Data_Structure_2567
C
[ "get_height", "update_height", "get_balance", "right_rotate", "left_rotate", "rebalance" ]
6
[ [ "get_balance", "get_height" ], [ "left_rotate", "update_height" ], [ "rebalance", "get_balance" ], [ "rebalance", "left_rotate" ], [ "rebalance", "right_rotate" ], [ "right_rotate", "update_height" ], [ "update_height", "get_height" ...
7
[]
false
[ "Node", "AvlTree" ]
true
pytest
true
[]
true
0efd45144b3aac9edf05f4fd5dd0ea5adb48fbff
a58cf8b5b8a3a7a3eb29c714fa079f013cc3f521
v1.0
complete
Data_Structure
Data_Structure_2510_C
def find_primitive_root_optimized(n: int) -> list: """ Find all primitive roots of a given integer n. Args: n (int): a positive integer Returns: list: a list of all primitive roots of the integer n in ascending order. If no primitive roots exist, return an empty list. ...
def gcd(a, b): while b: a, b = b, a % b return a def is_primitive_root(n, candidate): required_set = {num for num in range(1, n) if gcd(num, n) == 1} actual_set = {pow(candidate, powers, n) for powers in range(1, n)} return required_set == actual_set def find_primitive_root_optimized(n: in...
from solution import find_primitive_root_optimized def test_no_primitive_root(): assert find_primitive_root_optimized(10) == [] def test_small_prime(): assert find_primitive_root_optimized(7) == [3, 5] def test_large_prime(): assert find_primitive_root_optimized(13) == [2, 6, 7, 11] def test_non_prime()...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def is_primitive_root(n, candidate):", "function_name": "is_primitive_root", "parameter_list": "(n, candidate)" }, ...
[ 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": "import math\nfrom functools import lru_cache\n\ndef find_primitive_root_optimized(n: int) -> list:\n if n <= 1:\n return []\n\n def gcd(a, b):\n ...
trial_gpt4o_7
{ "original_instruction": "#### Context\nAlice is learning about number theory and cryptography. She is particularly fascinated by the concept of primitive roots and their importance in cryptographic algorithms. She needs to write a function to identify all the primitive roots of a given positive integer n. However, ...
0.493075
Data_Structure_2510
C
[ "gcd", "is_primitive_root", "find_primitive_root_optimized" ]
3
[ [ "is_primitive_root", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6d65edaca1a8fc818477535696ae21aaf3627ca6
38702e226b026e04f23efeb9d8eca43b7766bc66
v1.0
complete
Data_Structure
Data_Structure_2594_C
def verify_inversion(original_matrix: List[List[float]]) -> bool: """ Verify the correctness of the matrix inversion by checking the product of the original matrix and its inverted matrix. >>> original_matrix = [ ... [4, 7], ... [2, 6] ... ] >>> verify_inversion(original_matrix) Tru...
import numpy as np def invert_matrix(matrix): return np.linalg.inv(matrix) def verify_inversion(original_matrix): """ Verify if the inverse of a matrix is correct. """ # Convert the matrix to numpy array matrix_np = np.array(original_matrix) # Compute the inverse using the given funct...
def test_verify_inversion_simple_2x2(): original_matrix = [ [4, 7], [2, 6] ] assert verify_inversion(original_matrix) == True def test_verify_inversion_another_2x2(): original_matrix = [ [1, 2], [3, 4] ] assert verify_inversion(original_matrix) == True def test_...
[ { "docstring": null, "function_declaration": "def invert_matrix(matrix):", "function_name": "invert_matrix", "parameter_list": "(matrix)" }, { "docstring": "Verify if the inverse of a matrix is correct.", "function_declaration": "def verify_inversion(original_matrix):", "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": "import numpy as np\n\ndef invert_matrix(matrix):\n \"\"\"\n Computes the inverse of a given square matrix.\n This function assumes that the matrix pr...
trial_gpt4o_2
{ "original_instruction": "Matrix Inversion Verification\n\n**Objective**: Implement a function that verifies the correctness of the matrix inversion algorithm provided in the code snippet by checking the product of the original matrix and its inverted matrix.\n\n#### Problem Statement\nGiven a matrix `original_matri...
0.619502
Data_Structure_2594
C
[ "invert_matrix", "verify_inversion" ]
2
[ [ "verify_inversion", "invert_matrix" ] ]
1
[]
false
[]
false
pytest
false
[ "numpy" ]
false
b254b9f916d3367f422565d58db1513ca6af6134
a519e94a776137627a72d83891facbc4129a4913
v1.0
complete
Data_Structure
Data_Structure_1744_C
import math from typing import Any, Dict, Tuple def distance(x: Tuple[float, ...], y: Tuple[float, ...]) -> float: """ Computes the Euclidean distance between two vectors x and y. >>> distance((1.0, 2.0), (1.0, 1.0)) 1.0 """ assert len(x) == len(y), "Vectors must have the same length" retur...
import math def distance(x, y): """ Computes the Euclidean distance between two vectors x and y. """ assert len(x) == len(y), "Vectors must have the same length" return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y))) def nearest_neighbor(x, tSet): """ Classifies an input vector x by...
from solution import nearest_neighbor def test_example1(): x = (1.0, 2.0) tSet = { (1.0, 1.0): "Class A", (2.0, 2.0): "Class B", (3.0, 3.0): "Class C" } assert nearest_neighbor(x, tSet) == "Class A" def test_example2(): x = (3.5, 4.5) tSet = { (1.0, 2.0): "Class...
[ { "docstring": "Computes the Euclidean distance between two vectors x and y.", "function_declaration": "def distance(x, y):", "function_name": "distance", "parameter_list": "(x, y)" }, { "docstring": "Classifies an input vector x by comparing it to a training set tSet using the nearest neigh...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Returns the Euclidean distance between two vectors x and y.\n \"\"\"\n assert len(x) == len(y), \"Ve...
trial_gpt4o_2
{ "original_instruction": "### Nearest Neighbor Search\n\n**Scenario**:\nYou are tasked with improving the security of a biometric authentication system. The system initially classifies a user's input based on their closest recorded biometric template using the Nearest Neighbor method.\n\n### Task\n\nImplement a func...
0.647026
Data_Structure_1744
C
[ "distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b3aecca5d15e958b3679e8b04d285cef4932f870
4af1e8022ad94804bf9ccdb4a838768c359646c2
v1.0
complete
Data_Structure
Data_Structure_1922_C
def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def bogo_sort_limited(arr: List[int], max_shuffles: int) -> Tuple[List[int], bool]: """ Bogo sort implementation with limited shuffles. Try t...
import random from typing import List, Tuple def is_sorted(arr: List[int]) -> bool: """ Helper function to check if the array is sorted. """ return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) def bogo_sort_limited(arr: List[int], max_shuffles: int) -> Tuple[List[int], bool]: """ Bog...
from solution import bogo_sort_limited def test_sorted_array(): arr = [1, 2, 3] max_shuffles = 10 result = bogo_sort_limited(arr, max_shuffles) assert result == ([1, 2, 3], True) def test_unsorted_array_large_max_shuffles(): arr = [3, 1, 2] max_shuffles = 10000 result = bogo_sort_limited(a...
[ { "docstring": "Helper function to check if the array is sorted.", "function_declaration": "def is_sorted(arr):", "function_name": "is_sorted", "parameter_list": "(arr)" }, { "docstring": "Bogo sort implementation with limited shuffles.\n\n:param arr: List of integers to be sorted\n:param ma...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the given array is sorted in ascending order...
trial_gpt4o_2
{ "original_instruction": "### Coding Challenge: Bogo Sort Conceptual Implementation\n\n#### Context\nIn this challenge, you are required to implement a simplified variant of the Bogo Sort algorithm. As you have studied, Bogo Sort is an inefficient sorting algorithm that sorts an array by repetitively shuffling it un...
0.616612
Data_Structure_1922
C
[ "is_sorted", "bogo_sort_limited" ]
2
[ [ "bogo_sort_limited", "is_sorted" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b766c6db97e03830655cb2a13cbbea6add03c78
26de1e5b5765e1db19f7c054b04b5aeed041a25e
v1.0
complete
Data_Structure
Data_Structure_2531_C
def reverse_string(s: str, method: str) -> str: """ Reverse a string using the specified method. The method can be "recursive", "iterative", "pythonic", or "ultra_pythonic". >>> reverse_string("hello", "recursive") == "olleh" >>> reverse_string("world", "iterative") == "dlrow" >>> reverse_string("p...
def reverse_string(s: str, method: str) -> str: if method == "recursive": return recursive_reverse(s) elif method == "iterative": return iterative_reverse(s) elif method == "pythonic": return pythonic_reverse(s) elif method == "ultra_pythonic": return ultra_pythonic_rever...
from solution import reverse_string def test_reverse_string_recursive(): assert reverse_string("hello", "recursive") == "olleh" assert reverse_string("world", "recursive") == "dlrow" assert reverse_string("a", "recursive") == "a" def test_reverse_string_iterative(): assert reverse_string("hello", "ite...
[ { "docstring": null, "function_declaration": "def reverse_string(s, method):", "function_name": "reverse_string", "parameter_list": "(s, method)" }, { "docstring": null, "function_declaration": "def recursive_reverse(s):", "function_name": "recursive_reverse", "parameter_list": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_string(s, method):\n \"\"\"\n Reverses the input string `s` using the specified `method`.\n \n Parameters:\n s (str): The string to...
trial_gpt4o_2
{ "original_instruction": "### String Reversal Challenge\n\n#### Context:\nYou are given several methods to reverse a string, each demonstrating different concepts of algorithm design and performance characteristics. Your task is to implement a function to reverse a string using at least two distinct methods from the...
0.743823
Data_Structure_2531
C
[ "reverse_string", "recursive_reverse", "iterative_reverse", "pythonic_reverse", "ultra_pythonic_reverse" ]
5
[ [ "reverse_string", "iterative_reverse" ], [ "reverse_string", "pythonic_reverse" ], [ "reverse_string", "recursive_reverse" ], [ "reverse_string", "ultra_pythonic_reverse" ] ]
4
[]
false
[]
false
pytest
true
[]
true
17d37677aca5bed31a1f1b9f32028af8a174db66
2162fc94b16a011c0ed6b76a57ace89073108624
v1.0
complete
Data_Structure
Data_Structure_1367_C
def optimized_insertion_sort(arr: list) -> list: """ Sort an array using an optimized insertion sort algorithm. Parameters: arr (list): A list of integers to be sorted. Returns: list: A sorted list of integers. Examples: >>> optimized_insertion_sort([12, 11, 13, 5, 6]) [5, 6, 11, ...
def search_insert(arr, val, start, end): """ Uses binary search to find the index where 'val' should be inserted in 'arr' to maintain sorted order from indices 'start' to 'end'. """ if start == end: if arr[start] > val: return start else: return start + 1 ...
from solution import optimized_insertion_sort def test_sorted_array(): assert optimized_insertion_sort([5, 6, 11, 12, 13]) == [5, 6, 11, 12, 13] def test_reverse_sorted_array(): assert optimized_insertion_sort([13, 12, 11, 6, 5]) == [5, 6, 11, 12, 13] def test_unsorted_array(): assert optimized_insertion...
[ { "docstring": "Uses binary search to find the index where 'val' should be inserted in 'arr'\nto maintain sorted order from indices 'start' to 'end'.", "function_declaration": "def search_insert(arr, val, start, end):", "function_name": "search_insert", "parameter_list": "(arr, val, start, end)" }...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(arr, left, right, key):\n \"\"\"\n Uses binary search to find the index where 'key' should be inserted \n among existing elements i...
trial_gpt4o_2
{ "original_instruction": "Demonstrate your understanding of optimized insertion sort by implementing a function that uses binary search to find the correct insertion position. You need to implement the optimized insertion sort algorithm utilizing the provided `search_insert` helper function.\n\n### Function Signatur...
0.646327
Data_Structure_1367
C
[ "search_insert", "optimized_insertion_sort" ]
2
[ [ "optimized_insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
785ca7ca1ed002de16b78814f689c0a733901cd2
f324ff622e93aa717469e9af273e984c7e48bcd6
v1.0
complete
Data_Structure
Data_Structure_2117_C
def palindromic_substrings(s: str) -> List[List[str]]: """ Given a string s, return all the ways to partition s into substrings where each substring is a palindrome. >>> palindromic_substrings("abcbab") [['a', 'bcb', 'a', 'b'], ['a', 'b', 'c', 'bab'], ['a', 'b', 'c', 'b', 'a', 'b'], ['abcba', 'b']] >>> ...
def is_palindrome(s): return s == s[::-1] def palindromic_substrings(s): def dfs(start, path, result): if start == len(s): result.append(path) return for end in range(start + 1, len(s) + 1): if is_palindrome(s[start:end]): dfs(end, path + [s[s...
def test_palindromic_substrings(): assert sorted(palindromic_substrings('abcbab')) == sorted([['a', 'bcb', 'a', 'b'], ['a', 'b', 'c', 'bab'], ['a', 'b', 'c', 'b', 'a', 'b'], ['abcba', 'b']]) assert palindromic_substrings('a') == [['a']] assert palindromic_substrings('') == [[]] def test_palindromic_substri...
[ { "docstring": null, "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def palindromic_substrings(s):", "function_name": "palindromic_substrings", "parameter_list": "(s)" }...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(s):\n \"\"\"\n Helper function that checks if a string is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef palindromic_substr...
trial_gpt4o_1
{ "original_instruction": "### Palindromic Substring Partitioning\n\n#### Objective\nDesign a function that computes all ways to part a given string into substrings where each substring is a palindrome. As a subsequent task, improve the performance of this function using dynamic programming.\n\n#### Scenario\nYou are...
0.781743
Data_Structure_2117
C
[ "is_palindrome", "palindromic_substrings", "palindromic_substrings_dp" ]
3
[ [ "palindromic_substrings", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
false
[]
true
d52d6c9388c122255e1eb8c5b7f885bc71ce9851
d322817de2765a51b93cf77718279f40a0cbbbe5
v1.0
complete
Data_Structure
Data_Structure_1689_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def serialize(root): def helper(node): if not node: return "#" left_serialized = helper(node.left) right_serialized = helper(node.righ...
# Assuming the TreeNode class and serialization/deserialization functions are defined as follows: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def serialize(root): def helper(node): if not node: ...
def test_are_trees_identical_identical_trees(): tree1 = "1 2 # # 3 # #" tree2 = "1 2 # # 3 # #" assert are_trees_identical(tree1, tree2) def test_are_trees_identical_different_trees(): tree1 = "1 2 # # 3 # #" tree2 = "1 2 # # 4 # #" assert not are_trees_identical(tree1, tree2) def test_are_tre...
[]
[ 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": "# Assuming the TreeNode class and serialization/deserialization functions are defined as follows:\n\nclass TreeNode:\n def __init__(self, val=0, left=None,...
trial_gpt4o_0
{ "original_instruction": "### Question\nYou are given two functions, `serialize` and `deserialize`, for a binary tree. \n\n#### Objective:\nImplement a method to determine if two binary trees are identical using these functions. \n\n#### Instructions:\n1. Write a function `are_trees_identical(tree1, tree2)` that tak...
0.524903
Data_Structure_1689
C
[ "serialize", "deserialize", "are_trees_identical" ]
3
[ [ "are_trees_identical", "deserialize" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
false
[]
true
475b1148b2a2ba9a21f198448fbc9908522f37ec
45d3daf3f8e1e64137ebf8b69637cb2c18c6e569
v1.0
complete
Data_Structure
Data_Structure_1898_C
def optimized_bucket_sort(arr): ''' Optimized Bucket Sort This function sorts a list of integers using an optimized bucket sort method that leverages merge sort for sorting individual buckets. >>> optimized_bucket_sort([4, 2, 2, 8, 3, 3, 1]) [1, 2, 2, 3, 3, 4, 8] >>> optimized_bucket_sort([56, 89,...
def optimized_bucket_sort(arr): if len(arr) == 0: return arr # Find the maximum value in the array to determine the number of buckets max_value = max(arr) size = max_value // len(arr) + 1 # Create buckets and distribute the elements buckets = [[] for _ in range(size)] for n...
from solution import optimized_bucket_sort def test_optimized_bucket_sort_empty(): assert optimized_bucket_sort([]) == [] def test_optimized_bucket_sort_single_element(): assert optimized_bucket_sort([1]) == [1] def test_optimized_bucket_sort_sorted(): assert optimized_bucket_sort([1, 2, 3, 4, 5]) == [1,...
[ { "docstring": null, "function_declaration": "def optimized_bucket_sort(arr):", "function_name": "optimized_bucket_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def optimized_bucket_sort(arr):\n ''' Optimized Bucket Sort '''\n if len(arr) == 0:\n return arr\n\n # Find the maximum value to know the rang...
trial_gpt4o_2
{ "original_instruction": "### Bucket Sort Optimization Challenge\n\nYou are tasked with optimizing the Bucket Sort algorithm provided. The existing algorithm utilizes Insertion Sort for sorting the contents of each bucket. However, Insertion Sort may become inefficient for larger datasets. Your goal is to implement ...
0.559171
Data_Structure_1898
C
[ "optimized_bucket_sort", "merge_sort", "merge" ]
3
[ [ "merge_sort", "merge" ], [ "optimized_bucket_sort", "merge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0a0eee2a888d8e60b8ad8bcf24712fef64e52a20
5140caec6c1a448c400fe1fdc485692c4bd42ee2
v1.0
complete
Data_Structure
Data_Structure_2006_C
def enhanced_interpolation_search(array: List[int], search_key: int, switch_threshold: int = 3) -> int: """ Implement the Interpolation Search algorithm with an enhanced functionality to switch to Binary Search in case of frequent bad position estimates. Args: array (List[int]): A sorted list...
from typing import List def binary_search(array: List[int], search_key: int) -> int: low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == search_key: return mid elif array[mid] < search_key: low = mid + 1 else: ...
from solution import enhanced_interpolation_search def test_enhanced_interpolation_search_found(): array = [10, 12, 14, 17, 20, 21] search_key = 17 assert enhanced_interpolation_search(array, search_key, 2) == 3 def test_enhanced_interpolation_search_not_found(): array = [1, 3, 5, 7, 8, 9, 11] sea...
[ { "docstring": null, "function_declaration": "def binary_search(array, search_key):", "function_name": "binary_search", "parameter_list": "(array, search_key)" }, { "docstring": null, "function_declaration": "def enhanced_interpolation_search(array, search_key, switch_threshold=3):", ...
[ 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 binary_search(array: List[int], search_key: int) -> int:\n low, high = 0, len(array) - 1\n while low <= high:\n mi...
trial_gpt4o_0
{ "original_instruction": "### Problem Description\n\nYou are tasked with implementing the Interpolation Search algorithm, but with additional functionality to safeguard against performance degradation caused by non-uniform data distributions. Your enhanced version should switch to Binary Search if the calculated pro...
0.513577
Data_Structure_2006
C
[ "binary_search", "enhanced_interpolation_search" ]
2
[ [ "enhanced_interpolation_search", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e59d92fca84c67d64aef98722e7ace1856615ab
dfda14880f3bdf9e1a604356603afde22a9e847a
v1.0
complete
Data_Structure
Data_Structure_1436_C
def encode_file(input_file: str, encoded_file: str) -> None: """ Read the content of the specified `input_file`, encode the text using Huffman coding and write the encoded data to `encoded_file`. Store additional information to reconstruct the Huffman Tree during decoding. Args: input_file: The pat...
import heapq import os import pickle class HuffmanNode: def __init__(self, char=None, freq=None): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_frequency_dict(text): frequency =...
import os from solution import encode_file, decode_file def test_huffman_encoding_decoding(): input_filename = 'test_input.txt' encoded_filename = 'test_encoded.bin' decoded_filename = 'test_decoded.txt' # Prepare test input file with open(input_filename, 'w') as file: file.write("this...
[]
[ 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 heapq\nfrom collections import defaultdict, Counter\n\nclass HuffmanNode:\n def __init__(self, char=None, freq=0):\n self.char = char\n ...
trial_gpt4o_2
{ "original_instruction": "### Coding Problem: Huffman Coding Implementation\n\n#### Objective:\nImplement an algorithm to compress and decompress a given text file using Huffman coding. Your implementation should efficiently encode the input data and be capable of decoding it back to the original data.\n\n#### Funct...
0.541673
Data_Structure_1436
C
[ "build_frequency_dict", "build_huffman_tree", "build_codes", "encode_text", "pad_encoded_text", "get_byte_array", "encode_file", "remove_padding", "decode_text", "decode_file" ]
10
[ [ "decode_file", "decode_text" ], [ "decode_file", "remove_padding" ], [ "encode_file", "build_codes" ], [ "encode_file", "build_frequency_dict" ], [ "encode_file", "build_huffman_tree" ], [ "encode_file", "encode_text" ], [ "encode_file", ...
8
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
c138087633a982f839977dd908a9351cc350abdb
016ae8b7334a59da4fcff1e14a6dea48cd22fbad
v1.0
complete
Data_Structure
Data_Structure_2191_C
def counting_sort_for_radix(arr: List[int], exp: int, simulation: bool, iteration: int): # Helper function for radix_sort def radix_sort(arr: List[int], simulation: bool = False) -> List[int]: """ Implement the Radix Sort algorithm to sort a list of non-negative integers. Parameters: arr (List[in...
def counting_sort_for_radix(arr, exp, simulation, iteration): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index = (a...
from solution import radix_sort def test_radix_sort_basic(): arr = [170, 45, 75, 90, 802, 24, 2, 66] sorted_arr = [2, 24, 45, 66, 75, 90, 170, 802] assert radix_sort(arr) == sorted_arr def test_radix_sort_empty(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort...
[ { "docstring": null, "function_declaration": "def counting_sort_for_radix(arr, exp, simulation, iteration):", "function_name": "counting_sort_for_radix", "parameter_list": "(arr, exp, simulation, iteration)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, simulation=...
[ 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):\n n = len(arr)\n \n output = [0] * n \n ...
trial_gpt4o_2
{ "original_instruction": "You have been tasked to implement the Radix Sort algorithm to sort a list of non-negative integers without using any built-in sort functions. The algorithm should process each digit of the number starting from the least significant digit to the most significant digit.\n\n### Function Defini...
0.674189
Data_Structure_2191
C
[ "counting_sort_for_radix", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5fc1ef5d5c654c4668a3075a6e3ccf5e329f9f0a
07bd8a28be3d60a8a4ff92cd7a8ee57b9d3fc488
v1.0
complete
Data_Structure
Data_Structure_1320_C
def efficient_gcd(a: int, b: int) -> int: """ Computes the greatest common divisor (GCD) of integers 'a' and 'b' using efficient methods including bitwise operations. Args: a (int): First integer b (int): Second integer Returns: int: The GCD of 'a' and 'b' """ pass d...
def efficient_gcd(a: int, b: int) -> int: """ Computes the greatest common divisor (GCD) of integers 'a' and 'b' using efficient methods including bitwise operations. Args: a (int): First integer b (int): Second integer Returns: int: The GCD of 'a' and 'b' """ if a ==...
from solution import efficient_gcd, efficient_lcm def test_efficient_gcd_common(): assert efficient_gcd(48, 18) == 6 assert efficient_gcd(56, 98) == 14 assert efficient_gcd(1000000, 2) == 2 def test_efficient_gcd_zero(): assert efficient_gcd(0, 5) == 5 assert efficient_gcd(5, 0) == 5 assert ef...
[ { "docstring": "Computes the greatest common divisor (GCD) of integers 'a' and 'b'\nusing efficient methods including bitwise operations.\nArgs:\n a (int): First integer\n b (int): Second integer\nReturns:\n int: The GCD of 'a' and 'b'", "function_declaration": "def efficient_gcd(a, b):", "func...
[ 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 efficient_gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor (GCD) of integers 'a' and 'b'\n using efficient methods inc...
trial_gpt4o_2
{ "original_instruction": "You are required to implement a function that computes the greatest common divisor (GCD) of two integers but with an additional twist: you should incorporate detecting efficient edge cases handling that improve the performance specifically focusing on using bitwise operations. Additionally,...
0.721978
Data_Structure_1320
C
[ "efficient_gcd", "efficient_lcm" ]
2
[ [ "efficient_lcm", "efficient_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f13c3da72e1d232e86cac55fd7307da7e043fc99
329e41279ef8ed620385fb4dd2533b6ee1064ac9
v1.0
complete
Data_Structure
Data_Structure_1424_C
from typing import List def search_insert(array: List[int], val: int) -> int: """ Helper function using binary search to find the index where val should be inserted. """ low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: ...
def search_insert(array, val): """ Helper function using binary search to find the index where val should be inserted. """ low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high ...
from solution import insertion_sort def test_insertion_sort_already_sorted(): arr = [1, 2, 3, 4, 5, 6] insertion_sort(arr) assert arr == [1, 2, 3, 4, 5, 6] def test_insertion_sort_reverse_sorted(): arr = [6, 5, 4, 3, 2, 1] insertion_sort(arr) assert arr == [1, 2, 3, 4, 5, 6] def test_insertio...
[ { "docstring": "Helper function using binary search to find the index where val should be inserted.", "function_declaration": "def search_insert(array, val):", "function_name": "search_insert", "parameter_list": "(array, val)" }, { "docstring": "Sorts the array in-place using insertion sort ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl", "solution_code": "def search_insert(array, val):\n \"\"\"\n Helper function to determine the index where val should be inserted in the sorted part of the array.\n Uses...
trial_gpt4o_2
{ "original_instruction": "#### Scenario\nImagine you are working as a part of a development team responsible for developing a library of sorting algorithms. One of the fundamental algorithms you need to implement is Insertion Sort. You are provided with a helper function `search_insert` that determines the correct i...
0.686413
Data_Structure_1424
C
[ "search_insert", "insertion_sort" ]
2
[ [ "insertion_sort", "search_insert" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ea5896c76eba71dd19a64cd676c68f7a22ee40cf
0a3314e9ca3a195b111dd1d1a2a19565847ee503