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_22310_C
[Completion Task in Python] import requests def fetch_weather_data(location): """ Fetches the weather data for the specified location. Args: location (str): The location (city name). Returns: dict: The weather data in JSON format. """ API_KEY = 'your_api_key_here' # Replace with your...
import requests def fetch_weather_data(location): """ Fetches the weather data for the specified location. Args: location (str): The location (city name). Returns: dict: The weather data in JSON format. """ API_KEY = 'your_api_key_here' # Replace with your actual API key BASE_URL...
import pytest from unittest.mock import patch, Mock from solution import fetch_weather_data, analyze_weather_data def test_fetch_weather_data_success(): with patch('solution.requests.get') as mock_get: mock_response = Mock() expected_data = { 'list': [ {'dt': 1634140800,...
[ { "docstring": "Fetches the weather data for the specified location.\n\nArgs:\nlocation (str): The location (city name).\n\nReturns:\ndict: The weather data in JSON format.", "function_declaration": "def fetch_weather_data(location):", "function_name": "fetch_weather_data", "parameter_list": "(locat...
[ 1, 0, 0, 0, 1, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nimport json\n\ndef fetch_weather_data(location):\n \"\"\"\n Fetch weather data for the specified location from a mock API.\n \"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "### Weather Data Analyzer\n\nYou are provided with a function to analyze weather data fetched from an API. This function should:\n\n1. Fetch the weather data for a specified location.\n2. Parse the JSON response to extract relevant weather information.\n3. Calculate and display the average ...
0.620366
Algorithm_22310
C
[ "fetch_weather_data", "analyze_weather_data" ]
2
[ [ "analyze_weather_data", "fetch_weather_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
06030dd40be6810b664d51a4cae6fa5646577ccd
ddbc2797719b129fba8ccbf5aba4114d49a595d1
v1.0
complete
Algorithm
Algorithm_15882_C
import threading from typing import List def sum_of_squares(arr: List[int]) -> int: """Computes the sum of squares of the integers in the array.""" return sum(x ** 2 for x in arr) def sum_of_squares_multithreaded(data: List[int], num_threads: int) -> int: """Computes the sum of squares of the integers in ...
import threading def sum_of_squares(arr): """ Computes the sum of squares of the integers in the array. """ return sum(x ** 2 for x in arr) def sum_of_squares_multithreaded(data, num_threads): """ Computes the sum of squares of the integers in the data array using multi-threading. ...
import pytest from solution import sum_of_squares_multithreaded def test_sum_of_squares_empty_list(): assert sum_of_squares_multithreaded([], 4) == 0 def test_sum_of_squares_single_element(): assert sum_of_squares_multithreaded([3], 2) == 9 def test_sum_of_squares_two_even_chunks(): assert sum_of_squares...
[ { "docstring": "Computes the sum of squares of the integers in the array.", "function_declaration": "def sum_of_squares(arr):", "function_name": "sum_of_squares", "parameter_list": "(arr)" }, { "docstring": "Computes the sum of squares of the integers in the data array \nusing multi-threadin...
[ 1, 0, 1, 0, 0, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import threading\n\ndef sum_of_squares(arr):\n \"\"\"\n Returns the sum of squares of all integers in the array.\n \"\"\"\n return sum(x ** 2 for x i...
trial_gpt4o_6
{ "original_instruction": "### Context:\nYou need to optimize a large dataset processing task using multi-threading. Given a list of integers, you will split the list into chunks and compute the sum of squares of the integers in each chunk using multiple threads concurrently. Finally, you will combine the partial res...
0.707353
Algorithm_15882
C
[ "sum_of_squares", "sum_of_squares_multithreaded" ]
2
[ [ "sum_of_squares_multithreaded", "sum_of_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aaeff7024148b2098816de133968c4597f5a6c61
213a08419d0a488a074ade22017f652b8bc77976
v1.0
complete
Algorithm
Algorithm_38361_C
def counting_sort(arr, exp): """ A function to do counting sort of arr[] according to the digit represented by exp. """ pass def radix_sort(arr): """ A function to implement radix sort. Parameters: arr (List[int]): A list of non-negative integers to be sorted. Returns: ...
def counting_sort(arr, exp): """ A function to do counting sort of arr[] according to the digit represented by exp. """ n = len(arr) output = [0] * n # output array count = [0] * 10 # count array to store occurrences of digits (0 to 9) # Store count of occurrences in count[] for i in ...
def test_radix_sort_empty(): assert radix_sort([]) == [] def test_radix_sort_single_element(): assert radix_sort([1]) == [1] def test_radix_sort_sorted_list(): assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_radix_sort_reversed_list(): assert radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4,...
[ { "docstring": "A function to do counting sort of arr[] according to the digit represented by exp.", "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": "A function to implement radix sort.", "function...
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10 # Since we are dealing with digits 0-9\n\n for i in range(n):\n ...
trial_gpt4o_2
{ "original_instruction": "### Coding Assessment Question: Implementing and Using a Radix Sort Algorithm\n\n#### Context\nYou are tasked with improving the performance of a data processing pipeline that involves sorting large lists of non-negative integers. While the default sorting algorithms perform well in general...
0.656078
Algorithm_38361
C
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
false
[]
true
8031e971f9757887cdc8c4ecca92de57d0987ce1
70d7cbf1ee42f24e5d50a4eb9f46d8dc1d621fd9
v1.0
complete
Algorithm
Algorithm_20160_C
### Heap Sort Implementation Implement a function that sorts a list of integers in ascending order using the Heap Sort algorithm. def heapify(arr, n, i): """ Helper function to maintain the heap property of a subtree rooted at index i. n is the size of the heap. """ largest = i # Initialize l...
def heapify(arr, n, i): """ Helper function to maintain the heap property of a subtree rooted at index i. n is the size of the heap. """ largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists...
from solution import heap_sort def test_heap_sort_with_positive_numbers(): assert heap_sort([5, 3, 8, 4, 2]) == [2, 3, 4, 5, 8] def test_heap_sort_with_negative_numbers(): assert heap_sort([-1, -3, -2, -5, -4]) == [-5, -4, -3, -2, -1] def test_heap_sort_with_mixed_numbers(): assert heap_sort([3, -1, 0, -...
[ { "docstring": "Helper function to maintain the heap property of a subtree rooted at index i.\nn is the size of the heap.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Sorts a collection of integers in asce...
[ 0, 0, 1, 0, 0, 1, 0, 0, 1, 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 heap_sort(collection: list[int]) -> list[int]:\n \"\"\"\n Sorts a list of integers in ascending order using the Heap Sort algorithm.\n \"\"\"\n \...
trial_gpt4o_8
{ "original_instruction": "### Heap Sort Implementation Challenge\n\n**Scenario**:\nYou have been recruited as a software engineer by a tech company that requires efficient data organization solutions. One of your first tasks is to develop a reliable sorting algorithm for their system. Given the need for efficiency a...
0.683063
Algorithm_20160
C
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95ca85e34dd66978621b1a407301ffb01fddf8ee
e8b9b55bf30fc26ce67f130c31b30801ffce7d2f
v1.0
complete
Algorithm
Algorithm_45754_C
def matrix_determinant(matrix: list[list[float]]) -> float: """ Calculate the determinant of a square matrix. Validate the input to ensure it is a matrix and square. Args: matrix (list of list of float): A square matrix represented as a list of lists. Returns: float: Determinant of the...
def matrix_determinant(matrix: list[list[float]]) -> float: """ Calculate the determinant of a square matrix. Args: matrix (list of list of float): A square matrix represented as a list of lists. Returns: float: Determinant of the matrix. Raises: ValueError: If the input i...
from solution import matrix_determinant, minor import pytest def test_determinant_2x2_matrix(): assert matrix_determinant([[1, 2], [3, 4]]) == -2.0 def test_determinant_3x3_matrix(): assert matrix_determinant([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) == -306.0 def test_determinant_4x4_matrix(): assert matrix_d...
[ { "docstring": "Calculate the determinant of a square matrix.\n\nArgs:\nmatrix (list of list of float): A square matrix represented as a list of lists.\n\nReturns:\nfloat: Determinant of the matrix.\n\nRaises:\nValueError: If the input is not a matrix or the matrix is not square.", "function_declaration": "...
[ 1, 1, 0, 1, 0, 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": "def matrix_determinant(matrix: list[list[float]]) -> float:\n \"\"\"\n Calculates the determinant of a square matrix.\n \n Args:\n matrix (list of...
trial_gpt4o_9
{ "original_instruction": "### Question: Matrix Determinant Calculator Enhancement\n\nYou are provided with a function that calculates the determinant of a square matrix. The existing implementation can handle 2x2 and 3x3 matrices but needs enhancement for robustness and error handling.\n\n#### Your Task\nEnhance the...
0.473504
Algorithm_45754
C
[ "matrix_determinant", "minor" ]
2
[ [ "matrix_determinant", "minor" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89ba8a6dcca3fedc197434f9281e4b22dd79e22e
1bfcd959affb80a091c862f5d513c67f2c38252f
v1.0
complete
Algorithm
Algorithm_35033_C
import os import requests import coverage import subprocess def report_test_coverage() -> list[dict]: """ Fetches the list of modified Python files in the latest commit and generates a test coverage report for each script. >>> report_test_coverage() [{ "file_path": "script1.py", "coverage_percentage":...
import os import requests import coverage import json import subprocess def get_modified_files(): """ Fetches the list of modified Python files in the latest commit using GitHub API. """ token = os.getenv('GITHUB_TOKEN') repo = os.getenv('GITHUB_REPOSITORY') headers = { 'Authorization'...
import os from unittest.mock import patch, mock_open from solution import get_modified_files, calculate_coverage, report_test_coverage @patch('requests.get') def test_get_modified_files(mock_get): os.environ['GITHUB_TOKEN'] = 'fake_token' os.environ['GITHUB_REPOSITORY'] = 'fake_user/fake_repo' commit_data...
[ { "docstring": "Fetches the list of modified Python files in the latest commit using GitHub API.", "function_declaration": "def get_modified_files():", "function_name": "get_modified_files", "parameter_list": "()" }, { "docstring": "Runs the tests and calculates test coverage for the given P...
[ 0, 0, 0, 1, 0, 1, 1, 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": "import os\nimport requests\nimport coverage\nimport pytest\n\ndef get_modified_files() -> list[str]:\n \"\"\"\n Fetches the list of modified Python files i...
trial_gpt4o_5
{ "original_instruction": "### Coding Question: Implement an Automated Test Coverage Reporter\n\nAs part of your ongoing responsibilities to enhance code quality, you need to create a script that automatically calculates and reports test coverage for each Python script in your project whenever it's modified. This wil...
0.602667
Algorithm_35033
C
[ "get_modified_files", "calculate_coverage", "report_test_coverage" ]
3
[ [ "report_test_coverage", "calculate_coverage" ], [ "report_test_coverage", "get_modified_files" ] ]
2
[]
false
[]
false
pytest
true
[ "coverage", "requests" ]
false
db8599871e3763d5db1b5ff42f165e5c4031928c
2411576567e160165ff47197b54649c018fc058b
v1.0
complete
Algorithm
Algorithm_37147_C
def optimize_delivery_route(destinations: list[tuple[int, int]]) -> tuple[list[int], float]: """Find the shortest possible route starting and ending at the depot using a variation of the Nearest Neighbor Algorithm (NNA). Args: destinations (list[tuple[int, int]]): A list of tuples where each tuple ...
import math def calculate_distance(point1, point2): return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def optimize_delivery_route(destinations): if not destinations: return ([], 0.0) n = len(destinations) visited = [False] * n route = [0] total_distance = 0.0 ...
from solution import optimize_delivery_route def test_optimize_delivery_route_basic(): destinations = [(0, 0), (2, 3), (5, 8), (6, 2), (8, 6), (1, 7)] route, total_distance = optimize_delivery_route(destinations) assert route[0] == 0 and route[-1] == 0 assert isinstance(total_distance, float) asser...
[ { "docstring": null, "function_declaration": "def calculate_distance(point1, point2):", "function_name": "calculate_distance", "parameter_list": "(point1, point2)" }, { "docstring": null, "function_declaration": "def optimize_delivery_route(destinations):", "function_name": "optimize...
[ 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": "import math\nimport random\n\ndef euclidean_distance(p1, p2):\n return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)\n\ndef optimize_delivery_route(desti...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment Question\n\n#### Problem Statement\n\nYou are tasked with implementing a logistics optimization algorithm for a delivery truck. The goal is to minimize the total distance traveled while delivering packages to several destinations. The destinations will be represented b...
0.651983
Algorithm_37147
C
[ "calculate_distance", "optimize_delivery_route" ]
2
[ [ "optimize_delivery_route", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1867b5a772911039da1f17dd0d7ceccda85a523
3bb6ea3386f0ae479c2f8688fd9547cd7152ac10
v1.0
complete
Algorithm
Algorithm_22618_C
import numpy as np import matplotlib.pyplot as plt import requests def collect_dataset(url): """ Collect geolocation data from a given URL. Args: - url (str): The URL to the dataset. Returns: - np.array: The collected dataset as a numpy array. """ response = requests.get(url, timeout=10) ...
import numpy as np import matplotlib.pyplot as plt import requests def collect_dataset(url): response = requests.get(url, timeout=10) lines = response.text.splitlines() data = [] for item in lines[1:]: # Skip the header item = item.split(",") data.append([float(coord) for coord in item...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, compute_inertia, kmeans, elbow_method def test_initialize_centroids(): data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]) centroids = initialize_centroids(data, 2) assert centroids.shape == (2, 2) a...
[ { "docstring": null, "function_declaration": "def collect_dataset(url):", "function_name": "collect_dataset", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def initialize_centroids(dataset, k):", "function_name": "initialize_centroids", "parameter_lis...
[ 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": "import numpy as np\nimport matplotlib.pyplot as plt\nimport requests\n\ndef collect_dataset(url):\n response = requests.get(url, timeout=10)\n lines = resp...
trial_gpt4o_8
{ "original_instruction": "### K-Means Clustering Implementation with Optimal 'K'\n\n**Context**:\nYou are given a dataset containing geolocation information of various incidents such as emergency service calls within a city. You aim to cluster these incidents into different regions using the K-Means clustering algor...
0.6927
Algorithm_22618
C
[ "collect_dataset", "initialize_centroids", "assign_clusters", "update_centroids", "compute_inertia", "kmeans", "elbow_method", "plot_clusters", "main" ]
9
[ [ "elbow_method", "compute_inertia" ], [ "elbow_method", "kmeans" ], [ "kmeans", "assign_clusters" ], [ "kmeans", "initialize_centroids" ], [ "kmeans", "update_centroids" ] ]
5
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "requests" ]
false
3a8772a10fb616b3a333187d8ce8abd783c6d543
b59a04dc687c14075919862d0061f25b85c67fcd
v1.0
complete
Algorithm
Algorithm_1450_C
def find_shifted_index(s: str, shifted: str) -> Optional[int]: """ Returns the index i such that if we shift the characters of s at index i to the front, the resulting string is equal to shifted. If no such index exists, return None. >>> find_shifted_index("hello", "lohel") 3 >>> find_shifted_index("abc...
from typing import Optional def find_shifted_index(s: str, shifted: str) -> Optional[int]: """ Returns the index i such that if we shift the characters of s at index i to the front, the resulting string is equal to shifted. If no such index exists, return None. """ if len(s) != len(shifted): ...
from solution import find_shifted_index, are_rotations def test_find_shifted_index(): assert find_shifted_index("hello", "lohel") == 3 assert find_shifted_index("abcde", "deabc") == 3 assert find_shifted_index("abcd", "bcda") == 1 assert find_shifted_index("abcd", "abcd") == 0 assert find_shifted_i...
[ { "docstring": "Returns the index i such that if we shift the characters of s at index i to the front,\nthe resulting string is equal to shifted. If no such index exists, return None.", "function_declaration": "def find_shifted_index(s, shifted):", "function_name": "find_shifted_index", "parameter_l...
[ 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 typing import Optional\n\ndef find_shifted_index(s: str, shifted: str) -> Optional[int]:\n \"\"\"\n Returns the index i such that if we shift the char...
trial_gpt4o_0
{ "original_instruction": "### Problem Statement\n\nSuppose you are working on string manipulation functions and need to develop utilities to perform specific tasks. Implement the following functions:\n\n1. `find_shifted_index(s: str, shifted: str) -> Optional[int]`: This function takes two strings, `s` and `shifted`...
0.688905
Algorithm_1450
C
[ "find_shifted_index", "are_rotations" ]
2
[ [ "are_rotations", "find_shifted_index" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a29896c4c9720e13b60efe00073dc45af2f4e427
40d8038c4159fc8418657aa22f8bd000dc412788
v1.0
complete
Algorithm
Algorithm_22933_C
def is_sum_of_two_primes(n: int) -> bool: """ Determine if a given integer can be expressed as the sum of exactly two prime numbers. >>> is_sum_of_two_primes(10) True >>> is_sum_of_two_primes(11) False """ pass def sum_of_unique_prime_factors(n: int) -> int: """ Compute the sum of all unique pr...
def is_prime(num): if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 return True def is_sum_of_two_primes(n: in...
from solution import is_sum_of_two_primes, sum_of_unique_prime_factors def test_is_sum_of_two_primes_true_cases(): assert is_sum_of_two_primes(10) == True # 3 + 7 or 5 + 5 assert is_sum_of_two_primes(4) == True # 2 + 2 def test_is_sum_of_two_primes_false_cases(): assert is_sum_of_two_primes(11) == Fals...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def is_sum_of_two_primes(n):", "function_name": "is_sum_of_two_primes", "parameter_list": "(n)" }, { ...
[ 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": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n ...
trial_gpt4o_2
{ "original_instruction": "### Coding Assessment Question\n\nYou are asked to implement two functions that involve examining and working with prime numbers and their sums. You need to validate if a number can be expressed as a sum of exactly two prime numbers, and compute the sum of unique prime factors of a given nu...
0.654043
Algorithm_22933
C
[ "is_prime", "is_sum_of_two_primes", "prime_factors", "sum_of_unique_prime_factors" ]
4
[ [ "is_sum_of_two_primes", "is_prime" ], [ "sum_of_unique_prime_factors", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
578c2eecef29537986e6257be848add5152cfa4b
7a3f58672d9599d3a44ec4efbce5d429ca373a55
v1.0
complete
Algorithm
Algorithm_41892_C
""" Given a list of integers, you need to implement a function to find the k-th smallest element in the list. The function should be able to handle large lists efficiently. ### Function Signature def kth_smallest(arr: List[int], k: int) -> int: pass ### Inputs: * `arr: List[int]`: A list of integers. * `k: int...
from typing import List def quickselect(arr: List[int], left: int, right: int, k: int) -> int: """ Quickselect helper function to find k-th smallest element. """ if left == right: return arr[left] pivot_index = partition(arr, left, right) if k == pivot_index: return ar...
from solution import kth_smallest def test_kth_smallest(): assert kth_smallest([3, 2, 1, 5, 4], 3) == 3 assert kth_smallest([1, 1, 1, 1], 2) == 1 assert kth_smallest([5, 4, 3, 2, 1], 1) == 1 assert kth_smallest([7, 10, 4, 3, 20, 15], 4) == 10 assert kth_smallest([-1, -2, -3, 0], 1) == -3 assert...
[ { "docstring": "Quickselect helper function to find k-th smallest element.", "function_declaration": "def quickselect(arr, left, right, k):", "function_name": "quickselect", "parameter_list": "(arr, left, right, k)" }, { "docstring": "Partition the array and return the pivot index.", "fu...
[ 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 kth_smallest(arr: List[int], k: int) -> int:\n \"\"\"\n Returns the k-th smallest element in the array `arr`.\n Utilizes ...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nGiven a list of integers, you need to implement a function to find the k-th smallest element in the list. The function should be able to handle large lists efficiently. This is to ensure your understanding of efficient selection algorithms like the Quickselect algor...
0.67875
Algorithm_41892
C
[ "quickselect", "partition", "kth_smallest" ]
3
[ [ "kth_smallest", "quickselect" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ba989d50c151745327ffacc5811c88924642549e
d9ebd2bb0842bfd56f7fe688932d8a2846738153
v1.0
complete
Algorithm
Algorithm_699_C
from typing import List, Tuple def rotate_matrix_90_clockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotates the given matrix 90 degrees clockwise. """ pass def matrix_rotation_and_sum(matrix: List[List[int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> int: """ Rota...
from typing import List, Tuple def rotate_matrix_90_clockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotates the given matrix 90 degrees clockwise. """ rows, cols = len(matrix), len(matrix[0]) rotated_matrix = [[0] * rows for _ in range(cols)] for r in range(rows): for c in ra...
from solution import matrix_rotation_and_sum, rotate_matrix_90_clockwise def test_rotate_matrix_90_clockwise(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] rotated = [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] assert rotate_matrix_90_clockwise(matrix) == rot...
[ { "docstring": "Rotates the given matrix 90 degrees clockwise.", "function_declaration": "def rotate_matrix_90_clockwise(matrix):", "function_name": "rotate_matrix_90_clockwise", "parameter_list": "(matrix)" }, { "docstring": "Rotates the matrix 90 degrees clockwise and calculates the sum of...
[ 0, 1, 0, 1, 0, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "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 rotate_matrix_90_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates the matrix 90 degrees cloc...
trial_gpt4o_7
{ "original_instruction": "### Matrix Transformation and Querying\n\nYou are given a matrix of integers. Your task is to implement an algorithm that rotates the matrix 90 degrees clockwise and then calculates the sum of elements in a submatrix defined by two given coordinates.\n\n### Requirements\n\n1. **Function**: ...
0.566543
Algorithm_699
C
[ "rotate_matrix_90_clockwise", "matrix_rotation_and_sum" ]
2
[ [ "matrix_rotation_and_sum", "rotate_matrix_90_clockwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4c9bdf2b4393b981b23cce8508d94e5da9bad7b4
a21c621d92e7a625e1ebeb26820624ff44c5f35f
v1.0
complete
Algorithm
Algorithm_26189_C
def find_prime_sequences(numbers: list[int]) -> list[list[int]]: """ Identify prime number sequences within a list of integers. A prime number sequence is defined as a continuous sublist within the list where all the elements are prime numbers. Sequences consisting of a single prime number should not be includ...
from typing import List def is_prime(n: int) -> bool: 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_prime_sequences(numbers: List[int]) -...
from solution import find_prime_sequences, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(20) == False def test_find_prime_sequences_case1(): numbers = [2, 3, 4, 5, 7, 8, 13, 17, 19, 23...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_prime_sequences(numbers):", "function_name": "find_prime_sequences", "parameter_list": "(numbers)" } ]
[ 1, 1, 0, 1, 1, 0, 1, 1, 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 is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n r...
trial_gpt4o_1
{ "original_instruction": "### Prime Sequence Identification\n\nYou are tasked with creating a function that can identify prime number sequences within a list of integers. A prime number sequence is defined as a continuous sublist within the list where all the elements are prime numbers.\n\n#### Task\nCreate a functi...
0.801651
Algorithm_26189
C
[ "is_prime", "find_prime_sequences" ]
2
[ [ "find_prime_sequences", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a8d2fa1dc779829f499d43107f25a4a3e2377d01
7ecd48e35c9674ce027e123fa2158b6381f12685
v1.0
complete
Algorithm
Algorithm_47763_C
def validate_isbn(isbn: str) -> bool: """ Validates the ISBN number for correctness. The function returns True for valid ISBNs and False for invalid ones. >>> validate_isbn("0-306-40615-2") True >>> validate_isbn("0306406152") True >>> validate_isbn("978-3-16-148410-0") True >>> validate_isb...
def validate_isbn(isbn: str) -> bool: """ Validates the ISBN number for correctness. The function returns True for valid ISBNs and False for invalid ones. """ if not isinstance(isbn, str): raise TypeError(f"Expected string as input, found {type(isbn).__name__}") clean_isbn = isbn.re...
import pytest from solution import validate_isbn def test_validate_isbn_valid_10_digit(): assert validate_isbn("0-306-40615-2") == True assert validate_isbn("0306406152") == True def test_validate_isbn_invalid_10_digit(): assert validate_isbn("0-306-40615-9") == False assert validate_isbn("0306406159"...
[ { "docstring": "Validates the ISBN number for correctness.\nThe function returns True for valid ISBNs and False for invalid ones.", "function_declaration": "def validate_isbn(isbn):", "function_name": "validate_isbn", "parameter_list": "(isbn)" }, { "docstring": "Validates 10-digit ISBN usin...
[ 0, 1, 1, 1, 0, 1, 1, 0, 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 validate_isbn(isbn: str) -> bool:\n \"\"\"\n Validates an ISBN number, either 10 or 13 digits.\n ISBN can include dashes or spaces; the function wil...
trial_gpt4o_2
{ "original_instruction": "### Scenario\nA library management system requires a feature to automatically categorize books based on their ISBN number. An ISBN (International Standard Book Number) is either a 10-digit or 13-digit number that uniquely identifies a book. The 10-digit ISBN has a modulo 11 checksum, while ...
0.51721
Algorithm_47763
C
[ "validate_isbn", "validate_isbn_10", "validate_isbn_13" ]
3
[ [ "validate_isbn", "validate_isbn_10" ], [ "validate_isbn", "validate_isbn_13" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7e96f2c00d22d7630c220eedac4a28b6c40c1100
9a7c0a02c36eea7ab8df0a99adabfdcbb1dfe7e6
v1.0
complete
Algorithm
Algorithm_47931_C
from typing import List class DataIterator: def __init__(self, file_path: str, chunk_size: int): self.file_path = file_path self.chunk_size = chunk_size def __iter__(self): """Iterates through the file in chunks of lines.""" with open(self.file_path, 'r') as file: ...
import os from typing import List class DataIterator: def __init__(self, file_path: str, chunk_size: int): self.file_path = file_path self.chunk_size = chunk_size def __iter__(self): with open(self.file_path, 'r') as file: chunk = [] for line in file: ...
import os from solution import DataIterator, process_data, process_large_file def test_data_iterator(): test_file_path = 'test_input.txt' with open(test_file_path, 'w') as test_file: for i in range(10): test_file.write(f"line {i}\n") iterator = DataIterator(test_file_path, 3) ...
[]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\nclass DataIterator:\n def __init__(self, file_path: str, chunk_size: int):\n self.file_path = file_path\n self.chunk_...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement:\nImplement an advanced data processing pipeline that can efficiently handle large datasets. Your task is to create a framework to process data in a memory-efficient manner. This involves implementing a custom data iterator and integrating it with a basic data processi...
0.477581
Algorithm_47931
C
[ "process_data", "process_large_file" ]
2
[ [ "process_large_file", "process_data" ] ]
1
[ "process_data" ]
false
[ "DataIterator" ]
true
pytest
true
[]
true
b5a64dd2942ad90d994bbe9a7d8edc1632118edb
f4c1ed0cde746a661f0f03a9f7b0f3b74ca371eb
v1.0
complete
Algorithm
Algorithm_39954_C
def radix_sort(unsorted_collection: list[int]) -> list[int]: """ Sorts a list of non-negative integers in ascending order using the radix sort algorithm. Parameters: unsorted_collection (list[int]): A list of non-negative integers that need to be sorted. Returns: list[int]: A sorted li...
def radix_sort(unsorted_collection: list[int]) -> list[int]: if len(unsorted_collection) == 0: return unsorted_collection # Find the maximum number to determine the maximum number of digits max_number = max(unsorted_collection) # Initialize the exponent to 1 (10^0) exp = 1 while m...
from solution import radix_sort def test_radix_sort_example(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_dup_numbers(): assert radix_sort([1, 4, 1, 2, 7, 5, 2]) == [1, 1, 2, 2, 4, 5, 7] def test_radix_sort_large_numbers(): assert radix_s...
[ { "docstring": null, "function_declaration": "def radix_sort(unsorted_collection):", "function_name": "radix_sort", "parameter_list": "(unsorted_collection)" }, { "docstring": null, "function_declaration": "def counting_sort(collection, exp):", "function_name": "counting_sort", "...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def radix_sort(unsorted_collection: list[int]) -> list[int]:\n RADIX = 10 # We are working with base 10 numbers\n \n # Find the maximum number to figur...
trial_gpt4o_9
{ "original_instruction": "### Radix Sort Algorithm Assessment\n\n#### Context\nYou have been provided with a list of non-negative integers, and you need to sort the list in ascending order efficiently. Your task is to implement the radix sort algorithm to achieve this.\n\n#### Task\nWrite a function `radix_sort` tha...
0.646976
Algorithm_39954
C
[ "radix_sort", "counting_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89cb639e7c82cf548991601f106a5ca04d20da01
5301ef3d0bc1c3bfab5cfb61f2a2cf7fd4dd498e
v1.0
complete
Algorithm
Algorithm_6330_C
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error from typing import Tuple def preprocess_data(df): """ Preprocess the dataframe: handle missing values and encode categorical variables. ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error def preprocess_data(df): """ Preprocess the dataframe: handle missing values and encode categorical variables. """ # Handle missing ...
import pytest from sklearn.linear_model import LinearRegression from solution import build_and_train_linear_regression # Create a sample DataFrame for testing def create_sample_data(): data = { 'Feature1': [1, 2, 3, 4, 5], 'Feature2': ['A', 'B', 'A', 'B', 'A'], 'Price': [100, 150, 200, 250,...
[ { "docstring": "Preprocess the dataframe: handle missing values and encode categorical variables.", "function_declaration": "def preprocess_data(df):", "function_name": "preprocess_data", "parameter_list": "(df)" }, { "docstring": "Build and train a linear regression model and evaluate its p...
[ 0, 1, 0, 1, 1, 0, 1, 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": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_ab...
trial_gpt4o_9
{ "original_instruction": "### House Price Prediction using Linear Regression\n\n#### Context\n\nYou are given a dataset containing various features of houses and their corresponding prices. Your task is to predict the house prices based on the given features using a Linear Regression model.\n\n#### Task\n\nImplement...
0.796178
Algorithm_6330
C
[ "preprocess_data", "build_and_train_linear_regression" ]
2
[ [ "build_and_train_linear_regression", "preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
c4c45202a0ab5f6c2c51e22d476835f853c602ee
318477fed464e9ade5d9aa7d31865a0ce32fca98
v1.0
complete
Algorithm
Algorithm_7450_C
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sort_linked_list(head: ListNode) -> ListNode: """Sort a singly linked list using merge sort. Args: head (ListNode): The head of the linked list. Returns: ListNode: The head of the sor...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge_sort(head: ListNode) -> ListNode: if not head or not head.next: return head def split_list(node): slow = node fast = node.next while fast and fast.next: ...
from solution import ListNode, sort_linked_list def create_linked_list(arr): if not arr: return None head = ListNode(arr[0]) current = head for val in arr[1:]: current.next = ListNode(val) current = current.next return head def linked_list_to_list(head): result = [] ...
[]
[ 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": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef sort_linked_list(head: ListNode) -> ListNode:...
trial_gpt4o_9
{ "original_instruction": "**Problem Statement:**\n\nYou are given a singly linked list where each node contains an integer value. Your task is to implement a function that sorts the list using merge sort. The linked list should be sorted in non-decreasing order.\n\n### Function Signature\n```python\nclass ListNode:\...
0.520472
Algorithm_7450
C
[ "merge_sort", "sort_linked_list" ]
2
[ [ "sort_linked_list", "merge_sort" ] ]
1
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
e68aeee4c77753472459400fb545b2ca64832230
843ca9a2dc0c99e4dcd041e1c1eae0872e3cf5b4
v1.0
complete
Algorithm
Algorithm_22877_C
import heapq class Graph: def __init__(self): self.edges = {} def add_edge(self, node1, node2, weight): if node1 not in self.edges: self.edges[node1] = [] if node2 not in self.edges: self.edges[node2] = [] self.edges[node1].append((node2, weight)) ...
import heapq class Graph: def __init__(self): self.edges = {} def add_edge(self, node1, node2, weight): if node1 not in self.edges: self.edges[node1] = [] if node2 not in self.edges: self.edges[node2] = [] self.edges[node1].append((node2, weight)) ...
from solution import Graph, a_star_search def simple_heuristic(node, goal): return abs(ord(goal) - ord(node)) def test_path_exists(): graph = Graph() graph.add_edge('A', 'B', 1) graph.add_edge('B', 'C', 2) graph.add_edge('A', 'D', 4) graph.add_edge('C', 'D', 1) graph.add_edge('C', 'E', 3) ...
[]
[ 1, 1, 1, 1, 0, 1, 0, 1, 0, 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 heapq\n\nclass Graph:\n def __init__(self):\n self.edges = {}\n \n def add_edge(self, node1, node2, weight):\n if node1 not in self...
trial_gpt4o_9
{ "original_instruction": "### Question: Implement an A* Search Algorithm with Custom Heuristic\n\nYou are assigned to implement the A* Search Algorithm to find the shortest path from a start node to a goal node in a given weighted graph. Additionally, the algorithm should accept a custom heuristic function to potent...
0.625512
Algorithm_22877
C
[ "a_star_search", "reconstruct_path" ]
2
[ [ "a_star_search", "reconstruct_path" ] ]
1
[]
false
[ "Graph" ]
true
pytest
true
[]
true
2a081c95438febb25feaf07c01f4ecd30e06faf3
6c854a664242ee4c2e78125689c722f5154985f5
v1.0
complete
Algorithm
Algorithm_24157_C
from typing import List def student_gpa(grades: List[float]) -> float: """ Calculate a student's GPA based on their grades. Args: grades (List[float]): A list of the student's grades in various subjects. Returns: float: The calculated GPA for the student. >>> student_gpa([3.5, 2.7, 4....
from typing import List def student_gpa(grades: List[float]) -> float: if not grades: raise ValueError("Grades list cannot be empty.") for grade in grades: if not 0.0 <= grade <= 4.0: raise ValueError(f"Grade {grade} is out of acceptable range 0.0 to 4.0.") return sum(grades) / ...
def test_student_gpa(): assert student_gpa([3.5, 2.7, 4.0, 3.8]) == 3.5 assert student_gpa([4.0, 4.0, 4.0, 4.0]) == 4.0 assert student_gpa([0.0, 0.0, 0.0, 0.0]) == 0.0 assert student_gpa([3.0, 3.0, 3.0]) == 3.0 def test_student_gpa_invalid_grades(): try: student_gpa([4.5]) except ValueE...
[ { "docstring": null, "function_declaration": "def student_gpa(grades):", "function_name": "student_gpa", "parameter_list": "(grades)" }, { "docstring": null, "function_declaration": "def class_average_gpa(all_grades):", "function_name": "class_average_gpa", "parameter_list": "(al...
[ 0, 1, 0, 1, 0, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "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 student_gpa(grades: List[float]) -> float:\n if not grades:\n raise ValueError(\"Grades list cannot be empty.\")\n \n...
trial_gpt4o_8
{ "original_instruction": "### Objective\n\nGiven a set of students with their grades in different subjects, write a function to calculate each student's GPA and the class average GPA. Assume each subject carries the same weight.\n\n### Function Implementation\n\n#### Function 1: Calculate Student GPA\n\n- **Function...
0.757683
Algorithm_24157
C
[ "student_gpa", "class_average_gpa" ]
2
[ [ "class_average_gpa", "student_gpa" ] ]
1
[]
false
[]
false
pytest
false
[]
true
4359ed52f413f252c5fb1a9583ed4ad6d034da2e
2db12976af82fbdd300bb5a80bc46b7e8435d643
v1.0
complete
Algorithm
Algorithm_10812_C
def count_frequencies(data: list[int]) -> dict[int, int]: """ Given a list of integers, returns a dictionary with elements as keys and their frequencies as values. >>> count_frequencies([1, 2, 2, 3, 3, 3, 4, 4]) {1: 1, 2: 2, 3: 3, 4: 2} >>> count_frequencies([10, 20, 10, 30, 20, 10]) {10: 3, 20: 2, ...
def count_frequencies(data): """ Given a list of integers, returns a dictionary with elements as keys and their frequencies as values. """ frequency_dict = {} for element in data: if element in frequency_dict: frequency_dict[element] += 1 else: frequency_dict[...
def test_count_frequencies_empty_list(): assert count_frequencies([]) == {} def test_count_frequencies_single_element(): assert count_frequencies([5]) == {5: 1} def test_count_frequencies_multiple_elements(): assert count_frequencies([1, 2, 2, 3, 3, 3, 4, 4]) == {1: 1, 2: 2, 3: 3, 4: 2} assert count_f...
[ { "docstring": "Given a list of integers, returns a dictionary with elements as keys and their frequencies as values.", "function_declaration": "def count_frequencies(data):", "function_name": "count_frequencies", "parameter_list": "(data)" }, { "docstring": "Given a list of integers, return...
[ 1, 1, 1, 1, 1, 0, 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 count_frequencies(data):\n \"\"\"\n Returns a dictionary with the elements of the list as keys and their frequencies as values.\n \"\"\"\n freque...
trial_gpt4o_9
{ "original_instruction": "### Frequency Counter and Maximum Occurrence\n\n#### Context:\nAnalyzing the frequency of elements in a dataset is a common task in data analysis and programming, serving as the basis for various applications like mode finding, trend analysis, and more.\n\n#### Problem:\n1. **Frequency Coun...
0.748448
Algorithm_10812
C
[ "count_frequencies", "find_max_occurrence" ]
2
[ [ "find_max_occurrence", "count_frequencies" ] ]
1
[]
false
[]
false
pytest
false
[]
true
f225ab89a2d1fc792ec5c03ef08bbd3c16767105
5227205827dbe1b2704261db7f9d2fb94c7662c3
v1.0
complete
Algorithm
Algorithm_3275_C
def calculate_average_scores(test_scores: dict) -> dict: """ Calculate the average score for each student. >>> test_scores = { >>> "Alice": [95, 85, 92], >>> "Bob": [78, 81, 86], >>> "Charlie": [55, 60, 65], >>> "David": [99, 100, 98], >>> "Eve": [45, 50, 47] >>> } ...
def calculate_average_scores(test_scores: dict) -> dict: """ Calculate the average score for each student. """ average_scores = {} for student, scores in test_scores.items(): average_scores[student] = round(sum(scores) / len(scores), 2) return average_scores def highest_average_score(te...
from solution import calculate_average_scores, highest_average_score, group_by_grades def test_calculate_average_scores(): test_scores = { "Alice": [95, 85, 92], "Bob": [78, 81, 86], "Charlie": [55, 60, 65], "David": [99, 100, 98], "Eve": [45, 50, 47] } expected_outp...
[ { "docstring": "Calculate the average score for each student.", "function_declaration": "def calculate_average_scores(test_scores):", "function_name": "calculate_average_scores", "parameter_list": "(test_scores)" }, { "docstring": "Determine the student with the highest average score.", ...
[ 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 calculate_average_scores(test_scores: dict) -> dict:\n \"\"\"\n Calculates the average score for each student.\n \"\"\"\n average_scores = {}\n ...
trial_gpt4o_7
{ "original_instruction": "### Problem Statement:\n\nYou are given a list of student test scores in the form of a dictionary, where the keys are student names and the values are lists of test scores. Your task is to implement a set of functions to perform the following operations:\n\n1. Calculate the average score fo...
0.742023
Algorithm_3275
C
[ "calculate_average_scores", "highest_average_score", "group_by_grades" ]
3
[ [ "highest_average_score", "calculate_average_scores" ] ]
1
[]
false
[]
false
pytest
true
[]
true
608d307926c44ddf32bd199a6f94ea56fc5b62f2
adf3cd9129a3594ee29b77f07ec0f6a4dc8fa19c
v1.0
complete
Algorithm
Algorithm_14913_C
from typing import List from math import gcd from functools import reduce def compute_lcm(arr: List[int]) -> int: """ Compute the Least Common Multiple (LCM) of an array of positive integers. >>> compute_lcm([2, 7, 3, 9, 4]) == 252 >>> compute_lcm([5, 10, 20]) == 20 >>> compute_lcm([1, 1, 1]) == 1 ...
from typing import List from math import gcd from functools import reduce def lcm(a, b): return abs(a * b) // gcd(a, b) def compute_lcm(arr: List[int]) -> int: return reduce(lcm, arr)
from solution import compute_lcm def test_single_element(): assert compute_lcm([5]) == 5 assert compute_lcm([10]) == 10 def test_multiple_elements(): assert compute_lcm([2, 7, 3, 9, 4]) == 252 assert compute_lcm([5, 10, 20]) == 20 assert compute_lcm([1, 1, 1]) == 1 assert compute_lcm([3, 15, 2...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def compute_lcm(arr):", "function_name": "compute_lcm", "parameter_list": "(arr)" } ]
[ 1, 0, 1, 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 math\nfrom functools import reduce\nfrom typing import List\n\ndef lcm(a, b):\n return abs(a * b) // math.gcd(a, b)\n\ndef compute_lcm(arr: List[int]) ...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment Question\n\n#### Scenario:\nYou're working with a database system and often need to calculate the Least Common Multiple (LCM) of large sets of integers. This is particularly important for synchronizing processes running at different intervals. You need to create a func...
0.663466
Algorithm_14913
C
[ "lcm", "compute_lcm" ]
2
[ [ "compute_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8d868654929afc2ab27ce290e2777384dff46ff0
798592403212d07009529273f5c7d336074f1dc5
v1.0
complete
Algorithm
Algorithm_30462_C
import requests import statistics from datetime import datetime def fetch_stock_data(api_url: str, ticker_symbol: str, start_date: str, end_date: str) -> list: """ Fetch stock data from the mock API """ params = { 'ticker': ticker_symbol, 'start': start_date, 'end': end_date ...
import requests import statistics from datetime import datetime def fetch_stock_data(api_url: str, ticker_symbol: str, start_date: str, end_date: str) -> list: """ Fetch stock data from the mock API. """ params = { 'ticker': ticker_symbol, 'start': start_date, 'end': end_date ...
import pytest from unittest.mock import patch from solution import fetch_stock_data, stock_analysis fake_api_url = "https://api.mockstockdata.com/historical" fake_ticker = "AAPL" fake_start_date = "2021-01-01" fake_end_date = "2021-12-31" fake_data = [ {"date": "2021-01-01", "open": 130.0, "close": 132.0, "high"...
[ { "docstring": "Fetch stock data from the mock API.", "function_declaration": "def fetch_stock_data(api_url, ticker_symbol, start_date, end_date):", "function_name": "fetch_stock_data", "parameter_list": "(api_url, ticker_symbol, start_date, end_date)" }, { "docstring": "Fetches stock prices...
[ 0, 1, 0, 1, 1, 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 requests\nimport statistics\nfrom datetime import datetime\n\ndef fetch_stock_data(api_url: str, ticker_symbol: str, start_date: str, end_date: str) -> di...
trial_gpt4o_9
{ "original_instruction": "### Stock Price Analyzer\n\nYou have been provided with a function that fetches historical stock prices for the company of your choice from a mock API. The task is to enhance the functionality to compute various stock metrics.\n\n## Requirements\n1. **Function Implementation**:\n - Imple...
0.623473
Algorithm_30462
C
[ "fetch_stock_data", "stock_analysis" ]
2
[ [ "stock_analysis", "fetch_stock_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
13a20b5b7477f775906ebd6b16ceb8583ec68c96
31f4f44ad9e6795fbac27d24d3d052834b27c60b
v1.0
complete
Algorithm
Algorithm_17231_C
import logging from typing import List, Dict def send_emails_batch(users: List[Dict[str, str]], batch_size: int, email_content: str) -> None: """ Send emails in batches of specified size with personalized content. :param users: List of user dictionaries with 'email' and 'name' keys. :param batch_size: Numbe...
import smtplib from typing import List, Dict import logging # Configure logging to capture email failures logging.basicConfig(filename='email_failures.log', level=logging.ERROR) def send_individual_email(to_email: str, content: str) -> None: # This function mocks the actual email sending process. # Replace th...
from solution import send_emails_batch class MockSMTPException(Exception): pass # Mocking the send_individual_email function within the test file def send_individual_email(to_email: str, content: str) -> None: if 'fail' in to_email: raise MockSMTPException("Simulated email sending failure") def test_...
[ { "docstring": null, "function_declaration": "def send_individual_email(to_email, content):", "function_name": "send_individual_email", "parameter_list": "(to_email, content)" }, { "docstring": "Send emails in batches of specified size with personalized content.\n\n:param users: List of user...
[ 1, 1, 1, 1, 0, 0, 1, 0, 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": "import smtplib\nimport logging\n\nlogging.basicConfig(level=logging.ERROR, filename=\"email_failures.log\", filemode=\"w\")\n\ndef send_email(email, content):\n ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Context:\nYou are working on a customer relationship management (CRM) system that needs to send personalized email campaigns to a large number of users. To improve the system's efficiency, you are tasked with implementing a batch processing feature tha...
0.739368
Algorithm_17231
C
[ "send_individual_email", "send_emails_batch" ]
2
[ [ "send_emails_batch", "send_individual_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eac2f31ecdf2f0e4d3726a4b89b69d481bd917d6
dea1336ff2b464f035f4f8770a971a41770e0317
v1.0
complete
Algorithm
Algorithm_3966_C
import numpy as np from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from scipy.stats import zscore from typing import List def random_forest_predictor(dates: List[int], total_sales: List[int]) -> float: """ Random Forest Prediction model. Predicts sales for the next day based on hi...
import numpy as np from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from scipy.stats import zscore def random_forest_predictor(dates, total_sales): model = RandomForestRegressor() dates = np.array(dates).reshape(-1, 1) model.fit(dates, total_sales) next_day = [[dates[-1, 0]...
from solution import random_forest_predictor, gradient_boosting_predictor, z_score_checker, stock_quality_checker def test_random_forest_predictor(): dates = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] total_sales = [20, 25, 30, 35, 40, 45, 30, 50, 55, 60] prediction = random_forest_predictor(dates, total_sales) a...
[ { "docstring": null, "function_declaration": "def random_forest_predictor(dates, total_sales):", "function_name": "random_forest_predictor", "parameter_list": "(dates, total_sales)" }, { "docstring": null, "function_declaration": "def gradient_boosting_predictor(dates, total_sales):", ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 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 sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nimport numpy as np\nfrom scipy import stats\n\ndef random_forest_predictor(dates, ...
trial_gpt4o_7
{ "original_instruction": "### Coding Challenge\n\nYou are developing an inventory management system for an online bookstore. The system needs to predict the future sales of books based on historical sales data using ensemble modeling and perform quality checks for stock replenishment decisions.\n\n#### Requirements:...
0.639102
Algorithm_3966
C
[ "random_forest_predictor", "gradient_boosting_predictor", "z_score_checker", "stock_quality_checker" ]
4
[ [ "stock_quality_checker", "gradient_boosting_predictor" ], [ "stock_quality_checker", "random_forest_predictor" ], [ "stock_quality_checker", "z_score_checker" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
c979c8cac2e3c13f48140675298e8a9018c6ebff
20384625fce901fb354ca735c9cdfebf7dd869ed
v1.0
complete
Algorithm
Algorithm_24507_C
def polynomial_function(coefficients, x): """ Evaluate the polynomial at a given x value. """ def polynomial_derivative(coefficients, x): """ Evaluate the derivative of the polynomial at a given x value. """ def newtons_method(coefficients, initial_guess, tolerance, max_iterations): """ ...
def polynomial_function(coefficients, x): return sum(c * x**i for i, c in enumerate(reversed(coefficients))) def polynomial_derivative(coefficients, x): return sum(i * c * x**(i-1) for i, c in enumerate(reversed(coefficients)) if i != 0) def newtons_method(coefficients, initial_guess, tolerance, max_iteration...
from solution import newtons_method def test_newtons_method_simple(): # Polynomial: x^2 - 2 coefficients = [1, 0, -2] assert abs(newtons_method(coefficients, 1, 0.0001, 1000) - 1.4142135623730951) < 0.0001 def test_newtons_method_cubic(): # Polynomial: x^3 - x - 2 coefficients = [1, 0, -1, -2] ...
[ { "docstring": null, "function_declaration": "def polynomial_function(coefficients, x):", "function_name": "polynomial_function", "parameter_list": "(coefficients, x)" }, { "docstring": null, "function_declaration": "def polynomial_derivative(coefficients, x):", "function_name": "pol...
[ 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 polynomial_function(coefficients, x):\n \"\"\"\n Calculate the polynomial value for the given x.\n\n :param coefficients: List of coefficients for t...
trial_gpt4o_6
{ "original_instruction": "### Coding Assessment Question: Polynomial Root Finder Using Newton's Method\n\n#### Background\nNewton's Method (also known as the Newton-Raphson method) is an iterative root-finding algorithm that produces successively better approximations to the root (or zero) of a real-valued function....
0.693976
Algorithm_24507
C
[ "polynomial_function", "polynomial_derivative", "newtons_method" ]
3
[ [ "newtons_method", "polynomial_derivative" ], [ "newtons_method", "polynomial_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c64ddb88737a9c8438f5c2b1b0bc5e1d61270dd2
393d4c990ed2ea9d5c795f4c741c4f78efb369cb
v1.0
complete
Algorithm
Algorithm_29575_C
def matrix_multiply(A: list[list[int]], B: list[list[int]]) -> list[list[int]]: """ Multiplies two 2x2 matrices A and B. >>> matrix_multiply([[1, 1], [1, 0]], [[1, 1], [1, 0]]) [[2, 1], [1, 1]] """ def matrix_exponentiate(matrix: list[list[int]], power: int) -> list[list[int]]: """ Calculates...
def matrix_multiply(A: list[list[int]], B: list[list[int]]) -> list[list[int]]: """ Multiplies two 2x2 matrices A and B. """ return [ [ A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1] ], [ A[1][0] * B[0][0] + A[1][1...
from solution import matrix_multiply, matrix_exponentiate, fib def test_matrix_multiply(): A = [[1, 1], [1, 0]] B = [[1, 1], [1, 0]] expected = [[2, 1], [1, 1]] assert matrix_multiply(A, B) == expected def test_matrix_exponentiate(): matrix = [[1, 1], [1, 0]] power = 2 expected = [[2, 1], ...
[ { "docstring": "Multiplies two 2x2 matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Calculates matrix raised to a power using exponentiation by squaring.", "function_declaration": "...
[ 1, 0, 0, 1, 0, 1, 1, 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": "def matrix_multiply(A, B):\n return [\n [A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[0][1]*B[1][1]],\n [A[1][0]*B[0][0] + A[1][1]*B[1...
trial_gpt4o_9
{ "original_instruction": "### Fibonacci Sequence with Matrix Exponentiation\n\nYou are required to implement an efficient algorithm to find the Nth number in the Fibonacci sequence using matrix exponentiation.\n\n### Task\n\n1. Implement the `matrix_multiply` function to multiply two 2x2 matrices.\n2. Implement the ...
0.753028
Algorithm_29575
C
[ "matrix_multiply", "matrix_exponentiate", "fib" ]
3
[ [ "fib", "matrix_exponentiate" ], [ "matrix_exponentiate", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7231c05424bf9c75135682d876cb2b93c35b3128
15f294ec71f93f7be637d74547eadec8a3ee5287
v1.0
complete
Algorithm
Algorithm_36625_C
from typing import Tuple def event_overlap(event1: Tuple[str, str], event2: Tuple[str, str]) -> int: """Calculate the overlap duration in minutes between two events. Args: event1 (Tuple[str, str]): A tuple containing the start and end times of the first event ("HH:MM", "HH:MM"). event2 (Tuple[...
from typing import Tuple def time_to_minutes(time: str) -> int: """Convert time in "HH:MM" format to minutes since midnight.""" hours, minutes = map(int, time.split(":")) return hours * 60 + minutes def event_overlap(event1: Tuple[str, str], event2: Tuple[str, str]) -> int: """Calculate the overlap du...
from solution import event_overlap def test_event_overlap_with_no_overlap(): assert event_overlap(("09:00", "10:00"), ("10:00", "11:00")) == 0 def test_event_overlap_with_partial_overlap(): assert event_overlap(("10:00", "12:30"), ("11:00", "13:00")) == 90 assert event_overlap(("14:00", "15:00"), ("13:30"...
[ { "docstring": "Convert time in \"HH:MM\" format to minutes since midnight.", "function_declaration": "def time_to_minutes(time):", "function_name": "time_to_minutes", "parameter_list": "(time)" }, { "docstring": "Calculate the overlap duration in minutes between two events.", "function_...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import Tuple\n\ndef time_to_minutes(time: str) -> int:\n hours, minutes = map(int, time.split(\":\"))\n return hours * 60 + minutes\n\ndef even...
trial_gpt4o_9
{ "original_instruction": "### Event Time Overlap\n\nYou are creating a function to determine the overlapping duration between two events. Each event is characterized by a start time and an end time.\n\nThe times are given in 24-hour format (HH:MM), and you need to implement a function that returns the total overlapp...
0.600778
Algorithm_36625
C
[ "time_to_minutes", "event_overlap" ]
2
[ [ "event_overlap", "time_to_minutes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c1b5dfb49ffd8eea4c7837e1ebf6fe176f82ba70
e7a736b7ce31323b2b60a3ae5724acc4b4391858
v1.0
complete
Algorithm
Algorithm_34783_C
from typing import List def longest_common_prefix(strs: List[str]) -> str: """ Find the longest common prefix among a list of strings using Divide and Conquer approach. >>> longest_common_prefix(["flower", "flow", "flight"]) 'fl' >>> longest_common_prefix(["dog", "racecar", "car"]) '' >>> longe...
from typing import List def common_prefix(left: str, right: str) -> str: min_length = min(len(left), len(right)) for i in range(min_length): if left[i] != right[i]: return left[:i] return left[:min_length] def longest_common_prefix_helper(strs: List[str], l: int, r: int) -> str: if...
from solution import longest_common_prefix def test_common_cases(): assert longest_common_prefix(["flower","flow","flight"]) == "fl" assert longest_common_prefix(["dog","racecar","car"]) == "" assert longest_common_prefix(["interspecies","interstellar","interstate"]) == "inters" def test_edge_cases(): ...
[ { "docstring": null, "function_declaration": "def common_prefix(left, right):", "function_name": "common_prefix", "parameter_list": "(left, right)" }, { "docstring": null, "function_declaration": "def longest_common_prefix_helper(strs, l, r):", "function_name": "longest_common_prefix...
[ 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 common_prefix(str1: str, str2: str) -> str:\n min_length = min(len(str1), len(str2))\n for i in range(min_length):\n ...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nYou have been given the task of improving the performance of string comparison operations within a dataset containing various strings. Your goal is to efficiently find the longest common prefix shared among a list of strings using a Divide and Conquer approach. This...
0.772209
Algorithm_34783
C
[ "common_prefix", "longest_common_prefix_helper", "longest_common_prefix" ]
3
[ [ "longest_common_prefix", "longest_common_prefix_helper" ], [ "longest_common_prefix_helper", "common_prefix" ] ]
2
[]
false
[]
false
pytest
true
[]
true
00762a5563c8350c7fd787a1bfdc0eb966d42705
9f886b12ecff2cdb01293c15caa62a9c787847d0
v1.0
complete
Algorithm
Algorithm_2968_C
import asyncio import websockets from websockets import WebSocketServerProtocol connected_clients = set() async def register_client(client: WebSocketServerProtocol): """Register a new client to the set of connected clients""" connected_clients.add(client) print(f"{client.remote_address} connected") async...
import asyncio import websockets from websockets import WebSocketServerProtocol connected_clients = set() async def register_client(client: WebSocketServerProtocol): connected_clients.add(client) print(f"{client.remote_address} connected") async def unregister_client(client: WebSocketServerProtocol): con...
import pytest import asyncio import websockets from solution import main, connected_clients from websockets import connect @pytest.mark.asyncio async def test_server_accepts_client_connections(): server = asyncio.create_task(main()) await asyncio.sleep(1) # Allow server to start async with connect("ws://...
[]
[ 1, 1, 1, 1, 0, 1, 1, 0, 0, 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 asyncio\nimport websockets\nfrom websockets import WebSocketServerProtocol\n\nconnected_clients = set()\n\nasync def register_client(client: WebSocketServ...
trial_gpt4o_0
{ "original_instruction": "### Real-time Chat Server Implementation\n\nCreate a simple real-time chat server using WebSockets. The server should support multiple clients and broadcast messages to all connected clients. Below are the requirements:\n\n1. **Handle Client Connections**: Accept incoming client connections...
0.574979
Algorithm_2968
C
[ "register_client", "unregister_client", "broadcast_message", "handle_client", "main" ]
5
[ [ "handle_client", "broadcast_message" ], [ "handle_client", "register_client" ], [ "handle_client", "unregister_client" ] ]
3
[]
false
[]
false
pytest
true
[ "websockets" ]
false
1ae51024cb04eadb537dfb8fc69bfe3c1206852f
170acd41a47a7446c1664e5187216bde083d37af
v1.0
complete
Algorithm
Algorithm_38435_C
def merge_sort(arr: list[int]) -> list[int]: """ Sorts a list of integers using the Merge Sort algorithm. Args: arr (list[int]): A list of integers to be sorted. Returns: list[int]: A new list with the sorted integers. """ pass def binary_search(arr: list[int], target: int) ->...
def merge_sort(arr: list[int]) -> list[int]: """ Sorts a list of integers using the Merge Sort algorithm. Args: arr (list[int]): A list of integers to be sorted. Returns: list[int]: A new list with the sorted integers. """ if len(arr) <= 1: return arr mid = len...
from solution import merge_sort, binary_search def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_two_elements(): assert merge_sort([2, 1]) == [1, 2] def test_merge_sort_multiple_elements(): assert merge_so...
[ { "docstring": "Sorts a list of integers using the Merge Sort algorithm.\n\nArgs:\narr (list[int]): A list of integers to be sorted.\n\nReturns:\nlist[int]: A new list with the sorted integers.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)"...
[ 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 if len(arr) <= 1:\n return arr\n \n # Split the array into two halves\n mid = len(arr) // 2\n left_half = merge_sort...
trial_gpt4o_9
{ "original_instruction": "### Sorting and Searching Using Merge Sort\n\n**Context**: You are handling a large dataset and need to efficiently sort and search the dataset to find specific elements. Using the Merge Sort algorithm ensures that the sort operation is performed efficiently. Once sorted, you will also impl...
0.581766
Algorithm_38435
C
[ "merge_sort", "merge", "binary_search" ]
3
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bdecb1d1c0ed06bd0839e0325441853181c01d41
981546f61658b3da302bc4b3700e0a63b9801124
v1.0
complete
Algorithm
Algorithm_6497_C
from typing import List def calculate_waiting_times(duration_times: List[int]) -> List[int]: """Computes waiting times for the processes based on their duration times sorted in ascending order. >>> calculate_waiting_times([3, 6, 7, 8]) [0, 3, 9, 16] """ def calculate_turnaround_times(duration_time...
from typing import List def calculate_waiting_times(duration_times: List[int]) -> List[int]: """ Computes waiting times for the processes based on their duration times sorted in ascending order. """ n = len(duration_times) waiting_times = [0] * n for i in range(1, n): waiting_times...
import pytest from solution import ( calculate_waiting_times, calculate_turnaround_times, calculate_average_turnaround_time, calculate_average_waiting_time, ) def test_calculate_waiting_times(): duration_times = [3, 6, 7, 8] expected_waiting_times = [0, 3, 9, 16] assert calculate_waiting_ti...
[ { "docstring": "Computes waiting times for the processes based on their duration times sorted in ascending order.", "function_declaration": "def calculate_waiting_times(duration_times):", "function_name": "calculate_waiting_times", "parameter_list": "(duration_times)" }, { "docstring": "Comp...
[ 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 calculate_waiting_times(duration_times):\n \"\"\"\n Computes waiting times for the processes based on their duration times sorted in ascending order.\n...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment: Implement Shortest Job First Scheduling Algorithm\n\n#### Context\nYou are working on an operating system simulator featuring job scheduling algorithms. Another common and efficient algorithm used for scheduling is the Shortest Job First (SJF) scheduling algorithm. Th...
0.601986
Algorithm_6497
C
[ "calculate_waiting_times", "calculate_turnaround_times", "calculate_average_turnaround_time", "calculate_average_waiting_time", "display_process_information", "sjf_scheduling" ]
6
[ [ "display_process_information", "calculate_average_turnaround_time" ], [ "display_process_information", "calculate_average_waiting_time" ], [ "sjf_scheduling", "calculate_turnaround_times" ], [ "sjf_scheduling", "calculate_waiting_times" ], [ "sjf_scheduling", ...
5
[]
false
[]
false
pytest
true
[]
true
bb07b4a9854a0833fd3acddeff8ec023746e363f
f6a33f35073d70ea46ff1204fbc997abbf1ddc3a
v1.0
complete
Algorithm
Algorithm_7422_C
def determinant(mat: list[list[int]]) -> int: """ Calculate the determinant of a square matrix. >>> determinant([[1, 2], [3, 4]]) -2 >>> determinant([[4, 7], [2, 6]]) 10 """ def inverse(mat: list[list[int]]) -> list[list[float]]: """ Calculate the inverse of a square matrix. >>> inverse([[1, 2]...
def determinant(mat): """ Calculates the determinant of a square matrix. """ n = len(mat) if not all(len(row) == n for row in mat): raise ValueError("Matrix is not square") if n == 1: return mat[0][0] elif n == 2: return mat[0][0] * mat[1][1] - mat[0][1] * mat[1]...
from solution import determinant, inverse def test_determinant_2x2(): assert determinant([[1, 2], [3, 4]]) == -2 assert determinant([[4, 7], [2, 6]]) == 10 def test_determinant_3x3(): matrix = [ [6, 1, 1], [4, -2, 5], [2, 8, 7] ] assert determinant(matrix) == -306 def test...
[ { "docstring": "Calculates the determinant of a square matrix.", "function_declaration": "def determinant(mat):", "function_name": "determinant", "parameter_list": "(mat)" }, { "docstring": "Calculates the inverse of a square matrix.", "function_declaration": "def inverse(mat):", "fu...
[ 0, 1, 1, 0, 1, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def determinant(mat):\n \"\"\"\n Calculates the determinant of a given square matrix.\n \n :param mat: List of lists representing a square matrix.\n ...
trial_gpt4o_8
{ "original_instruction": "### Matrix Determinant and Inverse Calculation\n\nYou are required to implement functions to calculate the determinant and the inverse of a given square matrix. Ensure that your functions handle edge cases appropriately, such as non-invertible matrices.\n\n### Matrix Determinant\nImplement ...
0.481694
Algorithm_7422
C
[ "determinant", "inverse" ]
2
[ [ "inverse", "determinant" ] ]
1
[]
false
[]
false
pytest
true
[]
true
59c4f3f229dbaeaa2ad1819380d1f0739b9df81a
eb05ad13cc0aae33b8295d438423df923a9af864
v1.0
complete
Algorithm
Algorithm_27850_C
def reverse_words(sentence: str) -> str: ''' Reverse the order of words in a sentence. >>> reverse_words("hello world") "world hello" >>> reverse_words(" hello world ") "world hello" >>> reverse_words("hello") "hello" >>> reverse_words("") "" ''' pass def validate_reversal(original:...
def reverse_words(sentence: str) -> str: """ Reverse the order of words in a sentence. :param sentence: A string containing words separated by spaces. :return: A string with the words in reversed order. """ # Removing leading and trailing spaces and then split by spaces words = sentence...
from solution import reverse_words, validate_reversal def test_reverse_words_simple(): assert reverse_words("hello world") == "world hello" def test_reverse_words_with_extra_spaces(): assert reverse_words(" hello world ") == "world hello" assert reverse_words(" ") == "" def test_reverse_words_singl...
[ { "docstring": "Reverse the order of words in a sentence.\n\n:param sentence: A string containing words separated by spaces.\n:return: A string with the words in reversed order.", "function_declaration": "def reverse_words(sentence):", "function_name": "reverse_words", "parameter_list": "(sentence)"...
[ 0, 0, 0, 1, 1, 0, 1, 1, 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": "def reverse_words(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a given sentence.\n\n Args:\n sentence (str): A string containing ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question:\n\n#### String Manipulation: Word Reversal\n\nYou are tasked with implementing a function that performs a specific string manipulation: reversing the order of words in a given sentence while maintaining the words' original order of characters, and a function ...
0.643469
Algorithm_27850
C
[ "reverse_words", "validate_reversal" ]
2
[ [ "validate_reversal", "reverse_words" ] ]
1
[]
false
[]
false
pytest
true
[]
true
af17214e20ac7c4f7b1ffe7747303081377c64a9
1411e625f905b75467313706913dc9d9a99005b2
v1.0
complete
Algorithm
Algorithm_30586_C
def carmichael_lambda(n: int) -> int: """Computes the Carmichael function of a given integer. The Carmichael function of `n`, denoted λ(n), is the smallest positive integer `m` such that `a^m ≡ 1 (mod n)` for every integer `a` coprime to `n`. Args: n (int): A positive integer where 1 <...
from math import gcd from functools import reduce def lcm(a, b): return abs(a * b) // gcd(a, b) def prime_factors(n): factors = {} d = 2 while d * d <= n: while (n % d) == 0: if d in factors: factors[d] += 1 else: factors[d] = 1 ...
import pytest from solution import carmichael_lambda def test_carmichael_lambda(): # Base cases assert carmichael_lambda(1) == 1 # Small primes assert carmichael_lambda(7) == 6 assert carmichael_lambda(3) == 2 # Powers of two assert carmichael_lambda(4) == 2 assert carmichael_...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": null, ...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import gcd\nfrom functools import reduce\n\ndef lcm(a, b):\n \"\"\"Compute the least common multiple of a and b.\"\"\"\n return abs(a * b) // gcd...
trial_gpt4o_5
{ "original_instruction": "### Problem: Implement a Function to Compute the Carmichael Function\n\nGiven a positive integer `n`, write a function `carmichael_lambda(n: int) -> int` that computes the Carmichael function (also known as the reduced totient function). The function should return the smallest positive inte...
0.607348
Algorithm_30586
C
[ "lcm", "prime_factors", "carmichael_lambda" ]
3
[ [ "carmichael_lambda", "lcm" ], [ "carmichael_lambda", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ab6d726aa072bcf383fffa810355b2ab9beb1b61
af10c91373e926bd2b159fd938836d0a889e690b
v1.0
complete
Algorithm
Algorithm_43049_C
from typing import List def classify_numbers(numbers: List[int]) -> None: """ Analyze a given list of integers and classify each as "prime", "fibonacci", or "both". >>> classify_numbers([2, 3, 5, 8, 13, 21, 34, 89]) Prime numbers: [2, 3, 5, 13, 89] Fibonacci numbers: [2, 3, 5, 8, 13, 21, 34, 89...
from typing import List def is_prime(n: int) -> bool: 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 generate_fibonacci_upto(n: int) -> set: ...
from solution import classify_numbers def test_classify_numbers_example(): numbers = [2, 3, 5, 8, 13, 21, 34, 89] classify_numbers(numbers) def test_classify_only_primes(): numbers = [2, 3, 5, 7, 11] classify_numbers(numbers) def test_classify_only_fibonacci(): numbers = [0, 1, 1, 2, 3, 5, 8,...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def generate_fibonacci_upto(n):", "function_name": "generate_fibonacci_upto", "parameter_list": "(n)" }, { ...
[ 0, 0, 1, 1, 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": "from typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n ...
trial_gpt4o_9
{ "original_instruction": "**Context**:\nYou are to design a function that analyzes a given list of integer numbers and classifies each as \"prime\", \"fibonacci\", or \"both\". A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Fibonacci numbers are a sequence wh...
0.679125
Algorithm_43049
C
[ "is_prime", "generate_fibonacci_upto", "classify_numbers" ]
3
[ [ "classify_numbers", "generate_fibonacci_upto" ], [ "classify_numbers", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
26f0990ad242aaeb361e7779e4413dfa846b956f
33b109cf036e3183d45d58b42e0bfb86498de6dc
v1.0
complete
Algorithm
Algorithm_27445_C
def custom_sort(arr: List[int]) -> List[int]: """ Sort a list of integers in non-decreasing order using Bucket Sort. >>> custom_sort([4, 2, 2, 8, 3, 3, 1]) == [1, 2, 2, 3, 3, 4, 8] >>> custom_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> custom_sort([-5, 3, 0, -2, -1, 2, 1...
from typing import List def custom_sort(arr: List[int]) -> List[int]: if not arr: return arr min_val, max_val = min(arr), max(arr) bucket_range = (max_val - min_val) // len(arr) + 1 buckets = [[] for _ in range((max_val - min_val) // bucket_range + 1)] for num in arr: bucket_index...
from solution import custom_sort def test_empty_list(): assert custom_sort([]) == [] def test_single_element_list(): assert custom_sort([1]) == [1] assert custom_sort([-1]) == [-1] def test_multiple_elements(): assert custom_sort([4, 2, 2, 8, 3, 3, 1]) == [1, 2, 2, 3, 3, 4, 8] assert custom_sort(...
[ { "docstring": null, "function_declaration": "def custom_sort(arr):", "function_name": "custom_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def insertion_sort(bucket):", "function_name": "insertion_sort", "parameter_list": "(bucket)" } ]
[ 1, 0, 0, 1, 1, 0, 1, 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": "from typing import List\n\ndef custom_sort(arr: List[int]) -> List[int]:\n def insertion_sort(bucket: List[int]) -> List[int]:\n for i in range(1, len(...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n**Scenario**: In computer science, sorting algorithms are essential for efficiently organizing data. Sorting large datasets can significantly improve performance in data retrieval and manipulation tasks. While there are various common sorting algorithms lik...
0.699372
Algorithm_27445
C
[ "custom_sort", "insertion_sort" ]
2
[ [ "custom_sort", "insertion_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ddd719a462db0a136557b2f426b43448dfac41f
e4137405f6fd84953d647cf39ea5c9f2708a3d31
v1.0
complete
Algorithm
Algorithm_40665_C
from typing import List, Tuple def parse_time(time_str: str) -> Tuple[int, int]: """ Parses a time string in the format 'HH:MM' and returns a tuple of (hours, minutes). >>> parse_time("14:30") == (14, 30) >>> parse_time("00:00") == (0, 0) """ def event_conflict(event1: Tuple[str, str, str], event2: Tu...
from typing import List, Tuple def parse_time(time_str: str) -> Tuple[int, int]: hours, minutes = map(int, time_str.split(':')) return (hours, minutes) def event_conflict(event1: Tuple[str, str, str], event2: Tuple[str, str, str]) -> bool: _, start1, end1 = event1 _, start2, end2 = event2 start1_h...
def test_parse_time(): assert parse_time("14:30") == (14, 30) assert parse_time("00:00") == (0, 0) assert parse_time("23:59") == (23, 59) assert parse_time("08:05") == (8, 5) def test_event_conflict(): event1 = ("1", "09:00", "11:00") event2 = ("2", "10:30", "12:00") event3 = ("3", "11:00",...
[ { "docstring": null, "function_declaration": "def parse_time(time_str):", "function_name": "parse_time", "parameter_list": "(time_str)" }, { "docstring": null, "function_declaration": "def event_conflict(event1, event2):", "function_name": "event_conflict", "parameter_list": "(ev...
[ 0, 0, 0, 0, 0, 1, 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": "from typing import List, Tuple\n\ndef parse_time(time_str: str) -> Tuple[int, int]:\n hours, minutes = map(int, time_str.split(\":\"))\n return hours, minu...
trial_gpt4o_5
{ "original_instruction": "### Problem Statement\n\nYou are tasked with creating a scheduling system that checks for conflicts in a list of events and suggests optimal event slots based on given constraints. Each event has a start time, end time, and a unique identifier.\n\n#### Function Descriptions\n\n1. **parse_ti...
0.542538
Algorithm_40665
C
[ "parse_time", "event_conflict", "find_conflicts", "suggest_time_slot" ]
4
[ [ "event_conflict", "parse_time" ], [ "find_conflicts", "event_conflict" ], [ "suggest_time_slot", "parse_time" ] ]
3
[]
false
[]
false
pytest
false
[]
true
a5179945174534a9d701dbdb2b2760b5ef6a523d
01e74bf8f1840f757565de92d11957781147e540
v1.0
complete
Algorithm
Algorithm_8372_C
import numpy as np import pandas as pd from urllib.request import urlopen def load_dataset() -> np.matrix: """Reads and processes the dataset from the URL. Returns a numpy matrix of the dataset. >>> data = load_dataset() >>> data.shape[0] > 0 # Ensure data has been loaded True >>> data.shape[1] ==...
import numpy as np import pandas as pd from urllib.request import urlopen def load_dataset(): """ Reads and processes the dataset from the URL. Returns a numpy matrix of the dataset. """ url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv" df = pd.read_csv(url) ...
import numpy as np from solution import load_dataset, sigmoid, logistic_gradient_descent, predict, evaluate_model def test_load_dataset(): data = load_dataset() assert data.shape[0] > 0 # Ensure that data has been loaded assert data.shape[1] == 2 # Ensure there are two columns (feature and label) def te...
[ { "docstring": "Reads and processes the dataset from the URL.\nReturns a numpy matrix of the dataset.", "function_declaration": "def load_dataset():", "function_name": "load_dataset", "parameter_list": "()" }, { "docstring": "Computes sigmoid function.", "function_declaration": "def sigm...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\n\ndef load_dataset():\n \"\"\"\n Load the dataset from the provided URL and preprocess it.\n Returns the datase...
trial_gpt4o_3
{ "original_instruction": "### Logistic Regression for Binary Classification\n\nYou are required to implement a logistic regression model from scratch using batch gradient descent for optimization. Your goal is to:\n1. Load and preprocess a given dataset.\n2. Implement the logistic regression algorithm using gradient...
0.718956
Algorithm_8372
C
[ "load_dataset", "sigmoid", "logistic_gradient_descent", "predict", "evaluate_model", "main" ]
6
[ [ "logistic_gradient_descent", "sigmoid" ], [ "predict", "sigmoid" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
6c2d8ec1ff9e2f9294c876ba98fe298d9da46ed6
86ce5dec32cc8d90b8ba58a26515e0473b0666da
v1.0
complete
Algorithm
Algorithm_16634_C
def extract_group_identifier(isbn: str) -> str: """ Extract the group identifier from a given 13-digit ISBN. >>> extract_group_identifier("9781234567890") '978' >>> extract_group_identifier("1234567890123") '123' """ # Write your code here def validate_isbn(isbn: str) -> bool: """ Valid...
def extract_group_identifier(isbn): """ Extract the group identifier from a given 13-digit ISBN. Parameters: isbn (str): A string representation of a 13-digit ISBN. Returns: str: The group identifier (first digit of the ISBN). """ if len(isbn) != 13 or not isbn.isdigit(): raise...
import pytest from solution import extract_group_identifier, validate_isbn, format_isbn def test_extract_group_identifier_valid(): assert extract_group_identifier("9781234567890") == "978" def test_extract_group_identifier_invalid(): with pytest.raises(ValueError): extract_group_identifier("1234567890...
[ { "docstring": "Extract the group identifier from a given 13-digit ISBN.\n\nParameters:\nisbn (str): A string representation of a 13-digit ISBN.\n\nReturns:\nstr: The group identifier (first digit of the ISBN).", "function_declaration": "def extract_group_identifier(isbn):", "function_name": "extract_gr...
[ 0, 0, 0, 1, 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 re\n\ndef extract_group_identifier(isbn):\n \"\"\"\n Extract the group identifier from a given 13-digit ISBN.\n \"\"\"\n if len(isbn) != 13 or...
trial_gpt4o_3
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\nYou are developing a system for a library to manage and track the borrowing of its books. Each book has a unique International Standard Book Number (ISBN), and the library needs functions to manipulate and validate these ISBNs.\n\n### Objectiv...
0.430668
Algorithm_16634
C
[ "extract_group_identifier", "validate_isbn", "validate_isbn_10", "validate_isbn_13", "format_isbn", "format_isbn_10", "format_isbn_13" ]
7
[ [ "format_isbn", "format_isbn_10" ], [ "format_isbn", "format_isbn_13" ], [ "validate_isbn", "validate_isbn_10" ], [ "validate_isbn", "validate_isbn_13" ] ]
4
[]
false
[]
false
pytest
true
[]
true
dd4b425b3928d73a9df198bb16b37cbeadcf6946
e56aa431f2dd3a3999fae91199565a3b38324e70
v1.0
complete
Algorithm
Algorithm_26880_C
from functools import reduce from math import gcd from typing import List def lcm_multiple(nums: List[int]) -> int: """ Returns the least common multiple of a list of integers. Args: nums (List[int]): List of integers to calculate the LCM of. Returns: int: The LCM of the list ...
from functools import reduce from math import gcd from typing import List def lcm(a, b): """ Returns the least common multiple of a and b """ return abs(a * b) // gcd(a, b) def lcm_multiple(nums: List[int]) -> int: """ Returns the least common multiple of a list of integers """ if not ...
import pytest from solution import lcm_multiple def test_lcm_multiple_positive_numbers(): assert lcm_multiple([1, 2, 3, 4, 5]) == 60 def test_lcm_multiple_with_negative_numbers(): assert lcm_multiple([-5, 10, -20]) == 20 def test_lcm_multiple_one_element(): assert lcm_multiple([7]) == 7 def test_lcm_mul...
[ { "docstring": "Returns the least common multiple of a and b", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple of a list of integers", "function_declaration": "def lcm_multiple(nums):", ...
[ 0, 1, 1, 0, 1, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nfrom functools import reduce\nfrom math import gcd\n\ndef lcm(a: int, b: int) -> int:\n \"\"\"\n Calculates the least common multi...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: LCM of Multiple Numbers\n\n#### Objective\n\nImplement a function `lcm_multiple(nums: List[int]) -> int` that calculates the Least Common Multiple (LCM) of a list of integers. This function should handle various scenarios including lists with multiple element...
0.636082
Algorithm_26880
C
[ "lcm", "lcm_multiple" ]
2
[ [ "lcm_multiple", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
53d762019edfb405079b26e9c7e54ad3c607e4e0
a4db172974841c5928e84f26ead8caa19b853bc6
v1.0
complete
Algorithm
Algorithm_13740_C
import threading from typing import List def generate_primes(n: int, num_threads: int) -> List[int]: """ Generate all prime numbers up to a given number `n` using `num_threads` threads. >>> generate_primes(10, 2) [2, 3, 5, 7] >>> generate_primes(30, 3) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] >>> g...
import threading from typing import List def is_prime(num: int) -> bool: if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False ...
import pytest from solution import generate_primes def test_generate_primes_simple_case(): assert generate_primes(10, 2) == [2, 3, 5, 7] def test_generate_primes_single_thread(): assert generate_primes(30, 1) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] def test_generate_primes_multiple_threads(): assert gene...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def worker(start, end, primes, lock):", "function_name": "worker", "parameter_list": "(start, end, primes, lo...
[ 0, 0, 0, 1, 1, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport threading\n\ndef is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 ==...
trial_gpt4o_8
{ "original_instruction": "### Prime Number Generation with Multithreading\n\nWrite a function `generate_primes` that generates all prime numbers up to a given number `n`. To optimize the task, use multithreading to divide the work of checking for prime numbers among multiple threads.\n\n### Function Signature:\n```p...
0.635296
Algorithm_13740
C
[ "is_prime", "worker", "generate_primes" ]
3
[ [ "worker", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
647e32576849ddd74fd884e731d0caf60c574bb1
e76edeff8c82190a06592c4821ff79b84f540dab
v1.0
complete
Algorithm
Algorithm_39584_C
def are_boolean_expressions_equivalent(expr1: str, expr2: str) -> bool: """ Parse, evaluate, and compare two boolean algebra expressions given in infix notation. The function should return whether the two expressions are logically equivalent. >>> are_boolean_expressions_equivalent("(a & b) | !c", "(!c...
from itertools import product import re def parse_expression(expr): # Function to parse and convert infix expression to Postfix (RPN) precedence = {'!': 3, '&': 2, '|': 1, '(': 0, ')': 0} output = [] operators = [] def greater_precedence(op1, op2): return precedence[op1] > precedence[o...
from solution import are_boolean_expressions_equivalent def test_equivalent_expressions(): expr1 = "(a & b) | !c" expr2 = "(!c) | (b & a)" assert are_boolean_expressions_equivalent(expr1, expr2) == True def test_non_equivalent_expressions(): expr1 = "a & (b | c)" expr2 = "(a & b) | c" assert a...
[ { "docstring": null, "function_declaration": "def parse_expression(expr):", "function_name": "parse_expression", "parameter_list": "(expr)" }, { "docstring": null, "function_declaration": "def evaluate_postfix(postfix, values):", "function_name": "evaluate_postfix", "parameter_li...
[ 1, 0, 1, 0, 0, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import itertools\n\ndef eval_boolean_expression(expr, values):\n \"\"\" Evaluate boolean expression with given variable values \"\"\"\n for var, val in val...
trial_gpt4o_7
{ "original_instruction": "### Coding Assessment Question\n\n#### Objective:\nWrite a function to parse, evaluate, and compare two boolean algebra expressions given in infix notation. The function should return whether the two expressions are logically equivalent.\n\n#### Description:\nYou are given two boolean algeb...
0.522748
Algorithm_39584
C
[ "parse_expression", "evaluate_postfix", "are_boolean_expressions_equivalent" ]
3
[ [ "are_boolean_expressions_equivalent", "evaluate_postfix" ], [ "are_boolean_expressions_equivalent", "parse_expression" ] ]
2
[]
false
[]
false
pytest
true
[]
true
322dfdead43190dfebdf186a834f7d0b43d09c0a
44de424191727d4666be3877ffb7ed82f9f2d58f
v1.0
complete
Algorithm
Algorithm_22789_C
from typing import List, Dict import re def dynamic_word_counter(post: str, keywords: List[str]) -> Dict[str, int]: """ Counts the occurrences of each keyword from the 'keywords' list in the 'post' after sanitization. :param post: A string representing the user-generated post. :param keywords: A list ...
from typing import List, Dict import re def sanitize_text(text: str) -> str: """ Sanitizes the input text by converting to lowercase and removing non-alphanumeric characters. :param text: The text to sanitize. :return: A sanitized string. """ return re.sub(r'[^a-z0-9\s]', '', text.lower())...
from solution import dynamic_word_counter def test_dynamic_word_counter_with_simple_post(): post = "This social platform is great! I love this platform." keywords = ["social", "platform", "love"] expected_output = {'social': 1, 'platform': 2, 'love': 1} assert dynamic_word_counter(post, keywords) == ex...
[ { "docstring": "Sanitizes the input text by converting to lowercase and removing non-alphanumeric characters.\n\n:param text: The text to sanitize.\n:return: A sanitized string.", "function_declaration": "def sanitize_text(text):", "function_name": "sanitize_text", "parameter_list": "(text)" }, ...
[ 0, 1, 1, 1, 0, 0, 1, 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": "import re\nfrom typing import List, Dict\n\ndef sanitize_text(text: str) -> str:\n \"\"\"\n Sanitizes the text by converting it to lowercase and\n remov...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: Implementing Dynamic Word Counter\n\n#### Context:\nA social media platform wants to add a feature to dynamically count specific words in user-generated posts. This feature would assist in generating real-time statistics about how often specific terms are men...
0.733217
Algorithm_22789
C
[ "sanitize_text", "dynamic_word_counter" ]
2
[ [ "dynamic_word_counter", "sanitize_text" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5ef68dd438240fd25bf717ec1375d589790b6d76
3ba8e0a301a49140322a9c06a23c2f7505bdaba7
v1.0
complete
Algorithm
Algorithm_2192_C
def closest_pair(points: list[tuple[float, float]]) -> tuple: """ Find the pair of points with the smallest Euclidean distance between them. >>> closest_pair([(0, 0), (1, 1), (2, 2), (3, 3)]) ((0, 0), (1, 1)) >>> closest_pair([(1, 1), (1, 1), (2, 2), (3, 3)]) ((1, 1), (1, 1)) >>> closest_pair([(...
import math from itertools import combinations def euclidean_distance(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def closest_pair(points): """ Brute-force solution to find the closest pair of points in the plane """ min_distance = float('inf') closest_points = (poin...
from solution import closest_pair def test_closest_pair_simple(): points = [(0, 0), (1, 1), (2, 2), (3, 3)] assert closest_pair(points) in [((0, 0), (1, 1)), ((1, 1), (2, 2)), ((2, 2), (3, 3))] def test_closest_pair_duplicates(): points = [(1, 1), (1, 1), (2, 2), (3, 3)] assert closest_pair(points) ==...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": "Brute-force solution to find the closest pair of points in the plane", "function_declaration": "def closest_pair(points):...
[ 1, 0, 0, 0, 0, 0, 0, 0, 1, 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 math import sqrt\nfrom itertools import combinations\n\ndef euclidean_distance(point1, point2):\n return sqrt((point1[0] - point2[0])**2 + (point1[1] - p...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement\nYou are given a collection of 'n' points in the 2D plane represented by two arrays `X` and `Y`, where `X[i]` and `Y[i]` represent the x-coordinate and y-coordinate of the i-th point respectively. Your task is to implement a function that finds the pair of points with ...
0.779842
Algorithm_2192
C
[ "euclidean_distance", "closest_pair" ]
2
[ [ "closest_pair", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
72ed1cd8ba93a9776a47129625422ed37af6166d
3b9903f2c479fe93518dd3b2fa352006dff96a65
v1.0
complete
Algorithm
Algorithm_18613_C
def insert_into_book_hash_table(hash_table: list, isbn_title_pairs: list) -> None: """Inserts book titles into the hash table using double hashing. >>> hash_table = [None] * 10 >>> insert_into_book_hash_table(hash_table, [(12345, 'Book A')]) >>> hash_table[12345 % 10] (12345, 'Book A') >>> ...
def h1(key, table_size): """Primary hash function""" return key % table_size def h2(key, table_size): """Secondary hash function""" return 1 + (key % (table_size - 1)) def insert_into_book_hash_table(hash_table, isbn_title_pairs): """Inserts book titles into the hash table using double hashing."""...
from solution import insert_into_book_hash_table, retrieve_from_book_hash_table def test_insert_and_retrieve_single_entry(): hash_table = [None] * 10 insert_into_book_hash_table(hash_table, [(12345, 'Book A')]) assert retrieve_from_book_hash_table(hash_table, 12345) == 'Book A' def test_insert_and_retriev...
[ { "docstring": "Primary hash function", "function_declaration": "def h1(key, table_size):", "function_name": "h1", "parameter_list": "(key, table_size)" }, { "docstring": "Secondary hash function", "function_declaration": "def h2(key, table_size):", "function_name": "h2", "parame...
[ 0, 1, 1, 0, 0, 0, 1, 1, 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": "def h1(key, table_size):\n \"\"\"\n Primary hash function.\n \"\"\"\n return key % table_size\n\ndef h2(key, table_size):\n \"\"\"\n Secondary ...
trial_gpt4o_8
{ "original_instruction": "### Hash Table Manipulation: Implement Collision-Handled Hash Table with Double Hashing\n\nIn this task, you are required to handle collisions in a hash table using a double hashing technique.\n\n#### Scenario:\nYou are developing a library system to store book titles based on their unique ...
0.481076
Algorithm_18613
C
[ "h1", "h2", "insert_into_book_hash_table", "retrieve_from_book_hash_table" ]
4
[ [ "insert_into_book_hash_table", "h1" ], [ "insert_into_book_hash_table", "h2" ], [ "retrieve_from_book_hash_table", "h1" ], [ "retrieve_from_book_hash_table", "h2" ] ]
4
[]
false
[]
false
pytest
true
[]
true
447248133ce592f993dfad1392e37d3596dba7e1
e26b8513aeca68fa8506e46f7e59b6e5bcc1a839
v1.0
complete
Algorithm
Algorithm_32942_C
from typing import List, Tuple def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int: """ Heuristic function used for A* algorithm. Calculates the Manhattan distance between points a and b. """ return abs(a[0] - b[0]) + abs(a[1] - b[1]) def find_shortest_path( grid: List[List[int]], sta...
from typing import List, Tuple import heapq def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int: return abs(a[0] - b[0]) + abs(a[1] - b[1]) def find_shortest_path( grid: List[List[int]], start: Tuple[int, int], target: Tuple[int, int] ) -> int: rows, cols = len(grid), len(grid[0]) open_set = ...
from solution import find_shortest_path, is_path_possible def test_find_shortest_path_example(): grid = [ [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0] ] start = (0, 0) target = (4, 4) assert find_shortest_path(grid, star...
[ { "docstring": null, "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def find_shortest_path(grid, start, target):", "function_name": "find_shortest_path", "parameter_list": "...
[ 0, 0, 1, 1, 0, 0, 1, 1, 0, 1 ]
5
medium
0.5
{ "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\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n...
trial_gpt4o_9
{ "original_instruction": "### Introduction\nYou are enhancing a game where players control characters to perform various actions in a 2D grid-based world. One critical aspect is to accurately calculate the shortest path for a character to traverse from the starting position to a target position, considering any obst...
0.653049
Algorithm_32942
C
[ "heuristic", "find_shortest_path", "is_path_possible" ]
3
[ [ "find_shortest_path", "heuristic" ], [ "is_path_possible", "find_shortest_path" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2e478bf38ce8fa2ce0d74ae984b1029984c597ce
57f2a0ff193c87385108ca315c19e34d8d99fbe1
v1.0
complete
Algorithm
Algorithm_6116_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def rebalance_bst(root: TreeNode) -> TreeNode: """Rebalances an unbalanced binary search tree (BST). Args: root (TreeNode): The root node of a potentially un...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def in_order_traversal(node): if not node: return [] return in_order_traversal(node.left) + [node.val] + in_order_traversal(node.right) def sorted_array_to_b...
import pytest from solution import TreeNode, rebalance_bst def in_order_traversal(node): if not node: return [] return in_order_traversal(node.left) + [node.val] + in_order_traversal(node.right) def is_balanced(root): def height(node): if not node: return 0 left_height ...
[]
[ 0, 1, 0, 1, 1, 1, 1, 1, 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": "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 inord...
trial_gpt4o_7
{ "original_instruction": "### Context:\nYou are tasked to implement a rebalancing algorithm for a given binary search tree (BST). A BST is considered balanced if the height difference between the left and right subtrees of any node is no more than one. Your goal is to write a function that rebalances an unbalanced B...
0.669147
Algorithm_6116
C
[ "in_order_traversal", "sorted_array_to_bst", "rebalance_bst" ]
3
[ [ "rebalance_bst", "in_order_traversal" ], [ "rebalance_bst", "sorted_array_to_bst" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
4848d4f2d04a78b429d269a5ad5f2bf604f9611d
85b92da0c8b6cc80573ff89f49b51ba675840989
v1.0
complete
Algorithm
Algorithm_46541_C
def solve_sudoku(grid): """ Solves the given Sudoku puzzle in-place using backtracking. >>> grid = [ ... [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], ...
def is_valid_move(grid, row, col, num): """ Check if placing num at grid[row][col] is valid according to Sudoku rules. """ for i in range(9): # Check the row if grid[row][i] == num: return False # Check the column if grid[i][col] == num: return Fal...
from solution import solve_sudoku def test_sudoku_solver(): grid = [ [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], [0, 6, 0, 0, 0, ...
[ { "docstring": "Check if placing num at grid[row][col] is valid according to Sudoku rules.", "function_declaration": "def is_valid_move(grid, row, col, num):", "function_name": "is_valid_move", "parameter_list": "(grid, row, col, num)" }, { "docstring": "Solves the given Sudoku puzzle in-pla...
[ 1, 0, 0, 0, 1, 1, 1, 1, 1 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_valid(grid, r, c, num):\n # Check if 'num' is not in the current row, column and 3x3 sub-grid\n for i in range(9):\n if grid[r][i] == num or ...
trial_gpt4o_9
{ "original_instruction": "### Sudoku Solver\n\nYou are required to implement a Sudoku solver that fills in the missing numbers in a given 9x9 Sudoku grid. Your implementation will help assess your abilities to handle backtracking and constraint satisfaction problems in algorithm design.\n\n#### Problem Statement\n\n...
0.572324
Algorithm_46541
C
[ "is_valid_move", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid_move" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e2c05303e6beb1d86702050545dd9d21303e8876
251a0b0165d277f098951d77dbd6e296b2c17729
v1.0
complete
Algorithm
Algorithm_24592_C
from collections import Counter import math from typing import List def compute_distance(sample1: List[float], sample2: List[float]) -> float: """ Compute the Euclidean distance between two samples. Args: - sample1 (List[float]): First sample vector. - sample2 (List[float]): Second sample vector. ...
import math from collections import Counter def compute_distance(sample1: list[float], sample2: list[float]) -> float: """ Compute the Euclidean distance between two samples. Args: - sample1 (list[float]): First sample vector. - sample2 (list[float]): Second sample vector. Returns: - f...
import pytest from solution import compute_distance, get_neighbors, predict_class, evaluate_accuracy def test_compute_distance(): sample1 = [1.0, 2.0] sample2 = [4.0, 6.0] assert compute_distance(sample1, sample2) == 5.0 def test_get_neighbors(): training_samples = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0],...
[]
[ 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": "import math\nfrom collections import Counter\n\ndef compute_distance(sample1, sample2):\n \"\"\"\n Compute the Euclidean distance between two samples.\n ...
trial_gpt4o_4
{ "original_instruction": "### K-Nearest Neighbors (KNN) from Scratch\n\nYou are required to implement the K-Nearest Neighbors algorithm from scratch and optimize it for classification tasks. Implement the following functions:\n\n1. **compute_distance** - To compute the distance between two samples.\n2. **get_neighbo...
0.615773
Algorithm_24592
C
[ "compute_distance", "get_neighbors", "predict_class", "evaluate_accuracy" ]
4
[ [ "evaluate_accuracy", "predict_class" ], [ "get_neighbors", "compute_distance" ], [ "predict_class", "get_neighbors" ] ]
3
[]
false
[]
false
pytest
true
[]
true
cf8fc130d981e32d6412b387386aa0c7aecdd51b
c4b07873e04034b69c6f72745e71fc99dddb16d5
v1.0
complete
Algorithm
Algorithm_10203_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_symmetric(root): """Check if a given binary tree is symmetric. A binary tree is symmetric if it is a mirror of itself. Args: root (TreeNode):...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_mirror(t1, t2): if t1 is None and t2 is None: return True if t1 is None or t2 is None: return False return (t1.val == t2.val ...
from solution import TreeNode, is_symmetric def test_is_symmetric_example1(): # Example 1: symmetric tree # 1 # / \ # 2 2 # / \ / \ # 3 4 4 3 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = Tree...
[]
[ 0, 1, 1, 1, 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": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_sy...
trial_gpt4o_9
{ "original_instruction": "### Task\nImplement an algorithm to check if a given binary tree is symmetric. A binary tree is symmetric if it is a mirror of itself.\n\n### Objective\n\nGiven a binary tree, write a function `is_symmetric` that returns `True` if the tree is symmetric, and `False` otherwise.\n\n### Input\n...
0.647599
Algorithm_10203
C
[ "is_mirror", "is_symmetric" ]
2
[ [ "is_symmetric", "is_mirror" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
8ea04dfcd14b18224a77f89e76ed4ac324e2b4c7
6ccd98bfca0c2f4ad9fdfa1c13922045aa919008
v1.0
complete
Algorithm
Algorithm_42720_C
from typing import List, Dict def recommend_books(user_id: int, reading_history: List[str], preferences: Dict[str, int], max_recommendations: int = 5) -> List[str]: """ Recommend books to a user based on their reading history and preferences. >>> recommend_books(1, ["Book A", "Book B", "Book C"], {"Fiction": 5...
from typing import List, Dict import logging # Set up logging logging.basicConfig(level=logging.INFO) # Assume we have a database of books and their genres BOOK_DATABASE = { "Book D": "Fiction", "Book E": "Mystery", "Book F": "Sci-Fi", "Book G": "Romance", "Book H": "Fiction", "Book I": "Sci-F...
from solution import recommend_books def test_recommend_books_basic(): reading_history = ["Book A", "Book B", "Book C"] preferences = {"Fiction": 5, "Mystery": 3, "Sci-Fi": 4} recommendations = recommend_books(user_id=1, reading_history=reading_history, preferences=preferences) assert sorted(recommenda...
[ { "docstring": "Helper function to get books by genre", "function_declaration": "def get_books_by_genre(genre):", "function_name": "get_books_by_genre", "parameter_list": "(genre)" }, { "docstring": "Recommend books to a user based on their reading history and preferences.", "function_de...
[ 1, 1, 0, 0, 0, 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, Dict\nimport logging\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO)\n\n# Assume we have a database of books and their genr...
trial_gpt4o_0
{ "original_instruction": "### Coding Question\n\n#### Context\nYou are developing a library management system. One of the functionalities required is to recommend books based on the user's reading history and preferences. The system needs to process the user's reading data and return book titles that align with thei...
0.575695
Algorithm_42720
C
[ "get_books_by_genre", "recommend_books" ]
2
[ [ "recommend_books", "get_books_by_genre" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89b2903e02d142f519fc1a373497ed77ae6a409c
b199cbce4d31be5d5a866a1aa08d71c255334df3
v1.0
complete
Algorithm
Algorithm_13305_C
from typing import List, Tuple def is_prime(n: int) -> bool: """ Check if a number is prime.""" pass # Your implementation here def is_prime_path(matrix: List[List[int]], start: Tuple[int, int], end: Tuple[int, int]) -> bool: """ Determine if there is a prime path from start to end in the matrix. Arg...
from typing import List, Tuple from collections import deque def is_prime(n: int) -> bool: """ Check if a number is prime.""" if n <= 1: return False if n == 2: return True # 2 is the only even prime number if n % 2 == 0: return False max_divisor = int(n**0.5) + 1 for d...
from solution import is_prime_path def test_is_prime_path(): matrix = [ [2, 4, 3], [5, 9, 7], [11, 13, 8] ] start = (0, 0) end = (2, 1) assert is_prime_path(matrix, start, end) == True start = (0, 0) end = (2, 2) assert is_prime_path(matrix, start, end) == False...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Determine if there is a prime path from start to end in the matrix. ", "function_declaration": "def is_prime_path(matrix, star...
[ 0, 0, 1, 1, 0, 1, 1, 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": "from typing import List, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n ...
trial_gpt4o_5
{ "original_instruction": "### Prime Path Challenge \n\nYou are tasked with implementing a function to determine if there is a path of prime numbers between two given points in a matrix. A prime path is a sequence of moves from one cell to an adjacent cell (vertically or horizontally) where all cells in the path cont...
0.629714
Algorithm_13305
C
[ "is_prime", "is_prime_path" ]
2
[ [ "is_prime_path", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e913ecb4eb715e7736595e9d2b61d880ef5bfcc
547d9a075997c94f9169551bc6c97513cd9046e6
v1.0
complete
Algorithm
Algorithm_43975_C
def add_polynomials(poly1, poly2): result = [0] * max(len(poly1), len(poly2)) for i in range(len(poly1)): result[i] += poly1[i] for i in range(len(poly2)): result[i] += poly2[i] return result def subtract_polynomials(poly1, poly2): result = [0] * max(len(poly1), len(poly2)) for ...
from typing import List, Tuple, Union def add_polynomials(poly1, poly2): result = [0] * max(len(poly1), len(poly2)) for i in range(len(poly1)): result[i] += poly1[i] for i in range(len(poly2)): result[i] += poly2[i] return result def subtract_polynomials(poly1, poly2): result = [0]...
from solution import perform_polynomial_operations def test_add_polynomials(): operations = [("add", [[1, 2, 3], [4, 0, 5]])] result = perform_polynomial_operations(operations) assert result == [[5, 2, 8]] def test_subtract_polynomials(): operations = [("subtract", [[7, 2], [5, 1, 1]])] result = p...
[ { "docstring": null, "function_declaration": "def add_polynomials(poly1, poly2):", "function_name": "add_polynomials", "parameter_list": "(poly1, poly2)" }, { "docstring": null, "function_declaration": "def subtract_polynomials(poly1, poly2):", "function_name": "subtract_polynomials"...
[ 0, 1, 0, 0, 0, 1, 1, 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": "from typing import List, Tuple, Union\n\ndef add_polynomials(p1: List[int], p2: List[int]) -> List[int]:\n length = max(len(p1), len(p2))\n result = [0] * ...
trial_gpt4o_6
{ "original_instruction": "### Coding Assessment Question\n\n**Problem Statement:**\nYou are given a library for working with basic polynomial arithmetic. The library includes methods for adding, subtracting, multiplying, and evaluating polynomials. A polynomial is represented as a list of coefficients, starting with...
0.640482
Algorithm_43975
C
[ "add_polynomials", "subtract_polynomials", "multiply_polynomials", "evaluate_polynomial", "perform_polynomial_operations" ]
5
[ [ "perform_polynomial_operations", "add_polynomials" ], [ "perform_polynomial_operations", "evaluate_polynomial" ], [ "perform_polynomial_operations", "multiply_polynomials" ], [ "perform_polynomial_operations", "subtract_polynomials" ] ]
4
[]
false
[]
false
pytest
true
[]
true
433ef2441818370020b446b26a8660f57bd758df
962fe34d5845fb32d8480ddabce8d6a272ea50d8
v1.0
complete
Algorithm
Algorithm_18867_C
def merge_sort(arr: List[int]) -> List[int]: """ Write a function `merge_sort(arr: List[int]) -> List[int]` that implements the Merge Sort algorithm to sort a list of integers in ascending order. >>> merge_sort([5, 2, 9, 1, 5, 6]) [1, 2, 5, 5, 6, 9] >>> merge_sort([8, 3, 7, 4, 2, 6]) [2, 3, 4, 6...
from typing import List def merge_sort(arr: List[int]) -> List[int]: 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: List[int], right: List[int]) -> List[int]: so...
from solution import merge_sort def test_merge_sort_basic_cases(): assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] assert merge_sort([8, 3, 7, 4, 2, 6]) == [2, 3, 4, 6, 7, 8] def test_merge_sort_single_element(): assert merge_sort([10]) == [10] def test_merge_sort_empty_list(): assert mer...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 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 merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\nSorting algorithms are fundamental in computer science and have a wide range of applications, from data processing to efficient searching. Understanding and implementing sorting algorithms is crucial for optimizing performance in various compu...
0.640761
Algorithm_18867
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9dc90c294663b4f30c228cebfb46988bd4c7129c
dfd9942089e33a0dbd334299b8521f6963f4b7fe
v1.0
complete
Algorithm
Algorithm_21880_C
def primary_diagonal_sum(matrix: list[list[int]]) -> int: """ Computes the sum of the primary diagonal of a square matrix. Args: matrix (list[list[int]]): A square matrix. Returns: int: The sum of the primary diagonal. Raises: ValueError: If the input is not a square matri...
def primary_diagonal_sum(matrix: list[list[int]]) -> int: """ Computes the sum of the primary diagonal of a square matrix. Args: matrix (list[list[int]]): A square matrix. Returns: int: The sum of the primary diagonal. Raises: ValueError: If the input is not a square matri...
import pytest from solution import primary_diagonal_sum, secondary_diagonal_sum, diagonal_sums def test_primary_diagonal_sum(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] assert primary_diagonal_sum(matrix) == 15 def test_secondary_diagonal_sum(): matrix = [ [1, 2, 3]...
[ { "docstring": "Computes the sum of the primary diagonal of a square matrix.\n\nArgs:\nmatrix (list[list[int]]): A square matrix.\n\nReturns:\nint: The sum of the primary diagonal.\n\nRaises:\nValueError: If the input is not a square matrix.", "function_declaration": "def primary_diagonal_sum(matrix):", ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def primary_diagonal_sum(matrix: list[list[int]]) -> int:\n \"\"\"\n Computes the sum of the primary diagonal of a square matrix.\n :param matrix: A lis...
trial_gpt4o_8
{ "original_instruction": "### Matrix Diagonal Sum Calculation\n\n**Context**:\nMatrix operations are foundational in various fields including computer graphics, machine learning, and scientific computing. One common task is to calculate sums of elements along the diagonals of a matrix. In this exercise, you will imp...
0.525454
Algorithm_21880
C
[ "primary_diagonal_sum", "secondary_diagonal_sum", "diagonal_sums" ]
3
[ [ "diagonal_sums", "primary_diagonal_sum" ], [ "diagonal_sums", "secondary_diagonal_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b41d93c0f43f1486d6fe81b2a1d2dd2ab57834d3
70ccc0b28878d6cdd40e8fddc46ad1cd75a7e3e5
v1.0
complete
Algorithm
Algorithm_12983_C
from typing import List, Dict def naive_multiplication(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: """ Perform matrix multiplication using the naive approach. """ def strassen_multiplication(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: """ Perform matrix ...
import time from typing import List, Dict def naive_multiplication(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: """ Perform matrix multiplication using the naive approach. """ size = len(mat1) result = [[0] * size for _ in range(size)] for i in range(size): for j in...
import pytest from solution import naive_multiplication, strassen_multiplication def test_naive_multiplication(): mat1 = [ [1, 2], [3, 4] ] mat2 = [ [5, 6], [7, 8] ] expected_output = [ [19, 22], [43, 50] ] assert naive_multiplication(mat1, ma...
[ { "docstring": "Perform matrix multiplication using the naive approach.", "function_declaration": "def naive_multiplication(mat1, mat2):", "function_name": "naive_multiplication", "parameter_list": "(mat1, mat2)" }, { "docstring": "Perform matrix multiplication using Strassen's algorithm.", ...
[ 1, 1, 1, 0, 0, 1, 1, 0, 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": "import time\nfrom typing import List, Dict\n\ndef naive_multiplication(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Naive O...
trial_gpt4o_9
{ "original_instruction": "### Matrix Multiplication Optimization\n\nYou are to implement a naive matrix multiplication algorithm and improve it using the Strassen algorithm. Compare the performance of both algorithms using different sizes of square matrices.\n\n### Function Descriptions\n\n1. **naive_multiplication(...
0.509484
Algorithm_12983
C
[ "naive_multiplication", "strassen_multiplication", "performance_comparison" ]
3
[ [ "performance_comparison", "naive_multiplication" ], [ "performance_comparison", "strassen_multiplication" ] ]
2
[]
false
[]
false
pytest
true
[]
true
65841bb56436977d084ebd79066549d95e425576
ecfe46af6d34c6dec59e2c8adf1316760f5ea1c4
v1.0
complete
Algorithm
Algorithm_25620_C
def nth_fibonacci(n: int) -> int: """ Returns the N-th Fibonacci number using matrix exponentiation. >>> nth_fibonacci(0) 0 >>> nth_fibonacci(1) 1 >>> nth_fibonacci(2) 1 >>> nth_fibonacci(10) 55 >>> nth_fibonacci(50) 12586269025 """
def matrix_multiply(A, B): """ Multiplies two 2x2 matrices A and B. """ return [ [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]], [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]] ] def matrix_exponentiate(matrix, power): ...
from solution import nth_fibonacci def test_fibonacci_base_cases(): assert nth_fibonacci(0) == 0 assert nth_fibonacci(1) == 1 def test_fibonacci_small_numbers(): assert nth_fibonacci(2) == 1 assert nth_fibonacci(3) == 2 assert nth_fibonacci(4) == 3 assert nth_fibonacci(5) == 5 def test_fibona...
[ { "docstring": "Multiplies two 2x2 matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Exponentiates matrix to the given power using binary exponentiation.", "function_declaration": "d...
[ 0, 1, 1, 1, 1, 0, 1, 0, 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 nth_fibonacci(n: int) -> int:\n \"\"\"\n Returns the N-th Fibonacci number using matrix exponentiation.\n \"\"\"\n if n == 0:\n return 0\n...
trial_gpt4o_9
{ "original_instruction": "### N-th Fibonacci Number - Using Matrix Exponentiation\n\n#### Scenario:\nYou are tasked with implementing a high-performance function to calculate the N-th Fibonacci number for a large-scale simulation. The traditional recursive and iterative approaches become inefficient for very large v...
0.859284
Algorithm_25620
C
[ "matrix_multiply", "matrix_exponentiate", "nth_fibonacci" ]
3
[ [ "matrix_exponentiate", "matrix_multiply" ], [ "nth_fibonacci", "matrix_exponentiate" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2a69707705bf6edc45ef18e1b71ca8970ebdd771
b67be6d89d24e0941ad7d645fd36691a91f8f410
v1.0
complete
Algorithm
Algorithm_25051_C
[Completion Task in Python] """ Implement a function `play_tic_tac_toe` which initializes a 3x3 board and allows the players to make moves alternately. Each move involves placing either 'X' or 'O' on the board. The game should continue until one of the players wins or the board is full, resulting in a draw. Function S...
def initialize_board(): return [[' ' for _ in range(3)] for _ in range(3)] def print_board(board): for row in board: print(' | '.join(row)) print('-' * 5) def check_winner(board, marker): # Check rows, columns, and diagonals for row in board: if all(spot == marker for spot in r...
from solution import initialize_board, print_board, check_winner, is_board_full, get_player_move, play_tic_tac_toe def test_initialize_board(): board = initialize_board() assert board == [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] def test_check_winner(): board = [ ['X', 'X', 'X'], ...
[ { "docstring": null, "function_declaration": "def initialize_board():", "function_name": "initialize_board", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def print_board(board):", "function_name": "print_board", "parameter_list": "(board)" }, { ...
[ 0, 0, 0, 1, 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": "def check_winner(board):\n # Check rows and columns\n for i in range(3):\n if board[i][0] == board[i][1] == board[i][2] != ' ':\n return ...
trial_gpt4o_5
{ "original_instruction": "### Question: Implement a Text-based Tic-Tac-Toe Game\n\nCreate a basic text-based Tic-Tac-Toe game where two players can play against each other. Implement a function `play_tic_tac_toe` which initializes a 3x3 board and allows the players to make moves alternately. Each move involves placi...
0.598661
Algorithm_25051
C
[ "initialize_board", "print_board", "check_winner", "is_board_full", "get_player_move", "play_tic_tac_toe" ]
6
[ [ "play_tic_tac_toe", "check_winner" ], [ "play_tic_tac_toe", "get_player_move" ], [ "play_tic_tac_toe", "initialize_board" ], [ "play_tic_tac_toe", "is_board_full" ], [ "play_tic_tac_toe", "print_board" ] ]
5
[]
false
[]
false
pytest
true
[]
true
b9f941e2ec788aae6012e5abe0e0c68b8a9e62dd
140fc589e0cfa75657df84bf140f7c69c9bbbe7f
v1.0
complete
Algorithm
Algorithm_3089_C
def recursive_factorial_sum(n: int) -> int: """ Calculate the sum of factorials for numbers from 1 to n through a recursive method. Args: n (int): An integer representing the upper bound of the range (inclusive) for which the sum of factorials is to be calculated. Returns: int: The sum of ...
def factorial(n: int) -> int: """ Helper function to calculate the factorial of n recursively. """ if n == 1: return 1 else: return n * factorial(n-1) def recursive_factorial_sum(n: int) -> int: """ Function to calculate the sum of factorials from 1 to n recursively. """...
from solution import recursive_factorial_sum def test_recursive_factorial_sum_1(): assert recursive_factorial_sum(1) == 1 def test_recursive_factorial_sum_2(): assert recursive_factorial_sum(2) == 3 # 1! + 2! = 1 + 2 = 3 def test_recursive_factorial_sum_3(): assert recursive_factorial_sum(3) == 9 # 1! ...
[ { "docstring": "Helper function to calculate the factorial of n recursively.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Function to calculate the sum of factorials from 1 to n recursively.", "function_declaratio...
[ 1, 0, 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": "def factorial(n: int) -> int:\n if n == 0 or n == 1:\n return 1\n else:\n return n * factorial(n - 1)\n\ndef recursive_factorial_sum(n: int) ...
trial_gpt4o_9
{ "original_instruction": "### Recursive Factorial Sum\n\n#### Objective\nWrite a function to calculate the sum of factorials for numbers from 1 to n through a recursive method. The factorial of a number is the product of all integers from 1 to that number. The sum of factorials involves adding up the factorial resul...
0.698804
Algorithm_3089
C
[ "factorial", "recursive_factorial_sum" ]
2
[ [ "recursive_factorial_sum", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a0aa22a81e1184b2b396c083df0f3a9b331716d
9179f32afcd22470ff130f351595bbd337bfea12
v1.0
complete
Algorithm
Algorithm_45722_C
class ListNode: def __init__(self, x): self.val = x self.next = None def merge_sort(head: ListNode) -> ListNode: """ Implement a Merge Sort on a singly linked list. The function accepts the head of the list and returns the head of the sorted list. >>> class ListNode: ... de...
class ListNode: def __init__(self, x): self.val = x self.next = None def split_list(head): """ Split the linked list into two halves. """ fast = head slow = head prev = None while fast and fast.next: prev = slow slow = slow.next fast = fast.next.n...
def linked_list_from_array(arr): """ Helper function to create a linked list from an array of values. """ if not arr: return None head = ListNode(arr[0]) current = head for value in arr[1:]: current.next = ListNode(value) current = current.next return head def ar...
[]
[ 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": "class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef split_list(head):\n \"\"\"\n Split the linked list into ...
trial_gpt4o_9
{ "original_instruction": "### Coding Question: Implement a Merge Sort Algorithm for Linked List\n\n#### Context\nMerge Sort is an efficient, stable, and comparison-based sorting algorithm. It works by dividing the unsorted list into smaller sublists and then merges them back in a sorted manner. Sorting a linked list...
0.529112
Algorithm_45722
C
[ "split_list", "merge_lists", "merge_sort" ]
3
[ [ "merge_sort", "merge_lists" ], [ "merge_sort", "split_list" ] ]
2
[]
false
[ "ListNode" ]
true
pytest
false
[]
true
31c43555fb8a0acf7cda0c90d599f7d7e5e0acd1
be07fe529e377ddcbc646fd0fe8118734223b85e
v1.0
complete
Algorithm
Algorithm_3033_C
def prime_lcm(a: int, b: int) -> int: """ Compute the LCM of two numbers using their prime factorizations. >>> prime_lcm(12, 15) 60 >>> prime_lcm(100, 75) 300 >>> prime_lcm(1, 1) 1 >>> prime_lcm(2, 3) 6 """ def test_prime_lcm_basic(): assert prime_lcm(12, 15) == 6...
def sieve(limit: int) -> list: """ Generates a list of prime numbers up to the given limit using the Sieve of Eratosthenes algorithm. """ is_prime = [True] * (limit + 1) is_prime[0], is_prime[1] = False, False p = 2 while p * p <= limit: if is_prime[p]: for i in range(p *...
from solution import prime_lcm def test_prime_lcm_basic(): assert prime_lcm(12, 15) == 60 def test_prime_lcm_equal_numbers(): assert prime_lcm(21, 21) == 21 def test_prime_lcm_coprime_numbers(): assert prime_lcm(13, 17) == 221 def test_prime_lcm_one_is_multiple(): assert prime_lcm(25, 5) == 25 def ...
[ { "docstring": "Generates a list of prime numbers up to the given limit using the Sieve of Eratosthenes algorithm.", "function_declaration": "def sieve(limit):", "function_name": "sieve", "parameter_list": "(limit)" }, { "docstring": "Returns a dictionary where keys are the prime factors of ...
[ 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def sieve(limit: int) -> list:\n \"\"\"\n Generates a list of prime numbers up to the given limit using the Sieve of Eratosthenes algorithm.\n \"\"\"\n ...
trial_gpt4o_0
{ "original_instruction": "## Prime Factorization and Least Common Multiple\n\n### Context:\nPrime factorization is the process of determining the prime numbers that multiply together to give a certain original number. The least common multiple (LCM) of two integers is the smallest positive integer that is divisible ...
0.62099
Algorithm_3033
C
[ "sieve", "prime_factors", "prime_lcm" ]
3
[ [ "prime_lcm", "prime_factors" ], [ "prime_lcm", "sieve" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a96a652447f5893cfd8797d31ec0ad136bfaea8f
1cd6556520a99ca513c53f2bef160e583cd744b6
v1.0
complete
Algorithm
Algorithm_7120_C
from typing import List import math from functools import reduce def find_lcm(numbers: List[int]) -> int: """ Calculates the LCM of a list of integers ``numbers``. >>> find_lcm([4, 6, 8]) 24 >>> find_lcm([2, 5, 7, 11]) 770 >>> find_lcm([10, 20, 30, 40]) 120 >>> find_lcm([1, 2, 3...
from typing import List import math from functools import reduce def lcm(a, b): return abs(a * b) // math.gcd(a, b) def find_lcm(numbers: List[int]) -> int: return reduce(lcm, numbers)
from solution import find_lcm def test_find_lcm_simple_case(): assert find_lcm([4, 6, 8]) == 24 def test_find_lcm_prime_numbers(): assert find_lcm([2, 5, 7, 11]) == 770 def test_find_lcm_multiples(): assert find_lcm([10, 20, 30, 40]) == 120 def test_find_lcm_consecutive_numbers(): assert find_lcm([1...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def find_lcm(numbers):", "function_name": "find_lcm", "parameter_list": "(numbers)" } ]
[ 0, 1, 0, 1, 0, 0, 1, 0, 1, 1 ]
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\nimport math\nfrom functools import reduce\n\ndef find_lcm(numbers: List[int]) -> int:\n \"\"\"\n Calculates the LCM of a list of i...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement: Least Common Multiple (LCM) of Multiple Numbers\n\nContext:\nCalculating the Least Common Multiple (LCM) of two numbers is a common task in programming. This problem extends that concept to finding the LCM of multiple numbers. The LCM of a set of integers is the small...
0.71597
Algorithm_7120
C
[ "lcm", "find_lcm" ]
2
[ [ "find_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7f209c9a5defaa27b745ee28f81664c487febf62
2adac921fee21d172f8859c44be60a4aedbe34f7
v1.0
complete
Algorithm
Algorithm_21229_C
from typing import List from concurrent.futures import ThreadPoolExecutor def partition(arr, low, high): # Partition function code pass def quicksort(arr, low, high): # Quicksort function code pass def threaded_quicksort(arr, low, high): # Threaded quicksort function code pass def multi_thre...
from concurrent.futures import ThreadPoolExecutor from typing import List def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] ...
from solution import multi_threaded_quick_sort def test_empty_list(): assert multi_threaded_quick_sort([]) == [] def test_single_element(): assert multi_threaded_quick_sort([1]) == [1] def test_sorted_list(): assert multi_threaded_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_li...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quicksort(arr, low, high):", "function_name": "quicksort", "parameter_list": "(ar...
[ 0, 0, 1, 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 concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\n\ndef quick_sort(arr, low, high):\n if low < high:\n p = part...
trial_gpt4o_7
{ "original_instruction": "### Question: Implementing an Efficient Sorting Algorithm with Threading\n\n**Context**: Sorting is a fundamental task in computer science. Your task is to implement an efficient sorting algorithm that leverages the power of multithreading to enhance performance. The algorithm should be a m...
0.519265
Algorithm_21229
C
[ "partition", "quicksort", "threaded_quicksort", "multi_threaded_quick_sort" ]
4
[ [ "multi_threaded_quick_sort", "threaded_quicksort" ], [ "quicksort", "partition" ], [ "threaded_quicksort", "partition" ], [ "threaded_quicksort", "quicksort" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7662c67d1f9617b31eb8b788ef694635aedcf065
d47efae1f9c28d456612559e0476c328800e23e1
v1.0
complete
Algorithm
Algorithm_12151_C
def fake_send_email(recipient, subject, body): """ A fake email sending function to mock sending email and return a controlled response. """ if not recipient or "@" not in recipient: return {"status": "failed", "message": "Invalid recipient email format"} if not subject: return ...
def send_email_to_supplier(recipient, subject, body): # This function would typically send an email pass def send_reorder_notification(recipient, item_name): """ Send a reorder notification email to a supplier. Args: recipient (str): The email of the recipient. item_name (str): The nam...
import pytest def fake_send_email(recipient, subject, body): """ A fake email sending function to mock sending email and return a controlled response. """ if not recipient or "@" not in recipient: return {"status": "failed", "message": "Invalid recipient email format"} if not subject: ...
[ { "docstring": null, "function_declaration": "def send_email_to_supplier(recipient, subject, body):", "function_name": "send_email_to_supplier", "parameter_list": "(recipient, subject, body)" }, { "docstring": "Send a reorder notification email to a supplier.\n\nArgs:\nrecipient (str): The e...
[ 0, 0, 1, 0, 0, 1, 1, 1, 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": "def send_email_to_supplier(recipient, subject, body):\n # This function would typically send an email\n pass\n\ndef send_reorder_notification(recipient, it...
trial_gpt4o_2
{ "original_instruction": "You are working on an inventory management system that helps businesses track their stock levels and reorder products when necessary. The system should send an email notification when the stock level of an item falls below the reorder threshold. To ensure your code sends the correct email, ...
0.716902
Algorithm_12151
C
[ "send_email_to_supplier", "send_reorder_notification" ]
2
[ [ "send_reorder_notification", "send_email_to_supplier" ] ]
1
[]
false
[]
false
pytest
false
[]
true
97ff310eff83609926aeebfb5251ddc0a061ecfe
1df84f9689cdc281fe540733f8f6292adf7411e3
v1.0
complete
Algorithm
Algorithm_5344_C
from typing import List def is_balanced_or_can_be_reversed(s: str) -> str: """ Determine if the string has balanced brackets or can be made balanced by reversing a single contiguous substring. >>> is_balanced_or_can_be_reversed("([])") 'Balanced' >>> is_balanced_or_can_be_reversed("([)]") 'Can be b...
def is_balanced(s): """ Helper function to check if a string has balanced brackets. """ stack = [] matching_bracket = {')': '(', ']': '[', '}': '{'} for char in s: if char in matching_bracket.values(): stack.append(char) elif char in matching_bracket.keys(): ...
def test_balanced(): assert is_balanced_or_can_be_reversed("([])") == 'Balanced' assert is_balanced_or_can_be_reversed("()[]{}") == 'Balanced' assert is_balanced_or_can_be_reversed("{[()]}") == 'Balanced' def test_can_be_balanced_by_reversing(): assert is_balanced_or_can_be_reversed("([)]") == 'Can be ...
[ { "docstring": "Helper function to check if a string has balanced brackets.", "function_declaration": "def is_balanced(s):", "function_name": "is_balanced", "parameter_list": "(s)" }, { "docstring": "Helper function to check if reversing a substring can lead to a balanced string.", "func...
[ 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_balanced_or_can_be_reversed(s: str) -> str:\n def is_balanced(s: str) -> bool:\n stack = []\n matching_bracket = {')': '(', '}': '{', ']'...
trial_gpt4o_2
{ "original_instruction": "### Problem Statement\n\n**Balanced Brackets with String Reversal**\n\nGiven a string containing the characters `{`, `}`, `[`, `]`, `(`, and `)`, determine if the string has balanced brackets. Additionally, if the string is not balanced, determine if reversing any single contiguous substrin...
0.720484
Algorithm_5344
C
[ "is_balanced", "reverse_and_check_balanced", "is_balanced_or_can_be_reversed" ]
3
[ [ "is_balanced_or_can_be_reversed", "is_balanced" ], [ "is_balanced_or_can_be_reversed", "reverse_and_check_balanced" ], [ "reverse_and_check_balanced", "is_balanced" ] ]
3
[]
false
[]
false
pytest
false
[]
true
3542a91ecddb4707008bf195e3b4906cc743ae50
a61e6af1a62ca8dc21a590346ba815d52ca849fe
v1.0
complete
Algorithm
Algorithm_12390_C
from typing import List def merge(left: List[int], right: List[int]) -> List[int]: """ Merges two sorted lists (left and right) into a single sorted list. >>> merge([1, 3, 5], [2, 4, 6]) [1, 2, 3, 4, 5, 6] >>> merge([1, 2, 3, 4, 5], [2, 4]) [1, 2, 2, 3, 4, 4, 5] """ pass def merge_sor...
from typing import List def merge(left: List[int], right: List[int]) -> List[int]: """ Merges two sorted lists (left and right) into a single sorted list. """ result = [] i = j = 0 # Merge the two lists while maintaining order while i < len(left) and j < len(right): if left[i] ...
from solution import merge, merge_sort def test_merge_empty(): assert merge([], []) == [] def test_merge_single_element(): assert merge([1], []) == [1] assert merge([], [1]) == [1] def test_merge_sorted_lists(): assert merge([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6] def test_merge_left_longer(): ...
[ { "docstring": "Merges two sorted lists (left and right) into a single sorted list.", "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docstring": "Sorts a list of integers in ascending order using the Merge Sort algorithm."...
[ 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": "from typing import List\n\ndef merge(left: List[int], right: List[int]) -> List[int]:\n \"\"\"\n Merges two sorted lists into one sorted list.\n \"\"\"\...
trial_gpt4o_9
{ "original_instruction": "### Context\nYou have been asked to implement a sorting algorithm that sorts a list of integers in ascending order. Notably, you are required to implement the Merge Sort algorithm. Merge Sort is a classic divide-and-conquer algorithm that effectively handles large lists with efficiency.\n\n...
0.567861
Algorithm_12390
C
[ "merge", "merge_sort" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cbd932c3beaeeb59534e9023b1417cf77dbb7bd3
9149222ec472c3426bc2ced84c239bac02934852
v1.0
complete
Algorithm
Algorithm_40112_C
import numpy as np def custom_decision_tree(data: np.ndarray, labels: np.ndarray, max_depth: int = 10, min_samples_split: int = 2, verbose: bool = False) -> dict: """ Build a decision tree classifier. Parameters: data (np.ndarray): A 2D numpy array where each row is a data point. labels (np.ndarra...
import numpy as np def gini_impurity(labels): """Calculate the Gini impurity for a list of labels.""" unique_labels, counts = np.unique(labels, return_counts=True) probabilities = counts / len(labels) gini = 1 - np.sum(probabilities ** 2) return gini def find_best_split(data, labels): """Find ...
import numpy as np from solution import custom_decision_tree def test_single_split(): data = np.array([ [1, 2], [2, 3], [3, 4], [4, 5], [5, 6] ]) labels = np.array([0, 0, 1, 1, 1]) tree = custom_decision_tree(data, labels, max_depth=1) assert tree == {'featur...
[]
[ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "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 calculate_gini(labels):\n \"\"\"\n Calculate the Gini impurity for a list of labels.\n \"\"\"\n if len(labels) == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "### Implementing a Decision Tree from Scratch\n\nYou are required to write a function `custom_decision_tree` that builds a Decision Tree classifier for a given dataset. The function should include detailed logging for each step of the tree construction process and handle edge cases graceful...
0.616511
Algorithm_40112
C
[ "gini_impurity", "find_best_split", "build_tree", "custom_decision_tree" ]
4
[ [ "build_tree", "find_best_split" ], [ "custom_decision_tree", "build_tree" ], [ "find_best_split", "gini_impurity" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
14f0e701c19fd2b1e99f398085f46a3e7e2b19ad
4d0c9a5cf879baacaa05c48c4b0a8f6ed6e1d90d
v1.0
complete
Algorithm
Algorithm_1016_C
def parse_expression(expression: str) -> float: """ Implement a simple recursive descent parser for a subset of arithmetic expressions. Expressions consist of non-negative integers and the operators +, -, *, and /. Parentheses may be used to alter the default precedence. >>> parse_expression("2 + 3 * 4...
import re def parse_expression(expression: str) -> float: tokens = tokenize(expression) tokens.append('$') # End of input marker index = 0 def next_token(): nonlocal index return tokens[index] def consume_token(): nonlocal index index += 1 def err...
from solution import parse_expression def test_simple_addition(): assert parse_expression("2 + 3") == 5 def test_simple_subtraction(): assert parse_expression("7 - 2") == 5 def test_simple_multiplication(): assert parse_expression("3 * 4") == 12 def test_simple_division(): assert parse_expression("1...
[ { "docstring": null, "function_declaration": "def parse_expression(expression):", "function_name": "parse_expression", "parameter_list": "(expression)" }, { "docstring": null, "function_declaration": "def tokenize(expression):", "function_name": "tokenize", "parameter_list": "(ex...
[ 0, 0, 0, 0, 0, 0, 0, 1, 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 parse_expression(expression):\n \"\"\"\n Parses and evaluates an arithmetic expression.\n \"\"\"\n def tokenize(expression):\n tokens = []...
trial_gpt4o_7
{ "original_instruction": "### Problem: Implement a Simple Recursive Descent Parser\n\nYou are tasked with implementing a simple recursive descent parser for a subset of arithmetic expressions. The expressions consist of non-negative integers and the operators `+`, `-`, `*`, and `/`, with correct handling of operator...
0.590394
Algorithm_1016
C
[ "parse_expression", "tokenize" ]
2
[ [ "parse_expression", "tokenize" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2b1e580f09ac394d2f03febb2e188cd7c9188c50
65db44f38a82a5fe82cc5791e4f16e851aa49713
v1.0
complete
Algorithm
Algorithm_35352_C
def is_prime_sequence(sequence: list) -> bool: """ Returns True if all elements in the sequence are prime numbers, False otherwise. >>> is_prime_sequence([2, 3, 5, 7, 11]) True >>> is_prime_sequence([2, 4, 6, 8]) False """ pass def prime_count_upto(n: int) -> int: """ Retur...
import math def is_prime(num): if num < 2: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def is_prime_sequence(sequence: list) -> bool: """ Returns True if all elements in the sequence are prime numbers, False otherwi...
from solution import is_prime_sequence, prime_count_upto def test_is_prime_sequence_all_primes(): assert is_prime_sequence([2, 3, 5, 7, 11]) == True def test_is_prime_sequence_includes_non_prime(): assert is_prime_sequence([2, 4, 6, 8]) == False def test_is_prime_sequence_single_prime(): assert is_prime_...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns True if all elements in the sequence are prime numbers, False otherwise.", "function_declaration": "def is_prime_sequence(sequence):", ...
[ 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 is_prime(n: int) -> bool:\n \"\"\"\n Checks if a given integer n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\nYou are tasked with implementing two functions that handle and analyze sequences of integers with respect to prime numbers.\n\n#### Task\n\n**Function 1:** `is_prime_sequence(sequence: list) -> bool`\n\nImplement a function to verify if a given list consist...
0.773389
Algorithm_35352
C
[ "is_prime", "is_prime_sequence", "prime_count_upto" ]
3
[ [ "is_prime_sequence", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8d6e5f113cf3049b98a856906879622ff2330dd4
1f4642795fa521338cd128cfb1a460347a754929
v1.0
complete
Algorithm
Algorithm_17318_C
def is_rotatable_prime(number: int) -> bool: """ Checks if a given number is a rotatable prime. A number is considered to be a 'rotatable prime' if each rotation of its digits forms a valid prime number. >>> is_rotatable_prime(197) True >>> is_rotatable_prime(23) False >>> is_rotat...
def is_prime(n): """ Checks if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def ...
from solution import is_rotatable_prime def test_single_digit_primes(): assert is_rotatable_prime(2) == True assert is_rotatable_prime(3) == True assert is_rotatable_prime(5) == True assert is_rotatable_prime(7) == True def test_non_prime_single_digits(): assert is_rotatable_prime(1) == False ...
[ { "docstring": "Checks if a number is prime. ", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generate all rotations of the digits of a number ", "function_declaration": "def get_rotations(number):", "function_name...
[ 0, 0, 0, 0, 0, 0, 0, 1, 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 sympy import isprime\n\ndef rotate_number(number):\n \"\"\"\n Generator function which yields all rotations of a number's digits.\n \"\"\"\n num...
trial_gpt4o_7
{ "original_instruction": "### Problem Statement: Prime Number Rotation\n\nA prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A number is considered to be a \"rotatable prime\" if each rotation of its digits forms a valid prime number.\n\nFor example, 1...
0.743471
Algorithm_17318
C
[ "is_prime", "get_rotations", "is_rotatable_prime" ]
3
[ [ "is_rotatable_prime", "get_rotations" ], [ "is_rotatable_prime", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b5d871a331e954fbf3349ca787ac877ee926f990
cde163f0c3959aa6520e90f796edc6bbbb1a5881
v1.0
complete
Algorithm
Algorithm_46949_C
from typing import List def total_distance(distances: List[float]) -> float: """ Calculate the total distance run over a specified number of days. >>> total_distance([5.0, 7.2, 3.3, 4.7, 6.6]) 26.8 >>> total_distance([10.5, 8.6, 12.3, 7.4]) 38.8 """ def average_distance(distances: List[float]) -> ...
from typing import List def total_distance(distances: List[float]) -> float: if not all(d >= 0 for d in distances): raise ValueError("All distances must be non-negative") return round(sum(distances), 2) def average_distance(distances: List[float]) -> float: if not distances: return 0.0 ...
import pytest from solution import total_distance, average_distance, longest_run, running_summary def test_total_distance(): assert total_distance([5.0, 7.2, 3.3, 4.7, 6.6]) == 26.8 assert total_distance([10.5, 8.6, 12.3, 7.4]) == 38.8 with pytest.raises(ValueError): total_distance([-1.0, 5.0]) de...
[ { "docstring": null, "function_declaration": "def total_distance(distances):", "function_name": "total_distance", "parameter_list": "(distances)" }, { "docstring": null, "function_declaration": "def average_distance(distances):", "function_name": "average_distance", "parameter_li...
[ 0, 0, 0, 1, 0, 0, 1, 1, 1, 0 ]
4
medium
0.4
{ "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 total_distance(distances: List[float]) -> float:\n \"\"\"\n Returns the total distance run over the specified days.\n \"\...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement\n\nYou are tasked with developing a feature for a fitness tracking application that analyzes a user's running performance over a specified number of days. The application should calculate the user's total distance ran, average distance per day, and identify the longest...
0.633521
Algorithm_46949
C
[ "total_distance", "average_distance", "longest_run", "running_summary" ]
4
[ [ "running_summary", "average_distance" ], [ "running_summary", "longest_run" ], [ "running_summary", "total_distance" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2a7a54bec77a57d026975b2785b3fe1d7961034b
52c332a1c898b34d0688e0139fe869055972836c
v1.0
complete
Algorithm
Algorithm_10750_C
def prime_factors_count(x: int) -> int: """ Returns the count of distinct prime factors of x. >>> prime_factors_count(10) 2 >>> prime_factors_count(30) 3 >>> prime_factors_count(7) 1 >>> prime_factors_count(60) 3 >>> prime_factors_count(11) 1 """ pass def find_number...
import math def prime_factors_count(x: int) -> int: """ Returns the count of distinct prime factors of x. """ count = 0 if x % 2 == 0: count += 1 while x % 2 == 0: x //= 2 for i in range(3, int(math.sqrt(x)) + 1, 2): if x % i == 0: count += 1 ...
def test_prime_factors_count(): assert prime_factors_count(10) == 2 assert prime_factors_count(30) == 3 assert prime_factors_count(7) == 1 assert prime_factors_count(60) == 3 assert prime_factors_count(11) == 1 def test_find_number_with_k_prime_factors(): assert find_number_with_k_prime_factors...
[ { "docstring": "Returns the count of distinct prime factors of x.", "function_declaration": "def prime_factors_count(x):", "function_name": "prime_factors_count", "parameter_list": "(x)" }, { "docstring": "Finds the smallest integer greater than or equal to n\nthat has exactly k distinct pri...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def prime_factors_count(x: int) -> int:\n \"\"\"\n Returns the count of distinct prime factors of x.\n \"\"\"\n def is_prime(num):\n if num <=...
trial_gpt4o_9
{ "original_instruction": "**Context**:\nSuppose there is a problem involving the computation of prime factors and determining the smallest integer greater than or equal to a given number that has exactly a specified number of distinct prime factors. This problem requires handling number theory and optimization techn...
0.747251
Algorithm_10750
C
[ "prime_factors_count", "find_number_with_k_prime_factors" ]
2
[ [ "find_number_with_k_prime_factors", "prime_factors_count" ] ]
1
[]
false
[]
false
pytest
false
[]
true
9024662fa7cb52f53060a8b7547b77c99628edc4
c9211f9e5c83e07c3a6124e8a833741131a33244
v1.0
complete
Algorithm
Algorithm_13346_C
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import precision_score, recall_score def evaluate_recommendation_system(dataset: pd.DataFrame, user_id: int, test_size: float) -> None: """Evaluate the recommendation system for a specific user. ...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import precision_score, recall_score def data_handling(data: pd.DataFrame) -> tuple: """ Handle the data processing step. Args: - data (pd.DataFrame): The dataset containing 'userId', '...
import pandas as pd from solution import evaluate_recommendation_system def test_valid_evaluation(): data = pd.DataFrame({ 'userId': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'movieId': [10, 20, 30, 40, 50, 60, 70, 80, 90], 'rating': [4, 5, 3, 2, 5, 5, 4, 3, 2] }) evaluate_recommendation_system(...
[ { "docstring": "Handle the data processing step.\n\nArgs:\n- data (pd.DataFrame): The dataset containing 'userId', 'movieId', and 'rating' columns.\n\nReturns:\n- users (np.array): Unique user IDs.\n- movies (np.array): Unique movie IDs.", "function_declaration": "def data_handling(data):", "function_na...
[ 0, 0, 0, 1, 1, 1, 1, 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 pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_score, recall_score\n\ndef data_handling(data: p...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n**Title**: Build and Test a Recommendation System\n\n**Task**:\nUsing the provided dataset management and collaborative filtering methods, implement a function to process a dataset, generate movie recommendations for a specific user, and evaluate the recomm...
0.677846
Algorithm_13346
C
[ "data_handling", "collaborative_filtering", "evaluate_recommendation_system" ]
3
[ [ "evaluate_recommendation_system", "collaborative_filtering" ], [ "evaluate_recommendation_system", "data_handling" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
bbbd598e698b276c2514734a84aa2adf5d1a6c21
fe7d438c09bf30c0a87252dc6b4ee93ccf62bbeb
v1.0
complete
Algorithm
Algorithm_8022_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sort an array of integers using the merge sort algorithm and return the sorted array. >>> merge_sort([34, 7, 23, 32, 5, 62]) [5, 7, 23, 32, 34, 62] >>> merge_sort([]) [] >>> merge_sort([1]) [1] ...
from typing import List def merge_sort(arr: List[int]) -> List[int]: 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: List[int], right: List[int]) -> List[int]: so...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reversed_list(): assert merge...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 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 merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me...
trial_gpt4o_9
{ "original_instruction": "### Sorting an Array Using Merge Sort\n\n#### Context\nYou are asked to implement the merge sort algorithm to sort an array of integers. Merge sort is a classical divide-and-conquer algorithm that divides the array into halves, recursively sorts each half, and then merges the sorted halves ...
0.6571
Algorithm_8022
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11da94f612130fb49ed76423006fd9d18de4d1e1
5cb8890a27cfd3bfe8b6a936d752d0eadde7b34e
v1.0
complete
Algorithm
Algorithm_16618_C
def dp_fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using dynamic programming. >>> dp_fibonacci(5) == 5 >>> dp_fibonacci(0) == 0 >>> dp_fibonacci(-1) == "Error: Input must be a non-negative integer." """ pass def matrix_fibonacci(n: int) -> int: """ Calculate the nth Fib...
def dp_fibonacci(n: int) -> int: if n < 0: return "Error: Input must be a non-negative integer." if n == 0: return 0 if n == 1: return 1 fib = [0, 1] for i in range(2, n + 1): fib.append(fib[-1] + fib[-2]) return fib[n] def matrix_mult(A, B): return [[A[...
def test_dp_fibonacci(): assert dp_fibonacci(0) == 0 assert dp_fibonacci(1) == 1 assert dp_fibonacci(2) == 1 assert dp_fibonacci(3) == 2 assert dp_fibonacci(4) == 3 assert dp_fibonacci(5) == 5 assert dp_fibonacci(10) == 55 assert dp_fibonacci(-1) == "Error: Input must be a non-negative i...
[ { "docstring": null, "function_declaration": "def dp_fibonacci(n):", "function_name": "dp_fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def matrix_mult(A, B):", "function_name": "matrix_mult", "parameter_list": "(A, B)" }, { "docstri...
[ 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 dp_fibonacci(n: int) -> int:\n if n < 0:\n return \"Error: Input must be a non-negative integer.\"\n if n == 0:\n return 0\n if n == 1...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nYou are given the task of creating a function that calculates the nth Fibonacci number using two different techniques: dynamic programming and matrix exponentiation. Examine the strengths and weaknesses of each approach based on time and space complexity.\n\n### Req...
0.723684
Algorithm_16618
C
[ "dp_fibonacci", "matrix_mult", "matrix_pow", "matrix_fibonacci" ]
4
[ [ "matrix_fibonacci", "matrix_pow" ], [ "matrix_pow", "matrix_mult" ] ]
2
[]
false
[]
false
pytest
false
[]
true
f855f4495a386db86c6101c5ebf92a7f07d0ed3a
f2b3fd8f144b0eb035d9921f759766b92176e531
v1.0
complete
Algorithm
Algorithm_18146_C
def generate_fibonacci(n: int) -> list: """ Generate the first n terms of the Fibonacci sequence. Args: n: An integer representing the number of terms to generate Returns: list: A list containing the first n terms of the Fibonacci sequence Raises: ValueError: If n is not a positiv...
def generate_fibonacci(n: int) -> list: """ Generate the first n terms of the Fibonacci sequence. Args: n: An integer representing the number of terms to generate Returns: list: A list containing the first n terms of the Fibonacci sequence Raises: ValueError: If n is not a positive in...
from solution import generate_fibonacci, sum_of_even_fibonacci def test_generate_fibonacci_standard_cases(): assert generate_fibonacci(1) == [0] assert generate_fibonacci(2) == [0, 1] assert generate_fibonacci(5) == [0, 1, 1, 2, 3] assert generate_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] def...
[ { "docstring": "Generate the first n terms of the Fibonacci sequence.\n\nArgs:\nn: An integer representing the number of terms to generate\n\nReturns:\nlist: A list containing the first n terms of the Fibonacci sequence\n\nRaises:\nValueError: If n is not a positive integer", "function_declaration": "def ge...
[ 0, 1, 1, 1, 1, 1, 0, 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 generate_fibonacci(n: int) -> list:\n \"\"\"\n Generate the first n terms of the Fibonacci sequence.\n\n Args:\n n: An integer representing the n...
trial_gpt4o_8
{ "original_instruction": "### Fibonacci Sequence and Even Sum Calculation\n\n#### Context\nYou need to work with the Fibonacci sequence and perform operations on its even-valued terms. The Fibonacci sequence is defined as:\n\n- \\( F_0 = 0, F_1 = 1 \\)\n- \\( F_n = F_{n-1} + F_{n-2} \\) for \\( n \\geq 2 \\)\n\n####...
0.734291
Algorithm_18146
C
[ "generate_fibonacci", "sum_of_even_fibonacci" ]
2
[ [ "sum_of_even_fibonacci", "generate_fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3e4cd22330e28e98c393fe5c652697040bd6ae3e
e86f143e554e7888cb962e38032a7a0395445b94
v1.0
complete
Algorithm
Algorithm_12728_C
def shift_encrypt(shift: int, message: str) -> str: """ Encrypt the given message using the Shift Cipher with the given shift value. Args: shift (int): The number of positions to shift each letter. message (str): The message to encrypt. Returns: str: The encrypted message. ...
def shift_encrypt(shift, message): """ Encrypt the given message using the Shift Cipher with the given shift value. Args: shift (int): The number of positions to shift each letter. message (str): The message to encrypt. Returns: str: The encrypted message. """ encrypted_mes...
from solution import shift_encrypt, shift_decrypt def test_shift_encrypt(): assert shift_encrypt(3, "Hello, World!") == "Khoor, Zruog!" assert shift_encrypt(0, "Hello, World!") == "Hello, World!" assert shift_encrypt(26, "Hello, World!") == "Hello, World!" assert shift_encrypt(-3, "Hello, World!") == "...
[ { "docstring": "Encrypt the given message using the Shift Cipher with the given shift value.\n\nArgs:\nshift (int): The number of positions to shift each letter.\nmessage (str): The message to encrypt.\n\nReturns:\nstr: The encrypted message.", "function_declaration": "def shift_encrypt(shift, message):", ...
[ 1, 1, 0, 1, 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 shift_encrypt(shift: int, message: str) -> str:\n \"\"\"\n Encrypts the message using the Shift Cipher.\n \"\"\"\n encrypted_message = []\n fo...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: Implementing a Shift Cipher\n\n#### Scenario:\nYou are working on an encryption module for a secure communication app. Your task is to implement the Shift Cipher (also known as the Caesar Cipher) to provide basic encryption and decryption of user messages. Th...
0.768234
Algorithm_12728
C
[ "shift_encrypt", "shift_decrypt" ]
2
[ [ "shift_decrypt", "shift_encrypt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
61a7f402faaa6466a8099643a90ce2d54dd8527e
da6d412edc5796f39139cce79ccee888cba519ab
v1.0
complete
Algorithm
Algorithm_11810_C
def is_rotation(str1: str, str2: str) -> bool: """ Checks if str1 is a rotation of str2. >>> is_rotation("waterbottle", "erbottlewat") True >>> is_rotation("waterbottle", "bottlewater") True >>> is_rotation("waterbottle", "elttobretaw") False >>> is_rotation("rotation", "tationro") ...
def is_rotation(str1: str, str2: str) -> bool: """ Checks if str1 is a rotation of str2. """ if len(str1) != len(str2): return False return str2 in (str1 + str1) def visualize_rotation_check(str1: str, str2: str) -> str: """ Provides a visual representation of the rotation check pro...
from solution import is_rotation, visualize_rotation_check def test_is_rotation_true(): assert is_rotation("waterbottle", "erbottlewat") == True assert is_rotation("waterbottle", "bottlewater") == True assert is_rotation("rotation", "tationro") == True def test_is_rotation_false(): assert is_rotation(...
[ { "docstring": "Checks if str1 is a rotation of str2.", "function_declaration": "def is_rotation(str1, str2):", "function_name": "is_rotation", "parameter_list": "(str1, str2)" }, { "docstring": "Provides a visual representation of the rotation check process.", "function_declaration": "d...
[ 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 is_rotation(str1: str, str2: str) -> bool:\n \"\"\"\n Checks if str1 is a rotation of str2.\n \"\"\"\n if len(str1) != len(str2):\n return...
trial_gpt4o_9
{ "original_instruction": "### Question: String Rotation Checker\n\n#### Scenario:\nString manipulation is a common task in various programming challenges. One specific operation involves determining if one string is a rotation of another string. This can be useful in real-world applications such as password checks, ...
0.67223
Algorithm_11810
C
[ "is_rotation", "visualize_rotation_check" ]
2
[ [ "visualize_rotation_check", "is_rotation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1ca16aaf2d30c14bb1df78e78dc30b9cde3d6426
8f2c1899fb6e209c5ae94e3e7287a0aa417b3c76
v1.0
complete
Algorithm
Algorithm_22573_C
def rot13_encode(data: str) -> str: """ Encode the given string using ROT13. Only alphabet characters are transformed. Other characters remain unchanged. >>> rot13_encode("Hello, World!") "Uryyb, Jbeyq!" >>> rot13_encode("1234567890!@#$%^&*()") "1234567890!@#$%^&*()" >>> rot13_encode("a1b2c3!XyZ...
def rot13_encode(data: str) -> str: """ Encode the given string using ROT13. Only alphabet characters are transformed. Other characters remain unchanged. """ def encode_char(c): if 'a' <= c <= 'z': return chr((ord(c) - ord('a') + 13) % 26 + ord('a')) elif 'A' <= c <= ...
from solution import rot13_encode, rot13_decode def test_rot13_with_letters(): assert rot13_encode("Hello, World!") == "Uryyb, Jbeyq!" assert rot13_decode("Uryyb, Jbeyq!") == "Hello, World!" def test_rot13_with_empty_string(): assert rot13_encode("") == "" assert rot13_decode("") == "" def test_rot13...
[ { "docstring": "Encode the given string using ROT13.\nOnly alphabet characters are transformed.\nOther characters remain unchanged.", "function_declaration": "def rot13_encode(data):", "function_name": "rot13_encode", "parameter_list": "(data)" }, { "docstring": "Decode the given string usin...
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rot13_transform(char):\n \"\"\"\n Helper function to transform a single character using ROT13 substitution.\n \"\"\"\n if char.isalpha():\n ...
trial_gpt4o_8
{ "original_instruction": "### Rot13 Encoder/Decoder With Error Handling\n\nIn this task, you need to implement a Rot13 encoder and decoder that can handle various input scenarios, including edge cases. Rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. ...
0.67324
Algorithm_22573
C
[ "rot13_encode", "rot13_decode" ]
2
[ [ "rot13_decode", "rot13_encode" ] ]
1
[]
false
[]
false
pytest
true
[]
true
68bae7b1d89dc586de005948a42a27aa2a927e7d
bf71128ea7ce5f714bb46515c17a0ddd8cc0d050
v1.0
complete
Algorithm
Algorithm_1733_C
import hashlib import datetime def hash_block(block): """ Generates a SHA-256 hash for the given block. >>> block = {'index': 1, 'timestamp': datetime.datetime(2023, 1, 1), 'data': 'Test Block', 'prev_hash': '0000'} >>> block['hash'] = hash_block(block) >>> block['hash'] == hashlib.sha256(f"1{date...
import hashlib import datetime def hash_block(block): """ Generates a SHA-256 hash for the given block. """ block_str = f"{block['index']}{block['timestamp']}{block['data']}{block['prev_hash']}" return hashlib.sha256(block_str.encode()).hexdigest() def add_block(blockchain, data): """ Adds...
import datetime from solution import hash_block, add_block, is_valid_chain def test_hash_block(): block = { 'index': 1, 'timestamp': datetime.datetime(2023, 1, 1), 'data': 'Test Block', 'prev_hash': '0000' } block['hash'] = hash_block(block) expected_hash = hashlib.sha25...
[ { "docstring": "Generates a SHA-256 hash for the given block.", "function_declaration": "def hash_block(block):", "function_name": "hash_block", "parameter_list": "(block)" }, { "docstring": "Adds a new block with the provided data to the blockchain.", "function_declaration": "def add_bl...
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import hashlib\nimport datetime\n\ndef hash_block(block):\n block_str = f\"{block['index']}{block['timestamp']}{block['data']}{block['prev_hash']}\"\n retu...
trial_gpt4o_2
{ "original_instruction": "### Assignment: Implement a Simple Blockchain System\n\nYou will be creating a basic Blockchain system. This will involve creating blocks, adding them to the blockchain, and validating the entire blockchain.\n\n### Task:\n1. Improve the `hash_block` function to ensure it provides a unique a...
0.514653
Algorithm_1733
C
[ "hash_block", "add_block", "is_valid_chain" ]
3
[ [ "add_block", "hash_block" ], [ "is_valid_chain", "hash_block" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4a50d9ac912a6983a990630ad622709fb3796d88
b8f258638490eea1c9a20d71505010ea32198fea
v1.0
complete
Algorithm
Algorithm_16723_C
from typing import List, Tuple def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. """ pass def segregate_primes(arr: List[int]) -> Tuple[List[int], List[int]]: """ Given a list of integers, segregate them into two lists: one containing the prime numbers, and t...
import math from typing import List, Tuple def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 ...
from solution import segregate_primes def test_segregate_primes_basic(): assert segregate_primes([10, 29, 15, 23, 8, 1]) == ([29, 23], [10, 15, 8, 1]) assert segregate_primes([2, 3, 4, 5, 6]) == ([2, 3, 5], [4, 6]) def test_segregate_primes_edge_cases(): assert segregate_primes([]) == ([], []) assert ...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Given a list of integers, segregate them into two lists: one containing the prime numbers,\nand the other conta...
[ 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, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if a number is a prime.\n \n Args:\n n : i...
trial_gpt4o_6
{ "original_instruction": "### Coding Assessment Question\n\nIn a software application, you might need to process a list of integers to segregate the prime numbers from the non-prime ones, performing this task efficiently given the potential size of the data.\n\n#### Function Definition\n\n```python\ndef segregate_pr...
0.698983
Algorithm_16723
C
[ "is_prime", "segregate_primes" ]
2
[ [ "segregate_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7947697fb68c1191cd472834935118ead88a417
80b6a43216963139a3e166efa75cffa1d261b9e6
v1.0
complete
Algorithm
Algorithm_40653_C
def strassen_matrix_mult(A, B): """ Perform matrix multiplication using the Strassen algorithm. Args: A: List of lists representing a square matrix of size 2^n x 2^n. B: List of lists representing another square matrix of size 2^n x 2^n. Returns: List of lists represent...
import numpy as np def add_matrix(A, B): """ Adds two matrices A and B. """ return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))] def subtract_matrix(A, B): """ Subtracts matrix B from matrix A. """ return [[A[i][j] - B[i][j] for j in range(len(A[0]))] for i in ...
def test_strassen_matrix_mult_2x2(): A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] result = strassen_matrix_mult(A, B) assert result == [ [19, 22], [43, 50] ] def test_strassen_matrix_mult_4x4(): C = [ [1, 2, 3, 4], [5, 6, ...
[ { "docstring": "Adds two matrices A and B.", "function_declaration": "def add_matrix(A, B):", "function_name": "add_matrix", "parameter_list": "(A, B)" }, { "docstring": "Subtracts matrix B from matrix A.", "function_declaration": "def subtract_matrix(A, B):", "function_name": "subtr...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def strassen_matrix_mult(A, B):\n def add_matrix(X, Y):\n size = len(X)\n return [[X[i][j] + Y[i][j] for j in range(size)] for i in range(size)]...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nYou are to implement a function to calculate the **Matrix Product** using the Strassen Algorithm, which is more efficient than the standard matrix multiplication approach for larger matrices.\n\n### Requirements\n\nWrite a function `strassen_matrix_mult` that takes ...
0.497107
Algorithm_40653
C
[ "add_matrix", "subtract_matrix", "split_matrix", "strassen_matrix_mult" ]
4
[ [ "strassen_matrix_mult", "add_matrix" ], [ "strassen_matrix_mult", "split_matrix" ], [ "strassen_matrix_mult", "subtract_matrix" ] ]
3
[]
false
[]
false
pytest
false
[ "numpy" ]
false
6eb6767ecf2c668c0621be7b093d3a7e492167b8
7e2fb9b122d32d9cd4862d17d6fcad5367ca1096
v1.0
complete
Algorithm
Algorithm_41427_C
def approximate_steiner_tree(graph: dict[str, list[str]], required_vertices: set[str]) -> set[tuple[str, str]]: """ Approximate the Steiner tree for a given undirected graph and a set of required vertices. Args: graph (dict): A dictionary where keys are node identifiers (as strings), and values are...
import heapq from collections import defaultdict, deque def dijkstra(graph, start): """Helper function to perform Dijkstra's algorithm to find shortest paths.""" distances = {node: float('infinity') for node in graph} distances[start] = 0 priority_queue = [(0, start)] predecessors = {node: None for...
from solution import approximate_steiner_tree def test_approximate_steiner_tree_single_vertex(): graph = { "1": ["2", "3"], "2": ["1", "3", "4", "5"], "3": ["1", "2", "5"], "4": ["2"], "5": ["2", "3"] } required_vertices = {"1"} assert approximate_steiner_tree(gr...
[ { "docstring": "Helper function to perform Dijkstra's algorithm to find shortest paths.", "function_declaration": "def dijkstra(graph, start):", "function_name": "dijkstra", "parameter_list": "(graph, start)" }, { "docstring": "Helper function to reconstruct the shortest path from start to e...
[ 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": "import heapq\n\ndef dijkstra(graph, start):\n \"\"\"\n Dijkstra's Algorithm to find shortest paths from start node to all other nodes.\n \"\"\"\n dis...
trial_gpt4o_1
{ "original_instruction": "### Question: Finding Steiner Tree Approximation in an Undirected Graph\n\nThe Steiner tree problem for a given graph and a set of required vertices can be seen as finding a minimal subgraph that spans all the given required vertices. In this task, you are required to implement an approxima...
0.470685
Algorithm_41427
C
[ "dijkstra", "get_shortest_path", "approximate_steiner_tree" ]
3
[ [ "approximate_steiner_tree", "dijkstra" ], [ "approximate_steiner_tree", "get_shortest_path" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1088c98e45375700e8aa28387f2d43727304637d
86d1f96e7ad66290abdfa96b055b4b5e2208fa40
v1.0
complete
Algorithm
Algorithm_19143_C
def sort_quick(arr: list) -> list: """ Quick Sort algorithm implementation. This function takes a list of integers and returns a sorted list. >>> sort_quick([3, 6, 8, 10, 1, 2, 1]) [1, 1, 2, 3, 6, 8, 10] >>> sort_quick([1, 2, 3]) [1, 2, 3] >>> sort_quick([3, 2, 1]) [1, 2, 3] >>> sort_quick([]) [...
def sort_quick(arr): """ Quick Sort algorithm implementation. """ if not all(isinstance(x, int) for x in arr): raise TypeError("sort_quick() only accepts lists of integers") if len(arr) < 2: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] m...
def test_sort_quick(): assert sort_quick([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] assert sort_quick([1, 2, 3]) == [1, 2, 3] assert sort_quick([3, 2, 1]) == [1, 2, 3] assert sort_quick([]) == [] assert sort_quick([-1, -10, 5, 3, 0]) == [-10, -1, 0, 3, 5] try: sort_quick([1, 'two'...
[ { "docstring": "Quick Sort algorithm implementation.", "function_declaration": "def sort_quick(arr):", "function_name": "sort_quick", "parameter_list": "(arr)" }, { "docstring": "Merge Sort algorithm implementation.", "function_declaration": "def sort_merge(arr):", "function_name": "...
[ 1, 0, 1, 0, 1, 1, 1, 1, 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 sort_quick(arr):\n if not all(isinstance(x, int) for x in arr):\n raise TypeError(\"sort_quick() only accepts lists of integers\")\n if len(arr)...
trial_gpt4o_9
{ "original_instruction": "### Problem: Advanced Sorting Algorithms Implementation\n\nYour task is to implement advanced sorting algorithms that handle various data structures and ordering requirements efficiently. You'll implement functions for each sorting algorithm and validate their accuracy and performance.\n\n#...
0.614
Algorithm_19143
C
[ "sort_quick", "sort_merge", "sort_heap", "sort_counting", "sort_bucket" ]
5
[ [ "sort_bucket", "sort_quick" ] ]
1
[]
false
[]
false
pytest
false
[]
true
e6b2fcce45532f31a2cd3ea81d53ad91620b9941
81715733b63cc1e52b3030bcf80c65da0bf7690d
v1.0
complete
Algorithm
Algorithm_9294_C
def binary_search_insert_position(arr: list[int], val: int, start: int, end: int) -> int: """ Find the index to insert val in arr[start:end] using binary search. Args: - arr (list[int]): The list in which to search for the insertion position. - val (int): The value to be inserted. - start (...
def binary_search_insert_position(arr: list[int], val: int, start: int, end: int) -> int: """ Find the index to insert val in arr[start:end] using binary search. Args: - arr (list[int]): The list in which to search for the insertion position. - val (int): The value to be inserted. - start (...
from solution import binary_search_insert_position, binary_insertion_sort def test_binary_search_insert_position(): assert binary_search_insert_position([1, 3, 5, 7], 4, 0, 3) == 2 assert binary_search_insert_position([1, 3, 5, 7], 0, 0, 3) == 0 assert binary_search_insert_position([1, 3, 5, 7], 8, 0, 3) =...
[ { "docstring": "Find the index to insert val in arr[start:end] using binary search.\n\nArgs:\n- arr (list[int]): The list in which to search for the insertion position.\n- val (int): The value to be inserted.\n- start (int): The starting index of the search range (inclusive).\n- end (int): The ending index of t...
[ 0, 0, 1, 1, 1, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def binary_search_insert_position(arr: list[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Find the index to insert val in arr[start:end] using b...
trial_gpt4o_9
{ "original_instruction": "Binary Search and Sorting Algorithms\n\nYou are required to implement two functions from scratch: one for performing insertions using binary search and another for sorting a list using an insertion sort algorithm enhanced with binary search for finding the correct position. Implement the fo...
0.626639
Algorithm_9294
C
[ "binary_search_insert_position", "binary_insertion_sort" ]
2
[ [ "binary_insertion_sort", "binary_search_insert_position" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f25402cf7ffebfa6b10da1402e58d8764002c54a
702aab032727b09e940ba8c02d10462c0a8db7c1
v1.0
complete
Algorithm
Algorithm_19480_C
from typing import List def find_sync_time(intervals: List[int]) -> int: """ Function to find the first minute after the initial ringing when all the bells ring simultaneously again. >>> find_sync_time([5, 7, 11]) 385 >>> find_sync_time([2, 3, 4]) 12 """ pass def test_single_bell(): as...
from math import gcd from functools import reduce from typing import List def lcm(a: int, b: int) -> int: """ Helper function to calculate least common multiple (LCM) of two numbers. """ return abs(a * b) // gcd(a, b) def lcm_of_list(nums: List[int]) -> int: """ Helper function to calculate th...
from solution import find_sync_time def test_single_bell(): assert find_sync_time([5]) == 5 def test_multiple_bells(): assert find_sync_time([5, 7, 11]) == 385 assert find_sync_time([2, 3, 4]) == 12 assert find_sync_time([6, 8, 12]) == 24 def test_prime_intervals(): assert find_sync_time([3, 5, 7...
[ { "docstring": "Helper function to calculate least common multiple (LCM) of two numbers.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Helper function to calculate the LCM of a list of numbers.", "function_declaration": ...
[ 1, 1, 0, 0, 0, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import gcd\nfrom functools import reduce\nfrom typing import List\n\ndef lcm(x, y):\n return x * y // gcd(x, y)\n\ndef find_sync_time(intervals: Lis...
trial_gpt4o_7
{ "original_instruction": "### Programming Question: Synchronization of Bells\n\nIn a village, there are several churches, each having a bell that rings at a fixed interval in minutes. The intervals can vary from church to church. The bell in the first church rings every `a` minutes, the bell in the second church rin...
0.602016
Algorithm_19480
C
[ "lcm", "lcm_of_list", "find_sync_time" ]
3
[ [ "find_sync_time", "lcm_of_list" ], [ "lcm_of_list", "lcm" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cd55391271ff9c37b0448b19c6b637f65ab6a3c4
90c91dee4cd0816cf3ad904b53ba3420849af2c2
v1.0
complete
Algorithm
Algorithm_15251_C
class IntervalTreeNode: def __init__(self, interval, max_end, left=None, right=None): """ Initializes an Interval Tree node. :param interval: The interval represented by this node. :param max_end: The maximum end value of all intervals in the subtree rooted at this node. :pa...
class IntervalTreeNode: def __init__(self, interval, max_end, left=None, right=None): """ Initializes an Interval Tree node. :param interval: The interval represented by this node. :param max_end: The maximum end value of all intervals in the subtree rooted at this node. ...
import pytest from solution import IntervalTreeNode, build_interval_tree, find_overlapping_intervals def test_build_interval_tree_empty(): assert build_interval_tree([]) is None def test_build_interval_tree_single_interval(): interval = (1, 5) tree = build_interval_tree([interval]) assert tree is not ...
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class IntervalTreeNode:\n def __init__(self, interval):\n self.interval = interval\n self.left = None\n self.right = None\n self.m...
trial_gpt4o_4
{ "original_instruction": "### Interval Tree - Implementation and Overlapping Intervals Search\n\n#### Background:\nAn Interval Tree is a data structure to store intervals efficiently and allows for fast retrieving of all intervals that overlap with a given interval. It is particularly useful in applications such as ...
0.65843
Algorithm_15251
C
[ "build_interval_tree", "do_intervals_overlap", "find_overlapping_intervals" ]
3
[ [ "find_overlapping_intervals", "do_intervals_overlap" ] ]
1
[]
false
[ "IntervalTreeNode" ]
true
pytest
true
[]
true
648466f392fe8b79d2bde8810bda5e80ff2fb96d
6e99413c22f857999357b19fdb47bd1ada7a6c04
v1.0
complete
Algorithm
Algorithm_451_C
def compare_fib_methods(n: int) -> int: """ Calculate the n-th Fibonacci number using both recursive and iterative methods, and compare their results. >>> compare_fib_methods(0) 0 >>> compare_fib_methods(1) 1 >>> compare_fib_methods(5) 5 >>> compare_fib_methods(10) 55 >>> co...
def fibonacci_recursive(n): if n <= 1: return n return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) def fibonacci_iterative(n): if n <= 1: return n a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b def compare_fib_methods(n): if not isinstance(n,...
from solution import compare_fib_methods def test_fibonacci_0(): assert compare_fib_methods(0) == 0 def test_fibonacci_1(): assert compare_fib_methods(1) == 1 def test_fibonacci_5(): assert compare_fib_methods(5) == 5 def test_fibonacci_10(): assert compare_fib_methods(10) == 55 def test_fibonacci_...
[ { "docstring": null, "function_declaration": "def fibonacci_recursive(n):", "function_name": "fibonacci_recursive", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def fibonacci_iterative(n):", "function_name": "fibonacci_iterative", "parameter_list": "(n...
[ 0, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def fibonacci_recursive(n):\n \"\"\"\n Calculate the n-th Fibonacci number using the recursive method.\n \"\"\"\n if n <= 0:\n return 0\n e...
trial_gpt4o_1
{ "original_instruction": "### Fibonacci Sequence Calculation\n\nYou are given a task to implement two methods to calculate the \\(n\\)-th Fibonacci number: the Recursive Method and the Iterative Method. To further assess understanding, design a function that compares the performance of both methods.\n\n#### Objectiv...
0.827621
Algorithm_451
C
[ "fibonacci_recursive", "fibonacci_iterative", "compare_fib_methods" ]
3
[ [ "compare_fib_methods", "fibonacci_iterative" ], [ "compare_fib_methods", "fibonacci_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
42c41a5b502902d06deb35d1aa5401aeb7ac4e54
27662dbffac61e31b426df364ebf76cfb738b1fd
v1.0
complete
Algorithm
Algorithm_35217_C
def iterative_quick_sort(arr: list[int]) -> list[int]: """ Sorts a list of integers in ascending order using an iterative quick sort algorithm. >>> iterative_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] >>> iterative_quick_sort([1, 1, 1, 1, 1]) == [1, 1, 1, 1, 1] >>> iterative_quick_sort...
def iterative_quick_sort(arr: list[int]) -> list[int]: if len(arr) <= 1: return arr stack = [(0, len(arr) - 1)] while stack: start, end = stack.pop() if start < end: pivot_index = partition(arr, start, end) if pivot_index - 1 > ...
from solution import iterative_quick_sort def test_quick_sort_with_regular_list(): assert iterative_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] def test_quick_sort_with_duplicates(): assert iterative_quick_sort([1, 1, 1, 1, 1]) == [1, 1, 1, 1, 1] def test_quick_sort_empty_list(): assert ...
[ { "docstring": null, "function_declaration": "def iterative_quick_sort(arr):", "function_name": "iterative_quick_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(ar...
[ 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 iterative_quick_sort(arr: list[int]) -> list[int]:\n \"\"\"\n Perform an iterative quick sort on the given list and return the sorted list.\n \"\"\"...
trial_gpt4o_9
{ "original_instruction": "### Question: Implement an Iterative Quick Sort\n\nYou have to implement the quick sort algorithm iteratively. Given a list of integers, return the list sorted in ascending order using an iterative quick sort.\n\n#### Function Signature\n```python\ndef iterative_quick_sort(arr: list[int]) -...
0.627332
Algorithm_35217
C
[ "iterative_quick_sort", "partition" ]
2
[ [ "iterative_quick_sort", "partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
02d98ee7113d9996c91d45d1cbb78114086f7772
94068f6ccbb3ea8022bfde59e48783b495e71e29
v1.0
complete
Algorithm
Algorithm_32683_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sort a list of integers in ascending order using the Merge Sort algorithm. >>> merge_sort([38, 27, 43, 3, 9, 82, 10]) [3, 9, 10, 27, 38, 43, 82] >>> merge_sort([5, 2, 9, 1, 5, 6]) [1, 2, 5, 5, 6, 9] >>> merge_sort([]) ...
from typing import List def merge_sort(arr: List[int]) -> List[int]: 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: List[int], right: List[int]) -> List[int]...
from solution import merge_sort def test_merge_sort_basic(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert me...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 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 merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ...
trial_gpt4o_9
{ "original_instruction": "### Question: Implementing Merge Sort in Python\n\n**Scenario:**\nYou have been tasked with implementing a well-known sorting algorithm, Merge Sort, which is particularly efficient for large datasets because of its O(n log n) time complexity. Unlike quick sort, merge sort is a stable sort a...
0.629365
Algorithm_32683
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bc3b2e389ee5ae1aeb2919cd6e0ce70bc16f1a78
5ab903200915641e0de6f6f632d6c25dd523ab36
v1.0
complete
Algorithm
Algorithm_18576_C
import asyncio import websockets import logging from typing import List logging.basicConfig(level=logging.INFO) async def start_quiz_server(question_list: List[str]) -> None: """ Starts a real-time educational quiz server using WebSocket connections. The function takes a list of quiz questions and ...
import asyncio import websockets import logging from typing import List logging.basicConfig(level=logging.INFO) connected_clients = set() async def broadcast_questions(websocket, path, question_list): connected_clients.add(websocket) logging.info(f"New client connected. Total clients: {len(connected_clients)...
import asyncio import websockets import pytest import threading import time from solution import run_server @pytest.fixture def start_server(): questions = [ "What is the capital of France?", "What is the sum of 2 and 2?", "Name the largest planet in our solar system." ] server_thr...
[ { "docstring": null, "function_declaration": "def run_server(question_list):", "function_name": "run_server", "parameter_list": "(question_list)" } ]
[ 1, 0, 1, 1, 0, 1, 1, 1, 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": "import asyncio\nimport websockets\nimport logging\nfrom typing import List\nimport signal\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO)\n\nclie...
trial_gpt4o_7
{ "original_instruction": "### Real-Time Educational Quiz Application with WebSocket\n\nYou are tasked with developing the backend for a real-time educational quiz application that allows multiple clients to participate in a quiz simultaneously. The server needs to broadcast questions to all connected clients and han...
0.593671
Algorithm_18576
C
[ "broadcast_questions", "start_quiz_server", "run_server" ]
3
[ [ "run_server", "start_quiz_server" ], [ "start_quiz_server", "broadcast_questions" ] ]
2
[]
false
[]
false
pytest
true
[ "websockets" ]
false
7b3a5b08d98adfb35e17cbaa2b00d2810ee52ff0
02d65b3f444c34fadbc3d7b8ca64bde5a76f04d8
v1.0
complete
Algorithm
Algorithm_28035_C
from typing import List def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: """ Multiplies two matrices A and B. The number of columns in A must be equal to the number of rows in B. Returns the resulting matrix from the multiplication. >>> A = [[1, 2], [3, 4]] >>> B = [[...
from typing import List def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: num_rows_A, num_cols_A = len(A), len(A[0]) num_rows_B, num_cols_B = len(B), len(B[0]) assert num_cols_A == num_rows_B, "Number of columns in A must be equal to number of rows in B" C = [[0]...
from solution import matrix_multiply, matrix_reduce, matrix_mult_and_reduce def test_matrix_multiply(): A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8], [9, 10], [11, 12]] expected = [[58, 64], [139, 154]] assert matrix_multiply(A, B) == expected def test_matrix_reduc...
[ { "docstring": null, "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def matrix_reduce(matrix, operation):", "function_name": "matrix_reduce", "parameter_list": "...
[ 1, 0, 1, 0, 1, 1, 1, 1, 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": "from typing import List\n\ndef matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n num_rows_A, num_cols_A = len(A), len(A[0])\n n...
trial_gpt4o_0
{ "original_instruction": "### Matrix Multiplication and Reduction\n\n#### Your Task:\nImplement a function that multiplies two matrices, A and B, and then reduces the resulting matrix to a single value using a specified reduction operation.\n\n#### Function Description\n\n1. **matrix_multiply(A: List[List[int]], B: ...
0.629749
Algorithm_28035
C
[ "matrix_multiply", "matrix_reduce", "matrix_mult_and_reduce" ]
3
[ [ "matrix_mult_and_reduce", "matrix_multiply" ], [ "matrix_mult_and_reduce", "matrix_reduce" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3e1093eacf8b1455ed5d95226e5d9f2e1a3196e3
2d86798c029ca1ef104862ff25c2782c7c523dc7
v1.0
complete
Algorithm
Algorithm_37288_C
from typing import List def computeLPSArray(pattern: str) -> List[int]: """ Computes the Longest Prefix Suffix (LPS) array for the given pattern. Parameters: pattern (str): A string representing the pattern to search for. Returns: List[int]: A list of integers representing the LPS array. ...
from typing import List def computeLPSArray(pattern: str) -> List[int]: """Computes the Longest Prefix Suffix (LPS) array for the given pattern.""" length = 0 # Length of the previous longest prefix suffix lps = [0] * len(pattern) i = 1 while i < len(pattern): if pattern[i] == pattern...
from solution import computeLPSArray, KMPSearch def test_computeLPSArray_basic(): assert computeLPSArray("ababc") == [0, 0, 1, 2, 0] assert computeLPSArray("aaaa") == [0, 1, 2, 3] def test_computeLPSArray_edge_cases(): assert computeLPSArray("") == [] assert computeLPSArray("a") == [0] assert comp...
[ { "docstring": "Computes the Longest Prefix Suffix (LPS) array for the given pattern.", "function_declaration": "def computeLPSArray(pattern):", "function_name": "computeLPSArray", "parameter_list": "(pattern)" }, { "docstring": "Searches for occurrences of the pattern string within the text...
[ 1, 0, 0, 0, 0, 0, 1, 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 typing import List\n\ndef computeLPSArray(pattern: str) -> List[int]:\n \"\"\"Computes the Longest Prefix Suffix (LPS) array for the given pattern.\"\"\"...
trial_gpt4o_0
{ "original_instruction": "### Efficient String Matching Using KMP Algorithm\nYou are required to implement the Knuth-Morris-Pratt (KMP) string matching algorithm. The KMP algorithm searches for occurrences of a \"pattern\" string within a \"text\" string efficiently by avoiding redundant comparisons.\n\n#### Functio...
0.68746
Algorithm_37288
C
[ "computeLPSArray", "KMPSearch" ]
2
[ [ "KMPSearch", "computeLPSArray" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bf933cdcd287f82776cda9d413f20725fd0c74f0
10b205797bee84ae29cbaafa1d9d6b933ac18f4b
v1.0
complete
Algorithm
Algorithm_11760_C
from typing import List def sum_abs_non_diagonal(row: List[float], diag_index: int) -> float: return sum(abs(row[j]) for j in range(len(row)) if j != diag_index) def is_diagonally_dominant(matrix: List[List[float]]) -> bool: """ Check if the given square matrix is diagonally dominant. A square m...
from typing import List def sum_abs_non_diagonal(row: List[float], diag_index: int) -> float: return sum(abs(row[j]) for j in range(len(row)) if j != diag_index) def is_diagonally_dominant(matrix: List[List[float]]) -> bool: n = len(matrix) for i in range(n): diag_element = abs(matrix[i][i]) ...
from solution import is_diagonally_dominant def test_is_diagonally_dominant_example_1(): matrix = [ [3, -2, 1], [1, -4, 2], [1, 2, -5] ] assert is_diagonally_dominant(matrix) == True def test_is_diagonally_dominant_example_2(): matrix = [ [1, 2, 3], [4, 5, 6], ...
[ { "docstring": null, "function_declaration": "def sum_abs_non_diagonal(row, diag_index):", "function_name": "sum_abs_non_diagonal", "parameter_list": "(row, diag_index)" }, { "docstring": null, "function_declaration": "def is_diagonally_dominant(matrix):", "function_name": "is_diagon...
[ 1, 1, 1, 0, 0, 1, 0, 1, 1, 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\n\ndef sum_abs_non_diagonal(row: List[float], diag_index: int) -> float:\n return sum(abs(row[j]) for j in range(len(row)) if j != dia...
trial_gpt4o_8
{ "original_instruction": "### Context:\nIn numerical computing and scientific simulations, it is often necessary to determine whether a given matrix is diagonally dominant. This property is crucial, for example, in ensuring the convergence of various iterative methods for solving linear systems, such as the Jacobi o...
0.51683
Algorithm_11760
C
[ "sum_abs_non_diagonal", "is_diagonally_dominant" ]
2
[ [ "is_diagonally_dominant", "sum_abs_non_diagonal" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb04973fad46c2ed28ba07eabcffae1748271235
0578ecea1a5b77ce2e44faf7ff597dfb2f83a409
v1.0
complete
Algorithm
Algorithm_38544_C
from typing import List def solve_sudoku(board: List[List[int]]) -> List[List[int]]: """ Solve a given 9x9 Sudoku puzzle using backtracking. Each row, column, and 3x3 sub-grid must contain the digits from 1 to 9 without repetition. Args: board (List[List[int]]): A 9x9 matrix containing intege...
from typing import List, Tuple def find_empty_position(board: List[List[int]]) -> Tuple[int, int]: for i in range(9): for j in range(9): if board[i][j] == 0: return i, j return -1, -1 def is_valid(board: List[List[int]], row: int, col: int, num: int) -> bool: box_row_st...
from solution import solve_sudoku def test_sudoku_solver(): input_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], [0, 6, 0,...
[ { "docstring": null, "function_declaration": "def find_empty_position(board):", "function_name": "find_empty_position", "parameter_list": "(board)" }, { "docstring": null, "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list"...
[ 0, 0, 1, 1, 0, 0, 1, 0, 1 ]
4
medium
0.444
{ "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 find_empty_location(board: List[List[int]]):\n \"\"\"Finds an empty location on the Sudoku board represented by 0.\"\"\"\n f...
trial_gpt4o_6
{ "original_instruction": "### Problem Statement\nYou are asked to implement a Sudoku solver. The solver should fill in the empty cells of a given partially completed 9x9 Sudoku grid following the standard Sudoku rules.\n\n### Requirements\n1. **Sudoku Rules**: Each row, each column, and each 3x3 sub-grid must contai...
0.597825
Algorithm_38544
C
[ "find_empty_position", "is_valid", "solve_sudoku" ]
3
[ [ "solve_sudoku", "find_empty_position" ], [ "solve_sudoku", "is_valid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
51d6f47666b8f0737cb2a589b206b28d209305b4
ef3965be46918ae4f5ef13f994dfb4075b43710c
v1.0
complete
Algorithm
Algorithm_20935_C
def digital_root_sum_sequence(n: int) -> list: """ Generates a sequence of numbers where each number is the sum of digital roots of all numbers from 1 up to that number (inclusive). Parameters: n (int): The length of the sequence to be generated. Returns: list: A list of length `n` wh...
def digital_root(n): """ Returns the digital root of n. """ if n == 0: return 0 else: return (n - 1) % 9 + 1 def digital_root_sum_sequence(n): """ Returns a list of length n where the i-th element is the sum of digital roots of integers from 1 to i+1. """ sequen...
from solution import digital_root_sum_sequence def test_digital_root_sum_sequence_start(): assert digital_root_sum_sequence(1) == [1] def test_digital_root_sum_sequence_small(): assert digital_root_sum_sequence(5) == [1, 3, 6, 10, 15] def test_digital_root_sum_sequence_medium(): assert digital_root_sum_s...
[ { "docstring": "Returns the digital root of n.", "function_declaration": "def digital_root(n):", "function_name": "digital_root", "parameter_list": "(n)" }, { "docstring": "Returns a list of length n where the i-th element is the sum of \ndigital roots of integers from 1 to i+1.", "funct...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def digital_root(x):\n \"\"\"\n Return the digital root of x.\n The digital root is the single digit obtained by an \n iterative process of summing d...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement:\n\nYou are tasked with generating a sequence of numbers where each number is the sum of digital roots of all numbers from 1 up to that number (inclusive). The digital root of a number is the single digit obtained by an iterative process of summing digits, on each step...
0.55323
Algorithm_20935
C
[ "digital_root", "digital_root_sum_sequence" ]
2
[ [ "digital_root_sum_sequence", "digital_root" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7415e7fc9802aa6e5e1c4764e1e4d709ef83622c
741d382e24976bc8a6558725099bdd4b009e34e7
v1.0
complete
Algorithm
Algorithm_19227_C
import math from typing import List, Tuple def euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float: """ Calculate the Euclidean distance between two points. """ def calculate_distance(route: List[int], locations: List[Tuple[float, float]]) -> float: """ Calculate ...
import math from itertools import permutations def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def calculate_distance(route, locations): """ Calculate the total travel...
def test_euclidean_distance(): assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5.0) def test_calculate_distance(): locations = [(0, 0), (1, 0), (1, 1), (0, 1)] route = [0, 1, 2, 3] assert math.isclose(calculate_distance(route, locations), 4.0) def test_nearest_neighbor(): locations = [(0, ...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Calculate the total travel distance for the given route.", ...
[ 1, 0, 0, 0, 0, 0, 1, 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": "import math\nfrom itertools import permutations\n\ndef calculate_distance(locations, route):\n \"\"\"\n Calculate the total travel distance for a given rou...
trial_gpt4o_6
{ "original_instruction": "### Coding Assessment Question\n\nAs a data analyst at a logistics company, you have been tasked with developing a program to optimize delivery routes for a fleet of delivery vehicles. The program should identify the shortest route that a delivery vehicle can take, from the starting point t...
0.627006
Algorithm_19227
C
[ "euclidean_distance", "calculate_distance", "nearest_neighbor", "two_opt", "optimize_route" ]
5
[ [ "calculate_distance", "euclidean_distance" ], [ "nearest_neighbor", "euclidean_distance" ], [ "optimize_route", "calculate_distance" ], [ "optimize_route", "nearest_neighbor" ], [ "optimize_route", "two_opt" ], [ "two_opt", "calculate_distance" ...
6
[]
false
[]
false
pytest
false
[]
true
ad4fff73ebd945822ef40ba7b98b79c9b4ee3002
7284998917cab66571b4ab4fbb3f193a621300ed
v1.0
complete
Algorithm
Algorithm_22924_C
def kmeans_clustering(data: list[list[float]], k: int, max_iterations: int) -> list[int]: """ Implement the K-means algorithm to cluster the dataset into K clusters. Parameters: data (list of lists): Each inner list contains feature values of an instance. k (int): The number of clusters to form. ma...
import random from copy import deepcopy from math import sqrt def euclidean_distance(point1, point2): return sqrt(sum((coord1 - coord2) ** 2 for coord1, coord2 in zip(point1, point2))) def compute_centroids(data, assignments, k): clusters = [[] for _ in range(k)] for index, point in enumerate(data): ...
from solution import kmeans_clustering def test_kmeans_basic(): data = [ [1.0, 2.0], [2.0, 3.0], [1.1, 1.9], [10.0, 10.0], [10.1, 10.1], [9.9, 9.8] ] k = 2 max_iterations = 100 result = kmeans_clustering(data, k, max_iterations) assert result...
[ { "docstring": null, "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": null, "function_declaration": "def compute_centroids(data, assignments, k):", "function_name": "comput...
[ 1, 0, 0, 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 random\nfrom copy import deepcopy\n\ndef kmeans_clustering(data, k, max_iterations):\n \"\"\"\n Perform k-means clustering on the given dataset.\n ...
trial_gpt4o_7
{ "original_instruction": "### Question: Implementing K-means Clustering\n\nYou are given a dataset where each instance has a number of features. Your task is to implement the K-means algorithm to cluster the dataset into `K` clusters.\n\n#### Function Signature\n```python\ndef kmeans_clustering(data: list[list[float...
0.860622
Algorithm_22924
C
[ "euclidean_distance", "compute_centroids", "kmeans_clustering" ]
3
[ [ "kmeans_clustering", "compute_centroids" ], [ "kmeans_clustering", "euclidean_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cf41604ac1492c7f9a7b9564a24040ff9234c4f5
fcc6dfd7367319d351cea85941dc134d276ed9a9