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_21873_C
import numpy as np def initialize_centroids(image: np.ndarray, k: int) -> np.ndarray: """ Randomly pick k unique pixels from the image as the initial centroids. :param image: np.ndarray :param k: int :return: np.ndarray """ pass def assign_clusters(image: np.ndarray, centroids: np.ndarray...
import numpy as np def initialize_centroids(image: np.ndarray, k: int) -> np.ndarray: """ Randomly pick k unique pixels from the image as the initial centroids. :param image: np.ndarray :param k: int :return: np.ndarray """ flat_image = image.reshape(-1, 3) indices = np.random.choi...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, kmeans_compression def test_initialize_centroids(): image = np.array([[[10, 10, 10], [20, 20, 20]], [[30, 30, 30], [40, 40, 40]]]) k = 2 centroids = initialize_centroids(image, k) ass...
[ { "docstring": "Randomly pick k unique pixels from the image as the initial centroids.\n\n:param image: np.ndarray\n:param k: int\n:return: np.ndarray", "function_declaration": "def initialize_centroids(image, k):", "function_name": "initialize_centroids", "parameter_list": "(image, k)" }, { ...
[ 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef initialize_centroids(image: np.ndarray, k: int) -> np.ndarray:\n \"\"\"\n Randomly initialize k centroids from the image's pixel ...
trial_gpt4o_7
{ "original_instruction": "### Image Processing using K-means Clustering\n\n**Context**:\nYou are asked to perform image compression using the K-means clustering algorithm. K-means clustering is an unsupervised learning algorithm that partitions data into K number of clusters. By representing the image using fewer co...
0.770557
Algorithm_21873
C
[ "initialize_centroids", "assign_clusters", "update_centroids", "kmeans_compression" ]
4
[ [ "kmeans_compression", "assign_clusters" ], [ "kmeans_compression", "initialize_centroids" ], [ "kmeans_compression", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
a402fe5452bf244f22e83146f3ca7fef5900598b
608e5bb91b8c97afb6e50eb4cc284dfb068f1e76
v1.0
complete
Algorithm
Algorithm_28609_C
from typing import Callable, Any, List def merge_sort_custom(collection: List[Any], comparator: Callable[[Any, Any], bool]) -> List[Any]: """ Implement a merge sort function that allows for a custom comparator function to be passed in, enabling the sort order to be specified. :param collection: A mut...
from typing import Callable, Any, List def merge_sort_custom(collection: List[Any], comparator: Callable[[Any, Any], bool]) -> List[Any]: if len(collection) <= 1: return collection mid = len(collection) // 2 left = merge_sort_custom(collection[:mid], comparator) right = merge_sort_custom(colle...
from solution import merge_sort_custom def ascending(a, b): return a < b def descending(a, b): return a > b def test_merge_sort_custom_empty(): assert merge_sort_custom([], ascending) == [] def test_merge_sort_custom_single_element(): assert merge_sort_custom([1], ascending) == [1] def test_merge_s...
[ { "docstring": null, "function_declaration": "def merge_sort_custom(collection, comparator):", "function_name": "merge_sort_custom", "parameter_list": "(collection, comparator)" }, { "docstring": null, "function_declaration": "def merge(left, right, comparator):", "function_name": "m...
[ 1, 0, 1, 1, 1, 0, 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 Callable, Any\n\ndef merge_sort_custom(collection: list, comparator: Callable[[Any, Any], bool]) -> list:\n if len(collection) <= 1:\n ...
trial_gpt4o_9
{ "original_instruction": "### Merge Sort with Custom Comparator\n\n#### Objective:\nImplement a merge sort function that allows for a custom comparator function to be passed in, enabling the sort order to be specified (e.g., ascending, descending).\n\n#### Problem Statement:\nWrite a function `merge_sort_custom(coll...
0.568518
Algorithm_28609
C
[ "merge_sort_custom", "merge" ]
2
[ [ "merge_sort_custom", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ad87b9f969a3853df1112004edd35120af93f627
4ad10901752c1642f326827fa07bb4358ffb9350
v1.0
complete
Algorithm
Algorithm_10672_C
def is_leap_year(year: int) -> bool: """ Determine if the given year is a leap year. """ pass def days_in_month(year: int, month: int) -> int: """ Determine the number of days in a given month of a given year. """ pass def date_to_ordinal(year: int, month: int, day: int) -> int: """ Convert a date...
def is_leap_year(year): """ Determine if the given year is a leap year. Args: year (int): The year to check. Returns: bool: True if the year is a leap year, False otherwise. """ if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True ...
from solution import days_between_dates def test_days_between_dates_same_date(): assert days_between_dates("2000-01-01", "2000-01-01") == 0 def test_days_between_dates_start_year(): assert days_between_dates("2000-01-01", "2000-01-31") == 30 def test_days_between_dates_leap_year(): assert days_between_da...
[ { "docstring": "Determine if the given year is a leap year.\n\nArgs:\nyear (int): The year to check.\n\nReturns:\nbool: True if the year is a leap year, False otherwise.", "function_declaration": "def is_leap_year(year):", "function_name": "is_leap_year", "parameter_list": "(year)" }, { "doc...
[ 0, 0, 1, 1, 0, 1, 0, 0, 0 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_leap_year(year):\n if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):\n return True\n return False\n\ndef days_in_month(year, month...
trial_gpt4o_6
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\nYou are working on a calendar application that needs to calculate the number of days between two given dates. The application should handle different months and leap years correctly.\n\n#### Task\nImplement a function `days_between_dates(date1...
0.636869
Algorithm_10672
C
[ "is_leap_year", "days_in_month", "date_to_ordinal", "days_between_dates" ]
4
[ [ "date_to_ordinal", "days_in_month" ], [ "date_to_ordinal", "is_leap_year" ], [ "days_between_dates", "date_to_ordinal" ], [ "days_in_month", "is_leap_year" ] ]
4
[]
false
[]
false
pytest
true
[]
true
16c3c530c911617d608ae15df1cef26db674c873
4548eaca43b67d25d87112f960fb14c68da101c7
v1.0
complete
Algorithm
Algorithm_34316_C
from typing import Optional from dataclasses import dataclass @dataclass class TreeNode: data: int left: Optional['TreeNode'] = None right: Optional['TreeNode'] = None def insert_into_bst(root: Optional[TreeNode], data: int) -> TreeNode: """ Insert a new value into the BST and return the root of t...
from typing import Optional from dataclasses import dataclass @dataclass class TreeNode: data: int left: Optional['TreeNode'] = None right: Optional['TreeNode'] = None def insert_into_bst(root: Optional[TreeNode], data: int) -> TreeNode: """ Insert a new value into the BST and return the root of t...
from solution import TreeNode, insert_into_bst, find_kth_smallest def test_insert_into_bst(): root = insert_into_bst(None, 50) assert root.data == 50 root = insert_into_bst(root, 30) assert root.left.data == 30 root = insert_into_bst(root, 70) assert root.right.data == 70 roo...
[]
[ 0, 0, 0, 1, 0, 1, 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 dataclasses import dataclass\n\n@dataclass\nclass TreeNode:\n data: int\n left: 'TreeNode' | None = None\n right: 'TreeNode' | None = None\n\ndef i...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement\nYou are asked to work with binary search trees (BSTs) and perform two primary operations: inserting new nodes into the BST while maintaining its properties, and finding the k-th smallest element in the BST. Implement the insertion function `insert_into_bst` and the k-...
0.523521
Algorithm_34316
C
[ "insert_into_bst", "in_order_traversal", "find_kth_smallest" ]
3
[ [ "find_kth_smallest", "in_order_traversal" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
ac15511535116596339b5e1944236a385325f383
7cf2b43ef2c486d475cf2a35d63e13fa0e9eafd7
v1.0
complete
Algorithm
Algorithm_4257_C
from typing import List def insert_interval(intervals: List[List[int]], new_interval: List[int]) -> List[List[int]]: """ Insert new_interval into intervals and return the merged list of intervals. Args: intervals (List[List[int]]): A list of sorted, non-overlapping intervals. new_interval (List[in...
def insert_interval(intervals, new_interval): """ Insert new_interval into intervals and return the merged list of intervals. """ merged = [] i = 0 n = len(intervals) # Add all intervals that end before new_interval starts while i < n and intervals[i][1] < new_interval[0]: m...
from solution import insert_interval, perform_operations def test_insert_interval(): assert insert_interval([[1, 3], [6, 9]], [2, 5]) == [[1, 5], [6, 9]] assert insert_interval([[1, 5], [6, 9]], [8, 10]) == [[1, 5], [6, 10]] assert insert_interval([[1, 5], [6, 10]], [15, 18]) == [[1, 5], [6, 10], [15, 18]]...
[ { "docstring": "Insert new_interval into intervals and return the merged list of intervals.", "function_declaration": "def insert_interval(intervals, new_interval):", "function_name": "insert_interval", "parameter_list": "(intervals, new_interval)" }, { "docstring": "Initialize with initial_...
[ 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 insert_interval(intervals: List[List[int]], new_interval: List[int]) -> List[List[int]]:\n merged = []\n i = 0\n \n # ...
trial_gpt4o_9
{ "original_instruction": "### **Coding Challenge: Interval Insert and Query**\n\n#### Context\nYou are given a list of intervals and you need to perform operations on these intervals. Specifically, you need to insert new intervals and query the merged state of the intervals list after each insertion.\n\n#### Task\nI...
0.601411
Algorithm_4257
C
[ "insert_interval", "perform_operations" ]
2
[ [ "perform_operations", "insert_interval" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d721ac773abb455caacd806bee44a7de7504f8dd
7aa561aaaaa3ccf368d4b6be6b999b9a0fc6c113
v1.0
complete
Algorithm
Algorithm_8840_C
import requests import datetime import logging logging.basicConfig(level=logging.INFO) def get_flight_details(retry_limit=3): """Fetches flight details from an alternative API. Retries failed requests up to `retry_limit` times in case of network failures or API errors. Returns the flight data in JSON form...
import requests import datetime import logging logging.basicConfig(level=logging.INFO) def get_flight_details(retry_limit=3): url = "https://alternative-api.com/flights" retries = 0 while retries < retry_limit: try: response = requests.get(url) response.raise_for_status() ...
from solution import calculate_duration, display_flights, get_flight_details import datetime def test_calculate_duration(): dep_time = "2023-10-10T10:00:00" arr_time = "2023-10-10T12:30:00" assert calculate_duration(dep_time, arr_time) == "02:30" dep_time = "2023-10-10T23:00:00" arr_time = "2023-1...
[ { "docstring": null, "function_declaration": "def get_flight_details(retry_limit=3):", "function_name": "get_flight_details", "parameter_list": "(retry_limit=3)" }, { "docstring": null, "function_declaration": "def calculate_duration(departure_time, arrival_time):", "function_name": ...
[ 0, 1, 0, 1, 1, 1, 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": "import requests\nimport json\nfrom datetime import datetime, timedelta\n\ndef fetch_flights(retry_limit):\n url = \"https://alternative-api.com/flights\"\n ...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment Question\n\nYou have been hired as a software developer for a travel booking company. Your task is to enhance the company's system to fetch and display real-time flight information. The company wants to switch from their current flight information provider to a new one...
0.547641
Algorithm_8840
C
[ "get_flight_details", "calculate_duration", "display_flights", "main" ]
4
[ [ "display_flights", "calculate_duration" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
b3d2ae4d721d6611f58b2d022b7ecea0cafd4a97
71a8f6de08e08bb9c714cd3bb0fe5df8ada516eb
v1.0
complete
Algorithm
Algorithm_45161_C
import re import math from collections import Counter, defaultdict from typing import List, Dict def compute_tfidf(documents: List[str]) -> List[Dict[str, float]]: """ Calculates the TF-IDF scores for each term in each document. :param documents: a list of strings, where each string represents a document....
import math import re from collections import defaultdict, Counter from typing import List, Dict def tokenize(document: str) -> List[str]: """ Tokenizes a document into a list of words. Converts to lowercase and removes special characters. """ return re.findall(r'\b\w+\b', document.lower()) def comput...
import pytest from solution import compute_tfidf def test_compute_tfidf_single_document(): documents = ["The cat sat on the mat."] result = compute_tfidf(documents) assert len(result) == 1 assert 'cat' in result[0] def test_compute_tfidf_multiple_documents(): documents = [ "The cat sat on ...
[ { "docstring": "Tokenizes a document into a list of words. Converts to lowercase and removes special characters.", "function_declaration": "def tokenize(document):", "function_name": "tokenize", "parameter_list": "(document)" }, { "docstring": "Calculates the TF-IDF scores for each term in e...
[ 0, 0, 0, 0, 0, 0, 1, 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 re\nimport math\nfrom collections import Counter\nfrom typing import List, Dict\n\ndef compute_tfidf(documents: List[str]) -> List[Dict[str, float]]:\n ...
trial_gpt4o_7
{ "original_instruction": "## Problem Statement\n\nYou are tasked with implementing a feature extraction technique for text data, specifically the term frequency-inverse document frequency (TF-IDF) scheme. This task will involve calculating term frequencies (TF), inverse document frequencies (IDF), and combining thes...
0.801307
Algorithm_45161
C
[ "tokenize", "compute_tfidf" ]
2
[ [ "compute_tfidf", "tokenize" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5f685d36fc123f2eb5f2dcbf3f796331df9afd59
d7abeee88bd078f11be15cd064eb97bf3cfb93da
v1.0
complete
Algorithm
Algorithm_26142_C
import random import numpy as np from typing import List, Tuple def generate_linear_dataset(slope: float, intercept: float, noise_level: float, instance_count: int) -> List[Tuple[float, float]]: """ Generate a simple dataset based on a given linear relationship with some noise. :param slope: Slope of the l...
import random import numpy as np def generate_linear_dataset(slope, intercept, noise_level, instance_count): """ Generate a simple dataset based on a given linear relationship with some noise. """ dataset = [] for _ in range(instance_count): x = random.random() * 100 noise = random....
from solution import generate_linear_dataset, calculate_mean, calculate_covariance, calculate_variance, calculate_coefficients, predict_y_values, calculate_rmse def test_generate_linear_dataset(): data = generate_linear_dataset(2.0, 5.0, 1.0, 50) assert len(data) == 50 assert all(isinstance(point, tuple) a...
[ { "docstring": "Generate a simple dataset based on a given linear relationship with some noise.", "function_declaration": "def generate_linear_dataset(slope, intercept, noise_level, instance_count):", "function_name": "generate_linear_dataset", "parameter_list": "(slope, intercept, noise_level, inst...
[ 0, 0, 1, 0, 0, 1, 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 random\nimport math\n\ndef generate_linear_dataset(slope, intercept, noise_level, instance_count):\n \"\"\"\n Generate a dataset based on a linear r...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: Implement a Simple Linear Regression Model\n\nYou are required to implement a Simple Linear Regression model. This model should be capable of training on a given dataset (with a single feature) and predicting the continuous output for new input instances. You...
0.609951
Algorithm_26142
C
[ "generate_linear_dataset", "calculate_mean", "calculate_covariance", "calculate_variance", "calculate_coefficients", "predict_y_values", "calculate_rmse" ]
7
[ [ "calculate_covariance", "calculate_mean" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
41297e5e23641ac8700e8cc9ef4fed9f5a8d2673
d92ada7c74d7983141b89df0950c63194c29fa39
v1.0
complete
Algorithm
Algorithm_43900_C
def is_palindrome(substring: str) -> bool: """ Checks if the given substring is a palindrome. """ return substring == substring[::-1] def check_substrings_are_palindromes(s: str, substr1_start: int, substr1_end: int, substr2_start: int, substr2_end: int) -> bool: """ Checks if the substrings of...
def is_palindrome(substring: str) -> bool: """ Checks if the given substring is a palindrome. """ return substring == substring[::-1] def check_substrings_are_palindromes(s: str, substr1_start: int, substr1_end: int, substr2_start: int, substr2_end: int) -> bool: """ Checks if the substrings of...
def test_check_substrings_are_palindromes(): assert check_substrings_are_palindromes("madamracecar", 0, 4, 6, 11) == False assert check_substrings_are_palindromes("aabbaa", 0, 2, 3, 5) == False assert check_substrings_are_palindromes("abcdedcba", 1, 3, 5, 7) == False assert check_substrings_are_palindro...
[ { "docstring": "Checks if the given substring is a palindrome.", "function_declaration": "def is_palindrome(substring):", "function_name": "is_palindrome", "parameter_list": "(substring)" }, { "docstring": "Checks if the substrings of s from substr1_start to substr1_end and from substr2_star...
[ 0, 0, 0, 0, 1, 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": "def check_substrings_are_palindromes(s: str, substr1_start: int, substr1_end: int, substr2_start: int, substr2_end: int) -> bool:\n def is_palindrome(substrin...
trial_gpt4o_6
{ "original_instruction": "### Programming Assessment Question\n\n#### Context\nWorking with strings is a fundamental skill in programming. Understanding how to manipulate and analyze strings is crucial. In this task, you will build a function that helps detect palindromes under certain constraints.\n\n#### Task\n**O...
0.839944
Algorithm_43900
C
[ "is_palindrome", "check_substrings_are_palindromes" ]
2
[ [ "check_substrings_are_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
false
[]
true
7b05b627ac7df85a1994017164abc1b2a98cee7b
e8486b4514da12337a1a06f0d10a537c653a0116
v1.0
complete
Algorithm
Algorithm_18632_C
from typing import List, Tuple def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float: return ((p1[0] - p2[0]) ** 2 + (p2[1] - p2[1]) ** 2) ** 0.5 def optimize_routes(locations: List[Tuple[int, int]]) -> List[int]: """ Find an efficient route starting from the first location to visit all lo...
from typing import List, Tuple from itertools import permutations import math def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float: return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) def total_route_distance(route: List[int], locations: List[Tuple[int, int]]) -> float: total_distan...
from solution import optimize_routes def test_optimize_routes_case1(): locations = [(0, 0), (2, 2), (1, 1), (6, 6)] result = optimize_routes(locations) expected = [0, 2, 1, 3, 0] # Note: This is one possible correct route, ensure the distance is minimal assert set(result) == set(expected) # Check if ...
[ { "docstring": null, "function_declaration": "def calculate_distance(p1, p2):", "function_name": "calculate_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def total_route_distance(route, locations):", "function_name": "total_route_distance", ...
[ 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": "import itertools\nfrom typing import List, Tuple\n\ndef calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:\n \"\"\"\n Calculate the Euc...
trial_gpt4o_6
{ "original_instruction": "### Scenario\nYou are tasked with improving the delivery system for a courier service. Specifically, you need to optimize the delivery routes to minimize the total distance traveled while ensuring all deliveries are completed. This is a variant of the well-known Traveling Salesman Problem (...
0.678373
Algorithm_18632
C
[ "calculate_distance", "total_route_distance", "optimize_routes" ]
3
[ [ "optimize_routes", "total_route_distance" ], [ "total_route_distance", "calculate_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
93e17130014c4d237563dec5286051281bdf85dc
34d7b766d6f9d3acb8d7952b21ee34d975999c9b
v1.0
complete
Algorithm
Algorithm_2920_C
def is_palindrome(s: str) -> bool: """ Check if a given string is a palindrome. >>> is_palindrome('level') True >>> is_palindrome('world') False >>> is_palindrome('radar') True >>> is_palindrome('python') False >>> is_palindrome('madam') True >>> is_palindrome('') Tru...
def is_palindrome(s: str) -> bool: """ Check if a given string is a palindrome. """ return s == s[::-1] def find_palindromes(strings: list) -> list: """ Filter and return a list of palindromes from the given list of strings. """ return [s for s in strings if is_palindrome(s)] def main(...
from solution import is_palindrome, find_palindromes def test_is_palindrome(): assert is_palindrome('level') == True assert is_palindrome('world') == False assert is_palindrome('radar') == True assert is_palindrome('python') == False assert is_palindrome('madam') == True assert is_palindrome(''...
[ { "docstring": "Check if a given string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Filter and return a list of palindromes from the given list of strings.", "function_declaration": "def ...
[ 0, 0, 0, 1, 1, 1, 0, 1, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_palindrome(s: str) -> bool:\n \"\"\"\n Returns True if the input string s is a palindrome, False otherwise.\n \"\"\"\n...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Context:\nYou are working on a data analysis project that requires filtering and analyzing strings. One of the tasks involves processing a list of strings and identifying which strings are palindromes (i.e., strings that read the same forwards and back...
0.800329
Algorithm_2920
C
[ "is_palindrome", "find_palindromes", "main" ]
3
[ [ "find_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d44bf99d1c83f8a2614d05871cc0d4edb718920a
67011939e9fa1a3906479b4b15dba41688443524
v1.0
complete
Algorithm
Algorithm_12077_C
import math from typing import List def segmented_sieve(L: int, R: int) -> List[int]: """ Segmented sieve algorithm to find primes in [L, R]. Args: L (int): The starting range integer. R (int): The ending range integer. Returns: List[int]: A list of prime numbers within the given ...
import math def simple_sieve(limit): """ A simple sieve of Eratosthenes up to a given limit. """ is_prime = [True] * (limit + 1) p = 2 while p * p <= limit: if is_prime[p] == True: for i in range(p * p, limit + 1, p): is_prime[i] = False p += 1 pr...
def test_segmented_sieve_small_range(): assert segmented_sieve(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_segmented_sieve_single_prime(): assert segmented_sieve(29, 29) == [29] def test_segmented_sieve_large_range(): expected_primes = [101, 103, 107, 109, 113, 127, 131, 137, 139,...
[ { "docstring": "A simple sieve of Eratosthenes up to a given limit.", "function_declaration": "def simple_sieve(limit):", "function_name": "simple_sieve", "parameter_list": "(limit)" }, { "docstring": "Segmented sieve algorithm to find primes in [L, R].", "function_declaration": "def seg...
[ 1, 1, 1, 1, 1, 0, 0, 1, 0 ]
6
easy
0.667
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl", "solution_code": "def segmented_sieve(L, R):\n \"\"\"\n Returns a list of prime numbers in the range [L, R] using the segmented sieve algorithm.\n ...
trial_gpt4o_8
{ "original_instruction": "### Question: Implement Primes Sieve Using Segmented Sieve Algorithm\n\n#### Context\nThe Segmented Sieve Algorithm is an extension of the Sieve of Eratosthenes, which can find all prime numbers in a given range [L, R]. This approach is more efficient when dealing with a large range.\n\n###...
0.624827
Algorithm_12077
C
[ "simple_sieve", "segmented_sieve" ]
2
[ [ "segmented_sieve", "simple_sieve" ] ]
1
[]
false
[]
false
pytest
false
[]
true
3f8256aa9fca72f29e80603fe7914b7d0b2a419b
5e325edcd1adb9d58aa6bf2c3ced69bdaf4adfd2
v1.0
complete
Algorithm
Algorithm_40352_C
import numpy as np import random from matplotlib import pyplot as plt def euclidean_distance(point1: tuple, point2: tuple) -> float: """ Calculate the Euclidean distance between two 2D points. """ def k_means_clustering(points: list, k: int) -> list: """ Implement K-Means clustering algorith...
import numpy as np import random from matplotlib import pyplot as plt def euclidean_distance(point1: tuple, point2: tuple) -> float: """ Calculate the Euclidean distance between two 2D points. """ return np.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def k_means_clustering(points: li...
import pytest from solution import k_means_clustering, euclidean_distance def test_k_means_clustering(): points = [(2, 3), (3, 4), (5, 6), (8, 9), (1, 2), (7, 8)] k = 2 clusters, centroids = k_means_clustering(points, k) assert len(clusters) == k assert len(centroids) == k def test_k_means_differe...
[ { "docstring": "Calculate the Euclidean distance between two 2D points.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Implement K-Means clustering algorithm.", "function_...
[ 1, 0, 0, 1, 1, 1, 0, 1, 0 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport random\nfrom matplotlib import pyplot as plt\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean dista...
trial_gpt4o_6
{ "original_instruction": "### Question\nWrite a function that implements a basic K-Means clustering algorithm from scratch. This function should group a set of 2D points into k clusters based on their Euclidean distances. Additionally, visualize the clustered points after the algorithm has converged.\n\n### Requirem...
0.783203
Algorithm_40352
C
[ "euclidean_distance", "k_means_clustering", "plot_clusters" ]
3
[ [ "k_means_clustering", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
7d7d3f1b25ff4e1cbf866c0c690222924981e18d
452b7f7c46c405af32f4050f83d4521a56cad80e
v1.0
complete
Algorithm
Algorithm_36116_C
def find_anagram_pairs(words: list) -> list: """ Returns a list of tuples. Each tuple contains two words that are anagrams of each other. Args: words (list): A list of strings representing words. Returns: list: A list of tuples, where each tuple contains two strings that are anagrams of ea...
def clean_word(word): """ Returns a cleaned version of the word with all letters in lowercase, and all non-alphabetic characters removed. """ return ''.join(filter(str.isalpha, word)).lower() def find_anagram_pairs(words): """ Returns a list of tuples. Each tuple contains two words that are...
from solution import find_anagram_pairs def test_find_anagram_pairs_basic(): words = ["Listen", "Silent", "Dormitory", "Dirty room", "School master", "The classroom", "Hello", "Olelh"] expected = [("Listen", "Silent"), ("Dormitory", "Dirty room"), ("School master", "The classroom"), ("Hello", "Olelh")] ass...
[ { "docstring": "Returns a cleaned version of the word with all letters in lowercase,\nand all non-alphabetic characters removed.", "function_declaration": "def clean_word(word):", "function_name": "clean_word", "parameter_list": "(word)" }, { "docstring": "Returns a list of tuples. Each tupl...
[ 1, 0, 1, 1, 1, 1, 1, 0, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef find_anagram_pairs(words):\n def clean_word(word):\n return ''.join(sorted(re.sub(r'[^a-zA-Z]', '', word).lower()))\n\n found_pairs...
trial_gpt4o_8
{ "original_instruction": "## Anagram Pair Finder\n\n### Scenario\n\nYou are invited to take part in the development of a system that identifies pairs of words that are anagrams. Two words are considered anagrams if one word can be rearranged to form the other, using all the original letters exactly once.\n\n### Func...
0.552201
Algorithm_36116
C
[ "clean_word", "find_anagram_pairs" ]
2
[ [ "find_anagram_pairs", "clean_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab1147dae9641f20b6364b4e7d530bd4b137fabc
6f73c02c24aaf1afe3f39193f472f2ddfeea37cf
v1.0
complete
Algorithm
Algorithm_23368_C
""" Write a function named `compare_sorting_algorithms` that accepts a list of integers and measures the execution time of sorting them using Bubble Sort, Merge Sort, and Quick Sort algorithms. It should return a dictionary with the algorithm names as keys and their corresponding execution times (in seconds) as values....
import time def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[m...
from solution import compare_sorting_algorithms def test_compare_sorting_algorithms(): import time # Test with unsorted list arr = [64, 34, 25, 12, 22, 11, 90] result = compare_sorting_algorithms(arr) assert 'bubble_sort' in result assert 'merge_sort' in result assert 'quick_sort' in result...
[ { "docstring": null, "function_declaration": "def bubble_sort(arr):", "function_name": "bubble_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring...
[ 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": "import time\n\ndef compare_sorting_algorithms(arr: list) -> dict:\n def bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j...
trial_gpt4o_9
{ "original_instruction": "### Background\nIn order to compare the efficiency and performance of various sorting algorithms, you need to write a program that can execute different sorting techniques on a given list of integers. To provide a comprehensive comparison, your task involves implementing specific sorting al...
0.609136
Algorithm_23368
C
[ "bubble_sort", "merge_sort", "quick_sort", "compare_sorting_algorithms" ]
4
[ [ "compare_sorting_algorithms", "bubble_sort" ], [ "compare_sorting_algorithms", "merge_sort" ], [ "compare_sorting_algorithms", "quick_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
059fb139d3d4f628b2c236752ce7170a4dc87183
f332960ecd48b0a239d14e3990b4c3b07f0410a5
v1.0
complete
Algorithm
Algorithm_44294_C
import numpy as np def initialize_weights(input_size: int, hidden_size: int, output_size: int) -> tuple: """ Initialize weight matrices for a neural network with one hidden layer. Args: - input_size (int): Number of neurons in the input layer. - hidden_size (int): Number of neurons in the hidden la...
import numpy as np def initialize_weights(input_size: int, hidden_size: int, output_size: int) -> tuple: """ Initialize weight matrices for a neural network with one hidden layer. """ np.random.seed(42) # For reproducibility w1 = np.random.randn(input_size, hidden_size) * 0.01 w2 = np.random.r...
from solution import initialize_weights, feedforward, backpropagation, train_network def test_initialize_weights(): input_size, hidden_size, output_size = 2, 3, 1 w1, w2 = initialize_weights(input_size, hidden_size, output_size) assert w1.shape == (2, 3) assert w2.shape == (3, 1) def test_feedforward(...
[ { "docstring": "Initialize weight matrices for a neural network with one hidden layer.", "function_declaration": "def initialize_weights(input_size, hidden_size, output_size):", "function_name": "initialize_weights", "parameter_list": "(input_size, hidden_size, output_size)" }, { "docstring"...
[ 1, 0, 0, 0, 1, 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 numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\ndef initialize_weights(input_size...
trial_gpt4o_9
{ "original_instruction": "### Neural Network Backpropagation Implementation\n\nYou are required to implement a simple feedforward neural network from scratch and perform backpropagation to train the network. Implement the following functions:\n\n1. **initialize_weights** - To initialize the weight matrices for the n...
0.679404
Algorithm_44294
C
[ "initialize_weights", "sigmoid", "sigmoid_derivative", "feedforward", "backpropagation", "train_network" ]
6
[ [ "backpropagation", "sigmoid" ], [ "backpropagation", "sigmoid_derivative" ], [ "feedforward", "sigmoid" ], [ "sigmoid_derivative", "sigmoid" ], [ "train_network", "backpropagation" ], [ "train_network", "initialize_weights" ] ]
6
[]
false
[]
false
pytest
true
[ "numpy" ]
false
cda2e2304bf84a81cf9ffdd61028b867e7385b9f
961f451bd7062efa223ed8b825a11e6e4763ce6f
v1.0
complete
Algorithm
Algorithm_11567_C
def prime_shortest_path(start_prime: int, end_prime: int) -> int: """Determines the shortest path between two given 4-digit prime numbers by changing one digit at a time, ensuring each intermediate number is also a prime. Args: start_prime (int): The starting 4-digit prime number. end_prime (i...
from collections import deque from itertools import permutations def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i +=...
def test_prime_shortest_path_same_prime(): assert prime_shortest_path(1033, 1033) == 0 def test_prime_shortest_path_one_step(): assert prime_shortest_path(1033, 1733) == 1 def test_prime_shortest_path_multiple_steps(): assert prime_shortest_path(1033, 8179) == 6 def test_prime_shortest_path_no_connection...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def get_all_primes():", "function_name": "get_all_primes", "parameter_list": "()" }, { "docstring": null,...
[ 1, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import deque\nfrom itertools import permutations\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\...
trial_gpt4o_0
{ "original_instruction": "### Prime Path Finder\n\n#### Background\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to create a feature for a number analysis tool that determines the shortest path between two given prime numbers by changing one di...
0.584105
Algorithm_11567
C
[ "is_prime", "get_all_primes", "prime_neighbors", "prime_shortest_path" ]
4
[ [ "get_all_primes", "is_prime" ], [ "prime_neighbors", "is_prime" ], [ "prime_shortest_path", "get_all_primes" ], [ "prime_shortest_path", "prime_neighbors" ] ]
4
[]
false
[]
false
pytest
false
[]
true
ab16dd276592d61420b701687e7388e39f0bf3c3
1e30b13f906b526f062f16ba0d0055b9d7911500
v1.0
complete
Algorithm
Algorithm_39587_C
import requests import time from collections import namedtuple from typing import List, Dict from cachetools import TTLCache # Define the WeatherData named tuple WeatherData = namedtuple('WeatherData', ['temperature', 'humidity', 'description']) # Initialize cache with a TTL of 10 minutes (600 seconds) cache = TTLCac...
import requests import time from collections import namedtuple from typing import List, Dict from cachetools import TTLCache # Define the WeatherData named tuple WeatherData = namedtuple('WeatherData', ['temperature', 'humidity', 'description']) # Initialize cache with a TTL of 10 minutes (600 seconds) cache = TTLCac...
import pytest from unittest.mock import patch from solution import get_weather_data, WeatherData # Mocked response data mocked_response = { 'main': { 'temp': 20, 'humidity': 60 }, 'weather': [{ 'description': 'clear sky' }] } @patch('solution.requests.get') def test_get_weather...
[ { "docstring": null, "function_declaration": "def fetch_weather_data(city):", "function_name": "fetch_weather_data", "parameter_list": "(city)" }, { "docstring": null, "function_declaration": "def get_weather_data(cities):", "function_name": "get_weather_data", "parameter_list": ...
[ 0, 0, 0, 0, 1, 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": "import requests\nfrom collections import namedtuple\nfrom datetime import datetime, timedelta\nfrom typing import List, Dict\nimport time\n\n# Define the named t...
trial_gpt4o_8
{ "original_instruction": "### Question Title: Weather Data Aggregator with Caching and Rate Limiting\n\n### Scenario\n\nYou are required to develop a script that retrieves current weather data for a list of cities from a weather API. To optimize performance and avoid exceeding API rate limits, implement caching to s...
0.575624
Algorithm_39587
C
[ "fetch_weather_data", "get_weather_data" ]
2
[ [ "get_weather_data", "fetch_weather_data" ] ]
1
[]
false
[]
false
pytest
true
[ "cachetools", "requests" ]
false
507754cb4e15f1d8f39fd2c3f5bd22e5f5c4ef03
4887c8667ea62a5bf3b860a9a2c9bf87f9642e29
v1.0
complete
Algorithm
Algorithm_44498_C
from typing import List, Tuple def are_anagrams(str1: str, str2: str) -> bool: """ Determines if the two provided strings are anagrams of each other. >>> are_anagrams("listen", "silent") True >>> are_anagrams("triangle", "integral") True >>> are_anagrams("apple", "papel") True >>> are_anagrams("rat...
from typing import List, Tuple def are_anagrams(str1: str, str2: str) -> bool: """ Determines if the two provided strings are anagrams of each other. """ return sorted(str1) == sorted(str2) def check_anagrams(pairs: List[Tuple[str, str]]) -> List[bool]: """ Checks if each pair of strings in th...
from solution import are_anagrams, check_anagrams def test_are_anagrams(): assert are_anagrams("listen", "silent") == True assert are_anagrams("triangle", "integral") == True assert are_anagrams("apple", "papel") == True assert are_anagrams("rat", "car") == False assert are_anagrams("night", "thing...
[ { "docstring": "Determines if the two provided strings are anagrams of each other.", "function_declaration": "def are_anagrams(str1, str2):", "function_name": "are_anagrams", "parameter_list": "(str1, str2)" }, { "docstring": "Checks if each pair of strings in the list are anagrams and retur...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
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, Tuple\n\ndef are_anagrams(str1: str, str2: str) -> bool:\n \"\"\"\n Returns whether str1 and str2 are anagrams of each other.\n ...
trial_gpt4o_8
{ "original_instruction": "### Coding Challenge: String Anagram Checks\n\n#### Objective:\nDevelop a program to check if a list of given pairs of strings are anagrams of each other and summarize the results.\n\n#### Detailed Task Description:\n\n1. **Function Implementations**:\n - Implement `are_anagrams(str1: str...
0.631265
Algorithm_44498
C
[ "are_anagrams", "check_anagrams" ]
2
[ [ "check_anagrams", "are_anagrams" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3ebaaa40765391ed6d41f17aae61528ce105235b
5b41cd2b3f76609b5387b6755f269c32e1093329
v1.0
complete
Algorithm
Algorithm_32444_C
Implement the functionality to assign instances to clusters and calculate the final cluster centroids. import random import math def initialize_centroids(features, k): """ Randomly initialize the centroids by selecting 'k' random features as initial centroids. """ return random.sample(features, k) de...
import random import math def initialize_centroids(features, k): """ Randomly initialize the centroids by selecting 'k' random features as initial centroids. """ return random.sample(features, k) def assign_clusters(features, centroids): """ Assign each feature to the nearest centroid. """...
from solution import initialize_centroids, assign_clusters, update_centroids, k_means def test_initialize_centroids(): features = [[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.2, 2.5], [8.2, 8.1]] k = 2 centroids = initialize_centroids(features, k) assert len(centroids) == k for centroid in c...
[ { "docstring": "Randomly initialize the centroids by selecting 'k' random features as initial centroids.", "function_declaration": "def initialize_centroids(features, k):", "function_name": "initialize_centroids", "parameter_list": "(features, k)" }, { "docstring": "Assign each feature to th...
[ 0, 1, 0, 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": "import random\n\ndef initialize_centroids(features, k):\n \"\"\"\n Returns k initial centroids randomly selected from the set of features.\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment: Implementing K-Means Clustering Algorithm\n\n**Objective**: Implement the K-Means clustering algorithm to group a set of instances into specified clusters. You will use the provided utility functions as a reference to create new components to demonstrate your understa...
0.730193
Algorithm_32444
C
[ "initialize_centroids", "assign_clusters", "update_centroids", "euclidean_distance", "k_means" ]
5
[ [ "assign_clusters", "euclidean_distance" ], [ "k_means", "assign_clusters" ], [ "k_means", "initialize_centroids" ], [ "k_means", "update_centroids" ] ]
4
[]
false
[]
false
pytest
true
[]
true
0acb83ce5a6833a22a8bf7aec38d1e478e8611d9
915040c33b236b6428f820146b1430ccf86e2964
v1.0
complete
Algorithm
Algorithm_8273_C
from typing import List, Dict def avg_response_time(tickets: List[Dict]) -> float: """ Calculate the average response time of all support tickets. >>> tickets = [{'response_time': 10, 'resolution_time': 50, 'satisfaction': True}, {'response_time': 5, 'resolution_time': 30, 'satisfaction': False}, {'response_ti...
from typing import List, Dict def avg_response_time(tickets: List[Dict]) -> float: total_response_time = sum(ticket['response_time'] for ticket in tickets) return round(total_response_time / len(tickets), 2) def avg_resolution_time(tickets: List[Dict]) -> float: total_resolution_time = sum(ticket['resolut...
from solution import avg_response_time, avg_resolution_time, satisfaction_rate, service_summary def test_avg_response_time(): tickets = [ {'response_time': 10, 'resolution_time': 50, 'satisfaction': True}, {'response_time': 5, 'resolution_time': 30, 'satisfaction': False}, {'response_time':...
[ { "docstring": null, "function_declaration": "def avg_response_time(tickets):", "function_name": "avg_response_time", "parameter_list": "(tickets)" }, { "docstring": null, "function_declaration": "def avg_resolution_time(tickets):", "function_name": "avg_resolution_time", "parame...
[ 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 avg_response_time(tickets):\n total_response_time = sum(ticket['response_time'] for ticket in tickets)\n return round(total_response_time / len(tickets...
trial_gpt4o_5
{ "original_instruction": "### Problem Statement\n\nYou are commissioned to create a module that analyzes and summarizes the service management pattern of a company's customer support system. The module should determine the average response time, the average resolution time, and the customer satisfaction rate based o...
0.682427
Algorithm_8273
C
[ "avg_response_time", "avg_resolution_time", "satisfaction_rate", "service_summary" ]
4
[ [ "service_summary", "avg_resolution_time" ], [ "service_summary", "avg_response_time" ], [ "service_summary", "satisfaction_rate" ] ]
3
[]
false
[]
false
pytest
true
[]
true
eaac6c90100ceb66b2e45e3fdce98b3edab91d9c
fe1a1b40fe0ca38b7e5fc802953425f690d4c40d
v1.0
complete
Algorithm
Algorithm_5710_C
import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import train_test_split def data_preprocessing(reviews, labels) -> tuple: """ Vectorize the review...
import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import train_test_split def data_preprocessing(reviews, labels) -> tuple: """ Vectorize the review...
import pytest from solution import train_text_classifier def test_train_text_classifier(): # Sample data reviews = [ "I loved the movie! It was fantastic!", "The movie was awful and boring.", "What a great film with amazing performances!", "Terrible plot and bad acting.", ...
[ { "docstring": "Vectorize the reviews using TfidfVectorizer and split the data", "function_declaration": "def data_preprocessing(reviews, labels):", "function_name": "data_preprocessing", "parameter_list": "(reviews, labels)" }, { "docstring": "Implement and train the text classification mod...
[ 0, 0, 0, 0, 0, 0, 1, 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\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import...
trial_gpt4o_7
{ "original_instruction": "### Question\nYou are required to implement a text classification model using the `TfidfVectorizer` and `LogisticRegression` from the `scikit-learn` library. The goal is to build a model that can classify movie reviews into positive or negative sentiments. \n\n### Requirements:\n- Vectorize...
0.694119
Algorithm_5710
C
[ "data_preprocessing", "train_text_classifier" ]
2
[ [ "train_text_classifier", "data_preprocessing" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
564cbcae4a471f17b4177a8f795bfce85f45ad2b
0d48de1b028e0e4360e539cc6c74842f35b2394d
v1.0
complete
Algorithm
Algorithm_1265_C
def smallest_triangular_sum(k: int) -> int: """ Find the smallest possible triangular number which can be expressed as the sum of exactly `k` distinct triangular numbers. >>> smallest_triangular_sum(1) == 1 >>> smallest_triangular_sum(2) == 4 # 1 + 3 >>> smallest_triangular_sum(3) == 10 # 1 + 3 + 6 ...
def triangular_number(n): return n * (n + 1) // 2 def smallest_triangular_sum(k: int) -> int: triangular_numbers = [triangular_number(i) for i in range(1, k+1)] return sum(triangular_numbers)
def test_smallest_triangular_sum_1(): assert smallest_triangular_sum(1) == 1 def test_smallest_triangular_sum_2(): assert smallest_triangular_sum(2) == 4 # 1 + 3 def test_smallest_triangular_sum_3(): assert smallest_triangular_sum(3) == 10 # 1 + 3 + 6 def test_smallest_triangular_sum_4(): assert sm...
[ { "docstring": null, "function_declaration": "def triangular_number(n):", "function_name": "triangular_number", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def smallest_triangular_sum(k):", "function_name": "smallest_triangular_sum", "parameter_list":...
[ 1, 1, 1, 0, 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": "def smallest_triangular_sum(k: int) -> int:\n \"\"\"\n Returns the smallest possible triangular number which can be expressed as a\n sum of exactly 'k' ...
trial_gpt4o_9
{ "original_instruction": "### Question: Distinct Integer Sums in Triangular Numbers\n\n#### Background\nA triangular number or triangle number is a number that can form an equilateral triangle when represented as dots. The \\( n \\)-th triangular number is given by the formula \\( T_n = \\frac{n(n+1)}{2} \\). For ex...
0.55619
Algorithm_1265
C
[ "triangular_number", "smallest_triangular_sum" ]
2
[ [ "smallest_triangular_sum", "triangular_number" ] ]
1
[]
false
[]
false
pytest
false
[]
true
1c38cf1bbc2ec1a2ae831e349bcba488a209d2c9
efdd5adfa96144fec07bff68dca3a1cde1986263
v1.0
complete
Algorithm
Algorithm_35544_C
from typing import List, Tuple def prime_pairs(n: int) -> List[Tuple[int, int]]: """ Given an integer `n`, find all pairs of prime numbers `(p1, p2)` such that: - `p1` and `p2` are both prime numbers, - `p1 + p2 = n`, - and `p1 <= p2`. Returns a list of such pairs. >>> prime_pairs...
from typing import List, Tuple def sieve_of_eratosthenes(limit: int) -> List[bool]: """ Generates a list of booleans representing primality of numbers up to limit. """ is_prime = [True] * (limit + 1) is_prime[0], is_prime[1] = False, False # 0 and 1 are not primes p = 2 while (p * p <= limit)...
from solution import prime_pairs def test_prime_pairs_basic(): assert prime_pairs(10) == [(3, 7), (5, 5)] assert prime_pairs(14) == [(3, 11), (7, 7)] assert prime_pairs(5) == [(2, 3)] def test_prime_pairs_no_pairs(): assert prime_pairs(1) == [] assert prime_pairs(0) == [] assert prime_pairs(-1...
[ { "docstring": "Generates a list of booleans representing primality of numbers up to limit. ", "function_declaration": "def sieve_of_eratosthenes(limit):", "function_name": "sieve_of_eratosthenes", "parameter_list": "(limit)" }, { "docstring": "Returns a list of tuples (p1, p2) where p1 and ...
[ 0, 0, 0, 0, 1, 1, 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 typing import List, Tuple\n\ndef sieve_of_eratosthenes(n: int) -> List[bool]:\n \"\"\" Generates a list of booleans representing prime numbers up to n. \...
trial_gpt4o_7
{ "original_instruction": "### Question: Prime Number Pairs\n\n**Background**: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n**Problem**:\nGiven an integer `n`, find all pairs of prime numbers `(p1, p2)` such that:\n- `p1` and `p2` are both prime numbers,\...
0.745747
Algorithm_35544
C
[ "sieve_of_eratosthenes", "prime_pairs" ]
2
[ [ "prime_pairs", "sieve_of_eratosthenes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3f2b594fad95491971983034882cc130f6be484a
32ce2b4d0c4aa64673c5d1217ecd219cd28cf26b
v1.0
complete
Algorithm
Algorithm_27620_C
def factorial_comparison(number: int) -> str: """ Computes the factorial using both the iterative and recursive methods. Compares the results and returns a message indicating if they match or not. >>> factorial_comparison(5) 'Matching Factorials: 120' >>> factorial_comparison(10) 'Matching ...
def factorial_iterative(n): """ Computes the factorial of n using an iterative approach. """ result = 1 for i in range(2, n + 1): result *= i return result def factorial_recursive(n): """ Computes the factorial of n using a recursive approach. """ if n == 0 or n == 1: ...
from solution import factorial_comparison def test_factorial_comparison_positive(): assert factorial_comparison(5) == "Matching Factorials: 120" assert factorial_comparison(10) == "Matching Factorials: 3628800" assert factorial_comparison(0) == "Matching Factorials: 1" assert factorial_comparison(1) ==...
[ { "docstring": "Computes the factorial of n using an iterative approach.", "function_declaration": "def factorial_iterative(n):", "function_name": "factorial_iterative", "parameter_list": "(n)" }, { "docstring": "Computes the factorial of n using a recursive approach.", "function_declara...
[ 1, 1, 1, 1, 1, 0, 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": "def factorial_iterative(n):\n \"\"\"\n Computes the factorial of a non-negative integer iteratively.\n \"\"\"\n result = 1\n for i in range(2, n +...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment Question\n\nYou are provided with two implementations of an algorithm that computes the factorial of a non-negative integer. One implementation is iterative, and the other uses recursion.\n\n### Task\nWrite a Python function that performs the following steps:\n1. Reads...
0.664349
Algorithm_27620
C
[ "factorial_iterative", "factorial_recursive", "factorial_comparison" ]
3
[ [ "factorial_comparison", "factorial_iterative" ], [ "factorial_comparison", "factorial_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d4dd974b427ae6daf5c97f70840dcedb6a07182f
e95d96001afdb181a939ef071cd8ea85db3c154a
v1.0
complete
Algorithm
Algorithm_42848_C
def is_prime(n: int) -> bool: """ Check if a number is prime. """ # Implementation here def prime_fibonacci(k: int) -> list: """ Finds the first `k` numbers in the Fibonacci sequence which are also prime numbers. >>> prime_fibonacci(5) [2, 3, 5, 13, 89] >>> prime_fibonacci(10) [2, ...
def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def prime_fibonacci(k): if k <= 0: ...
from solution import prime_fibonacci, is_prime def test_is_prime(): assert is_prime(1) == False assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(30) == False def test_prime_fibonacci_length_1(): assert prime_fibon...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def prime_fibonacci(k):", "function_name": "prime_fibonacci", "parameter_list": "(k)" } ]
[ 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 prime_fibonacci(k):\n def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % ...
trial_gpt4o_8
{ "original_instruction": "### Code Exercise:\nWrite a function that finds the first `k` numbers in the Fibonacci sequence which are also prime numbers. Return these prime Fibonacci numbers as a list.\n\n### Function Signature\n```python\ndef prime_fibonacci(k: int) -> list:\n```\n\n### Input\n- An integer `k`, where...
0.848214
Algorithm_42848
C
[ "is_prime", "prime_fibonacci" ]
2
[ [ "prime_fibonacci", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1428fa3bfaa204e602bca9dc8beeb8857949b2fd
3d6599982007f550eb822c5917e14abdaba30913
v1.0
complete
Algorithm
Algorithm_38723_C
def k_means_clustering(points: np.ndarray, k: int, max_iters: int, random_seed: int) -> (np.ndarray, np.ndarray): """ Implement the K-Means clustering algorithm to assign clusters to data points and compute centroids. Args: points (np.ndarray): A matrix of shape (n, d) representing n data points wi...
import numpy as np import matplotlib.pyplot as plt def initialize_centroids(points, k, random_seed): np.random.seed(random_seed) random_indices = np.random.choice(points.shape[0], k, replace=False) centroids = points[random_indices] return centroids def closest_centroid(points, centroids): distanc...
import numpy as np from solution import k_means_clustering def test_k_means_clustering(): points = np.array([[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0], [8.0, 2.0], [10.0, 2.0]]) k = 3 max_iters = 100 random_seed = 42 cluster_labels, centroids =...
[ { "docstring": null, "function_declaration": "def initialize_centroids(points, k, random_seed):", "function_name": "initialize_centroids", "parameter_list": "(points, k, random_seed)" }, { "docstring": null, "function_declaration": "def closest_centroid(points, centroids):", "functio...
[ 1, 1, 1, 0, 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": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef initialize_centroids(points, k, random_seed):\n np.random.seed(random_seed)\n random_indices = n...
trial_gpt4o_9
{ "original_instruction": "### K-Means Clustering Implementation and Cluster Visualization\n\n#### Context\nYou are working as a data scientist for a retail company. Your task is to segment customers based on their purchasing behaviors to identify distinct customer clusters. To achieve this, you decide to use the K-M...
0.841308
Algorithm_38723
C
[ "initialize_centroids", "closest_centroid", "move_centroids", "k_means_clustering", "plot_clusters" ]
5
[ [ "k_means_clustering", "closest_centroid" ], [ "k_means_clustering", "initialize_centroids" ], [ "k_means_clustering", "move_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
17dc14611f87735774333b2c6140067380ede3f6
82b56c21bab3bf0336a07ed92dbcb172b35bc587
v1.0
complete
Algorithm
Algorithm_6309_C
import numpy as np def initialize_centroids(features: np.ndarray, k: int) -> np.ndarray: """ Initialize k cluster centroids randomly from the dataset. >>> features = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) >>> k = 2 >>> centroids = initialize_centroids(features, k) >>> centroids.shape (2, 2)...
import numpy as np def initialize_centroids(features: np.ndarray, k: int) -> np.ndarray: """ Initialize k cluster centroids randomly from the dataset. """ n_samples = features.shape[0] indices = np.random.choice(n_samples, k, replace=False) centroids = features[indices] return centroids de...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, compute_within_cluster_sums_of_squares, k_means_clustering def test_initialize_centroids(): features = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) k = 2 centroids = initialize_centroids(features, k) assert c...
[ { "docstring": "Initialize k cluster centroids randomly from the dataset.", "function_declaration": "def initialize_centroids(features, k):", "function_name": "initialize_centroids", "parameter_list": "(features, k)" }, { "docstring": "Assign each data point to the nearest cluster centroid."...
[ 0, 0, 0, 0, 1, 0, 1, 1, 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": "import numpy as np\n\ndef initialize_centroids(features: np.ndarray, k: int) -> np.ndarray:\n \"\"\"\n Randomly initializes k centroids from the dataset.\n...
trial_gpt4o_9
{ "original_instruction": "### Question: Implement k-Means Clustering\n\nYou are provided a dataset with multiple features. Write code to implement the k-Means clustering algorithm to group the data into k clusters. Your implementation should include the method to initialize the cluster centroids, assign data points ...
0.789497
Algorithm_6309
C
[ "initialize_centroids", "assign_clusters", "update_centroids", "compute_within_cluster_sums_of_squares", "k_means_clustering" ]
5
[ [ "k_means_clustering", "assign_clusters" ], [ "k_means_clustering", "compute_within_cluster_sums_of_squares" ], [ "k_means_clustering", "initialize_centroids" ], [ "k_means_clustering", "update_centroids" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy" ]
false
ab0248b5bd1b30188d6e7ee75d1f81b57a418379
87d789f0ab4f9a4e3d442c35183d9f3247e09e9b
v1.0
complete
Algorithm
Algorithm_10290_C
from collections import Counter import math def compute_euclidean_distance(point1: list[float], point2: list[float]) -> float: """ Returns the Euclidean distance between two points. Parameters: point1 (list of float): The first point. point2 (list of float): The second point. Returns:...
from collections import Counter import math def compute_euclidean_distance(point1, point2): """ Returns the Euclidean distance between two points. Parameters: point1 (list of float): The first point. point2 (list of float): The second point. Returns: float: The Euclidean distance ...
def test_compute_euclidean_distance(): assert math.isclose(compute_euclidean_distance([1.0, 2.0], [5.0, 8.0]), 7.211102550927978) assert math.isclose(compute_euclidean_distance([0, 0], [0, 0]), 0.0) assert math.isclose(compute_euclidean_distance([1, 1], [4, 5]), 5.0) def test_determine_k_nearest_neighb...
[]
[ 0, 1, 1, 1, 0, 0, 0, 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": "import math\nfrom collections import Counter\nfrom typing import List\n\ndef compute_euclidean_distance(point1: List[float], point2: List[float]) -> float:\n ...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment: K-Nearest Neighbors (KNN) Algorithm Implementation\n\n**Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. Use the provided structure and existing utility functions to create new components, demonstrating your understanding ...
0.698389
Algorithm_10290
C
[ "compute_euclidean_distance", "determine_k_nearest_neighbors", "predict_class" ]
3
[ [ "determine_k_nearest_neighbors", "compute_euclidean_distance" ] ]
1
[]
false
[]
false
pytest
false
[]
true
8efa2776b09774e7511fa5c2852a38e82e91362c
0666bd4cc905e8da263261a82dbcfc46adba0ce1
v1.0
complete
Algorithm
Algorithm_33057_C
def bubble_sort_iterative(nums: list[int | float]) -> list[int | float]: """ Sorts a list using iterative bubble sort algorithm. """ def merge_sort_recursive(nums: list[int | float]) -> list[int | float]: """ Sorts a list using recursive merge sort algorithm. """ # Test cases for the iterati...
def bubble_sort_iterative(nums: list[int | float]) -> list[int | float]: """ Sorts a list using iterative bubble sort algorithm. """ n = len(nums) for i in range(n): for j in range(0, n-i-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] retu...
from solution import bubble_sort_iterative, merge_sort_recursive def test_bubble_sort_iterative(): assert bubble_sort_iterative([3, 2, 1]) == [1, 2, 3] assert bubble_sort_iterative([-3, -2, -1]) == [-3, -2, -1] assert bubble_sort_iterative([3, -3, 0]) == [-3, 0, 3] assert bubble_sort_iterative([3.0, 3....
[ { "docstring": "Sorts a list using iterative bubble sort algorithm.", "function_declaration": "def bubble_sort_iterative(nums):", "function_name": "bubble_sort_iterative", "parameter_list": "(nums)" }, { "docstring": "Sorts a list using recursive merge sort algorithm.", "function_declara...
[ 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 bubble_sort_iterative(nums: list[int | float]) -> list[int | float]:\n \"\"\"\n Sorts a list of numbers using the bubble sort algorithm iteratively.\n ...
trial_gpt4o_9
{ "original_instruction": "### Sort the List: Iterative vs Recursive\n\nYou are given two algorithms to sort a list of numbers: an iterative approach using bubble sort and a recursive approach using merge sort. Your task is to implement a function that leverages these algorithms to sort the provided list of numbers i...
0.515226
Algorithm_33057
C
[ "bubble_sort_iterative", "merge_sort_recursive", "merge" ]
3
[ [ "merge_sort_recursive", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
66d21226779d901f51a7d1664a96bbd06603a6cb
cc5816c35c82f12a13b1efaf9f38ca6766fe8716
v1.0
complete
Algorithm
Algorithm_34082_C
def find_lcm_of_three(a: int, b: int, c: int) -> int: """ Determine and return the least common multiple (LCM) of three integers. >>> find_lcm_of_three(4, 6, 8) 24 >>> find_lcm_of_three(12, 15, 20) 60 >>> find_lcm_of_three(7, 13, 19) 1729 """
import math def find_lcm(x, y): """ Helper function to find the least common multiple (LCM) of two numbers. """ return x * y // math.gcd(x, y) def find_lcm_of_three(a: int, b: int, c: int) -> int: """ Determine and return the least common multiple (LCM) of three integers. """ lcm_ab = ...
from solution import find_lcm_of_three def test_find_lcm_of_three(): assert find_lcm_of_three(4, 6, 8) == 24 assert find_lcm_of_three(12, 15, 20) == 60 assert find_lcm_of_three(7, 13, 19) == 1729 assert find_lcm_of_three(1, 1, 1) == 1 assert find_lcm_of_three(10, 20, 30) == 60 assert find_lcm_o...
[ { "docstring": "Helper function to find the least common multiple (LCM) of two numbers.", "function_declaration": "def find_lcm(x, y):", "function_name": "find_lcm", "parameter_list": "(x, y)" }, { "docstring": "Determine and return the least common multiple (LCM) of three integers.", "f...
[ 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": "import math\n\ndef lcm(x, y):\n \"\"\"\n Returns the least common multiple (LCM) of two integers x and y.\n \"\"\"\n return abs(x * y) // math.gcd(x,...
trial_gpt4o_6
{ "original_instruction": "## Question: Least Common Multiple (LCM) of Three Numbers\n\n#### Scenario\nGiven three integers, determine the least common multiple (LCM) of these numbers. The least common multiple of three integers is the smallest positive integer that is divisible by all three of the given integers.\n\...
0.656671
Algorithm_34082
C
[ "find_lcm", "find_lcm_of_three" ]
2
[ [ "find_lcm_of_three", "find_lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
edeebce51aa11338a8263714354fd137964cda02
abe3eef005c087b843869f478d44687582a514ec
v1.0
complete
Algorithm
Algorithm_26198_C
def spell_check(text, dictionary): """ Check the spelling of each word in the text against the provided dictionary. Return a dictionary of words and their list of suggested corrections based on Levenshtein distance. >>> spell_check("speling correctin", ["spelling", "correction", "checking", "words"]) ...
def levenshtein_distance(word1, word2): """ Calculate the Levenshtein distance between two words. """ if len(word1) < len(word2): return levenshtein_distance(word2, word1) # Initialization of the distance matrix previous_row = range(len(word2) + 1) for i, c1 in enumerate(word1): ...
from solution import spell_check def test_spell_check_simple(): text = "speling correctin" dictionary = ["spelling", "correction", "checking", "words"] expected_output = {'speling': ['spelling'], 'correctin': ['correction']} assert spell_check(text, dictionary) == expected_output def test_spell_check_...
[ { "docstring": "Calculate the Levenshtein distance between two words.", "function_declaration": "def levenshtein_distance(word1, word2):", "function_name": "levenshtein_distance", "parameter_list": "(word1, word2)" }, { "docstring": "Check the spelling of each word in the text against the pr...
[ 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": "def levenshtein_distance(a, b):\n \"\"\"\n Calculate the Levenshtein distance between two strings a and b.\n \"\"\"\n if len(a) < len(b):\n re...
trial_gpt4o_7
{ "original_instruction": "**Scenario**:\nYou are tasked with developing a spell checker for a text editor. The requirement is to check if each word in a given text exists in a provided dictionary of words. If a word is not found in the dictionary, you need to suggest corrections based on the Levenshtein distance, wh...
0.545479
Algorithm_26198
C
[ "levenshtein_distance", "spell_check" ]
2
[ [ "spell_check", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fdb3b0b7398118831b56eb226a05a83b6ea49126
5921d4f740adc8d9f3e2605cf5ce45b6d9f67bb2
v1.0
complete
Algorithm
Algorithm_44177_C
from typing import List def distributed_matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: """ Multiplies two matrices A and B using a distributed computing approach. Parameters: A (List[List[int]]): A 2D list representing matrix A. B (List[List[int]]): A 2D ...
from typing import List from multiprocessing import Pool def single_element_multiplication(args): A, B, i, j = args return sum(A[i][k] * B[k][j] for k in range(len(B))) def distributed_matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: if not A or not B or len(A[0]) != len(B...
from solution import distributed_matrix_multiplication def test_distributed_matrix_multiplication_basic(): A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] result = distributed_matrix_multiplication(A, B) expected = [ [19, 22], [43, 50] ] ass...
[ { "docstring": null, "function_declaration": "def single_element_multiplication(args):", "function_name": "single_element_multiplication", "parameter_list": "(args)" }, { "docstring": null, "function_declaration": "def distributed_matrix_multiplication(A, B):", "function_name": "dist...
[ 1, 1, 0, 1, 0, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nfrom multiprocessing import Pool\n\ndef single_element_multiplication(args):\n A, B, i, j = args\n return sum(A[i][k] * B[k][j] fo...
trial_gpt4o_0
{ "original_instruction": "### Coding Assessment Question\n\n#### Scenario: Distributed Matrix Multiplication\n\nYou are implementing a distributed computing system where large matrix multiplications are offloaded to a cluster of machines. Your task is to design a distributed matrix multiplication algorithm that divi...
0.547955
Algorithm_44177
C
[ "single_element_multiplication", "distributed_matrix_multiplication" ]
2
[ [ "distributed_matrix_multiplication", "single_element_multiplication" ] ]
1
[]
false
[]
false
pytest
true
[]
true
180b00a9ddc572fd1b1e4df2523bd7a3f7a54c2f
beba9ab780d8494efad2d119553d9e880f633d45
v1.0
complete
Algorithm
Algorithm_24987_C
def efficient_pathfinder(graph, start, end): """ Find the shortest path in a graph that may contain negative edge weights using a combination of Dijkstra's and Bellman-Ford algorithms. - graph: Dictionary of dictionaries representing the weighted graph. - start: Identifier of the starting node. - end: I...
import heapq def bellman_ford(graph, start, end): # Initialization distance = {node: float('inf') for node in graph} predecessor = {node: None for node in graph} distance[start] = 0 # Relax edges |V|-1 times for _ in range(len(graph) - 1): for u in graph: for v in graph...
from solution import efficient_pathfinder def test_no_negative_edges(): graph = { 'A': {'B': 1, 'C': 4}, 'B': {'C': 2, 'D': 5}, 'C': {'D': 1}, 'D': {} } assert efficient_pathfinder(graph, 'A', 'D') == (['A', 'B', 'C', 'D'], 4) def test_with_negative_edges(): graph = { ...
[ { "docstring": null, "function_declaration": "def bellman_ford(graph, start, end):", "function_name": "bellman_ford", "parameter_list": "(graph, start, end)" }, { "docstring": null, "function_declaration": "def dijkstra(graph, start, end):", "function_name": "dijkstra", "paramete...
[ 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 efficient_pathfinder(graph, start, end):\n import heapq\n\n def dijkstra(graph, start):\n pq = [(0, start)]\n dist = {node: float('inf') ...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment Question\nAs part of your assessments on graph theory and pathfinding algorithms, you are tasked with implementing a more efficient version of a classic pathfinding algorithm. This problem requires enhancing the Dijkstra's algorithm to efficiently handle graphs contain...
0.632781
Algorithm_24987
C
[ "bellman_ford", "dijkstra", "has_negative_edge", "efficient_pathfinder" ]
4
[ [ "efficient_pathfinder", "bellman_ford" ], [ "efficient_pathfinder", "dijkstra" ], [ "efficient_pathfinder", "has_negative_edge" ] ]
3
[]
false
[]
false
pytest
true
[]
true
dbd396ec956f680494676d698dde7e0b9fecd3d3
8e36da991498e0a0d195f5f343488b3c47a701d0
v1.0
complete
Algorithm
Algorithm_2502_C
def sum_of_primes_in_range(L: int, R: int) -> int: """Returns the sum of all primes within the specified range [L, R]. >>> sum_of_primes_in_range(10, 20) 60 >>> sum_of_primes_in_range(5, 5) 5 >>> sum_of_primes_in_range(14, 16) 0 >>> sum_of_primes_in_range(1, 10) 17 """ pass ...
def sieve(n): """Helper function to generate a list of primes up to n using the Sieve of Eratosthenes""" is_prime = [True] * (n + 1) is_prime[0], is_prime[1] = False, False # 0 and 1 are not prime numbers p = 2 while (p * p <= n): if is_prime[p]: for i in range(p * p, n + 1, p):...
from solution import sum_of_primes_in_range, count_primes_in_range def test_sum_of_primes_in_range_basic(): assert sum_of_primes_in_range(10, 20) == 60 def test_sum_of_primes_in_range_inclusive(): assert sum_of_primes_in_range(5, 5) == 5 def test_sum_of_primes_in_range_noprimes(): assert sum_of_primes_in...
[ { "docstring": "Helper function to generate a list of primes up to n using the Sieve of Eratosthenes", "function_declaration": "def sieve(n):", "function_name": "sieve", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def sum_of_primes_in_range(L, R):", "func...
[ 0, 1, 0, 0, 1, 0, 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 sum_of_primes_in_range(L: int, R: int) -> int:\n \"\"\"Returns the sum of all prime numbers in the range [L, R] inclusive.\"\"\"\n if L > R:\n r...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment Question\n\n**Context**:\n\nIn competitive programming, efficient calculation of prime numbers is a crucial skill. The Sieve of Eratosthenes is an ancient algorithm used to find all prime numbers up to a given limit. Given a range [L, R], your task is to implement a fu...
0.736712
Algorithm_2502
C
[ "sieve", "sum_of_primes_in_range", "count_primes_in_range" ]
3
[ [ "count_primes_in_range", "sieve" ], [ "sum_of_primes_in_range", "sieve" ] ]
2
[]
false
[]
false
pytest
true
[]
true
17ea769edc7333a5886eb2a64d5ced210f8869c2
08ce295c019010709b08f832efd5a64b413f6c7d
v1.0
complete
Algorithm
Algorithm_4917_C
def char_frequency(s: str) -> dict: """ Returns a dictionary with character frequencies in the input string. :param s: Input string :return: Dictionary with characters as keys and their frequencies as values. Example: >>> char_frequency("mississippi") {'m': 1, 'i': 4, 's': 4, 'p': 2} ...
def char_frequency(s): """ Returns a dictionary with character frequencies in the input string. :param s: Input string :return: Dictionary with characters as keys and their frequencies as values """ frequency = {} for char in s: if char in frequency: frequency[char] ...
from solution import char_frequency, highest_frequency_char def test_char_frequency(): assert char_frequency("mississippi") == {'m': 1, 'i': 4, 's': 4, 'p': 2} assert char_frequency("abcabc") == {'a': 2, 'b': 2, 'c': 2} assert char_frequency("aaa") == {'a': 3} assert char_frequency("aba") == {'a': 2, '...
[ { "docstring": "Returns a dictionary with character frequencies in the input string.\n\n:param s: Input string\n:return: Dictionary with characters as keys and their frequencies as values", "function_declaration": "def char_frequency(s):", "function_name": "char_frequency", "parameter_list": "(s)" ...
[ 1, 0, 1, 1, 1, 1, 0, 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 collections import Counter\n\ndef char_frequency(s):\n \"\"\"\n Computes the frequency of each character in the string.\n \n Params:\n - s (s...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nIn this task, you will be working with a string manipulation and computation problem that involves frequency analysis. Implement a function that accepts a string and computes the frequency of each character in the string. Additionally, enhance this function to find ...
0.650721
Algorithm_4917
C
[ "char_frequency", "highest_frequency_char" ]
2
[ [ "highest_frequency_char", "char_frequency" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de5f87c1e44d2236ff22c710719352aba0158649
c76626de10274864339bc8b5682f5c2904dfae14
v1.0
complete
Algorithm
Algorithm_14774_C
""" function compute_user_statistics(logfile: str, num_threads: int) -> dict: ''' Processes a log file and computes basic statistical summaries (mean, median, and standard deviation) for each user, using multi-threading to handle large datasets. Args: logfile : str : Path to the log file to be pro...
import csv import os import threading from collections import defaultdict from statistics import mean, median, stdev from concurrent.futures import ThreadPoolExecutor def compute_statistics(values): return { 'mean': mean(values), 'median': median(values), 'std_dev': stdev(values) if len(val...
import os import pytest from solution import compute_user_statistics def create_log_file(content, filename="test_logfile.txt"): with open(filename, "w") as f: f.write(content) def remove_log_file(filename="test_logfile.txt"): if os.path.exists(filename): os.remove(filename) def test_compute_u...
[ { "docstring": null, "function_declaration": "def compute_statistics(values):", "function_name": "compute_statistics", "parameter_list": "(values)" }, { "docstring": null, "function_declaration": "def process_chunk(chunk, user_data):", "function_name": "process_chunk", "parameter...
[ 1, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom concurrent.futures import ThreadPoolExecutor\nimport threading\n\ndef compute_user_statistics(logfile, num_threads):\n \"\"\"\n Pr...
trial_gpt4o_1
{ "original_instruction": "### Compiling Large-Scale Statistical Summaries\n\n#### Scenario\nYou have a large log file composed of individual records, each containing an entry for a user, a timestamp, and an associated numeric value. You need to process this file to compute statistical summaries for each user efficie...
0.709804
Algorithm_14774
C
[ "compute_statistics", "process_chunk", "read_in_chunks", "compute_user_statistics" ]
4
[ [ "compute_user_statistics", "compute_statistics" ], [ "compute_user_statistics", "process_chunk" ], [ "compute_user_statistics", "read_in_chunks" ] ]
3
[]
false
[]
false
pytest
true
[]
true
08f9574425830f3751de55b663bd7c4531458d5e
e7e19381811e84afd1ea73f4dc78c8114bd3d9c0
v1.0
complete
Algorithm
Algorithm_33317_C
def combinatorial_selection(n, k): """ Calculate the total number of unique selections of k items from a set of n items. >>> combinatorial_selection(5, 3) 10 >>> combinatorial_selection(6, 2) 15 >>> combinatorial_selection(0, 0) 1 >>> combinatorial_selection(10, 0) 1 >>> combinat...
def combinatorial_selection(n, k): if k > n or n < 0 or k < 0: raise ValueError("Invalid input: n and k must be such that 0 ≤ k ≤ n and both are non-negative integers.") if k == 0 or k == n: return 1 k = min(k, n - k) # Take advantage of symmetry C(n, k) == C(n, n-k) result = ...
import pytest from solution import combinatorial_selection, print_combinatorial_selection def test_combinatorial_selection_basic(): assert combinatorial_selection(5, 3) == 10 assert combinatorial_selection(6, 2) == 15 assert combinatorial_selection(0, 0) == 1 assert combinatorial_selection(10, 0) == 1 ...
[ { "docstring": null, "function_declaration": "def combinatorial_selection(n, k):", "function_name": "combinatorial_selection", "parameter_list": "(n, k)" }, { "docstring": null, "function_declaration": "def print_combinatorial_selection(n, k):", "function_name": "print_combinatorial_...
[ 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 combinatorial_selection(n: int, k: int) -> int:\n \"\"\"\n Calculate the number of unique combinations of k items out of n items (C(n, k)).\n Uses a...
trial_gpt4o_9
{ "original_instruction": "### Combinatorial Selection\n\nWrite a function that calculates the total number of unique selections of `k` items from a set of `n` items. This is a classic problem of combinatorics, often referred to as \"n choose k\" or binomial coefficient, calculated as:\n\n\\[ C(n, k) = \\frac{n!}{k!(...
0.539459
Algorithm_33317
C
[ "combinatorial_selection", "print_combinatorial_selection" ]
2
[ [ "print_combinatorial_selection", "combinatorial_selection" ] ]
1
[]
false
[]
false
pytest
true
[]
true
afc16292513cc91033d5bf5309ce71b5c51cc856
69ab6b24d98f48b5e853f22992b02a983c216553
v1.0
complete
Algorithm
Algorithm_39082_C
def modified_quick_sort(arr: list, threshold: int = 10) -> None: """ Perform a modified quick sort on a nearly sorted array. Args: arr (list): The list of elements to be sorted. threshold (int): The size below which Insertion Sort is used instead of Quick Sort. Default value is 10. Raises:...
def insertion_sort(arr, left, right): """ Helper function to perform insertion sort on a subarray from left to right. """ for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j...
from solution import modified_quick_sort def test_already_sorted(): arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] modified_quick_sort(arr) assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def test_reverse_sorted(): arr = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] modified_quick_sort(arr) assert arr == [1, 2, 3, 4, ...
[ { "docstring": "Helper function to perform insertion sort on a subarray from left to right.", "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": "Partition the array for quicksort using ...
[ 1, 1, 1, 1, 0, 1, 0, 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 modified_quick_sort(array, threshold=10):\n \"\"\"\n Sorts an array in place using a modified version of the Quick Sort algorithm\n optimized for ne...
trial_gpt4o_7
{ "original_instruction": "### Task: Implement a Modified Quick Sort for Nearly Sorted Arrays\n\n#### Scenario\nYou are presented with an algorithm challenge to implement a modified version of the Quick Sort algorithm. This variant should take advantage of the input array's almost sorted nature. The task requires you...
0.613236
Algorithm_39082
C
[ "insertion_sort", "modified_partition", "modified_quick_sort_rec", "modified_quick_sort" ]
4
[ [ "modified_quick_sort", "modified_quick_sort_rec" ], [ "modified_quick_sort_rec", "insertion_sort" ], [ "modified_quick_sort_rec", "modified_partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
ad533b7aec18909bd736017637159a04ebb58c20
0926f9eb0c01be4ae47e016a9cd67e7b9ebb115f
v1.0
complete
Algorithm
Algorithm_35901_C
def jaccard_similarity(s1: str, s2: str, n: int) -> float: """ Returns the Jaccard similarity coefficient between two strings based on their n-grams. >>> jaccard_similarity("abcde", "cdefg", 2) 0.3333333333333333 >>> jaccard_similarity("abc", "def", 1) 0.0 >>> jaccard_similarity("abc", "abc...
def generate_ngrams(s, n): """Generate n-grams for a given string and length.""" return {s[i:i+n] for i in range(len(s) - n + 1)} def jaccard_similarity(s1, s2, n): """ Returns the Jaccard similarity coefficient between two strings based on their n-grams. """ if n > len(s1) or n > len(s2): ...
def test_jaccard_similarity_simple_case(): s1 = "abcde" s2 = "cdefg" n = 2 assert jaccard_similarity(s1, s2, n) == 2 / 6 def test_jaccard_similarity_no_overlap(): s1 = "abc" s2 = "def" n = 1 assert jaccard_similarity(s1, s2, n) == 0.0 def test_jaccard_similarity_full_overlap(): s1 ...
[ { "docstring": "Generate n-grams for a given string and length.", "function_declaration": "def generate_ngrams(s, n):", "function_name": "generate_ngrams", "parameter_list": "(s, n)" }, { "docstring": "Returns the Jaccard similarity coefficient between two strings based on their n-grams.", ...
[ 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 generate_ngrams(s: str, n: int):\n \"\"\"\n Generate n-grams from the given string.\n \"\"\"\n return {s[i:i+n] for i in range(len(s) - n + 1)}\n...
trial_gpt4o_2
{ "original_instruction": "### Problem Statement\n\nYou are tasked with implementing a function to evaluate the similarity between two strings using the Jaccard similarity coefficient. The Jaccard similarity coefficient is defined as the size of the intersection divided by the size of the union of the sample sets. In...
0.697717
Algorithm_35901
C
[ "generate_ngrams", "jaccard_similarity" ]
2
[ [ "jaccard_similarity", "generate_ngrams" ] ]
1
[]
false
[]
false
pytest
false
[]
true
a68733953d66996c98cb8fc5d93a6cbf65c5c943
5612ce88dba50d9ecbd20e90fc5fd9059f60146f
v1.0
complete
Algorithm
Algorithm_32708_C
def gcd(a: int, b: int) -> int: """ Computes the Greatest Common Divisor (GCD) of two positive integers a and b using the Euclidean algorithm. Raises a ValueError if either a or b is non-positive. >>> gcd(48, 18) 6 >>> gcd(-1, 10) Traceback (most recent call last): ... ValueError: Bo...
def gcd(a: int, b: int) -> int: """ Computes the Greatest Common Divisor (GCD) of two positive integers a and b using the Euclidean algorithm. Raises a ValueError if either a or b is non-positive. """ if a <= 0 or b <= 0: raise ValueError("Both numbers must be positive") while b: ...
from solution import gcd, lcm def test_gcd_positive_numbers(): assert gcd(48, 18) == 6 assert gcd(100, 10) == 10 assert gcd(7, 5) == 1 assert gcd(20, 25) == 5 def test_gcd_with_non_positive_raises_error(): try: gcd(-5, 10) except ValueError as e: assert str(e) == "Both numbers ...
[ { "docstring": "Computes the Greatest Common Divisor (GCD) of two positive integers a and b using the Euclidean algorithm.\nRaises a ValueError if either a or b is non-positive.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of two positive integers a and b using the Euclidean algorithm.\n Raises ValueError ...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement: LCM and GCD Calculator\n\nYou are tasked with creating a small utility library that helps in calculating the Least Common Multiple (LCM) and the Greatest Common Divisor (GCD) for given input values. This library should provide functions to compute these properties usi...
0.836667
Algorithm_32708
C
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1ec0df6762b2a358b3cb32f331491af7dc095f63
caf9dab15dfe6f77777d78bafad0c380813796eb
v1.0
complete
Algorithm
Algorithm_48267_C
class AVLTreeNode: def __init__(self, value: int): self.value = value self.left = None self.right = None self.height = 1 def insert(root: Optional[AVLTreeNode], value: int) -> AVLTreeNode: """Insert a node into the AVL tree and perform necessary rotations to maintain the AVL pro...
class AVLTreeNode: def __init__(self, value: int): self.value = value self.left = None self.right = None self.height = 1 def get_height(node: AVLTreeNode) -> int: return node.height if node else 0 def get_balance(node: AVLTreeNode) -> int: return get_height(node.left) - get...
from solution import AVLTreeNode, insert, rotate_left, rotate_right def in_order_traversal(root, result=None): if result is None: result = [] if root: in_order_traversal(root.left, result) result.append(root.value) in_order_traversal(root.right, result) return result def te...
[]
[ 1, 1, 0, 0, 0, 0, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class AVLTreeNode:\n def __init__(self, value: int):\n self.value = value\n self.left = None\n self.right = None\n self.height = 1...
trial_gpt4o_0
{ "original_instruction": "### AVL Tree Insertion and Rotation\n\n#### Background:\nAVL trees are a type of self-balancing binary search tree where the height difference between the left and right subtrees of any node is at most one. To maintain this property during insertions, AVL trees perform rotations to rebalanc...
0.402782
Algorithm_48267
C
[ "get_height", "get_balance", "update_height", "rotate_left", "rotate_right", "insert" ]
6
[ [ "get_balance", "get_height" ], [ "insert", "get_balance" ], [ "insert", "rotate_left" ], [ "insert", "rotate_right" ], [ "insert", "update_height" ], [ "rotate_left", "update_height" ], [ "rotate_right", "update_height" ], [ "...
8
[]
false
[ "AVLTreeNode" ]
true
pytest
true
[]
true
b13b76efe49b44eda6d6d0922eb49c470169ac6b
b0e883468ea6c2ae10cc07cdb6e609eff6c79754
v1.0
complete
Algorithm
Algorithm_24023_C
def can_multiply_matrices(A: list, B: list) -> bool: """ Check if two matrices can be multiplied. Parameters: A (list of list of int): Matrix A B (list of list of int): Matrix B Returns: bool: True if matrices can be multiplied, otherwise False >>> can_multiply_matrices([[...
def can_multiply_matrices(A, B): """ Check if two matrices can be multiplied. Parameters: A (list of list of int): Matrix A B (list of list of int): Matrix B Returns: bool: True if matrices can be multiplied, otherwise False """ # Number of columns in A should be equal to t...
import pytest from solution import can_multiply_matrices, multiply_matrices def test_can_multiply_matrices_true(): assert can_multiply_matrices([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]]) == True assert can_multiply_matrices([[1, 2]], [[3, 4], [5, 6]]) == True assert can_multiply_matrices([[2]], ...
[ { "docstring": "Check if two matrices can be multiplied.\n\nParameters:\nA (list of list of int): Matrix A\nB (list of list of int): Matrix B\n\nReturns:\nbool: True if matrices can be multiplied, otherwise False", "function_declaration": "def can_multiply_matrices(A, B):", "function_name": "can_multipl...
[ 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": "def can_multiply_matrices(A, B):\n \"\"\"\n Check if the matrices A and B can be multiplied.\n \"\"\"\n if len(A[0]) == len(B):\n return True\...
trial_gpt4o_9
{ "original_instruction": "### Matrix Multiplication Validator\n\nAs part of a system that performs matrix operations, you have been asked to create a function that validates if two matrices can be multiplied and then performs the multiplication if valid.\n\n#### Task\n\n1. Implement two functions:\n - `can_multipl...
0.555452
Algorithm_24023
C
[ "can_multiply_matrices", "multiply_matrices" ]
2
[ [ "multiply_matrices", "can_multiply_matrices" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e597b9e1a76e90f6995bf043bba5c2d12c0f9e23
0fd4ff477a2a06b0f584f95b6b207a96829338eb
v1.0
complete
Algorithm
Algorithm_24420_C
from typing import List def dfs(row: int, col: int, grid: List[List[int]], visited: List[List[bool]]) -> int: """ Perform a Depth-First Search to calculate the size of the island. - `row`: The row index of the current cell. - `col`: The column index of the current cell. - `grid`: A 2D list of integ...
from typing import List def dfs(row: int, col: int, grid: List[List[int]], visited: List[List[bool]]) -> int: """ Perform a Depth-First Search to calculate the size of the island. """ # Check for bounds and if the cell is water or already visited if row < 0 or row >= len(grid) or col < 0 or col >= ...
def test_dfs_island_size(): grid = [ [1, 1, 0, 0, 0], [1, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1] ] visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))] assert dfs(0, 0, grid, visited) == 4 visited = [[False for _ in range(len(grid[0]))] fo...
[ { "docstring": "Perform a Depth-First Search to calculate the size of the island.", "function_declaration": "def dfs(row, col, grid, visited):", "function_name": "dfs", "parameter_list": "(row, col, grid, visited)" }, { "docstring": "Find the size of the largest island in the grid.", "fu...
[ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef dfs(row: int, col: int, grid: List[List[int]], visited: List[List[bool]]) -> int:\n # If we are out of bounds or at a cell that...
trial_gpt4o_2
{ "original_instruction": "### Problem Statement\nYou are given a 2D grid filled with integers where each cell is either land (`1`) or water (`0`). Your task is to find the size of the largest island of land. An island is a group of adjacent lands horizontally or vertically (not diagonally). You need to implement fun...
0.601635
Algorithm_24420
C
[ "dfs", "largest_island" ]
2
[ [ "largest_island", "dfs" ] ]
1
[]
false
[]
false
pytest
false
[]
true
3f4c1c9734b71990fe50759d18a37c34b88ecaf9
bb67135a8b6daf86b6b71484e3a7f1ffaae4c92e
v1.0
complete
Algorithm
Algorithm_2672_C
### Implement a `spell_checker` function to identify misspelled words and suggest corrections using the provided dictionary. def spell_checker(filename: str, dictionary: list) -> dict: """ Spell checker function to identify misspelled words and suggest corrections. Args: - filename (str): The name ...
import re from collections import defaultdict def levenshtein_distance(word1, word2): """ Calculate the Levenshtein distance (edit distance) between two words. """ m, n = len(word1), len(word2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i for j in r...
from solution import spell_checker import pytest def create_test_file(content, filename): """ Helper function to create a test file with the given content. """ with open(filename, 'w') as file: file.write(content) def test_spell_checker(): # Prepare the dictionary dictionary = ["hello"...
[ { "docstring": "Calculate the Levenshtein distance (edit distance) between two words.", "function_declaration": "def levenshtein_distance(word1, word2):", "function_name": "levenshtein_distance", "parameter_list": "(word1, word2)" }, { "docstring": "Find the closest matching word in the dict...
[ 0, 1, 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": "import os\n\ndef levenshtein_distance(a, b):\n \"\"\"\n Compute the Levenshtein distance between two strings a and b\n \"\"\"\n if len(a) < len(b):\n...
trial_gpt4o_9
{ "original_instruction": "### Context\nYou are developing a spell checker program. The program needs to read a text file containing various words, identify if they are correctly spelled, and suggest corrections for misspelled words. You are provided with a dictionary of correctly spelled words.\n\n### Task\nYour tas...
0.582564
Algorithm_2672
C
[ "levenshtein_distance", "find_closest_word", "spell_checker" ]
3
[ [ "find_closest_word", "levenshtein_distance" ], [ "spell_checker", "find_closest_word" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b6558e5a01e5e106581f8594ff37ac007575684d
b547188306ceadfec8262b8910bc7916e18674a8
v1.0
complete
Algorithm
Algorithm_14983_C
import json import os TASKS_FILE = 'tasks.json' def load_tasks(): if not os.path.isfile(TASKS_FILE): return [] with open(TASKS_FILE, 'r') as file: return json.load(file) def save_tasks(tasks): with open(TASKS_FILE, 'w') as file: json.dump(tasks, file) def add_task(task_descriptio...
import json import os # Define the file name for storing tasks TASKS_FILE = 'tasks.json' def load_tasks(): if not os.path.isfile(TASKS_FILE): return [] with open(TASKS_FILE, 'r') as file: return json.load(file) def save_tasks(tasks): with open(TASKS_FILE, 'w') as file: json.dump(t...
import os import pytest from solution import add_task, list_tasks, complete_task, load_tasks, save_tasks @pytest.fixture(autouse=True) def setup_and_teardown(): # Setup: Backup pre-existing tasks file and create a fresh one. if os.path.isfile('tasks.json'): os.rename('tasks.json', 'tasks_backup.json') ...
[ { "docstring": null, "function_declaration": "def load_tasks():", "function_name": "load_tasks", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def save_tasks(tasks):", "function_name": "save_tasks", "parameter_list": "(tasks)" }, { "docstring": n...
[ 1, 1, 1, 1, 0, 1, 1, 0, 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 json\nimport os\n\nTASKS_FILE = 'tasks.json'\n\ndef load_tasks():\n if os.path.exists(TASKS_FILE):\n with open(TASKS_FILE, 'r') as file:\n ...
trial_gpt4o_8
{ "original_instruction": "### Task: Create a Simple CLI Task Manager\n\n#### Scenario\nYou are required to develop a simple Command-Line Interface (CLI) Task Manager application that allows users to manage their to-do tasks. The tool should support adding, listing, and marking tasks as completed.\n\n#### Requirement...
0.632619
Algorithm_14983
C
[ "load_tasks", "save_tasks", "add_task", "list_tasks", "complete_task" ]
5
[ [ "add_task", "load_tasks" ], [ "add_task", "save_tasks" ], [ "complete_task", "load_tasks" ], [ "complete_task", "save_tasks" ], [ "list_tasks", "load_tasks" ] ]
5
[]
false
[]
false
pytest
true
[]
true
55864c26109fbf4abe90965d8412f7d43de7dca0
135cd65ba61ec2872c6fbdcc90c25052192c6060
v1.0
complete
Algorithm
Algorithm_43533_C
def is_perfect_number(n: int) -> bool: """ Check if a given positive integer is a perfect number. >>> is_perfect_number(28) True >>> is_perfect_number(12) False >>> is_perfect_number(6) True >>> is_perfect_number(1) False """ def count_perfect_numbers_in_range(lower: int, upper:...
def is_perfect_number(n: int) -> bool: if n < 2: return False divisors_sum = 1 for i in range(2, int(n**0.5) + 1): if n % i == 0: divisors_sum += i if i != n // i: divisors_sum += n // i return divisors_sum == n def count_perfect_number...
import pytest from solution import is_perfect_number, count_perfect_numbers_in_range def test_is_perfect_number(): assert is_perfect_number(6) == True assert is_perfect_number(28) == True assert is_perfect_number(12) == False assert is_perfect_number(1) == False assert is_perfect_number(496) == Tru...
[ { "docstring": null, "function_declaration": "def is_perfect_number(n):", "function_name": "is_perfect_number", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def count_perfect_numbers_in_range(lower, upper):", "function_name": "count_perfect_numbers_in_rang...
[ 1, 0, 1, 1, 0, 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 is_perfect_number(n: int) -> bool:\n \"\"\"\n Determine if n is a perfect number.\n \"\"\"\n if n <= 1:\n return False\n\n sum_divisors...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\nA perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, the proper divisors of 6 are 1, 2, and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number.\n\nDefine a function `is_perfect_number(n: int) -> bool` that ...
0.577438
Algorithm_43533
C
[ "is_perfect_number", "count_perfect_numbers_in_range" ]
2
[ [ "count_perfect_numbers_in_range", "is_perfect_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7ce42bad924dd737616c091f464a4c70fd273d48
ffcdce9048f6425d36b751632f4d46037d084dec
v1.0
complete
Algorithm
Algorithm_4695_C
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def has_duplicate_subtree(root: TreeNode) -> bool: """ Check for the presence of duplicate subtrees in a binary tree. Args: root (TreeNode): The root of the binary tree. Ret...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def serialize_and_check(root, subtree_map): if not root: return "#" left_serial = serialize_and_check(root.left, subtree_map) right_serial = serialize_and_check(root.right, subtre...
import pytest from solution import has_duplicate_subtree, build_tree, TreeNode def test_empty_tree(): assert has_duplicate_subtree(None) == False def test_single_node_tree(): tree = build_tree([1]) assert has_duplicate_subtree(tree) == False def test_no_duplicate_subtree(): tree = build_tree([1, 2, 3...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef has_duplicate_subtree(root: TreeNod...
trial_gpt4o_9
{ "original_instruction": "### Binary Tree: Duplicate Subtree Detection\n\n#### Background:\nYou need to detect whether a binary tree contains any duplicate subtrees. A subtree is considered a duplicate if another subtree with the same structure and node values exists elsewhere in the tree.\n\n#### Task:\nWrite a fun...
0.61465
Algorithm_4695
C
[ "serialize_and_check", "has_duplicate_subtree", "build_tree" ]
3
[ [ "has_duplicate_subtree", "serialize_and_check" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
ec03aba204cb211f8b179675635ba336d4ffcc11
732c33e6139ac1725acc2c93ff5af42924f454b3
v1.0
complete
Algorithm
Algorithm_19890_C
def initialize_dp_table(n: int, target: int) -> list[list[bool]]: """ Initializes the DP table for subset sum problem. Parameters: - n: Number of items in the nums array - target: The target sum Returns: - DP table as a list of lists (2D table), where dp[i][j] is True if a subset ...
def initialize_dp_table(n, target): """ Initializes the DP table for subset sum problem. Parameters: - n: Number of items in the nums array - target: The target sum Returns: - DP table as a list of lists (2D table), where dp[i][j] is True if a subset with sum j can be achieve...
from solution import initialize_dp_table, fill_dp_table, subset_reconstruction, subset_sum def test_initialize_dp_table(): dp = initialize_dp_table(3, 5) assert len(dp) == 4 # Should have 4 rows (0 to 3) assert len(dp[0]) == 6 # Should have 6 columns (0 to 5) assert all(dp[i][0] for i in range(4)) #...
[ { "docstring": "Initializes the DP table for subset sum problem.\n\nParameters:\n- n: Number of items in the nums array\n- target: The target sum\n\nReturns:\n- DP table as a list of lists (2D table), where dp[i][j] is True if a subset\n with sum j can be achieved using the first i items.", "function_decla...
[ 1, 0, 0, 1, 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 initialize_dp_table(n: int, target: int) -> list[list[bool]]:\n \"\"\"\n Initializes a 2D DP table with dimensions (n+1) x (target+1)\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "### Subset Sum Problem using Dynamic Programming\n\n**Context**:\nYou are asked to solve an instance of the Subset Sum Problem using Dynamic Programming. The Subset Sum Problem is a classic problem in computer science where the objective is to determine whether there is a subset of the give...
0.568739
Algorithm_19890
C
[ "initialize_dp_table", "fill_dp_table", "subset_reconstruction", "subset_sum" ]
4
[ [ "subset_sum", "fill_dp_table" ], [ "subset_sum", "initialize_dp_table" ], [ "subset_sum", "subset_reconstruction" ] ]
3
[]
false
[]
false
pytest
true
[]
true
8ba9958736452eac6265663549c781b19306691b
b614ea83ae40214a5c7627d606cf8ee175d6ea72
v1.0
complete
Algorithm
Algorithm_1913_C
def can_obtain_by_rotation(matrix1: list[list[int]], matrix2: list[list[int]]) -> bool: """ Checks if matrix2 can be obtained by rotating matrix1 by 90, 180, or 270 degrees. >>> can_obtain_by_rotation([[1, 2], [3, 4]], [[1, 2], [3, 4]]) True >>> can_obtain_by_rotation([[1, 2], [3, 4]], [[3, 1], [4,...
def rotate_90(matrix): """ Rotates the matrix by 90 degrees clockwise. """ n = len(matrix) return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)] def can_obtain_by_rotation(matrix1, matrix2): """ Checks if matrix2 can be obtained by rotating matrix1 by 90, 180, or 270 degrees. ...
def test_can_obtain_by_rotation_identical(): matrix1 = [[1, 2], [3, 4]] matrix2 = [[1, 2], [3, 4]] assert can_obtain_by_rotation(matrix1, matrix2) == True def test_can_obtain_by_rotation_90_degrees(): matrix1 = [[1, 2], [3, 4]] matrix2 = [[3, 1], [4, 2]] assert can_obtain_by_rotation(matrix1, m...
[ { "docstring": "Rotates the matrix by 90 degrees clockwise.", "function_declaration": "def rotate_90(matrix):", "function_name": "rotate_90", "parameter_list": "(matrix)" }, { "docstring": "Checks if matrix2 can be obtained by rotating matrix1 by 90, 180, or 270 degrees.", "function_decl...
[ 0, 0, 0, 0, 0, 1, 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 rotate_90(matrix):\n \"\"\"\n Rotates the given square matrix by 90 degrees.\n \"\"\"\n n = len(matrix)\n return [[matrix[n - j - 1][i] for j ...
trial_gpt4o_5
{ "original_instruction": "### Matrix Rotation Validator\n\nYou are tasked to implement a function that checks if one matrix can be obtained by rotating another matrix by 90-degree increments. This task will evaluate your understanding of matrix manipulation and rotations.\n\n#### Function Definition\nWrite a functio...
0.528157
Algorithm_1913
C
[ "rotate_90", "can_obtain_by_rotation" ]
2
[ [ "can_obtain_by_rotation", "rotate_90" ] ]
1
[]
false
[]
false
pytest
false
[]
true
4bccaf12730530f9b430418939e8e04a67651409
7552ba74fd41f328d11959b2fa5b69697c4ae7a9
v1.0
complete
Algorithm
Algorithm_33075_C
def is_perfect_number(number: int) -> bool: """ Check if the given number is a perfect number. >>> is_perfect_number(28) True >>> is_perfect_number(27) False """ pass def perfect_numbers_sum() -> int: """ Find all perfect numbers within the range 2 to 10000 and return their sum. >>>...
def is_perfect_number(number: int) -> bool: """ Check if the given number is a perfect number. """ if number < 2: return False proper_divisors_sum = sum(i for i in range(1, number // 2 + 1) if number % i == 0) return proper_divisors_sum == number def perfect_numbers_sum() -> int: ""...
from solution import is_perfect_number, perfect_numbers_sum def test_is_perfect_number(): assert is_perfect_number(6) == True assert is_perfect_number(28) == True assert is_perfect_number(496) == True assert is_perfect_number(8128) == True assert is_perfect_number(1) == False assert is_perfect_...
[ { "docstring": "Check if the given number is a perfect number.", "function_declaration": "def is_perfect_number(number):", "function_name": "is_perfect_number", "parameter_list": "(number)" }, { "docstring": "Find all perfect numbers within the range 2 to 10000 and return their sum.", "f...
[ 1, 0, 0, 1, 0, 0, 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": "def is_perfect_number(number: int) -> bool:\n \"\"\"\n Checks if a given number is a perfect number.\n \"\"\"\n if number < 2:\n return False\...
trial_gpt4o_6
{ "original_instruction": "**Perfect Number Finder**\n\n#### Problem Statement:\nA perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). For example, 28 is a perfect number because its proper divisors are 1, 2, 4, 7, and 14, and their sum is 28. Your task ...
0.585365
Algorithm_33075
C
[ "is_perfect_number", "perfect_numbers_sum" ]
2
[ [ "perfect_numbers_sum", "is_perfect_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
05cec36164942e35ad9df1f98893b021e593e55e
bb976e0fb8e555daf463fdd00811e788f61ba2fa
v1.0
complete
Algorithm
Algorithm_42634_C
from typing import List def count_valid_parentheses(strings: List[str]) -> int: """ Takes a list of strings and returns the count of strings that are valid parentheses strings. >>> count_valid_parentheses(["(", "()", "(())", "()", "(()"]) 3 >>> count_valid_parentheses(["", "()", "()()", "(()(...
from typing import List def is_valid_parentheses(s: str) -> bool: """ Helper function to determine if the given string is a valid parentheses string. """ stack = [] for char in s: if char == '(': stack.append('(') elif char == ')': if not stack: ...
def test_count_valid_parentheses(): assert count_valid_parentheses(["(", "()", "(())", "()", "(()"]) == 3, "Test Case 1 Failed" assert count_valid_parentheses(["", "()", "()()", "(()())", "((()"]) == 4, "Test Case 2 Failed" assert count_valid_parentheses([")", "((()())", "(()))", "()()()"]) == 1, "Test Case...
[ { "docstring": "Helper function to determine if the given string is a valid parentheses string.", "function_declaration": "def is_valid_parentheses(s):", "function_name": "is_valid_parentheses", "parameter_list": "(s)" }, { "docstring": "Counts the number of valid parentheses strings in the ...
[ 0, 1, 1, 0, 1, 0, 1, 1, 0 ]
5
medium
0.556
{ "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_valid_parentheses_string(s: str) -> bool:\n stack = []\n for char in s:\n if char == '(':\n stack.appen...
trial_gpt4o_7
{ "original_instruction": "### Question: Counting Valid Parentheses Strings\n\n**Scenario:**\nYou are tasked with evaluating various strings to determine how many of them are valid parentheses strings. A valid parentheses string is defined by the following conditions:\n1. An empty string is a valid parentheses string...
0.721453
Algorithm_42634
C
[ "is_valid_parentheses", "count_valid_parentheses" ]
2
[ [ "count_valid_parentheses", "is_valid_parentheses" ] ]
1
[]
false
[]
false
pytest
false
[]
true
03afd7529043d96eb7345215afad6400dec26137
b0004658768a54b3e2d2a8d8df7984f1b73a6a67
v1.0
complete
Algorithm
Algorithm_28525_C
def max_subarray_sum(arr: list) -> int: """Find the maximum sum of any contiguous subarray within a list of integers using the Divide and Conquer approach. >>> max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) 6 >>> max_subarray_sum([1]) 1 >>> max_subarray_sum([-1, -2, -3]) -1 """ def max...
def max_crossing_sum(arr, left, mid, right): """ Helper function to find the maximum possible sum in arr[] such that the sum includes elements on the left of mid and elements on the right of mid """ # Include elements on left of mid sm = 0 left_sum = float('-inf') for i in range(mid, lef...
from solution import max_subarray_sum def test_single_element(): assert max_subarray_sum([1]) == 1 assert max_subarray_sum([-1]) == -1 def test_all_negative(): assert max_subarray_sum([-2, -3, -4, -1, -2, -1, -5, -3]) == -1 def test_mixed_elements(): assert max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) =...
[ { "docstring": "Helper function to find the maximum possible sum in arr[] such that\nthe sum includes elements on the left of mid and elements on the right of mid", "function_declaration": "def max_crossing_sum(arr, left, mid, right):", "function_name": "max_crossing_sum", "parameter_list": "(arr, l...
[ 1, 1, 1, 1, 1, 1, 0, 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 max_crossing_sum(arr, left, mid, right):\n # Include elements on left of mid.\n sm = 0\n left_sum = float('-inf')\n for i in range(mid, left - 1,...
trial_gpt4o_9
{ "original_instruction": "### Maximum Subarray Sum using Divide and Conquer\n\nYou are required to find the maximum sum of any contiguous subarray within a given list of integers using the Divide and Conquer approach. This problem is a classic example that can be solved efficiently by dividing the array into smaller...
0.735545
Algorithm_28525
C
[ "max_crossing_sum", "max_subarray_sum_util", "max_subarray_sum" ]
3
[ [ "max_subarray_sum", "max_subarray_sum_util" ], [ "max_subarray_sum_util", "max_crossing_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6e3a66cc4750763b1e63a3ebb049fc5b39d3ece2
2f5d76d6bbaa67206954fd5bce387eb578f77655
v1.0
complete
Algorithm
Algorithm_266_C
import math def hexagon_perimeter(side: float) -> float: """ Calculate the perimeter of a regular hexagon. >>> hexagon_perimeter(4) 24 >>> hexagon_perimeter(1) 6 >>> hexagon_perimeter(-3) Traceback (most recent call last): ... ValueError: Length must be a positive number. """ ...
import math def hexagon_perimeter(side: float) -> float: """ Calculate the perimeter of a regular hexagon. :param side: Length of one side of the hexagon. :return: Perimeter of the hexagon. """ if side <= 0: raise ValueError("Length must be a positive number.") return 6 * side ...
import pytest from solution import hexagon_perimeter, hexagon_area, describe_hexagon def test_hexagon_perimeter(): assert hexagon_perimeter(4) == 24 assert hexagon_perimeter(1) == 6 with pytest.raises(ValueError): hexagon_perimeter(-3) with pytest.raises(ValueError): hexagon_perimeter(0...
[ { "docstring": "Calculate the perimeter of a regular hexagon.\n\n:param side: Length of one side of the hexagon.\n:return: Perimeter of the hexagon.", "function_declaration": "def hexagon_perimeter(side):", "function_name": "hexagon_perimeter", "parameter_list": "(side)" }, { "docstring": "C...
[ 0, 1, 0, 1, 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": "import math\n\ndef hexagon_perimeter(side: float) -> float:\n \"\"\"\n Calculates the perimeter of a regular hexagon.\n\n Parameters:\n side (float):...
trial_gpt4o_7
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\n\nYou are developing a module for a math tutoring application designed to help students understand properties of various two-dimensional shapes. The next task on your list is to add functionality to compute properties of regular polygons. A sp...
0.593341
Algorithm_266
C
[ "hexagon_perimeter", "hexagon_area", "describe_hexagon" ]
3
[ [ "describe_hexagon", "hexagon_area" ], [ "describe_hexagon", "hexagon_perimeter" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b669d6fbec54fe1b8bd6ecd9e7bafe39b6cf9f77
479a3ef67842ca55f89e67f92f57928689f2f477
v1.0
complete
Algorithm
Algorithm_32190_C
class ListNode: def __init__(self, x): self.val = x self.next = None def merge_sort(head: ListNode) -> ListNode: """ Implement merge sort algorithm for sorting a singly linked list. >>> head = list_to_linked_list([4, 2, 1, 3]) >>> sorted_head = merge_sort(head) >>> linked_list_to_li...
class ListNode: def __init__(self, x): self.val = x self.next = None def merge_sort(head: ListNode) -> ListNode: if not head or not head.next: return head def find_middle(head): slow, fast = head, head.next while fast and fast.next: slow = slow.next ...
from solution import ListNode, merge_sort def list_to_linked_list(lst): if not lst: return None head = ListNode(lst[0]) current = head for value in lst[1:]: current.next = ListNode(value) current = current.next return head def linked_list_to_list(head): lst = [] whi...
[]
[ 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 merge_sort(head: ListNode) -> ListNode:\n if not head or no...
trial_gpt4o_8
{ "original_instruction": "### Question: Implement Merge Sort for Linked Lists\n\n#### Problem Statement\nYour task is to implement the merge sort algorithm for sorting a singly linked list. Merge sort is a divide and conquer algorithm that splits the list into halves, recursively sorts each half, and then merges the...
0.482943
Algorithm_32190
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
aaaac16e3588334c31d657b408636f7face2c31c
3208e3bb8b925aef35e6a27652e5286cfd780294
v1.0
complete
Algorithm
Algorithm_15597_C
def merge_sort(arr: list[int]) -> list[int]: """ Sorts an array of integers using the merge sort algorithm. >>> merge_sort([38, 27, 43, 3, 9, 82, 10]) [3, 9, 10, 27, 38, 43, 82] >>> merge_sort([1, 5, 3, 2, 8, 7, 6, 4]) [1, 2, 3, 4, 5, 6, 7, 8] >>> merge_sort([]) [] >>> merge_sort([1]) ...
def merge_sort(arr: list[int]) -> list[int]: """ Sorts an array of integers using the merge sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def...
from solution import merge_sort def test_merge_sort_with_positive_numbers(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_with_unsorted_list(): assert merge_sort([1, 5, 3, 2, 8, 7, 6, 4]) == [1, 2, 3, 4, 5, 6, 7, 8] def test_merge_sort_with_empty_list(): ...
[ { "docstring": "Sorts an array of integers using the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists into one sorted list.", "function_declaration": "def merge(left...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
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: list[int]) -> list[int]:\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \n Parameters:\n arr (list[in...
trial_gpt4o_9
{ "original_instruction": "### Merge Sort - Recursive Sorting Algorithm\n\nYou are a software engineer at a company focused on developing efficient sorting algorithms. Your latest task involves implementing the \"Merge Sort\" algorithm, which is a classic divide-and-conquer algorithm.\n\n#### Merge Sort\nMerge Sort w...
0.6604
Algorithm_15597
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2e11e823c11c6ac65c10b8aed666046b1130c291
19f6256941959d9de0a34ace64fa093237ea96c4
v1.0
complete
Algorithm
Algorithm_12070_C
def closest_pair_of_points(points: list[tuple[int, int]]) -> float: """ Given a list of n points on the 2D plane, where each point is represented as a tuple of two integers (x, y), find and return the minimum distance between any two points from the list. Args: points (list[tuple[int, int]]): A l...
import math def euclidean_distance(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y): # Base case if len(points_sorted_by_x) <= 3: min_dist = float('inf') for i in range(len(points_sorted_by_x)): ...
import pytest from solution import closest_pair_of_points def test_closest_pair_basic(): assert math.isclose(closest_pair_of_points([(0, 0), (1, 1), (4, 5), (2, 2)]), 1.4142135623730951, rel_tol=1e-9) def test_closest_pair_less_than_two_points(): with pytest.raises(ValueError, match="At least two points are r...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y):", "function_name": ...
[ 1, 1, 1, 1, 1, 0, 0, 0, 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 math\nfrom typing import List, Tuple\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n return math.sqrt((point1[0...
trial_gpt4o_8
{ "original_instruction": "### Closest Pair of Points\n\n**Problem Statement:**\n\nGiven a list of `n` points on the 2D plane, where each point is represented as a tuple of two integers `(x, y)`, write a function `closest_pair_of_points(points: list[tuple[int, int]]) -> float` that finds and returns the minimum dista...
0.736075
Algorithm_12070
C
[ "euclidean_distance", "closest_pair_recursive", "closest_pair_of_points" ]
3
[ [ "closest_pair_of_points", "closest_pair_recursive" ], [ "closest_pair_recursive", "euclidean_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
35aa3f8735181cd72461d84dfc8d49a11b72d01d
e30b8bc4352d635126f75e9e044b269a7168a65d
v1.0
complete
Algorithm
Algorithm_24644_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ This function should sort the list `arr` using merge sort algorithm and return the sorted list. >>> merge_sort([38, 27, 43, 3, 9, 82, 10]) [3, 9, 10, 27, 38, 43, 82] >>> merge_sort([1, 4, 2, 8, 5, 7]) [1, 2, 4, 5, 7, ...
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_unsorted(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_mixed_numbers(): assert merge_sort([10, -1, 2, 5, 0, 6, 4, -5]) == [-5, -1, 0, 2, 4, 5, 6, 10] def test_merge_sort_random_order(): assert merge_s...
[ { "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 \"\"\"\n This function sorts the list `arr` using merge sort algorithm and return...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nYou are given a list of integers. Your task is to implement a function that sorts the list using the merge sort algorithm.\n\n### Function Signature\n```python\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n This function should sort the list `arr` us...
0.619409
Algorithm_24644
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9a62df242508c24bf5a9b1a59f8620eaf66c4924
dfd9942089e33a0dbd334299b8521f6963f4b7fe
v1.0
complete
Algorithm
Algorithm_26173_C
def triangulate_polygon(vertices: list[list[float]]) -> list[list[list[float]]]: """ Triangulate the given simple polygon. >>> triangulate_polygon([ [0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [2.0, 4.0], [0.0, 3.0] ]) [[ [0.0, 0.0], [4.0, 0.0], [4.0, 3.0] ], [...
def is_convex(a, b, c): """ Returns True if the triangle (a, b, c) is convex, otherwise False. """ # Calculate cross product to determine the orientation return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) > 0 def is_point_in_triangle(pt, v1, v2, v3): """ Returns True if pt is inside t...
from solution import triangulate_polygon def test_triangulate_square(): vertices = [ [0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0] ] expected = [ [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0]], [[0.0, 0.0], [2.0, 2.0], [0.0, 2.0]], ] result = triangulate_polyg...
[ { "docstring": "Returns True if the triangle (a, b, c) is convex, otherwise False. ", "function_declaration": "def is_convex(a, b, c):", "function_name": "is_convex", "parameter_list": "(a, b, c)" }, { "docstring": "Returns True if pt is inside the triangle (v1, v2, v3), otherwise False. ", ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_counter_clockwise(p0, p1, p2):\n \"\"\"\n Check if the turn formed by the points p0, p1, p2 is counter-clockwise.\n \"\"\"\n return (p1[0] - p...
trial_gpt4o_8
{ "original_instruction": "### Triangulating a Simple Polygon\n\n#### Background:\nA simple polygon is a polygon that does not intersect itself and has only one boundary. Triangulation of a simple polygon is the process of dividing the polygon into non-overlapping triangles. Triangulating a polygon is an important op...
0.486043
Algorithm_26173
C
[ "is_convex", "is_point_in_triangle", "is_ear", "triangulate_polygon" ]
4
[ [ "is_ear", "is_convex" ], [ "is_ear", "is_point_in_triangle" ], [ "triangulate_polygon", "is_ear" ] ]
3
[]
false
[]
false
pytest
true
[]
true
56468defe831da9ca428f38263b37665259436f5
eeb632a5d5e69e3b9bafe5c38d9bd4e7fc3009c6
v1.0
complete
Algorithm
Algorithm_44125_C
from typing import List from math import isqrt def is_prime(n: int) -> bool: """ Check if a number is prime. >>> is_prime(2) True >>> is_prime(4) False >>> is_prime(11) True """ pass def sum_of_unique_primes(arr: List[int]) -> int: """ Calculate the sum of all unique prime num...
from math import isqrt def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def sum_of_unique_prim...
from solution import sum_of_unique_primes, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(25) == False assert is_prime(29) == True def test_sum_of_unique_primes(): assert sum_of_uniq...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculate the sum of all unique prime numbers in the given array.\n\n:param arr: list: the list of integers to check\n:return: int: sum of unique prime num...
[ 0, 0, 1, 1, 1, 0, 0, 1, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import isqrt\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ...
trial_gpt4o_9
{ "original_instruction": "### Sum of Unique Primes\n\n#### Problem Statement:\n\nGiven an array of integers, determine the sum of all unique prime numbers present in the array. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to implement a functio...
0.697667
Algorithm_44125
C
[ "is_prime", "sum_of_unique_primes" ]
2
[ [ "sum_of_unique_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e5388e23c7a061d0f09c3968a02beb49005b48b7
34edd5d4b36363ce7132ce86c99cd3ec7b777832
v1.0
complete
Algorithm
Algorithm_43042_C
def solve_hanoi(num_disks: int) -> int: """ Calculate the minimum number of moves required to solve the Tower of Hanoi problem with the given number of disks. Args: num_disks (int): The number of disks in the Tower of Hanoi problem. Returns: int: The minimum number of moves req...
def tower_of_hanoi(n, source, target, auxiliary): if n == 1: return 1 else: moves_before = tower_of_hanoi(n - 1, source, auxiliary, target) move_disk = 1 moves_after = tower_of_hanoi(n - 1, auxiliary, target, source) return moves_before + move_disk + moves_after def solv...
from solution import solve_hanoi def test_solve_hanoi_1_disk(): assert solve_hanoi(1) == 1 def test_solve_hanoi_2_disks(): assert solve_hanoi(2) == 3 def test_solve_hanoi_3_disks(): assert solve_hanoi(3) == 7 def test_solve_hanoi_4_disks(): assert solve_hanoi(4) == 15 def test_solve_hanoi_5_disks()...
[ { "docstring": null, "function_declaration": "def tower_of_hanoi(n, source, target, auxiliary):", "function_name": "tower_of_hanoi", "parameter_list": "(n, source, target, auxiliary)" }, { "docstring": null, "function_declaration": "def solve_hanoi(num_disks):", "function_name": "sol...
[ 1, 1, 0, 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": "def solve_hanoi(num_disks: int) -> int:\n \"\"\"\n Calculates and returns the number of moves required to solve the Tower of Hanoi\n problem with the gi...
trial_gpt4o_9
{ "original_instruction": "### Tower of Hanoi Recursive Solution and Analysis\n\n**Background**:\nThe Tower of Hanoi is a classic problem in computer science that involves moving a set of disks from one peg to another, following specific rules. This problem is often used to teach recursion and algorithmic thinking.\n...
0.4739
Algorithm_43042
C
[ "tower_of_hanoi", "solve_hanoi" ]
2
[ [ "solve_hanoi", "tower_of_hanoi" ] ]
1
[]
false
[]
false
pytest
true
[]
true
17f45a5e996046f203859e5545360eb89e297241
1f2e8de7d2358df770437f6f085ea8a5d3a10087
v1.0
complete
Algorithm
Algorithm_29992_C
def merge_k_sorted(lists: list[list[int | float]]) -> list[int | float]: """ Merge k sorted lists into a single sorted list using a recursive divide-and-conquer strategy. >>> merge_k_sorted([[1, 4, 5], [1, 3, 4], [2, 6]]) == [1, 1, 2, 3, 4, 4, 5, 6] >>> merge_k_sorted([[], [1], [2, 5, 8]]) == [1, 2, 5, 8] ...
def merge_two_sorted_lists(l1, l2): result = [] i, j = 0, 0 while i < len(l1) and j < len(l2): if l1[i] < l2[j]: result.append(l1[i]) i += 1 else: result.append(l2[j]) j += 1 result.extend(l1[i:]) result.extend(l2[j:]) return result...
def test_merge_k_sorted(): assert merge_k_sorted([[1, 4, 5], [1, 3, 4], [2, 6]]) == [1, 1, 2, 3, 4, 4, 5, 6] assert merge_k_sorted([[], [1], [2, 5, 8]]) == [1, 2, 5, 8] assert merge_k_sorted([[10, 15, 30], [5, 6, 6], [1, 2, 3]]) == [1, 2, 3, 5, 6, 6, 10, 15, 30] assert merge_k_sorted([[]]) == [] ass...
[ { "docstring": null, "function_declaration": "def merge_two_sorted_lists(l1, l2):", "function_name": "merge_two_sorted_lists", "parameter_list": "(l1, l2)" }, { "docstring": null, "function_declaration": "def merge_k_sorted(lists):", "function_name": "merge_k_sorted", "parameter_...
[ 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_two_lists(l1, l2):\n \"\"\"Helper function to merge two sorted lists\"\"\"\n merged = []\n i, j = 0, 0\n while i < len(l1) and j < len(l2):...
trial_gpt4o_6
{ "original_instruction": "### Question\nYou are given two functions, `merge_sorted_iterative` and `merge_sorted_recursive`, which merge two sorted lists of numbers into a single sorted list using iterative and recursive methods respectively. However, to handle more complex real-world scenarios, another useful functi...
0.563762
Algorithm_29992
C
[ "merge_two_sorted_lists", "merge_k_sorted" ]
2
[ [ "merge_k_sorted", "merge_two_sorted_lists" ] ]
1
[]
false
[]
false
pytest
false
[]
true
74e337119c6068b96578bc5ff774e69e3c9a5446
429f4c45053f0b1fe21f181d4c386d1f8df7df55
v1.0
complete
Algorithm
Algorithm_35353_C
import random import math def ackley_function(x, y): """Computes the Ackley function value for given x and y. >>> ackley_function(0, 0) 0.0 """ return -20 * math.exp(-0.2 * math.sqrt(0.5 * (x**2 + y**2))) - math.exp(0.5 * (math.cos(2 * math.pi * x) + math.cos(2 * math.pi * y))) + math.e + 20 def c...
import random import math def ackley_function(x, y): return -20 * math.exp(-0.2 * math.sqrt(0.5 * (x**2 + y**2))) - math.exp(0.5 * (math.cos(2 * math.pi * x) + math.cos(2 * math.pi * y))) + math.e + 20 def crossover(parent1, parent2, crossover_rate): if random.random() < crossover_rate: return (parent...
from solution import genetic_algorithm_ackley_minimization, ackley_function def test_ackley_function(): assert ackley_function(0, 0) == 0 def test_genetic_algorithm_ackley_minimization(): initial_population = [(20, 30), (-10, -20), (15, 25)] result = genetic_algorithm_ackley_minimization(initial_populatio...
[ { "docstring": null, "function_declaration": "def ackley_function(x, y):", "function_name": "ackley_function", "parameter_list": "(x, y)" }, { "docstring": null, "function_declaration": "def crossover(parent1, parent2, crossover_rate):", "function_name": "crossover", "parameter_l...
[ 0, 0, 0, 0, 0, 0, 0, 1, 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": "import random\nimport math\n\ndef ackley_function(x, y):\n \"\"\"\n Ackley function defined for two input values x and y.\n \"\"\"\n part_1 = -20 * m...
trial_gpt4o_9
{ "original_instruction": "### Genetic Algorithm for Optimizing Ackley Function\n\n#### Context\nYou are a graduate student working on optimization techniques in your computational mathematics course. Your project is to implement a Genetic Algorithm to optimize the Ackley function, which is a popular test case for op...
0.484316
Algorithm_35353
C
[ "ackley_function", "crossover", "mutate", "select", "genetic_algorithm_ackley_minimization" ]
5
[ [ "genetic_algorithm_ackley_minimization", "ackley_function" ], [ "genetic_algorithm_ackley_minimization", "crossover" ], [ "genetic_algorithm_ackley_minimization", "mutate" ], [ "genetic_algorithm_ackley_minimization", "select" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ee38cb61dbb5bf1d4965b804813bdb3d05961532
bccf4d47ed0017c1f5cec65cd7ade4554951565c
v1.0
complete
Algorithm
Algorithm_7699_C
def build_kmp_table(pattern: str) -> list: """ Builds the KMP table for a given pattern. """ length = len(pattern) kmp_table = [0] * length j = 0 for i in range(1, length): while (j > 0 and pattern[i] != pattern[j]): j = kmp_table[j - 1] if pattern[i] == pattern...
def build_kmp_table(pattern: str) -> list: """ Builds the KMP table for a given pattern. """ length = len(pattern) kmp_table = [0] * length j = 0 for i in range(1, length): while (j > 0 and pattern[i] != pattern[j]): j = kmp_table[j - 1] if pattern[i] == pattern...
from solution import build_kmp_table, kmp_search def test_build_kmp_table(): assert build_kmp_table("ABABCABAA") == [0, 0, 1, 2, 0, 1, 2, 3, 1] assert build_kmp_table("AAAA") == [0, 1, 2, 3] assert build_kmp_table("ABCDABD") == [0, 0, 0, 0, 1, 2, 0] def test_kmp_search(): assert kmp_search("ABABDABACD...
[ { "docstring": "Builds the KMP table for a given pattern.", "function_declaration": "def build_kmp_table(pattern):", "function_name": "build_kmp_table", "parameter_list": "(pattern)" }, { "docstring": "Implements the KMP search algorithm to find all occurrences of the pattern in the text.", ...
[ 0, 0, 0, 0, 0, 1, 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": "def build_kmp_table(pattern: str) -> list:\n \"\"\"\n Builds the KMP table (partial match table) for a given pattern.\n \n :param pattern: The patter...
trial_gpt4o_6
{ "original_instruction": "### String Pattern Matching Assessment\n\nString pattern matching is a common problem in computer science, which involves finding occurrences of a pattern string within another string. Your task is to implement a function that performs the KMP (Knuth-Morris-Pratt) pattern matching algorithm...
0.489936
Algorithm_7699
C
[ "build_kmp_table", "kmp_search" ]
2
[ [ "kmp_search", "build_kmp_table" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb93a0e91b78bb269cf928c7d8f3485410f81cb5
bf76af7fcb81e772de64c57d30bb59e3761f0b6c
v1.0
complete
Algorithm
Algorithm_15271_C
def find_largest_number(arr: list) -> str: """ Rearranges the numbers to form the largest possible concatenated number. Example: >>> find_largest_number([10, 2]) '210' >>> find_largest_number([3, 30, 34, 5, 9]) '9534330' >>> find_largest_number([1, 10, 100, 1000]) '1101001000' >...
def custom_compare(x, y): if x + y > y + x: return -1 elif x + y < y + x: return 1 else: return 0 def find_largest_number(arr: list) -> str: """ Rearranges the numbers to form the largest possible concatenated number. """ from functools import cmp_to_key # C...
from solution import find_largest_number def test_find_largest_number_basic(): assert find_largest_number([10, 2]) == "210" def test_find_largest_number_longer_list(): assert find_largest_number([3, 30, 34, 5, 9]) == "9534330" def test_find_largest_number_with_zeros(): assert find_largest_number([0, 0, 0...
[ { "docstring": null, "function_declaration": "def custom_compare(x, y):", "function_name": "custom_compare", "parameter_list": "(x, y)" }, { "docstring": "Rearranges the numbers to form the largest possible concatenated number.", "function_declaration": "def find_largest_number(arr):", ...
[ 0, 0, 0, 0, 1, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from functools import cmp_to_key\n\ndef compare(a, b):\n \"\"\"\n Custom comparator for sorting.\n If a + b is greater than b + a, then a should come be...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement:\n\nYou are given a collection of numbers, each represented as a list of digits. Your task is to write a function `find_largest_number(arr: list) -> str` that arranges the numbers in such a way that they form the largest possible concatenated number.\n\n### Function Si...
0.752056
Algorithm_15271
C
[ "custom_compare", "find_largest_number" ]
2
[ [ "find_largest_number", "custom_compare" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4c43c54080671a1b8e1eb245bde8c6120a9ba781
1177d75b05a4e67b500b305be402012ed87417dc
v1.0
complete
Algorithm
Algorithm_22302_C
### Maximum Twin Number Finder **Context**: A twin number is defined as a number that, when reversed, forms itself. For example, 121 and 12321 are twin numbers because reversing them results in 121 and 12321 respectively. **Objective**: Write a function that finds the largest twin number within a specified range. ##...
def is_twin_number(n: int) -> bool: """ Checks if a number is a twin number (i.e., palindrome). """ return str(n) == str(n)[::-1] def max_twin_number(upper_limit: int) -> int: """ Finds the largest twin number less than or equal to the upper_limit. """ for number in range(upper_limit, -...
from solution import is_twin_number, max_twin_number def test_is_twin_number(): assert is_twin_number(121) == True assert is_twin_number(12321) == True assert is_twin_number(1234567) == False assert is_twin_number(0) == True assert is_twin_number(1) == True def test_max_twin_number(): assert m...
[ { "docstring": "Checks if a number is a twin number (i.e., palindrome).", "function_declaration": "def is_twin_number(n):", "function_name": "is_twin_number", "parameter_list": "(n)" }, { "docstring": "Finds the largest twin number less than or equal to the upper_limit.", "function_decla...
[ 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": "def is_twin_number(n: int) -> bool:\n \"\"\"\n Checks if a number is a twin number (i.e., palindrome).\n \"\"\"\n return str(n) == str(n)[::-1]\n\nde...
trial_gpt4o_0
{ "original_instruction": "### Maximum Twin Number Finder\n\n**Context**: A twin number is defined as a number that, when reversed, forms itself. For example, 121 and 12321 are twin numbers because reversing them results in 121 and 12321 respectively.\n\n**Objective**: Write a function that finds the largest twin num...
0.588566
Algorithm_22302
C
[ "is_twin_number", "max_twin_number" ]
2
[ [ "max_twin_number", "is_twin_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5478a899bc2ab4b9f5645a98384ebc36be740aa4
b639019c3f256c309d3939baee9164891b5d3c70
v1.0
complete
Algorithm
Algorithm_23357_C
import re import numpy as np from collections import Counter def count_words(text): """ Counts the number of occurrences of each word in the given text. :param text: A string of text. :return: A dictionary where keys are unique words and values are their counts. """ # Your code here pass ...
import re import numpy as np from collections import Counter def count_words(text): """ Counts the number of occurrences of each word in the given text. :param text: A string of text. :return: A dictionary where keys are unique words, and values are their counts. """ # Convert text to lowercas...
from solution import count_words, sentence_length_statistics def test_count_words_single_sentence(): text = "Hello world, hello!" expected = {'hello': 2, 'world': 1} assert count_words(text) == expected def test_count_words_multiple_sentences(): text = "This is a test. This test is simple. Simple is g...
[ { "docstring": "Counts the number of occurrences of each word in the given text.\n\n:param text: A string of text.\n:return: A dictionary where keys are unique words, and values are their counts.", "function_declaration": "def count_words(text):", "function_name": "count_words", "parameter_list": "(...
[ 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 re\nimport numpy as np\nfrom collections import Counter\n\ndef count_words(text):\n \"\"\"\n Count the occurrences of each word in the given text.\n...
trial_gpt4o_8
{ "original_instruction": "### Context:\nYou are working on the implementation of a text processing module for a natural language processing (NLP) pipeline. Part of your task is to create a function that can extract and analyze particular text features.\n\n### Task:\n1. **Implement Custom Text Processing Functions**:...
0.713387
Algorithm_23357
C
[ "count_words", "sentence_length_statistics", "example" ]
3
[ [ "example", "count_words" ], [ "example", "sentence_length_statistics" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
1e297fda0f7edf1d7dc0c4eb1a768033d9abb70e
c57b516d75574206ec410cd20ddac0712d34cbf4
v1.0
complete
Algorithm
Algorithm_12178_C
def integer_divide(dividend: int, divisor: int) -> int: """ Perform integer division without using the division or multiplication operators. >>> integer_divide(10, 3) 3 >>> integer_divide(43, -8) -5 """ pass def integer_divide_with_remainder(dividend: int, divisor: int) -> (int, int): "...
def integer_divide(dividend: int, divisor: int) -> int: if dividend == 0: return 0 negative = (dividend < 0) != (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) quotient = 0 current_sum = divisor while dividend >= current_sum: current_quota = 1 while cur...
def test_integer_divide_positive_division(): assert integer_divide(10, 3) == 3 def test_integer_divide_negative_divisor(): assert integer_divide(43, -8) == -5 def test_integer_divide_negative_dividend(): assert integer_divide(-43, 8) == -5 def test_integer_divide_negative_both(): assert integer_divid...
[ { "docstring": null, "function_declaration": "def integer_divide(dividend, divisor):", "function_name": "integer_divide", "parameter_list": "(dividend, divisor)" }, { "docstring": null, "function_declaration": "def integer_divide_with_remainder(dividend, divisor):", "function_name": ...
[ 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": "def integer_divide(dividend: int, divisor: int) -> int:\n if dividend == 0:\n return 0\n \n negative = (dividend < 0) != (divisor < 0)\n divid...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nImplement a function to perform integer division without using the division or multiplication operators. Additionally, implement another function to perform integer division and return the remainder as well.\n\n### Function 1: `integer_divide(dividend: int, divisor:...
0.645359
Algorithm_12178
C
[ "integer_divide", "integer_divide_with_remainder" ]
2
[ [ "integer_divide_with_remainder", "integer_divide" ] ]
1
[]
false
[]
false
pytest
false
[]
true
3622a059737f3e0ce0dfdd0ac268a53476d3e266
fc7ddc1a09cd25a75024f8e3c5f4d8c1cca1ce8e
v1.0
complete
Algorithm
Algorithm_25103_C
import numpy as np def sigmoid(x: float) -> float: """ Sigmoid activation function. >>> sigmoid(0) # produces 0.5 >>> sigmoid(2) # produces approximately 0.8808 >>> sigmoid(-2) # produces approximately 0.1192 """ def sigmoid_derivative(x: float) -> float: """ Derivative of the sig...
import numpy as np def sigmoid(x: float) -> float: """ Sigmoid activation function. """ return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x: float) -> float: """ Derivative of the sigmoid function. """ return x * (1 - x) def initialize_weights(input_size: int, hidden_size: int) -> tu...
import numpy as np from solution import sigmoid, sigmoid_derivative, initialize_weights, forward_propagation, back_propagation, train_neural_network, predict def test_sigmoid(): assert np.isclose(sigmoid(0), 0.5) assert np.isclose(sigmoid(2), 0.880797) assert np.isclose(sigmoid(-2), 0.119203) def test_sig...
[ { "docstring": "Sigmoid activation function.", "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": "Derivative of the sigmoid function.", "function_declaration": "def sigmoid_derivative(x):", "function_name": "sigmoid_deriv...
[ 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef sigmoid(x: float) -> float:\n \"\"\"\n Returns the sigmoid of x.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_deri...
trial_gpt4o_9
{ "original_instruction": "### Neural Network from Scratch\n\nYour task is to implement a simple feedforward neural network from scratch, using only Python's standard libraries. This network will perform binary classification on a provided dataset. The neural network will have one input layer, one hidden layer, and o...
0.604875
Algorithm_25103
C
[ "sigmoid", "sigmoid_derivative", "initialize_weights", "forward_propagation", "back_propagation", "train_neural_network", "predict" ]
7
[ [ "back_propagation", "sigmoid_derivative" ], [ "forward_propagation", "sigmoid" ], [ "predict", "forward_propagation" ], [ "train_neural_network", "back_propagation" ], [ "train_neural_network", "forward_propagation" ], [ "train_neural_network", "...
6
[]
false
[]
false
pytest
true
[ "numpy" ]
false
dc95e20f15ac463bdd04d3968ed397d35b01e860
1774ab53cd7ab7c20dfe86012101ebd022e2a99a
v1.0
complete
Algorithm
Algorithm_23157_C
[Completion Task in Python] # Define the function start_server def start_server(port: int) -> None: """ Starts a multi-threaded web server that listens on the specified port. """ # Define the function handle_client def handle_client(client_socket: socket.socket) -> None: """ Handles communication wi...
import socket import threading def start_server(port): """ Starts a multi-threaded web server that listens on the specified port. Parameters: port (int): The port number on which the server will listen. Returns: None """ server_socket = socket.socket(socket.AF_INET, socket.SOC...
import socket import threading import time from contextlib import closing import pytest from solution import start_server, generate_response @pytest.fixture(scope='module') def server(): port = 8080 server_thread = threading.Thread(target=start_server, args=(port,), daemon=True) server_thread.start() ...
[ { "docstring": "Starts a multi-threaded web server that listens on the specified port.\n\nParameters:\nport (int): The port number on which the server will listen.\n\nReturns:\nNone", "function_declaration": "def start_server(port):", "function_name": "start_server", "parameter_list": "(port)" }, ...
[ 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": "import socket\nimport threading\n\ndef start_server(port):\n \"\"\"\n Starts a multi-threaded web server that listens on the specified port.\n \n Par...
trial_gpt4o_0
{ "original_instruction": "### Assignment: Implement a Basic Multi-threaded Web Server\n\nYou will be creating a simple multi-threaded web server that can handle multiple client requests concurrently. This will involve setting up a basic server, using threads to manage different client connections, and sending approp...
0.657463
Algorithm_23157
C
[ "start_server", "handle_client", "generate_response" ]
3
[ [ "handle_client", "generate_response" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a82b9b8a4378ac11bfc821c94b693d0584ab39e
9ca5b2e488519591e4a49d79aa579a78e3e100ba
v1.0
complete
Algorithm
Algorithm_43989_C
import numpy as np from typing import Tuple def matrix_multiplication(matrix_a: np.ndarray, matrix_b: np.ndarray) -> np.ndarray: """ Multiplies two matrices and returns the result. Parameters: matrix_a (np.ndarray): First input matrix. matrix_b (np.ndarray): Second input matrix. Returns: ...
import numpy as np def matrix_multiplication(matrix_a, matrix_b): """ Multiplies two matrices and returns the result. """ if matrix_a.shape[1] != matrix_b.shape[0]: raise ValueError("Incompatible dimensions for matrix multiplication") return np.dot(matrix_a, matrix_b) def transpose_matrix(...
import numpy as np from solution import matrix_multiplication, transpose_matrix, matrix_multiplication_with_transpose def test_matrix_multiplication(): matrix_a = np.array([[1, 2], [3, 4]]) matrix_b = np.array([[5, 6], [7, 8]]) expected = np.array([[19, 22], [43, 50]]) assert np.array_equal(matrix_mult...
[ { "docstring": "Multiplies two matrices and returns the result.", "function_declaration": "def matrix_multiplication(matrix_a, matrix_b):", "function_name": "matrix_multiplication", "parameter_list": "(matrix_a, matrix_b)" }, { "docstring": "Computes and returns the transpose of a matrix.", ...
[ 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": "import numpy as np\n\ndef matrix_multiplication(matrix_a: np.ndarray, matrix_b: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the product of two matrices.\...
trial_gpt4o_8
{ "original_instruction": "Matrix Multiplication and Transposition\n\nYou are provided with a function to multiply two matrices and return the result. Your task is to extend the functionality of this function by adding another feature: computing the transpose of the resultant matrix after the multiplication.\n\n### I...
0.665321
Algorithm_43989
C
[ "matrix_multiplication", "transpose_matrix", "matrix_multiplication_with_transpose" ]
3
[ [ "matrix_multiplication_with_transpose", "matrix_multiplication" ], [ "matrix_multiplication_with_transpose", "transpose_matrix" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
cdacc6c41dcd69763a37181bfb40fbb2821243c7
d2d7dbe2ed60a34e4f0a048ece2b8412a7356ae8
v1.0
complete
Algorithm
Algorithm_7274_C
import multiprocessing import logging from typing import List logging.basicConfig(level=logging.INFO) def generate_primes(n: int) -> List[int]: """Generate prime numbers up to `n` using concurrent processing. >>> generate_primes(10) [2, 3, 5, 7] >>> generate_primes(1) [] >>> generate_primes(2)...
import multiprocessing import logging from math import isqrt from typing import List logging.basicConfig(level=logging.INFO) def is_prime(num): if num < 2: return False for i in range(2, isqrt(num) + 1): if num % i == 0: return False return True def worker(start, end, queue): ...
from solution import generate_primes def test_generate_primes_small_range(): assert generate_primes(10) == [2, 3, 5, 7] def test_generate_primes_no_primes(): assert generate_primes(1) == [] def test_generate_primes_large_range(): primes = generate_primes(100) assert primes == [2, 3, 5, 7, 11, 13, 17,...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def worker(start, end, queue):", "function_name": "worker", "parameter_list": "(start, end, queue)" }, { ...
[ 0, 0, 1, 1, 1, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import multiprocessing\nimport logging\nfrom typing import List\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(processName)s - %(levelname)s ...
trial_gpt4o_9
{ "original_instruction": "### Concurrent Prime Number Generator\n\nYou are required to create a program that generates prime numbers up to `n` using concurrent processing. The goal is to refactor a basic prime number generator to utilize multiple processes, thereby improving computational efficiency for large values...
0.619797
Algorithm_7274
C
[ "is_prime", "worker", "generate_primes" ]
3
[ [ "worker", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3fb446fff19a4bedcf3b3c3a661e37218773da35
1e0e70ec4ae60c9019fb2d2a46f60ec02612e4be
v1.0
complete
Algorithm
Algorithm_20955_C
from typing import List def find_lcm(arr: List[int]) -> int: """ Calculate the least common multiple (LCM) of an array of integers. >>> find_lcm([2, 7, 3]) 42 >>> find_lcm([5, 10, 20]) 20 >>> find_lcm([4, 6, 8]) 24 """ from functools import reduce from math import gcd def test_find_lc...
from math import gcd from functools import reduce from typing import List def lcm(a: int, b: int) -> int: """ Helper function to find the LCM of two numbers. """ return a * b // gcd(a, b) def find_lcm(arr: List[int]) -> int: """ Returns the LCM of an array of integers. """ return reduc...
from solution import find_lcm def test_find_lcm_single_element(): assert find_lcm([1]) == 1 assert find_lcm([4]) == 4 def test_find_lcm_two_elements(): assert find_lcm([2, 3]) == 6 assert find_lcm([6, 8]) == 24 def test_find_lcm_multiple_elements(): assert find_lcm([2, 7, 3]) == 42 assert fin...
[ { "docstring": "Helper function to find the LCM of two numbers.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the LCM of an array of integers.", "function_declaration": "def find_lcm(arr):", "function_name": ...
[ 1, 0, 1, 1, 0, 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": "from math import gcd\nfrom functools import reduce\nfrom typing import List\n\ndef find_lcm(arr: List[int]) -> int:\n \"\"\"\n Returns the least common mul...
trial_gpt4o_8
{ "original_instruction": "## Problem Statement\nYou are tasked with writing a function that calculates the least common multiple (LCM) of an array of integers. The least common multiple of a set of positive integers is the smallest positive integer that is divisible by each of them.\n\n### Function Signature\n```pyt...
0.660007
Algorithm_20955
C
[ "lcm", "find_lcm" ]
2
[ [ "find_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0155f84955686beca6b8c4898ea5c84b440b78d5
f94ccd2b122ac3fdb7bed8eeb6f738bee2541dc3
v1.0
complete
Algorithm
Algorithm_2505_C
import csv def convert_to_numeric(value): """ Convert a string value to its appropriate numeric type if possible. >>> convert_to_numeric('42') == 42 >>> convert_to_numeric('42.5') == 42.5 >>> convert_to_numeric('abc') == 'abc' >>> convert_to_numeric('') == '' """ pass def process_csv(file_...
import csv def convert_to_numeric(value): try: int_value = int(value) return int_value except ValueError: try: float_value = float(value) return float_value except ValueError: return value def process_csv(file_path: str) -> dict: result =...
import os from solution import process_csv, convert_to_numeric import tempfile def test_convert_to_numeric(): assert convert_to_numeric('42') == 42 assert convert_to_numeric('42.5') == 42.5 assert convert_to_numeric('abc') == 'abc' assert convert_to_numeric('') == '' def test_process_csv(): co...
[ { "docstring": null, "function_declaration": "def convert_to_numeric(value):", "function_name": "convert_to_numeric", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def process_csv(file_path):", "function_name": "process_csv", "parameter_list": "(fil...
[ 0, 1, 1, 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": "import csv\n\ndef convert_to_numeric(value):\n try:\n if '.' in value:\n return float(value)\n return int(value)\n except ValueErr...
trial_gpt4o_9
{ "original_instruction": "### Scenario\nYou are a developer for a company that works with huge datasets stored in CSV files. One of your tasks is to clean and preprocess these datasets before they are fed into a data analysis pipeline. \n\nYou need to implement a function that reads a CSV file, processes the data by...
0.669865
Algorithm_2505
C
[ "convert_to_numeric", "process_csv" ]
2
[ [ "process_csv", "convert_to_numeric" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d0ef97792e18264dc70b99a0000c86e212cb6232
9b2dd822ad4c885579a8534074b8a773d65f3ec8
v1.0
complete
Algorithm
Algorithm_8171_C
from typing import List def compute_pwm_duty_cycle(brightness: int) -> float: """ Computes the PWM duty cycle as a percentage based on the provided brightness. Parameters: brightness (int): The brightness level of the LED, ranging from 0 (off) to 255 (full brightness). Returns: float: The dut...
def compute_pwm_duty_cycle(brightness: int) -> float: """ Computes the PWM duty cycle as a percentage based on the provided brightness. Parameters: brightness (int): The brightness level of the LED, ranging from 0 (off) to 255 (full brightness). Returns: float: The duty cycle as a percentage. ...
from solution import compute_pwm_duty_cycle, set_brightness_level import pytest def test_compute_pwm_duty_cycle(): assert compute_pwm_duty_cycle(128) == pytest.approx(50.19607843137255, 0.0001) assert compute_pwm_duty_cycle(255) == 100.0 assert compute_pwm_duty_cycle(0) == 0.0 with pytest.raises(ValueE...
[ { "docstring": "Computes the PWM duty cycle as a percentage based on the provided brightness.\n\nParameters:\nbrightness (int): The brightness level of the LED, ranging from 0 (off) to 255 (full brightness).\n\nReturns:\nfloat: The duty cycle as a percentage.", "function_declaration": "def compute_pwm_duty_...
[ 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 List\n\ndef compute_pwm_duty_cycle(brightness: int) -> float:\n if not (0 <= brightness <= 255):\n raise ValueError(\"Brightness mus...
trial_gpt4o_9
{ "original_instruction": "### CODING ASSESSMENT QUESTION\n\n#### Introduction\nYou are developing software for a simple microcontroller-based light-dimming system using Pulse Width Modulation (PWM). PWM is a technique used to control the brightness of an LED by varying the duty cycle of a square wave signal. The fre...
0.424834
Algorithm_8171
C
[ "compute_pwm_duty_cycle", "set_brightness_level" ]
2
[ [ "set_brightness_level", "compute_pwm_duty_cycle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d86e8e6d14ea6717cd755724847d9275f67bc68c
3cdb4f19469adcb694f399c6084338661c14eab8
v1.0
complete
Algorithm
Algorithm_8449_C
import math def calculate_perimeter(length: float, width: float) -> float: """ Calculates the perimeter of a rectangle given its length and width. >>> calculate_perimeter(10, 5) 30.0 >>> calculate_perimeter(8, 6) 28.0 """ def calculate_area(length: float, width: float) -> float: ...
import math def calculate_perimeter(length, width): """ Calculates the perimeter of a rectangle given its length and width. """ return 2 * (length + width) def calculate_area(length, width): """ Calculates the area of a rectangle given its length and width. """ return length * width d...
from solution import calculate_perimeter, calculate_area, calculate_diagonal, garden_summary import pytest def test_calculate_perimeter(): assert calculate_perimeter(10, 5) == 30 assert calculate_perimeter(8, 6) == 28 def test_calculate_area(): assert calculate_area(10, 5) == 50 assert calculate_area(...
[ { "docstring": "Calculates the perimeter of a rectangle given its length and width.", "function_declaration": "def calculate_perimeter(length, width):", "function_name": "calculate_perimeter", "parameter_list": "(length, width)" }, { "docstring": "Calculates the area of a rectangle given its...
[ 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": "import math\n\ndef calculate_perimeter(length, width):\n \"\"\"\n Calculate and return the perimeter of a rectangular garden plot.\n \"\"\"\n if leng...
trial_gpt4o_9
{ "original_instruction": "## Problem Statement\n\nYou are tasked with developing a module to assist in calculating various metrics for a rectangular garden plot based on user inputs for the length and width of the garden. The module should include functions to compute the perimeter, the area, and diagonal length of ...
0.547033
Algorithm_8449
C
[ "calculate_perimeter", "calculate_area", "calculate_diagonal", "garden_summary" ]
4
[ [ "garden_summary", "calculate_area" ], [ "garden_summary", "calculate_diagonal" ], [ "garden_summary", "calculate_perimeter" ] ]
3
[]
false
[]
false
pytest
true
[]
true
701484dc7157e413cbea9c43b0fa6e67f369c210
39a606f08d9c475aae71112606bb5cff713c7695
v1.0
complete
Algorithm
Algorithm_33696_C
def strassen_multiply(matrix1, matrix2): """Multiply two matrices using Strassen's algorithm. Args: matrix1: 2D list of integers representing the first matrix. matrix2: 2D list of integers representing the second matrix. Returns: 2D list of integers representing the product...
def matrix_addition(A, B): """Add two matrices A and B.""" n = len(A) return [[A[i][j] + B[i][j] for j in range(n)] for i in range(n)] def matrix_subtraction(A, B): """Subtract matrix B from matrix A.""" n = len(A) return [[A[i][j] - B[i][j] for j in range(n)] for i in range(n)] def matrix_spl...
def test_matrix_addition(): A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]] expected = [[6, 8], [10, 12]] assert matrix_addition(A, B) == expected def test_matrix_subtraction(): A = [[5, 6], [7, 8]] B = [[1, 2], [3, 4]] expected = [[4, 4], [4, 4]] assert matrix_subtraction(A, B) == expected ...
[ { "docstring": "Add two matrices A and B.", "function_declaration": "def matrix_addition(A, B):", "function_name": "matrix_addition", "parameter_list": "(A, B)" }, { "docstring": "Subtract matrix B from matrix A.", "function_declaration": "def matrix_subtraction(A, B):", "function_na...
[ 1, 1, 1, 1, 1, 1, 0, 1, 0, 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 add_matrices(matrix1, matrix2):\n return [\n [\n matrix1[i][j] + matrix2[i][j]\n for j in range(len(matrix1))\n ]\n ...
trial_gpt4o_7
{ "original_instruction": "### Matrix Multiplication using Strassen's Algorithm\n\n#### Context\nMatrix multiplication is a fundamental operation in various scientific computations. Strassen's algorithm is an efficient algorithm for matrix multiplication that reduces the time complexity compared to the conventional a...
0.499011
Algorithm_33696
C
[ "matrix_addition", "matrix_subtraction", "matrix_split", "matrix_combine", "strassen_multiply" ]
5
[ [ "strassen_multiply", "matrix_addition" ], [ "strassen_multiply", "matrix_combine" ], [ "strassen_multiply", "matrix_split" ], [ "strassen_multiply", "matrix_subtraction" ] ]
4
[]
false
[]
false
pytest
false
[]
true
64fabb5c98e5f5320b10a0c380c3d323a3f0aa64
a1a2303d33ad8d7cf5ab2f627b389c2ee5a2f749
v1.0
complete
Algorithm
Algorithm_44364_C
def edit_distance(word1: str, word2: str) -> int: """ Calculate the edit distance between two words. >>> edit_distance("kitten", "sitting") == 3 >>> edit_distance("flaw", "lawn") == 2 """ pass def correct_spelling(text: str, dictionary: set) -> str: """ Correct the spelling errors in th...
def edit_distance(word1, word2): """ Calculate the edit distance between two words. """ dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)] for i in range(len(word1) + 1): for j in range(len(word2) + 1): if i == 0: dp[i][j] = j elif j == ...
from solution import correct_spelling def test_correct_spelling_basic(): text = "the quikc bron fox jmps ovr the lazi dog" dictionary = {"the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"} expected = "the quick brown fox jumps over the lazy dog" assert correct_spelling(text, dictionary) == ...
[ { "docstring": "Calculate the edit distance between two words.", "function_declaration": "def edit_distance(word1, word2):", "function_name": "edit_distance", "parameter_list": "(word1, word2)" }, { "docstring": "Correct the spelling errors in the text using the provided dictionary.", "f...
[ 1, 0, 0, 0, 0, 1, 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": "def edit_distance(word1, word2):\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n \n for i in range(m + 1):\n fo...
trial_gpt4o_7
{ "original_instruction": "### Problem Statement\n\nYou are tasked with implementing a system that detects and corrects spelling errors in a given text. The system will use a dictionary of known words to identify misspelled words and suggest possible corrections based on edit distance. The edit distance is defined as...
0.545915
Algorithm_44364
C
[ "edit_distance", "correct_spelling" ]
2
[ [ "correct_spelling", "edit_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
65da36adffcb436a66160be675ddf9d964cc66a0
7e8c130180120cbcdd2f03476954c0cc3a0e31e3
v1.0
complete
Algorithm
Algorithm_41575_C
from typing import List, Dict, Union def classify_books(books: List[Dict[str, Union[str, int]]]) -> Dict[str, Union[List[str], Dict[str, List[str]]]]: """ Classify books into different categories based on their publication year and title. >>> books = [ >>> {"title": "A Tale of Two Cities", "year": 185...
from typing import List, Dict, Union def is_vowel(char: str) -> bool: return char.lower() in 'aeiou' def classify_books(books: List[Dict[str, Union[str, int]]]) -> Dict[str, Union[List[str], Dict[str, List[str]]]]: categorized_books = { "before_2000": [], "from_2000": [], "vowel_titles...
def test_classify_books(): books = [ {"title": "A Tale of Two Cities", "year": 1859}, {"title": "Effective Python", "year": 2015}, {"title": "To Kill a Mockingbird", "year": 1960}, {"title": "The Great Gatsby", "year": 1925}, {"title": "1984", "year": 1949}, {"title":...
[ { "docstring": null, "function_declaration": "def is_vowel(char):", "function_name": "is_vowel", "parameter_list": "(char)" }, { "docstring": null, "function_declaration": "def classify_books(books):", "function_name": "classify_books", "parameter_list": "(books)" } ]
[ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Union\n\ndef is_vowel(char: str) -> bool:\n return char.lower() in 'aeiou'\n\ndef classify_books(books: List[Dict[str, Union[st...
trial_gpt4o_0
{ "original_instruction": "### Scenario\n\nYou are developing a library management system that manages book records. This system needs to categorize books according to their publication years and titles.\n\n### Problem Statement\n\nWrite a function `classify_books(books: List[Dict[str, Union[str, int]]]) -> Dict[str,...
0.605953
Algorithm_41575
C
[ "is_vowel", "classify_books" ]
2
[ [ "classify_books", "is_vowel" ] ]
1
[]
false
[]
false
pytest
false
[]
true
9779379486aaf1cb77aa4fd702800edc392b3b11
2148be6a24bf79f7b76f228b25aa6ac4978145a8
v1.0
complete
Algorithm
Algorithm_34074_C
def optimized_fibonacci(n: int) -> int: """ Computes the nth Fibonacci number using matrix exponentiation. The Fibonacci sequence is a series where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes like this: 0, 1, 1, 2, 3, 5, 8, ... Args: ...
def multiply_matrices(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_power(matrix, n): """ ...
def test_optimized_fibonacci(): # Testing base cases assert optimized_fibonacci(0) == 0 assert optimized_fibonacci(1) == 1 # Testing small values assert optimized_fibonacci(2) == 1 assert optimized_fibonacci(3) == 2 assert optimized_fibonacci(4) == 3 assert optimized_fibonacci(5) ==...
[ { "docstring": "Multiplies two 2x2 matrices A and B.", "function_declaration": "def multiply_matrices(A, B):", "function_name": "multiply_matrices", "parameter_list": "(A, B)" }, { "docstring": "Performs matrix exponentiation. Returns matrix^n.", "function_declaration": "def matrix_power...
[ 1, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def multiply_matrices(A, B):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \"\"\"\n return [\n [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0...
trial_gpt4o_5
{ "original_instruction": "## Fibonacci Sequence Algorithm Optimization\n\n### Objective\nImplement a Python function that efficiently computes the nth Fibonacci number. You are required to write a function optimized for both space and time complexity.\n\n### Description\nThe Fibonacci sequence is a series of numbers...
0.749977
Algorithm_34074
C
[ "multiply_matrices", "matrix_power", "optimized_fibonacci" ]
3
[ [ "matrix_power", "multiply_matrices" ], [ "optimized_fibonacci", "matrix_power" ] ]
2
[]
false
[]
false
pytest
false
[]
true
d317e9be0349dd0e0a3dfe390ab91235bc5b35e7
e9fba22b098123d2d1783342611cf3af2adaf85e
v1.0
complete
Algorithm
Algorithm_12765_C
import requests from typing import Optional def fetch_and_save_weather_data(api_key: str, city: str, filename: Optional[str] = None) -> None: """ Fetches current weather data for the specified city and prints the details. Optionally, saves the data to a provided file. Parameters: api_key (str): W...
import requests from typing import Optional def fetch_and_save_weather_data(api_key: str, city: str, filename: Optional[str] = None) -> None: """ Fetches current weather data for the specified city and prints the details. Optionally, saves the data to a provided file. Parameters: api_key (str): W...
import pytest from unittest.mock import patch, mock_open from solution import fetch_and_save_weather_data def test_blank_api_key(): with pytest.raises(ValueError): fetch_and_save_weather_data('', 'London') @patch('solution.requests.get') def test_city_not_found(mock_get): mock_get.return_value.status_...
[ { "docstring": "Fetches current weather data for the specified city and prints the details. \nOptionally, saves the data to a provided file.\n\nParameters:\napi_key (str): Weather API key.\ncity (str): Name of the city to fetch weather data for.\nfilename (Optional[str]): Name of the file to save the weather da...
[ 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": "import requests\nfrom typing import Optional\n\ndef fetch_and_save_weather_data(api_key: str, city: str, filename: Optional[str] = None) -> None:\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement:\nYou need to develop a Python script that interacts with a weather API to fetch current weather data for a given city. The resulting data should be printed to the console and optionally saved to a file if a filename is provided. Your function should handle edge cases ...
0.712492
Algorithm_12765
C
[ "fetch_and_save_weather_data", "print_weather_info" ]
2
[ [ "fetch_and_save_weather_data", "print_weather_info" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
1a38341cceca3d0599571302adf48ad39daa41a3
b8acd865bc8b88e8d0b39be4753573c2ad551395
v1.0
complete
Algorithm
Algorithm_45662_C
import requests from datetime import datetime from typing import List, Dict def get_peak_traffic_hours(intersections: List[str], date: str, threshold=1000) -> Dict[str, List[str]]: """ Analyze traffic data to determine peak traffic hours. Args: intersections (list): A list of intersection names. ...
import requests from datetime import datetime def get_peak_traffic_hours(intersections, date, threshold=1000): """ Returns a dictionary where keys are intersection names and values are lists of hours during which the traffic count exceeded the specified threshold. """ # Check if the input date is ...
# solution.py should contain the solution code written above from solution import get_peak_traffic_hours, validate_date import pytest import requests from unittest.mock import patch def test_validate_date(): assert validate_date('2021-09-01') == True assert validate_date('2021-09-31') == False assert valid...
[ { "docstring": "Returns a dictionary where keys are intersection names and values are lists of \nhours during which the traffic count exceeded the specified threshold.", "function_declaration": "def get_peak_traffic_hours(intersections, date, threshold=1000):", "function_name": "get_peak_traffic_hours",...
[ 0, 0, 0, 0, 0, 1, 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": "import requests\nfrom datetime import datetime\n\ndef get_peak_traffic_hours(intersections: list, date: str, threshold=1000):\n \"\"\"\n Analyzes traffic d...
trial_gpt4o_5
{ "original_instruction": "### Coding Assessment Question\n\nYou are tasked with implementing a function that analyzes traffic data collected from a city's main intersections to determine peak traffic hours. The data is obtained from an API that provides traffic counts at each intersection for every hour of the day.\...
0.631775
Algorithm_45662
C
[ "get_peak_traffic_hours", "validate_date" ]
2
[ [ "get_peak_traffic_hours", "validate_date" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
c8fbd7d22ec6c0e5016d511310e2fc9397911311
fd48f0461fee363a991c50fa6ecbe546866f6985
v1.0
complete
Algorithm
Algorithm_7147_C
import numpy as np import matplotlib.pyplot as plt def k_means_clustering(X, k, max_iters=100, tol=1e-4): """ K-Means Algorithm to segment customers. Args: X: A 2D NumPy array of annual income and spending score. k: The number of clusters. max_iters: Maximum number of iterations to run the algorith...
import numpy as np import matplotlib.pyplot as plt # K-Means Algorithm def k_means_clustering(X, k, max_iters=100, tol=1e-4): n_samples, n_features = X.shape centroids = X[np.random.choice(n_samples, k, replace=False)] prev_centroids = np.zeros_like(centroids) for _ in range(max_iters): # Assi...
from solution import k_means_clustering, plot_elbow_method, plot_clusters import numpy as np import matplotlib.pyplot as plt def test_k_means_clustering_basic(): # Create a simple dataset X = np.array([ [1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0] ]) k = 2 cluster_assignment, c...
[ { "docstring": null, "function_declaration": "def k_means_clustering(X, k, max_iters=100, tol=0.0001):", "function_name": "k_means_clustering", "parameter_list": "(X, k, max_iters=100, tol=0.0001)" }, { "docstring": null, "function_declaration": "def plot_elbow_method(X, max_k=10):", ...
[ 1, 0, 0, 1, 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": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# K-Means Algorithm\ndef k_means_clustering(X, k, max_iters=100, tol=1e-4):\n n_samples, n_features = X...
trial_gpt4o_0
{ "original_instruction": "### Question\n\nYou are required to implement a K-Means Clustering algorithm from scratch to segment customers based on their annual income and spending score, using a customer dataset for a marketing analysis.\n\n#### Dataset Preparation\n1. Download the dataset from the link: [Mall Custom...
0.768109
Algorithm_7147
C
[ "k_means_clustering", "plot_elbow_method", "plot_clusters" ]
3
[ [ "plot_elbow_method", "k_means_clustering" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
094c737b8669c32703735bd7dd86912b7a82ec27
75d6b5b25e568900500b12d726dc283fecb72742
v1.0
complete
Algorithm
Algorithm_10346_C
def recommend_books( user_ratings: dict[int, dict[int, float]], target_user: int, k: int, min_ratings: int) -> list[int]: """ Recommend books to a user using User-based Collaborative Filtering. Parameters: user_ratings (dict): A dictionary where keys are user identifiers and values ...
from collections import defaultdict import math def pearson_correlation(user_ratings, user1, user2, min_ratings): common_ratings = [book for book in user_ratings[user1] if book in user_ratings[user2]] if len(common_ratings) < min_ratings: return 0 ratings1 = [user_ratings[user1][book] for...
from solution import recommend_books def test_recommend_books_no_common(): user_ratings = { 1: {101: 5.0}, 2: {102: 4.0} } assert recommend_books(user_ratings, 1, 1, 1) == [] def test_recommend_books_single_user(): user_ratings = { 1: {101: 4.0, 102: 5.0} } assert recom...
[ { "docstring": null, "function_declaration": "def pearson_correlation(user_ratings, user1, user2, min_ratings):", "function_name": "pearson_correlation", "parameter_list": "(user_ratings, user1, user2, min_ratings)" }, { "docstring": null, "function_declaration": "def recommend_books(use...
[ 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": "from typing import Dict, List\nimport numpy as np\nfrom collections import defaultdict\n\ndef pearson_correlation(user_ratings1: Dict[int, float], user_ratings2:...
trial_gpt4o_2
{ "original_instruction": "## Context\nYou are tasked with developing a recommendation system for an online bookstore. The system needs to suggest books to users based on their past reading history and ratings. A well-regarded approach to building such systems is using Collaborative Filtering, where predictions are m...
0.656363
Algorithm_10346
C
[ "pearson_correlation", "recommend_books" ]
2
[ [ "recommend_books", "pearson_correlation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
42eb68bec094b238a6a581e7bd1eee84c4e6cc21
1fb2e55ea427a05751792d8ea8d3f2a37f3a92ee
v1.0
complete
Algorithm
Algorithm_43187_C
def maximum_subarray_sum(arr: list[int]) -> int: """ Find the maximum sum of a contiguous subarray within a given one-dimensional numeric array using the Divide and Conquer approach. >>> maximum_subarray_sum([]) 0 >>> maximum_subarray_sum([1]) 1 >>> maximum_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) ...
def max_crossing_sum(arr, low, mid, high): # Include elements on left of mid sum_left = float('-inf') temp_sum = 0 for i in range(mid, low - 1, -1): temp_sum += arr[i] if temp_sum > sum_left: sum_left = temp_sum # Include elements on right of mid sum_right = floa...
from solution import maximum_subarray_sum def test_empty_array(): assert maximum_subarray_sum([]) == 0 def test_single_element(): assert maximum_subarray_sum([1]) == 1 assert maximum_subarray_sum([-1]) == -1 def test_all_negative_nums(): assert maximum_subarray_sum([-1, -2, -3, -4]) == -1 def test_m...
[ { "docstring": null, "function_declaration": "def max_crossing_sum(arr, low, mid, high):", "function_name": "max_crossing_sum", "parameter_list": "(arr, low, mid, high)" }, { "docstring": null, "function_declaration": "def max_subarray_sum(arr, low, high):", "function_name": "max_sub...
[ 1, 0, 0, 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": "def max_crossing_sum(arr, low, mid, high):\n \"\"\"\n Helper function to find the maximum subarray sum that crosses the midpoint.\n \"\"\"\n left_sum...
trial_gpt4o_9
{ "original_instruction": "### Maximum Subarray Sum using Divide and Conquer\n\nThe Maximum Subarray Sum problem involves finding the maximum sum of a contiguous subarray within a given one-dimensional numeric array. Your task is to implement this using the Divide and Conquer approach in Python.\n\n#### Instructions\...
0.798953
Algorithm_43187
C
[ "max_crossing_sum", "max_subarray_sum", "maximum_subarray_sum" ]
3
[ [ "max_subarray_sum", "max_crossing_sum" ], [ "maximum_subarray_sum", "max_subarray_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1a7e43d90f26726f8775494033757aaaa641d6b0
2b8e2196aeaccf32b35d85335877b1fd534ee88a
v1.0
complete
Algorithm
Algorithm_11090_C
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def insert_into_bst(root, value): """ Helper function to insert value into the BST. """ pass def build_bst(values): """ Constructs a BST from the list of values. """ pass def r...
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def insert_into_bst(root, value): if root is None: return TreeNode(value) if value < root.value: root.left = insert_into_bst(root.left, value) else: root.righ...
from solution import bst_range_sum def test_bst_range_sum_example1(): values = [10, 5, 15, 3, 7, 18] low = 7 high = 15 assert bst_range_sum(values, low, high) == 32 def test_bst_range_sum_example2(): values = [10, 5, 15, 3, 7, 18] low = 6 high = 10 assert bst_range_sum(values, low, hig...
[]
[ 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": "class TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = None\n\ndef insert_into_bst(root, val):\n...
trial_gpt4o_8
{ "original_instruction": "### Binary Search Tree (BST) Construction and Range Sum Query\n\nYou are given a list of integers representing node values. Your task is to construct a Binary Search Tree (BST) from this list and implement a function to find the sum of all node values within a given range [low, high].\n\n##...
0.562759
Algorithm_11090
C
[ "insert_into_bst", "build_bst", "range_sum_bst", "bst_range_sum" ]
4
[ [ "bst_range_sum", "build_bst" ], [ "bst_range_sum", "range_sum_bst" ], [ "build_bst", "insert_into_bst" ] ]
3
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
b38bfdbd3d329535ea27470beb8de0153d4b4866
146c26e462eb9a2d137ee1105119e9467ebc2969
v1.0
complete
Algorithm
Algorithm_16727_C
from typing import List def custom_sort(arr: List[int]) -> List[int]: """ Return the list sorted in ascending order while maintaining the position of zeros. :param arr: List[int]: The list of integers to be sorted. :return: List[int]: The sorted list with zeroes in their original positions. ...
def custom_sort(arr): """ Return the list sorted in ascending order while maintaining the position of zeros. :param arr: List[int]: The list of integers to be sorted. :return: List[int]: The sorted list with zeroes in their original positions. """ # Store the original positions of all zeroe...
from solution import custom_sort def test_custom_sort_example1(): assert custom_sort([0, 3, 1, 0, 2, 5, 4, 0]) == [0, 1, 2, 0, 3, 4, 5, 0] def test_custom_sort_example2(): assert custom_sort([4, 0, 7, 0, 2, 5]) == [2, 0, 4, 0, 5, 7] def test_custom_sort_example3(): assert custom_sort([0, 0, 1]) == [0, 0,...
[ { "docstring": "Return the list sorted in ascending order while maintaining the position of zeros.\n\n:param arr: List[int]: The list of integers to be sorted.\n:return: List[int]: The sorted list with zeroes in their original positions.", "function_declaration": "def custom_sort(arr):", "function_name"...
[ 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 custom_sort(arr):\n \"\"\"\n Return the list sorted in ascending order while maintaining the position of zeros.\n \n :param arr: List[int]: The l...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\nSorting algorithms are fundamental to computer science and are widely used in various applications. One of the common problems is sorting an array of integers. Each sorting algorithm has its own strengths and weaknesses in terms of time comple...
0.723535
Algorithm_16727
C
[ "custom_sort", "merge_sort", "merge" ]
3
[ [ "custom_sort", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e534161ffde2f9e6b1d67694f74d10eee2b1423a
8a6f2ced80ce1ec2e53a1f7c8c809d46a8ec0879
v1.0
complete
Algorithm
Algorithm_9123_C
def iterative_count(input_list, target): """ Counts the occurrences of the target value using an iterative method. """ count = 0 for num in input_list: if num == target: count += 1 return count def recursive_count(input_list, target, index=0): """ Counts the occurren...
def iterative_count(input_list, target): """ Counts the occurrences of the target value using an iterative method. """ count = 0 for num in input_list: if num == target: count += 1 return count def recursive_count(input_list, target, index=0): """ Counts the occurren...
from solution import find_target_count def test_find_target_count_matching(): assert find_target_count([1, 3, 1, 7, 1, 2, 1, 6, 1, 10], 1) == "Matching Counts: 5" assert find_target_count([4, -2, 19, -30, 0, 18, 19], 19) == "Matching Counts: 2" assert find_target_count([1, 2, 3, 4, 5], 6) == "Matching Coun...
[ { "docstring": "Counts the occurrences of the target value using an iterative method.", "function_declaration": "def iterative_count(input_list, target):", "function_name": "iterative_count", "parameter_list": "(input_list, target)" }, { "docstring": "Counts the occurrences of the target val...
[ 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 find_target_count(input_list, target):\n if not input_list:\n return \"Empty list provided\"\n \n def iterative_count(lst, tgt):\n ret...
trial_gpt4o_6
{ "original_instruction": "```markdown\n### Coding Assessment Question\n\nYou are given two different implementations to find the number of occurrences of a target value within a list. One implementation uses a simple iterative method, and the other uses a recursive method.\n\n### Task\nWrite a Python function that p...
0.621164
Algorithm_9123
C
[ "iterative_count", "recursive_count", "find_target_count" ]
3
[ [ "find_target_count", "iterative_count" ], [ "find_target_count", "recursive_count" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e6c0aa0ac4b1927fecb6185a20501847d88a8e65
4e4bb10423871809cf6caeb7eeb3143ef068954c
v1.0
complete
Algorithm
Algorithm_14931_C
def smallest_divisible(max_divisor: int) -> int: """ Compute the smallest positive number that is evenly divisible by all numbers from 1 to max_divisor. >>> smallest_divisible(10) 2520 >>> smallest_divisible(15) 360360 """
import math from functools import reduce def lcm(a, b): """ Compute the least common multiple of a and b. """ return abs(a * b) // math.gcd(a, b) def smallest_divisible(max_divisor: int) -> int: """ Returns the smallest positive number that is evenly divisible by all numbers from 1 to max_divi...
from solution import smallest_divisible def test_smallest_divisible_edge_cases(): assert smallest_divisible(1) == 1 assert smallest_divisible(2) == 2 def test_smallest_divisible_typical_cases(): assert smallest_divisible(3) == 6 assert smallest_divisible(4) == 12 assert smallest_divisible(5) == 60...
[ { "docstring": "Compute the least common multiple of a and b.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the smallest positive number that is evenly divisible by all numbers from 1 to max_divisor.", "function_...
[ 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": "import math\nfrom functools import reduce\n\ndef lcm(a, b):\n return abs(a*b) // math.gcd(a, b)\n\ndef smallest_divisible(max_divisor: int) -> int:\n if ma...
trial_gpt4o_9
{ "original_instruction": "### Question: Smallest Divisible Number\n\n#### Context\nFinding the smallest number that is divisible by a subset of integers enhances understanding of number theory and efficient algorithm design.\n\n#### Task\nWrite a function `smallest_divisible(max_divisor: int) -> int` that computes t...
0.82561
Algorithm_14931
C
[ "lcm", "smallest_divisible" ]
2
[ [ "smallest_divisible", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9e0a9230b8f63a6f252de0e27999e69b32092ff5
2efa30bd09c12bb1f75a851f7188d61d91546adc
v1.0
complete
Algorithm
Algorithm_36253_C
import csv import json import re def import_contacts(csv_file_path: str, existing_contacts: list[dict]) -> list[dict]: """ Reads contact details from a CSV file and adds them to the contact list. Ensures that duplicates (contacts with the same email) are not added. Parameters: csv_file_path (str):...
import csv import json import re def is_valid_email(email: str) -> bool: """ Helper function to validate email format using regex. """ regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' return re.match(regex, email) is not None def import_contacts(csv_file_path: str, existing_contacts: li...
import pytest from solution import import_contacts, export_contacts, is_valid_email def test_is_valid_email(): assert is_valid_email("test@example.com") == True assert is_valid_email("invalid-email") == False assert is_valid_email("another.test@domain.co.uk") == True assert is_valid_email("yet@another@...
[ { "docstring": "Helper function to validate email format using regex.", "function_declaration": "def is_valid_email(email):", "function_name": "is_valid_email", "parameter_list": "(email)" }, { "docstring": "Reads contact details from a CSV file and adds them to the contact list.\nEnsures th...
[ 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": "import csv\nimport json\nimport re\n\ndef is_valid_email(email: str) -> bool:\n \"\"\"\n Helper function to validate email format.\n \n A basic regex...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nYou are tasked with implementing a contact management system for small businesses. The initial framework for managing contacts is already in place, but several improvements are necessary. Specifically, you need to add functionality for importing contacts from a CSV ...
0.576379
Algorithm_36253
C
[ "is_valid_email", "import_contacts", "export_contacts" ]
3
[ [ "import_contacts", "is_valid_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cc241dbdaedfa7914807ed062a59ab204df368f2
a76e8ad315ece17d22abd82ce96e3a2bebaa6efe
v1.0
complete
Algorithm
Algorithm_14683_C
import numpy as np from typing import Callable, Tuple def mandelbrot_point(c: complex, transform: Callable[[complex], complex], max_iter: int, escape_radius: float) -> int: """ Compute the escape iteration for a point in the Mandelbrot set. """ # implementation def compute_row(args): """ Compute a row...
import numpy as np import matplotlib.pyplot as plt from multiprocessing import Pool from typing import Callable, Tuple def mandelbrot_point(c: complex, transform: Callable[[complex], complex], max_iter: int, escape_radius: float) -> int: z = c for i in range(max_iter): z = transform(z) if abs(z...
import pytest from solution import generate_mandelbrot_fractal import numpy as np def basic_transformation(z): return z**2 + 0.355 + 0.355j def test_mandelbrot_basic_scenario(): generate_mandelbrot_fractal(basic_transformation, 10, 2.0, (-2.0, 1.0), (-1.5, 1.5), 100) def test_large_grid_parallel_processing()...
[ { "docstring": null, "function_declaration": "def mandelbrot_point(c, transform, max_iter, escape_radius):", "function_name": "mandelbrot_point", "parameter_list": "(c, transform, max_iter, escape_radius)" }, { "docstring": null, "function_declaration": "def compute_row(args):", "fun...
[ 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\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Callable, Tuple\n\ndef mandelbrot(c: c...
trial_gpt4o_8
{ "original_instruction": "### Problem Description\n\nYou are required to design a function that generates a complex Mandelbrot fractal visualization. The function should be able to handle different types of complex transformations, efficiently support high-resolution grids, and optimize performance using parallel pr...
0.490512
Algorithm_14683
C
[ "mandelbrot_point", "compute_row", "generate_mandelbrot_fractal" ]
3
[ [ "compute_row", "mandelbrot_point" ], [ "generate_mandelbrot_fractal", "compute_row" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
39d8b36d9d06e4942528a44b3e54877fb0e225a3
d0144279588b8d4ff677de11aaa1d0799eb42506
v1.0
complete
Algorithm
Algorithm_45922_C
from typing import List from itertools import permutations def isMagicSquare(grid: List[List[int]]) -> bool: """Checks if a 3x3 grid forms a magic square. >>> isMagicSquare([[2, 7, 6], [9, 5, 1], [4, 3, 8]]) == True >>> isMagicSquare([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == False """ pass def countMa...
from itertools import permutations def isMagicSquare(grid): """ Checks if a 3x3 grid forms a magic square. """ # Check sums of rows, columns, and diagonals sums = [sum(row) for row in grid] + \ [sum(grid[i][j] for i in range(3)) for j in range(3)] + \ [sum(grid[i][i] for i in ...
import pytest from solution import isMagicSquare, countMagicSquares def test_isMagicSquare_true(): assert isMagicSquare([[2, 7, 6], [9, 5, 1], [4, 3, 8]]) == True def test_isMagicSquare_false(): assert isMagicSquare([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == False def test_countMagicSquares(): assert countMag...
[ { "docstring": "Checks if a 3x3 grid forms a magic square.", "function_declaration": "def isMagicSquare(grid):", "function_name": "isMagicSquare", "parameter_list": "(grid)" }, { "docstring": "Returns the count of all possible 3x3 magic squares using numbers 1 to 9.", "function_declarati...
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 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 itertools import permutations\n\ndef isMagicSquare(grid):\n \"\"\"\n Check if a 3x3 grid forms a magic square.\n \"\"\"\n target_sum = 15 # Bec...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: Magic Square Permutations\n\n#### Background:\n\nA magic square is a 3x3 grid of distinct numbers from 1 to 9 such that the sums of numbers in each row, each column, and both main diagonals are equal.\n\nConsider a function `isMagicSquare(grid)` that returns ...
0.596396
Algorithm_45922
C
[ "isMagicSquare", "countMagicSquares" ]
2
[ [ "countMagicSquares", "isMagicSquare" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b26ded9f3698cc783f41d1e3fd13a5783811a353
6c2e979cd1f9a198e5362a4e826af3b4645de076
v1.0
complete
Algorithm
Algorithm_32071_C
from typing import List def binary_search(collection: List[int], item: int) -> int: """ Searches for an item in a sorted collection using binary search. :param collection: A list of integers in ascending order. :param item: The integer item to search for. :return: The index of the item if found, o...
def binary_search(collection, item): """ Searches for an item in a sorted collection using binary search. :param collection: A list of integers in ascending order. :param item: The integer item to search for. :return: The index of the item if found, otherwise -1. """ left, right = 0, len(co...
from solution import binary_search, sorted_deletion def test_binary_search_found(): collection = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] assert binary_search(collection, 14) == 6 assert binary_search(collection, 2) == 0 assert binary_search(collection, 20) == 9 def test_binary_search_not_found(): col...
[ { "docstring": "Searches for an item in a sorted collection using binary search.\n\n:param collection: A list of integers in ascending order.\n:param item: The integer item to search for.\n:return: The index of the item if found, otherwise -1.", "function_declaration": "def binary_search(collection, item):"...
[ 1, 1, 1, 1, 1, 1, 1, 0, 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 binary_search(collection, item):\n \"\"\"\n Searches for an item in a sorted collection using binary search.\n\n :param collection: A list of intege...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Context and Scenario:\nYou are building a hospital management system where patient records are stored based on their unique identifiers. The list of patient IDs is sorted in ascending order. To ensure efficient data retrieval and updating, you need to ...
0.578842
Algorithm_32071
C
[ "binary_search", "sorted_deletion" ]
2
[ [ "sorted_deletion", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
47ca5ddeba1ec11c00d8af08f599574eaa480915
6019536eaf73586775f709ae77f45ed15e712ca1
v1.0
complete
Algorithm
Algorithm_8523_C
def hash_function(s: str, prime: int = 101) -> int: """ Compute the rolling hash of a string. Args: s (str): The input string. prime (int): The prime number used for hashing (default 101). Returns: int: The hash value of the string. """ def rabin_karp(text: str, pa...
def hash_function(s: str, prime: int = 101) -> int: """ Compute the rolling hash of a string. Args: s (str): The input string. prime (int): The prime number used for hashing. Returns: int: The hash value of the string. """ hash_value = 0 for i in range(len(s)): hash_valu...
from solution import hash_function, rabin_karp def test_hash_function(): assert hash_function("a", 101) == ord("a") % 101 assert hash_function("abc", 101) == (ord("a") * (256**2) + ord("b") * 256 + ord("c")) % 101 assert hash_function("aaa", 101) == (ord("a") * (256**2) + ord("a") * 256 + ord("a")) % 101 ...
[ { "docstring": "Compute the rolling hash of a string.\nArgs:\ns (str): The input string.\nprime (int): The prime number used for hashing.\n\nReturns:\nint: The hash value of the string.", "function_declaration": "def hash_function(s, prime=101):", "function_name": "hash_function", "parameter_list": ...
[ 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": "def hash_function(s: str, prime: int = 101) -> int:\n \"\"\"\n Compute the rolling hash of a string.\n Args:\n s (str): The input string.\n prime ...
trial_gpt4o_0
{ "original_instruction": "### Rabin-Karp Algorithm for Substring Search\n\nYou are given a text string and a pattern string. Your task is to implement the Rabin-Karp algorithm to search for the pattern within the text and return the starting indices of all occurrences of the pattern.\n\n### Task\n\n1. Implement a fu...
0.573321
Algorithm_8523
C
[ "hash_function", "rabin_karp" ]
2
[ [ "rabin_karp", "hash_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
161a40f66956bacc5d5b236d45596d325fce4feb
e4ae2c517969230a8f446205aeeeba13d2b21103
v1.0
complete
Algorithm
Algorithm_21945_C
[Completion Task in Python] def merge_sort(arr): """ Sorts the list arr using the Merge Sort algorithm. Parameters: arr (list): List of integers to sort. Returns: list: Sorted list in ascending order. """ def merge(left, right): """ Merges two sorted lists into one sorted list. ...
def merge_sort(arr): """ Sorts the list arr using the Merge Sort algorithm. Parameters: arr (list): List of integers to sort. Returns: list: Sorted list in ascending order. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) r...
from solution import merge_sort def test_merge_sort_basic(): assert merge_sort([4, 2, 5, 3, 0, 1]) == [0, 1, 2, 3, 4, 5] def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([2]) == [2] def test_merge_sort_presorted(): assert merge_sort([1,...
[ { "docstring": "Sorts the list arr using the Merge Sort algorithm.\n\nParameters:\narr (list): List of integers to sort.\n\nReturns:\nlist: Sorted list in ascending order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstri...
[ 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": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half = merge_sort(arr[:mid])\n right_half = merge_sor...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question:\n\nYou are given a list of integers. Your task is to implement the Merge Sort algorithm to sort the list in ascending order. Write a function `merge_sort(arr)` that takes a list of integers `arr` and sorts it using the Merge Sort algorithm.\n\n#### Input:\n* ...
0.587899
Algorithm_21945
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
740c8d31393abc324fed1959806a26af6fbdf058
4eaff50af8ef5d9d1c8b5da7bc7692de42cb913c
v1.0
complete
Algorithm
Algorithm_13577_C
class ListNode: """ Definition for singly-linked list node. """ def __init__(self, val=0, next=None): self.val = val self.next = next def reverse_k_group(head: ListNode, k: int) -> ListNode: """ Reverse the linked list in groups of size `k` and return the modified list. If the number o...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverse_k_group(head: ListNode, k: int) -> ListNode: if k == 1 or not head: return head dummy = ListNode() dummy.next = head prev_group_end = dummy while True: kth_node = ...
import pytest from solution import ListNode, reverse_k_group # Helper function to create a linked list from a list of values def create_linked_list(lst): dummy = ListNode(0) curr = dummy for val in lst: curr.next = ListNode(val) curr = curr.next return dummy.next # Helper function to c...
[]
[ 1, 1, 1, 1, 0, 1, 1, 1, 0, 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 ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef reverse_k_group(head: ListNode, k: int) -> Li...
trial_gpt4o_7
{ "original_instruction": "### Coding Assessment Question\n\n#### Problem Statement\nYou are given a linked list where each node contains an integer value. Your task is to reverse the linked list in groups of size `k` and return the modified list. If the number of nodes is not a multiple of `k` then left-out nodes, i...
0.563476
Algorithm_13577
C
[ "reverse_k_group", "get_kth_node" ]
2
[ [ "reverse_k_group", "get_kth_node" ] ]
1
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
bc4cb2b22c52a1dde9116476538d4e0fab6e74dc
0b7db73cf332695800b0562016e035df6c869057
v1.0
complete
Algorithm
Algorithm_35158_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Implement the Merge Sort algorithm to sort a list in ascending order. >>> merge_sort([38, 27, 43, 3, 9, 82, 10]) [3, 9, 10, 27, 38, 43, 82] >>> merge_sort([5, 2, 4, 6, 1, 3]) [1, 2, 3, 4, 5, 6] """ pass
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(): assert merge_sort([]) == [] assert merge_sort([1]) == [1] assert merge_sort([2, 1]) == [1, 2] assert merge_sort([5, 2, 4, 6, 1, 3]) == [1, 2, 3, 4, 5, 6] assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] 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": "### Problem Statement\n\n#### Context\nIn modern software systems, efficient sorting algorithms are crucial in handling large datasets. One of the well-known algorithms is **Merge Sort**, which is a divide-and-conquer algorithm with a time complexity of O(n log n). For this task, you are re...
0.657401
Algorithm_35158
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed8d103d577dc3e26cd389d68fa10ff181885bb9
22488cac7c43bd57abf6a29c6a6dc52793ede9b2
v1.0
complete
Algorithm
Algorithm_40206_C
def merge_sort(arr): """ Sorts a list of integers using the merge sort algorithm. Parameters: arr (list): A list of integers to be sorted. Returns: list: A new list of integers sorted in ascending order. Examples: >>> merge_sort([34, 7, 23, 32, 5, 62]) [5, 7, 23, 32, 34, 6...
def merge_sort(arr): """ Sorts a list of integers using the merge sort algorithm. Parameters: arr (list): A list of integers to be sorted. Returns: list: A new list of integers sorted in ascending order. """ if len(arr) <= 1: return arr # Divide the list into two h...
from solution import merge_sort def test_merge_sort_basic(): assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62] def test_merge_sort_with_negative_numbers(): assert merge_sort([-3, -1, -2, -4, -5]) == [-5, -4, -3, -2, -1] def test_merge_sort_single_element(): assert merge_sort([1]) == [1]...
[ { "docstring": "Sorts a list of integers using the merge sort algorithm.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A new list of integers sorted in ascending order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list"...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Function to sort an array using the merge sort algorithm\n \"\"\"\n if len(arr) <= 1:\n return arr\n\n # Sp...
trial_gpt4o_9
{ "original_instruction": "### Question\nCreate a function that implements the merge sort algorithm to sort a list of integers. Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts both halves, and then merges them to create the final sorted list.\n\n#### Specif...
0.659292
Algorithm_40206
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fa051fd29b30a3b8417513d7ac30dc9f9817b7a6
d1c51b2c8620cd849f04fae47eead7a36973fe16
v1.0
complete
Algorithm
Algorithm_20032_C
def is_prime(number: int) -> bool: """ Checks if a number is prime. :param number: int :return: bool >>> is_prime(2) True >>> is_prime(4) False """ def sum_of_squares_of_primes(numbers: List[int]) -> int: """ Takes a list of integers and returns the sum of squares of prime ...
from math import isqrt def is_prime(number): """ Checks if a number is prime. :param number: int :return: bool """ if number <= 1: return False if number == 2: return True if number % 2 == 0: return False for i in range(3, isqrt(number) + 1, 2): ...
import pytest from solution import sum_of_squares_of_primes, is_prime def test_is_prime(): assert not is_prime(1) assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(17) def test_empty_list(): assert sum_of_squares_of_p...
[ { "docstring": "Checks if a number is prime.\n\n:param number: int\n:return: bool", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Takes a list of integers and returns the sum of squares of prime numbers in the li...
[ 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \n :param n: int - The number to check.\n :return: bool - True if n is a prime ...
trial_gpt4o_3
{ "original_instruction": "### Problem Description:\nYou need to implement a function `sum_of_squares_of_primes` which takes a list of integers as an input. The function should filter out prime numbers from the list, compute the square of each prime, and then return the sum of these squares.\n\n### Input/Output:\n- *...
0.697952
Algorithm_20032
C
[ "is_prime", "sum_of_squares_of_primes" ]
2
[ [ "sum_of_squares_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8eaa75aa115bfa4f9fc4e1eadcfa77d65142a730
2eb2ae7cdebe0b6e65501e47f6e9a9e7b4c1f0ae
v1.0
complete
Algorithm
Algorithm_31181_C
import time import requests import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email_alert(to_email, subject, body): from_email = "alert@example.com" password = "password" # Placeholder: this should be securely managed msg = MIMEMultipart() msg...
import time import requests import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email_alert(to_email, subject, body): from_email = "alert@example.com" password = "password" # Placeholder: this should be securely managed msg = MIMEMultipart() msg...
import pytest from unittest.mock import patch, call from solution import monitor_service, send_email_alert @patch('solution.requests.get') @patch('solution.send_email_alert') def test_service_available(mock_send_email_alert, mock_requests_get): mock_requests_get.return_value.status_code = 200 with patch('time....
[ { "docstring": null, "function_declaration": "def send_email_alert(to_email, subject, body):", "function_name": "send_email_alert", "parameter_list": "(to_email, subject, body)" }, { "docstring": null, "function_declaration": "def monitor_service(url, email, check_interval):", "funct...
[ 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 requests\nimport smtplib\nimport time\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef monitor_service(url: st...
trial_gpt4o_3
{ "original_instruction": "## Coding Assessment Question\n\nYou are tasked with designing a function that monitors the state of a web service and sends an alert through email when the service becomes unavailable. You will build a function based on the provided code snippet.\n\n### Function Signature\n```python\ndef m...
0.689593
Algorithm_31181
C
[ "send_email_alert", "monitor_service" ]
2
[ [ "monitor_service", "send_email_alert" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
2754881960dfa9405b5764edf2f9ecd64897e841
e9e40336cb0d5e38359703f17581ec407d269eb4