version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Algorithm
Algorithm_5801_I
### Inventory Management System Enhancement You're given a function that manages the inventory of a small bookstore. The current function handles: 1. Adding new books to the inventory. 2. Updating the quantity of existing books. 3. Removing books that are out of stock. Your task is to enhance this function with the ...
import json import os INVENTORY_FILE = 'inventory.json' def load_inventory(): """Load the inventory from the inventory.json file.""" if not os.path.exists(INVENTORY_FILE): return {} with open(INVENTORY_FILE, 'r') as file: return json.load(file) def save_inventory(inventory): """S...
from solution import manage_inventory, load_inventory, save_inventory import os import pytest inventory_backup = None def setup_module(module): """ Backup the original inventory if it exists """ global inventory_backup if os.path.exists('inventory.json'): with open('inventory.json', 'r') as file: ...
[ { "docstring": "Load the inventory from the inventory.json file.", "function_declaration": "def load_inventory():", "function_name": "load_inventory", "parameter_list": "()" }, { "docstring": "Save the inventory to the inventory.json file.", "function_declaration": "def save_inventory(in...
[ 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": "import json\nimport os\n\nINVENTORY_FILE = 'inventory.json'\n\ndef load_inventory():\n if os.path.isfile(INVENTORY_FILE):\n with open(INVENTORY_FILE, '...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000005801", "row_id": 5801, "seed_ids": "[2300]" }
0.461485
Algorithm_5801
I
[ "load_inventory", "save_inventory", "manage_inventory" ]
3
[ [ "manage_inventory", "load_inventory" ], [ "manage_inventory", "save_inventory" ] ]
2
[]
false
[]
false
pytest
true
[]
true
71e27f44477284c9a33eb2b9ce91f6f517778753
f8000a8b16ab67d15ed8c8ad6a618da0d0f03ccc
v1.0
instruct
Algorithm
Algorithm_5830_I
### Coding Assessment Question: Real-Time Traffic Density Analysis #### Context: You are working on a traffic monitoring system that analyzes live video feeds from various road segments. The goal is to estimate the current traffic density in real-time and classify it into categories such as ‘Low’, ‘Medium’, or ‘High’....
import numpy as np def load_vehicle_detection_model(model_path): """ Assume this function loads the vehicle detection model. Model loading logic is abstracted for this example. """ pass def detect_vehicles(model, frame): """ Assume this function uses the loaded model to detect vehicles in ...
import numpy as np from unittest.mock import patch from solution import analyze_traffic_density def mocked_load_vehicle_detection_model(model_path): return "mocked_model" def test_analyze_traffic_density_low(): frame = np.random.rand(480, 640, 3) # Dummy frame model_path = "path/to/vehicle_detection_mod...
[ { "docstring": "Assume this function loads the vehicle detection model.\nModel loading logic is abstracted for this example.", "function_declaration": "def load_vehicle_detection_model(model_path):", "function_name": "load_vehicle_detection_model", "parameter_list": "(model_path)" }, { "docs...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import cv2\nimport numpy as np\n\ndef analyze_traffic_density(frame: np.ndarray, model_path: str, low_threshold: int, high_threshold: int) -> str:\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000005830", "row_id": 5830, "seed_ids": "[4966]" }
0.513293
Algorithm_5830
I
[ "load_vehicle_detection_model", "detect_vehicles", "analyze_traffic_density" ]
3
[ [ "analyze_traffic_density", "detect_vehicles" ], [ "analyze_traffic_density", "load_vehicle_detection_model" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
fd043cc3f23f7137963e843d2759496e399aa460
5f3651fed1195f78e3973e157f04a04ebb5ff44f
v1.0
instruct
Algorithm
Algorithm_5837_I
### Problem Statement: Write a function that takes a list of integers and returns a list of the prime factors for each number in the list. Prime factors are the set of prime numbers that multiply together to give the original integer. ### Function Signature: ```python def find_prime_factors(numbers: List[int]) -> Lis...
from typing import List def sieve_of_eratosthenes(limit: int) -> List[int]: """Compute all prime numbers up to the given limit using the sieve of Eratosthenes.""" is_prime = [True] * (limit + 1) p = 2 while (p * p <= limit): if is_prime[p]: for i in range(p * p, limit + 1, p): ...
from solution import find_prime_factors def test_find_prime_factors_basic(): assert find_prime_factors([28, 45, 100]) == [[2, 2, 7], [3, 3, 5], [2, 2, 5, 5]] def test_find_prime_factors_single_prime(): assert find_prime_factors([7, 29, 37]) == [[7], [29], [37]] def test_find_prime_factors_large_number(): ...
[ { "docstring": "Compute all prime numbers up to the given limit using the sieve of Eratosthenes.", "function_declaration": "def sieve_of_eratosthenes(limit):", "function_name": "sieve_of_eratosthenes", "parameter_list": "(limit)" }, { "docstring": "Find all prime factors of the number n usin...
[ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_prime_factors(numbers: List[int]) -> List[List[int]]:\n def sieve(n: int) -> List[int]:\n \"\"\" Return a list of p...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000005837", "row_id": 5837, "seed_ids": "[5343]" }
0.839677
Algorithm_5837
I
[ "sieve_of_eratosthenes", "prime_factors", "find_prime_factors" ]
3
[ [ "find_prime_factors", "prime_factors" ], [ "find_prime_factors", "sieve_of_eratosthenes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cd588f324a44f2fc6f8c32dcfde8e0f5c5a5293f
ca353dceae70feef89a16be8234812d08ff0eca9
v1.0
instruct
Algorithm
Algorithm_5851_I
**Problem Statement**: Given a list of integers, write a function `find_longest_run_of_ones` that finds the length of the longest run of 1s in the binary representation of any number in the list. Additionally, write a function `max_ones_in_list` that returns the maximum length of 1s sequences among all numbers in the l...
def find_longest_run_of_ones(n: int) -> int: """ Returns the length of the longest run of 1s in the binary representation of the integer n. """ # convert to binary and remove the '0b' prefix binary_representation = bin(n)[2:] # split by '0' to find consecutive 1s runs ones_splits = binar...
from solution import find_longest_run_of_ones, max_ones_in_list def test_find_longest_run_of_ones(): assert find_longest_run_of_ones(15) == 4 # "1111" assert find_longest_run_of_ones(32) == 1 # "100000" assert find_longest_run_of_ones(0) == 0 # "0" assert find_longest_run_of_ones(1) == 1 # "1" ...
[ { "docstring": "Returns the length of the longest run of 1s in the binary\nrepresentation of the integer n.", "function_declaration": "def find_longest_run_of_ones(n):", "function_name": "find_longest_run_of_ones", "parameter_list": "(n)" }, { "docstring": "Returns the maximum length of 1s s...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def find_longest_run_of_ones(n: int) -> int:\n \"\"\"\n Returns the length of the longest run of 1s in the binary representation of n.\n \"\"\"\n ret...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000005851", "row_id": 5851, "seed_ids": "[2770]" }
0.61067
Algorithm_5851
I
[ "find_longest_run_of_ones", "max_ones_in_list" ]
2
[ [ "max_ones_in_list", "find_longest_run_of_ones" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9384f5969f8adaae893fa9677cfdd70e5ee7b024
203d54fe0574e29557553c3773add7bfb640b144
v1.0
instruct
Algorithm
Algorithm_5885_I
### Problem Statement Write a function that takes a string representing a formula for a truth table and generates the corresponding truth table. ### Task Description 1. **Function: `generate_truth_table(expression: str) -> List[Tuple[Dict[str, bool], bool]]`** - The function should parse the given logical express...
from typing import List, Tuple, Dict import itertools def evaluate_expression(variables: Dict[str, bool], expression: str) -> bool: # Replace variable names with their boolean values in the expression for var, val in variables.items(): expression = expression.replace(var, str(val)) # Replace l...
from solution import generate_truth_table def test_generate_truth_table_basic_and(): assert generate_truth_table("a&b") == [({'a': False, 'b': False}, False), ({'a': False, 'b': True}, False), ({'a': True, 'b': False}, False), ...
[ { "docstring": null, "function_declaration": "def evaluate_expression(variables, expression):", "function_name": "evaluate_expression", "parameter_list": "(variables, expression)" }, { "docstring": null, "function_declaration": "def generate_truth_table(expression):", "function_name"...
[ 1, 0, 1, 0, 0, 1, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple, Dict\n\ndef generate_truth_table(expression: str) -> List[Tuple[Dict[str, bool], bool]]:\n import re\n from itertools impor...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000005885", "row_id": 5885, "seed_ids": "[1800]" }
0.528618
Algorithm_5885
I
[ "evaluate_expression", "generate_truth_table" ]
2
[ [ "generate_truth_table", "evaluate_expression" ] ]
1
[]
false
[]
false
pytest
true
[]
true
470a1fd774f56dc52ba13327dd1f8b6c23f12aae
16ea9b8725ae61b997eeb2ab709f19bb492aee51
v1.0
instruct
Algorithm
Algorithm_5906_I
#### Coding Assessment Question You are given the task of developing a student grading application. The application should read a list of student test scores, categorize each score into a letter grade, and then calculate statistics about the categorization. Letter grades are assigned based on the following rules: - `...
from typing import List, Dict def assign_grades(scores: List[int]) -> List[str]: """ Returns a list of letter grades corresponding to the given scores. """ def grade(score): if score >= 90: return 'A' elif score >= 80: return 'B' elif score >= 70: ...
import pytest from solution import assign_grades, grade_statistics, solution def test_assign_grades(): assert assign_grades([95, 82, 74, 61, 59]) == ['A', 'B', 'C', 'D', 'F'] assert assign_grades([100, 78, 85, 93, 67]) == ['A', 'C', 'B', 'A', 'D'] assert assign_grades([90, 80, 70, 60, 59]) == ['A', 'B', '...
[ { "docstring": "Returns a list of letter grades corresponding to the given scores.", "function_declaration": "def assign_grades(scores):", "function_name": "assign_grades", "parameter_list": "(scores)" }, { "docstring": "Returns a dictionary with the count of each letter grade in the 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": "from typing import List, Dict\n\ndef assign_grades(scores: List[int]) -> List[str]:\n \"\"\"\n Assign letter grades based on the provided scores.\n \"\"...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000005906", "row_id": 5906, "seed_ids": "[2699]" }
0.750038
Algorithm_5906
I
[ "assign_grades", "grade_statistics", "solution" ]
3
[ [ "solution", "assign_grades" ], [ "solution", "grade_statistics" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f12441d854516547403ea339091f0b5f74486497
b9ac837bfbd950c6c1e66be8ac0e81754a8e2155
v1.0
instruct
Algorithm
Algorithm_5926_I
### Problem Statement: You are given a grid with `n` rows and `m` columns. Each cell in the grid contains either a `0` or a `1`. Your task is to determine the largest rectangle (subgrid) composed entirely of `1`s within the given grid. ### Function Signature: ```python def largest_rectangle(grid: List[List[int]]) -> i...
from typing import List def largest_histogram_area(heights: List[int]) -> int: """ Helper function to calculate the largest area of a rectangle in a histogram. This uses a stack-based approach for efficient O(n) computation. """ stack = [] max_area = 0 for i, height in enumerate(heights): ...
from solution import largest_rectangle def test_largest_rectangle_example1(): grid = [ [1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0] ] assert largest_rectangle(grid) == 6 def test_largest_rectangle_example2(): grid = [ [0, 1], [1, 1]...
[ { "docstring": "Helper function to calculate the largest area of a rectangle in a histogram.\nThis uses a stack-based approach for efficient O(n) computation.", "function_declaration": "def largest_histogram_area(heights):", "function_name": "largest_histogram_area", "parameter_list": "(heights)" ...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef largest_rectangle(grid: List[List[int]]) -> int:\n def max_histogram_area(heights: List[int]) -> int:\n stack = []\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000005926", "row_id": 5926, "seed_ids": "[2097]" }
0.687579
Algorithm_5926
I
[ "largest_histogram_area", "largest_rectangle" ]
2
[ [ "largest_rectangle", "largest_histogram_area" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cbda837533548ad0541a9881ed9724383904927f
44d691b5ae4bbe1e65a6c6f0b795f675904be574
v1.0
instruct
Algorithm
Algorithm_6018_I
### Context You are familiar with implementing sorting algorithms and have learned about the Merge Sort algorithm, which is a divide-and-conquer sorting technique known for its efficiency. ### Problem Implement the Merge Sort algorithm to sort a given list of integers. Additionally, implement a helper function to merg...
from typing import List def merge(left: List[int], right: List[int]) -> List[int]: """ Merges two sorted lists into one sorted list. """ merged = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: merged.append(left[i]) i += 1 ...
from solution import merge_sort, merge def test_merge_sort_examples(): assert merge_sort([3, 1, 2]) == [1, 2, 3] assert merge_sort([]) == [] assert merge_sort([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5] assert merge_sort([2, 1]) == [1, 2] assert merge_sort([9, -2, 7, 3, 8]) == [-2, 3, 7, 8, 9] def test_me...
[ { "docstring": "Merges two sorted lists into one sorted list.", "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docstring": "Sorts the list using the Merge Sort algorithm.", "function_declaration": "def merge_sort(arr):...
[ 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 merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts the list using the Merge Sort algorithm.\n \"\"\"\n def merg...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006018", "row_id": 6018, "seed_ids": "[2982]" }
0.622677
Algorithm_6018
I
[ "merge", "merge_sort" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8066cead47010887fc12d41cec9eb4f454348ed7
287600b4d7d029c674cbe01190dbcf6dddd0fb09
v1.0
instruct
Algorithm
Algorithm_6028_I
### Coding Assessment Question #### Problem Statement You are given an implementation of the Merge Sort algorithm, which is used to sort arrays. Your task is to write a function that will apply this algorithm to multiple input arrays and compare the sorting results with the built-in Python `sorted` function to ensure...
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]: sorted_array = [] i = j =...
from solution import validate_merge_sort def test_validate_merge_sort(): arrays_to_sort = [ [3, 1, 4, 1, 5, 9, 2, 6, 5, 3], [-1, -3, -2, -5, -4, 0, 2, 1], [5, 7, 3, -1, 4, -2, 0], [1, 2, 3, 4, 5], # Already sorted [5, 4, 3, 2, 1], # Reverse order ...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docst...
[ 1, 1, 1, 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": "def merge_sort(arr: list[int]) -> list[int]:\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left_half = merge_sort(arr[:mid])\n righ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000006028", "row_id": 6028, "seed_ids": "[3982]" }
0.637464
Algorithm_6028
I
[ "merge_sort", "merge", "validate_merge_sort" ]
3
[ [ "merge_sort", "merge" ], [ "validate_merge_sort", "merge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
439db72949836775a12907d7f92c28b32ee59423
cd0f002d462dfb697c9426efee11d3f7632e96ba
v1.0
instruct
Algorithm
Algorithm_6044_I
### Coding Question **Problem Statement**: You are provided with the task of finding the smallest positive number that is evenly divisible by all of the numbers from 1 to `n` (inclusive). In other words, you need to find the least common multiple (LCM) of the set {1, 2, ..., `n`}. **Objective**: Write a function `s...
from math import gcd def lcm(a, b): """Helper function to calculate least common multiple of a and b.""" return a * b // gcd(a, b) def smallest_multiple(n: int) -> int: """ Returns the smallest positive number that is evenly divisible by all of the numbers from 1 to n. """ result = 1 for i...
from solution import smallest_multiple def test_smallest_multiple_1(): assert smallest_multiple(1) == 1 def test_smallest_multiple_2(): assert smallest_multiple(2) == 2 def test_smallest_multiple_3(): assert smallest_multiple(3) == 6 def test_smallest_multiple_4(): assert smallest_multiple(4) == 12 ...
[ { "docstring": "Helper function to calculate 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 of the numbers from 1 to n.", ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom functools import reduce\n\ndef lcm(a, b):\n return abs(a * b) // math.gcd(a, b)\n\ndef smallest_multiple(n: int) -> int:\n \"\"\"\n Re...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006044", "row_id": 6044, "seed_ids": "[2194]" }
0.644041
Algorithm_6044
I
[ "lcm", "smallest_multiple" ]
2
[ [ "smallest_multiple", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95c515a3d9dc0768c7a68e995205c9a928a0655b
0756b5c88f89f0d4bc5e2cc3a12c0ee19bd4ad53
v1.0
instruct
Algorithm
Algorithm_6057_I
You are asked to design a software module that manipulates a complex nested dictionary to filter and sort data for a reporting tool. The dictionary contains data about different products, with each product having attributes like name, category, price, and ratings. The reporting module needs to provide functionalities t...
from typing import Dict, List, Any def filter_products_by_category(products: Dict[str, Dict[str, Any]], category: str) -> List[Dict[str, Any]]: """ Filters products by a given category. """ return [details for details in products.values() if details['category'] == category] def sort_products(products:...
import pytest from solution import filter_products_by_category, sort_products, generate_report products = { "p1": {"name": "Product 1", "category": "Electronics", "price": 99.99, "ratings": 4.5}, "p2": {"name": "Product 2", "category": "Books", "price": 12.49, "ratings": 4.7}, "p3": {"name": "Product 3", "...
[ { "docstring": "Filters products by a given category.", "function_declaration": "def filter_products_by_category(products, category):", "function_name": "filter_products_by_category", "parameter_list": "(products, category)" }, { "docstring": "Sorts products based on a specified key.", "...
[ 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 Dict, Any, List\n\ndef filter_products_by_category(products: Dict[str, Dict[str, Any]], category: str) -> List[Dict[str, Any]]:\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006057", "row_id": 6057, "seed_ids": "[1830]" }
0.571325
Algorithm_6057
I
[ "filter_products_by_category", "sort_products", "generate_report" ]
3
[ [ "generate_report", "filter_products_by_category" ], [ "generate_report", "sort_products" ] ]
2
[]
false
[]
false
pytest
true
[]
true
df4c43e77086f6a97949be929d52a176d2925b28
3306ba6eedc83a1230e4374e01ae2ca96c439ff2
v1.0
instruct
Algorithm
Algorithm_6098_I
### Problem Statement You are tasked with implementing a function that determines if a given string can be rearranged to form a palindrome. A palindrome is a word that reads the same forwards and backwards. The function should handle case insensitivity and disregard any non-alphabetical characters. Additionally, you a...
import time from collections import Counter def can_form_palindrome(s: str) -> bool: """ Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach. """ s = ''.join(filter(str.isalpha, s)).lower() count = Counter(s) odd_count = sum(1 for cnt in count.va...
from solution import can_form_palindrome, can_form_palindrome_bit, benchmark_palindrome def test_can_form_palindrome(): assert can_form_palindrome("civic!") == True assert can_form_palindrome("ivicc") == True assert can_form_palindrome("hello") == False assert can_form_palindrome("A man, a plan, a cana...
[ { "docstring": "Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach.", "function_declaration": "def can_form_palindrome(s):", "function_name": "can_form_palindrome", "parameter_list": "(s)" }, { "docstring": "Determine if a given string can be...
[ 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 can_form_palindrome(s: str) -> bool:\n \"\"\"\n Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach.\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006098", "row_id": 6098, "seed_ids": "[3159]" }
0.783043
Algorithm_6098
I
[ "can_form_palindrome", "can_form_palindrome_bit", "benchmark_palindrome" ]
3
[ [ "benchmark_palindrome", "can_form_palindrome" ], [ "benchmark_palindrome", "can_form_palindrome_bit" ] ]
2
[]
false
[]
false
pytest
true
[]
true
61d9d75536a0f94a3d5c842169217c8fd4e60f7f
6be7d1e952ac73accaca1be4888e7343fc14e5ca
v1.0
instruct
Algorithm
Algorithm_6116_I
### Context: You are tasked to implement a rebalancing algorithm for a given binary search tree (BST). A BST is considered balanced if the height difference between the left and right subtrees of any node is no more than one. Your goal is to write a function that rebalances an unbalanced BST while maintaining the binar...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def in_order_traversal(node): if not node: return [] return in_order_traversal(node.left) + [node.val] + in_order_traversal(node.right) def sorted_array_to_b...
import pytest from solution import TreeNode, rebalance_bst def in_order_traversal(node): if not node: return [] return in_order_traversal(node.left) + [node.val] + in_order_traversal(node.right) def is_balanced(root): def height(node): if not node: return 0 left_height ...
[]
[ 0, 1, 0, 1, 1, 1, 1, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef inord...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000006116", "row_id": 6116, "seed_ids": "[355]" }
0.676283
Algorithm_6116
I
[ "in_order_traversal", "sorted_array_to_bst", "rebalance_bst" ]
3
[ [ "rebalance_bst", "in_order_traversal" ], [ "rebalance_bst", "sorted_array_to_bst" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
77bbe892253e94ae9e112d2b9e156ff6a100add0
85b92da0c8b6cc80573ff89f49b51ba675840989
v1.0
instruct
Algorithm
Algorithm_6221_I
### Question: Matrix Rotation Validator You are tasked with writing a function that validates whether a given matrix is a rotation of another matrix. A matrix rotation is defined as rotating the matrix 90 degrees to the right (clockwise). The function should determine if the second matrix can be obtained by rotating t...
def rotate_90(matrix): """ Rotates the given square 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 rotate_180(matrix): """ Rotates the given square matrix by 180 degrees. """ return rotate_90(rotate_90(matr...
def test_is_matrix_rotation(): matrix_a = [ [1, 2], [3, 4] ] matrix_b_90 = [ [3, 1], [4, 2] ] matrix_b_180 = [ [4, 3], [2, 1] ] matrix_b_270 = [ [2, 4], [1, 3] ] matrix_b_false = [ [1, 2], [4, 3] ] ...
[ { "docstring": "Rotates the given square matrix by 90 degrees clockwise.", "function_declaration": "def rotate_90(matrix):", "function_name": "rotate_90", "parameter_list": "(matrix)" }, { "docstring": "Rotates the given square matrix by 180 degrees.", "function_declaration": "def rotate...
[ 0, 1, 0, 0, 1, 0, 0, 1, 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": "def rotate_90(matrix):\n n = len(matrix)\n return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)]\n\ndef rotate_180(matrix):\n return rotat...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006221", "row_id": 6221, "seed_ids": "[3560]" }
0.508582
Algorithm_6221
I
[ "rotate_90", "rotate_180", "rotate_270", "is_matrix_rotation" ]
4
[ [ "is_matrix_rotation", "rotate_180" ], [ "is_matrix_rotation", "rotate_270" ], [ "is_matrix_rotation", "rotate_90" ], [ "rotate_180", "rotate_90" ], [ "rotate_270", "rotate_90" ] ]
5
[]
false
[]
false
pytest
false
[]
true
f13569a100d5f4e4db9585be9d860a5668e49134
6701663d9a4679644fc0c9bccdaf4efc02e5e861
v1.0
instruct
Algorithm
Algorithm_6242_I
### Prime Number Validation and Sum: #### Problem Statement: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Identifying prime numbers is fundamental in various fields of science and cryptography. You are required to implement two functions, `is_prime` and `sum...
def is_prime(n: int) -> bool: if n < 2: raise ValueError("Input must be greater than or equal to 2.") if n in (2, 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 Fal...
from solution import is_prime, sum_of_primes def test_is_prime_basic(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True def test_is_prime_larger_numbers(): assert is_prime(29) == True assert is_prime(97) == True assert is_prime(9...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def sum_of_primes(limit):", "function_name": "sum_of_primes", "parameter_list": "(limit)" } ]
[ 0, 1, 0, 1, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n: int) -> bool:\n if n < 2:\n raise ValueError(\"Input must be greater than or equal to 2.\")\n \n if n in (2, 3):\n return ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000006242", "row_id": 6242, "seed_ids": "[830]" }
0.743027
Algorithm_6242
I
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cfc63a4840a7b3f50cd6b81784f7dc9b5a4266a2
a5cd75b8b8cfe83d2ee8e61f220806d0fe3b48d5
v1.0
instruct
Algorithm
Algorithm_6308_I
You are required to implement a function to fetch weather data from a provided API for multiple cities and process it concurrently to improve performance. The function should efficiently handle multiple cities using asynchronous programming and ensure the correct error handling strategy. 1. **Concurrency**: - Use ...
import aiohttp import asyncio import random from typing import List, Dict, Union from aiohttp import ClientSession async def fetch_city_weather(api_url: str, session: ClientSession, city: str, fields: List[str], retry: int = 5) -> Dict[str, Union[str, float, int]]: url = f"{api_url}?q={city}" for attempt in ra...
import pytest from solution import get_weather_data import asyncio @pytest.mark.asyncio async def test_weather_data_success(): # Mock an API server and provide some fake data for testing api_url = "https://api.mockweather.com/weather" cities = ["New York", "London", "Tokyo"] fields = ["temperature", "h...
[]
[ 1, 0, 1, 0, 0, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nimport random\nimport time\nfrom typing import List, Dict, Union\n\nasync def fetch_weather_data(session, url, city, fields):\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000006308", "row_id": 6308, "seed_ids": "[1907]" }
0.611396
Algorithm_6308
I
[ "fetch_city_weather", "get_weather_data" ]
2
[ [ "get_weather_data", "fetch_city_weather" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
d47dd2b68570b001746199ce81d4112200b4a010
eb12ebb424c014156fa1fd650220c99ab6989508
v1.0
instruct
Algorithm
Algorithm_6309_I
### Question: Implement k-Means Clustering You 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 to clusters, update the centroi...
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": "", "prompt_id": "0000006309", "row_id": 6309, "seed_ids": "[510]" }
0.768951
Algorithm_6309
I
[ "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
91fb74a5cec38ae0f472d4eafcf5f7f594932cfe
87d789f0ab4f9a4e3d442c35183d9f3247e09e9b
v1.0
instruct
Algorithm
Algorithm_6330_I
### House Price Prediction using Linear Regression #### Context You are given a dataset containing various features of houses and their corresponding prices. Your task is to predict the house prices based on the given features using a Linear Regression model. #### Task Implement a function `build_and_train_linear_r...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error def preprocess_data(df): """ Preprocess the dataframe: handle missing values and encode categorical variables. """ # Handle missing ...
import pytest from sklearn.linear_model import LinearRegression from solution import build_and_train_linear_regression # Create a sample DataFrame for testing def create_sample_data(): data = { 'Feature1': [1, 2, 3, 4, 5], 'Feature2': ['A', 'B', 'A', 'B', 'A'], 'Price': [100, 150, 200, 250,...
[ { "docstring": "Preprocess the dataframe: handle missing values and encode categorical variables.", "function_declaration": "def preprocess_data(df):", "function_name": "preprocess_data", "parameter_list": "(df)" }, { "docstring": "Build and train a linear regression model and evaluate its p...
[ 0, 1, 0, 1, 1, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_ab...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006330", "row_id": 6330, "seed_ids": "[673]" }
0.782354
Algorithm_6330
I
[ "preprocess_data", "build_and_train_linear_regression" ]
2
[ [ "build_and_train_linear_regression", "preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
74102a9d20d21353d0226d6e10dc992364f01823
318477fed464e9ade5d9aa7d31865a0ce32fca98
v1.0
instruct
Algorithm
Algorithm_6400_I
### Coding Assessment Question **Title**: Implement Customizable Caesar Cipher **Objective**: Create a customizable Caesar cipher that allows dynamic shifting amounts and supports both encryption and decryption of messages with alphabetic characters. **Context**: Alice wants to use a Caesar cipher to encrypt her mes...
def custom_encrypt(message: str, shift: int) -> str: def shift_char(c, shift): if 'a' <= c <= 'z': return chr((ord(c) - ord('a') + shift) % 26 + ord('a')) elif 'A' <= c <= 'Z': return chr((ord(c) - ord('A') + shift) % 26 + ord('A')) return c return ''.join(sh...
from solution import custom_encrypt, custom_decrypt def test_custom_encrypt(): assert custom_encrypt("HELLO", 3) == "KHOOR" assert custom_encrypt("GoodBye", -1) == "FnncAxd" assert custom_encrypt("abcdef", 26) == "abcdef" assert custom_encrypt("Python", 5) == "Udymts" assert custom_encrypt("Shift12...
[ { "docstring": null, "function_declaration": "def custom_encrypt(message, shift):", "function_name": "custom_encrypt", "parameter_list": "(message, shift)" }, { "docstring": null, "function_declaration": "def custom_decrypt(encrypted_message, shift):", "function_name": "custom_decryp...
[ 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def custom_encrypt(message: str, shift: int) -> str:\n encrypted = []\n for char in message:\n if char.isupper():\n encrypted.append(chr(...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000006400", "row_id": 6400, "seed_ids": "[220]" }
0.666738
Algorithm_6400
I
[ "custom_encrypt", "custom_decrypt" ]
2
[ [ "custom_decrypt", "custom_encrypt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5508bcd21e32e59fa38e9927d5156204dd8f4258
26960c565f897166dc633589a451c14e1afcdd2b
v1.0
instruct
Algorithm
Algorithm_6433_I
### Problem Statement: You are tasked with implementing a k-means clustering algorithm to categorize a set of data points into 'k' clusters. The goal is to determine the optimal placement of centroids and assign each data point to the closest centroid, forming clusters. Implement the `k_means_clustering` function which...
import random def euclidean_distance(point1, point2): return sum((x - y) ** 2 for x, y in zip(point1, point2)) ** 0.5 def assign_clusters(data, centroids): clusters = [[] for _ in range(len(centroids))] for point in data: distances = [euclidean_distance(point, centroid) for centroid in centroids] ...
from solution import k_means_clustering def test_k_means_simple(): data = [ [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 result = k_means_clustering(data, k) assert len(result) == len(data) assert set(result) == {0, 1,...
[ { "docstring": null, "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": null, "function_declaration": "def assign_clusters(data, centroids):", "function_name": "assign_cluste...
[ 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 random\nimport math\n\ndef euclidean_distance(point1, point2):\n return sum((x - y) ** 2 for x, y in zip(point1, point2)) ** 0.5\n\ndef calculate_centr...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000006433", "row_id": 6433, "seed_ids": "[565]" }
0.77423
Algorithm_6433
I
[ "euclidean_distance", "assign_clusters", "calculate_centroids", "k_means_clustering" ]
4
[ [ "assign_clusters", "euclidean_distance" ], [ "k_means_clustering", "assign_clusters" ], [ "k_means_clustering", "calculate_centroids" ], [ "k_means_clustering", "euclidean_distance" ] ]
4
[]
false
[]
false
pytest
true
[]
true
738d78e07d348a0b6ebef23ccc97e5c23578c695
9f47de1a5d925391c73bc2b924e85bb9976667ac
v1.0
instruct
Algorithm
Algorithm_6476_I
## Prompt: You are hired to improve a sorting system that involves multiple stages of sorting using different algorithms. The final goal is to sort a list of integers using a series of sorting methods in a specified order. 1. **Stage 1**: Sort the list using the Bubble Sort algorithm. 2. **Stage 2**: Sort the resultin...
def bubble_sort(arr): """ Sorts the list using the Bubble Sort algorithm and returns the sorted list. """ n = len(arr) for i in range(n): swapped = False for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] sw...
from solution import bubble_sort, insertion_sort, merge_sort, multi_stage_sort def test_bubble_sort(): assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90] assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8] assert bubble_sort([]) == [] assert bubble_sort([1]) == [1] ...
[ { "docstring": "Sorts the list using the Bubble Sort algorithm and returns the sorted list.", "function_declaration": "def bubble_sort(arr):", "function_name": "bubble_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts the list using the Insertion Sort algorithm and returns the sorted...
[ 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 bubble_sort(arr):\n \"\"\"\n Sorts the list using the Bubble Sort algorithm and returns the sorted list.\n \"\"\"\n n = len(arr)\n for i in ra...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006476", "row_id": 6476, "seed_ids": "[295]" }
0.577354
Algorithm_6476
I
[ "bubble_sort", "insertion_sort", "merge_sort", "multi_stage_sort" ]
4
[ [ "multi_stage_sort", "bubble_sort" ], [ "multi_stage_sort", "insertion_sort" ], [ "multi_stage_sort", "merge_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3345a59ced86554091caf369cf550a29682eb364
e2e268c0ee5406e782bede2a964a5a39db9ced1d
v1.0
instruct
Algorithm
Algorithm_6497_I
### Coding Assessment: Implement Shortest Job First Scheduling Algorithm #### Context You are working on an operating system simulator featuring job scheduling algorithms. Another common and efficient algorithm used for scheduling is the Shortest Job First (SJF) scheduling algorithm. The SJF algorithm schedules the pr...
from typing import List def calculate_waiting_times(duration_times: List[int]) -> List[int]: """ Computes waiting times for the processes based on their duration times sorted in ascending order. """ n = len(duration_times) waiting_times = [0] * n for i in range(1, n): waiting_times...
import pytest from solution import ( calculate_waiting_times, calculate_turnaround_times, calculate_average_turnaround_time, calculate_average_waiting_time, ) def test_calculate_waiting_times(): duration_times = [3, 6, 7, 8] expected_waiting_times = [0, 3, 9, 16] assert calculate_waiting_ti...
[ { "docstring": "Computes waiting times for the processes based on their duration times sorted in ascending order.", "function_declaration": "def calculate_waiting_times(duration_times):", "function_name": "calculate_waiting_times", "parameter_list": "(duration_times)" }, { "docstring": "Comp...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def calculate_waiting_times(duration_times):\n \"\"\"\n Computes waiting times for the processes based on their duration times sorted in ascending order.\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000006497", "row_id": 6497, "seed_ids": "[4443]" }
0.582451
Algorithm_6497
I
[ "calculate_waiting_times", "calculate_turnaround_times", "calculate_average_turnaround_time", "calculate_average_waiting_time", "display_process_information", "sjf_scheduling" ]
6
[ [ "display_process_information", "calculate_average_turnaround_time" ], [ "display_process_information", "calculate_average_waiting_time" ], [ "sjf_scheduling", "calculate_turnaround_times" ], [ "sjf_scheduling", "calculate_waiting_times" ], [ "sjf_scheduling", ...
5
[]
false
[]
false
pytest
true
[]
true
ab7cf83e5774b5f214830fa181aee23f8ac75ff9
f6a33f35073d70ea46ff1204fbc997abbf1ddc3a
v1.0
instruct
Algorithm
Algorithm_6513_I
### Context Sorting algorithms are fundamental in computer science and have various applications in data processing. One commonly used sorting algorithm is Merge Sort, which has a time complexity of O(n log n). ### Problem Statement Write a function, `merge_sort(lst)`, that sorts a list of integers in ascending order ...
from typing import List def merge_sort(lst: List[int]) -> List[int]: if len(lst) <= 1: return lst # Split the list into two halves middle = len(lst) // 2 left_half = merge_sort(lst[:middle]) right_half = merge_sort(lst[middle:]) # Merge the sorted halves return merge(left_...
from solution import merge_sort def test_empty_list(): assert merge_sort([]) == [] def test_single_element(): assert merge_sort([1]) == [1] def test_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_list(): assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4,...
[ { "docstring": null, "function_declaration": "def merge_sort(lst):", "function_name": "merge_sort", "parameter_list": "(lst)" }, { "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(lst: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in ascending order using the merge sort algorit...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006513", "row_id": 6513, "seed_ids": "[4332]" }
0.646861
Algorithm_6513
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7d36f8aeb11c5ce21b348d95ea2ac29544634cc8
cfc6b10019c818058911d6d596501c97e7ceba3d
v1.0
instruct
Algorithm
Algorithm_6518_I
**[Question 2]:** You are tasked with implementing a task scheduling function that organizes a list of tasks to be executed in a way that minimizes the total time. Each task has a specific duration, and certain tasks cannot start until others are completed. This is a classic instance of the "task scheduling problem" wi...
from typing import List, Dict from collections import deque, defaultdict def topological_sort(tasks: List[str], dependencies: Dict[str, List[str]]) -> List[str]: # Building adjacency list and in-degree counts adj_list = defaultdict(list) in_degree = {task: 0 for task in tasks} for task, deps in de...
from solution import schedule_tasks def test_basic_schedule(): tasks = ["A", "B", "C", "D", "E"] durations = {"A": 3, "B": 2, "C": 1, "D": 4, "E": 1} dependencies = { "B": ["A"], "C": ["A"], "D": ["B", "C"], "E": ["D"] } n = 2 result = schedule_tasks(tasks, durations, de...
[ { "docstring": null, "function_declaration": "def topological_sort(tasks, dependencies):", "function_name": "topological_sort", "parameter_list": "(tasks, dependencies)" }, { "docstring": null, "function_declaration": "def schedule_tasks(tasks, durations, dependencies, n):", "functio...
[ 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Tuple\nfrom collections import deque, defaultdict\n\ndef topological_sort(tasks: List[str], dependencies: Dict[str, List[str]]) ->...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000006518", "row_id": 6518, "seed_ids": "[1907]" }
0.561458
Algorithm_6518
I
[ "topological_sort", "schedule_tasks" ]
2
[ [ "schedule_tasks", "topological_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cf8c3fb1a4da48dd2875b8f60bcfb80f802d6761
c795ddfc7f0cb478434976fc860852c51f60db1a
v1.0
instruct
Algorithm
Algorithm_6578_I
### Matrix Rotation Checker You are working as a software developer for a company that specializes in image processing. One common operation is rotating images represented as 2D matrices. Your task is to determine whether a given 2D matrix is a rotation (by 90, 180, or 270 degrees) of another 2D matrix. **Problem Sta...
from typing import List def rotate_90(mat: List[List[int]]) -> List[List[int]]: return [list(reversed(col)) for col in zip(*mat)] def rotate_180(mat: List[List[int]]) -> List[List[int]]: return rotate_90(rotate_90(mat)) def rotate_270(mat: List[List[int]]) -> List[List[int]]: return rotate_90(rotate_180(...
from solution import is_rotation def test_is_rotation_90_degrees(): mat1 = [ [1, 2], [3, 4] ] mat2 = [ [3, 1], [4, 2] ] assert is_rotation(mat1, mat2) def test_is_rotation_180_degrees(): mat1 = [ [1, 2], [3, 4] ] mat2 = [ [4, 3], ...
[ { "docstring": null, "function_declaration": "def rotate_90(mat):", "function_name": "rotate_90", "parameter_list": "(mat)" }, { "docstring": null, "function_declaration": "def rotate_180(mat):", "function_name": "rotate_180", "parameter_list": "(mat)" }, { "docstring": n...
[ 0, 1, 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": "from typing import List\n\ndef rotate_90(mat: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates the matrix 90 degrees clockwise.\n \"\"\"\n n =...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006578", "row_id": 6578, "seed_ids": "[915]" }
0.513633
Algorithm_6578
I
[ "rotate_90", "rotate_180", "rotate_270", "is_rotation" ]
4
[ [ "is_rotation", "rotate_180" ], [ "is_rotation", "rotate_270" ], [ "is_rotation", "rotate_90" ], [ "rotate_180", "rotate_90" ], [ "rotate_270", "rotate_180" ], [ "rotate_270", "rotate_90" ] ]
6
[]
false
[]
false
pytest
true
[]
true
50e83bce976ab926f31afe1f17c83eb5876bf4a2
3c6fbf055f97b905b236e881b83e30707c033b46
v1.0
instruct
Algorithm
Algorithm_6604_I
### Matrix Rotation and Image Transformation You are tasked with implementing functionality for rotating a matrix and applying that transformation to an image. Specifically, you need to create a function that rotates a given NxM matrix clockwise by 90 degrees and another function that uses this to rotate an image (rep...
def rotate_matrix_90_clockwise(matrix: list[list[int]]) -> list[list[int]]: """ Rotates a given NxM matrix 90 degrees clockwise. """ # Transpose the matrix transposed_matrix = list(zip(*matrix)) # Reverse each row of the transposed matrix to get the rotated matrix rotated_matrix = [list(reve...
from solution import rotate_matrix_90_clockwise, rotate_image_90_clockwise def test_rotate_matrix_90_clockwise_3x3(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] expected = [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] assert rotate_matrix_90_clockwise(matrix)...
[ { "docstring": "Rotates a given NxM matrix 90 degrees clockwise.", "function_declaration": "def rotate_matrix_90_clockwise(matrix):", "function_name": "rotate_matrix_90_clockwise", "parameter_list": "(matrix)" }, { "docstring": "Rotates a given image (represented as a 2D list of integers) 90...
[ 1, 1, 1, 0, 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": "def rotate_matrix_90_clockwise(matrix: list[list[int]]) -> list[list[int]]:\n \"\"\"\n Rotates the provided NxM matrix 90 degrees clockwise.\n \n Arg...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006604", "row_id": 6604, "seed_ids": "[1870]" }
0.590233
Algorithm_6604
I
[ "rotate_matrix_90_clockwise", "rotate_image_90_clockwise" ]
2
[ [ "rotate_image_90_clockwise", "rotate_matrix_90_clockwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cdbd1912953474812ef3462b7a99211012d28aae
ef6b992dd3661596080d579b7f0b66dea0c3abe9
v1.0
instruct
Algorithm
Algorithm_6717_I
### Binary Search Tree Insertion and Balancing You are given a Binary Search Tree (BST) and a series of nodes to be inserted into the tree. Your task is to insert the nodes one by one and ensure the tree remains balanced. A BST is balanced if the height of the two subtrees of any node differ by no more than one. ### ...
class TreeNode: def __init__(self, key): self.left = None self.right = None self.val = key def height(node): return 0 if node is None else max(height(node.left), height(node.right)) + 1 def get_balance(node): return 0 if node is None else height(node.left) - height(node.right) def...
from solution import TreeNode, balanced_insert def test_balanced_insert_single(): root = None keys = [10] new_root = balanced_insert(root, keys) assert new_root.val == 10 assert new_root.left is None assert new_root.right is None def test_balanced_insert_multiple(): root = None key...
[]
[ 1, 0, 1, 0, 1, 0, 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": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef height(node):\n if node is N...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000006717", "row_id": 6717, "seed_ids": "[5244]" }
0.648356
Algorithm_6717
I
[ "height", "get_balance", "right_rotate", "left_rotate", "insert_node", "balanced_insert" ]
6
[ [ "balanced_insert", "insert_node" ], [ "get_balance", "height" ], [ "insert_node", "get_balance" ], [ "insert_node", "left_rotate" ], [ "insert_node", "right_rotate" ] ]
5
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
22218d49df51cd1408e50bb5d3df403db749d25c
7e69ccdce6f57e31eaa0111c603e3ddc680d37fb
v1.0
instruct
Algorithm
Algorithm_6732_I
### Scenario: You are tasked with developing a basic command-line tool to help software engineers track their daily coding activities. The tool tracks the time spent on different programming projects and generates daily reports. ### Task: Implement a command-line tool that allows users to log the start and end times f...
import json import os from datetime import datetime, timedelta from collections import defaultdict SESSIONS_FILE = "sessions.json" def load_sessions(): if os.path.exists(SESSIONS_FILE): with open(SESSIONS_FILE, "r") as file: return json.load(file) return {} def save_sessions(sessions): ...
import os import json from datetime import datetime, timedelta from solution import start_session, stop_session, generate_report, load_sessions, save_sessions, SESSIONS_FILE def test_start_stop_session(): if os.path.exists(SESSIONS_FILE): os.remove(SESSIONS_FILE) start_session('TestProject') s...
[ { "docstring": null, "function_declaration": "def load_sessions():", "function_name": "load_sessions", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def save_sessions(sessions):", "function_name": "save_sessions", "parameter_list": "(sessions)" }, { ...
[ 0, 1, 0, 0, 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": "import json\nimport os\nfrom datetime import datetime, timedelta\n\nDATA_FILE = 'coding_sessions.json'\n\ndef load_data():\n if not os.path.exists(DATA_FILE):...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000006732", "row_id": 6732, "seed_ids": "[4169]" }
0.569127
Algorithm_6732
I
[ "load_sessions", "save_sessions", "start_session", "stop_session", "generate_report" ]
5
[ [ "generate_report", "load_sessions" ], [ "start_session", "load_sessions" ], [ "start_session", "save_sessions" ], [ "stop_session", "load_sessions" ], [ "stop_session", "save_sessions" ] ]
5
[]
false
[]
false
pytest
true
[]
true
24da4c0158d3d2540b4cdc986d2e9aa9b2e53d32
21fb51ea12113de9a15b688070bde5962b4ee2b8
v1.0
instruct
Algorithm
Algorithm_6739_I
### Coding Assessment Question Graph traversal algorithms are crucial for understanding the structure and properties of graph-based systems, like social networks, transportation grids, and web crawlers. Depth-First Search (DFS) is one such algorithm that explores as far as possible along each branch before backtrackin...
from typing import List, Dict, Set def depth_first_search(graph: Dict[int, List[int]], start: int, visited: Set[int]) -> List[int]: visited.add(start) components = [start] for neighbor in graph[start]: if neighbor not in visited: components.extend(depth_first_search(graph, neighbor, vis...
from solution import depth_first_search, find_connected_components def test_simple_graph(): graph = { 0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2, 4], 4: [3] } assert find_connected_components(graph) == [[0, 1, 3, 2, 4]] def test_disjoint_graph(): graph = { ...
[ { "docstring": null, "function_declaration": "def depth_first_search(graph, start, visited):", "function_name": "depth_first_search", "parameter_list": "(graph, start, visited)" }, { "docstring": null, "function_declaration": "def find_connected_components(graph):", "function_name": ...
[ 1, 0, 1, 1, 1, 1, 0, 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": "from typing import List, Dict\n\ndef depth_first_search(graph: Dict[int, List[int]], start: int, visited: set) -> List[int]:\n \"\"\"\n Perform DFS recursi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006739", "row_id": 6739, "seed_ids": "[4819]" }
0.549658
Algorithm_6739
I
[ "depth_first_search", "find_connected_components" ]
2
[ [ "find_connected_components", "depth_first_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a4008b0b9fa9dfbcd1204a6610ccad0dc3cfb09
5cf13b11a74d34666471d9ce9d05d17924c5d189
v1.0
instruct
Algorithm
Algorithm_6778_I
### Coding Question: Prime Number and Factorial Analysis #### Objective: You are given two functions: one that checks if a number is prime, and another that computes the factorial of a number. Your task is to enhance these functions and write a new function that works with both to solve a given problem. #### Problem ...
import math def is_prime(number): """ Check if a number is a prime number. """ if number < 2: return False for i in range(2, int(math.sqrt(number)) + 1): if number % i == 0: return False return True def compute_factorial(number): """ Compute the factorial of...
from solution import analyze_number def test_analyze_number_prime_and_factorial(): assert analyze_number(5) == (True, 120) assert analyze_number(7) == (True, 5040) def test_analyze_number_non_prime_and_factorial(): assert analyze_number(4) == (False, 24) assert analyze_number(8) == (False, 40320) def...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Compute the factorial of a number.", "function_declaration": "def compute_factorial(number):", "functio...
[ 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 is_prime(number):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if number <= 1:\n return False\n if number == 2:\n return Tr...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006778", "row_id": 6778, "seed_ids": "[4064]" }
0.659893
Algorithm_6778
I
[ "is_prime", "compute_factorial", "analyze_number" ]
3
[ [ "analyze_number", "compute_factorial" ], [ "analyze_number", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
41c34bb8c16b3aa6d3d1c093f37e11584f55b5b3
9c8551a75f1ae0426c118696902c05722bfa7380
v1.0
instruct
Algorithm
Algorithm_6807_I
### Network Optimization As a network administrator, you are tasked with optimizing the network routes within a large corporation. The corporation's network can be represented as a directed graph where nodes represent devices, and edges represent the direct communication links between them. You need to identify the op...
import heapq from typing import Dict, List, Tuple def shortest_path(graph: Dict[int, List[Tuple[int, int]]], start: int, end: int) -> List[int]: """ Returns the shortest path from start to end node using Dijkstra's algorithm. """ # Priority queue for Dijkstra's algorithm pq = [(0, start)] dista...
from solution import shortest_path, detect_cycles, optimize_network def test_shortest_path(): network = { 0: [(1, 2), (2, 4)], 1: [(2, 1), (3, 7)], 2: [(4, 3)], 3: [(4, 1)], 4: [] } assert shortest_path(network, 0, 4) == [0, 1, 2, 4] assert shortest_path(network,...
[ { "docstring": "Returns the shortest path from start to end node using Dijkstra's algorithm.", "function_declaration": "def shortest_path(graph, start, end):", "function_name": "shortest_path", "parameter_list": "(graph, start, end)" }, { "docstring": "Returns True if there is a cycle in the...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict, deque\n\ndef shortest_path(graph, start, end):\n \"\"\"\n Returns the shortest path from start to end us...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000006807", "row_id": 6807, "seed_ids": "[533]" }
0.641442
Algorithm_6807
I
[ "shortest_path", "detect_cycles", "optimize_network" ]
3
[ [ "optimize_network", "detect_cycles" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c9a6b6fce1e13c3dc093012c0c4756c56f656379
b9a25296c1251f9dc0cd506713fbfa2918d1cee4
v1.0
instruct
Algorithm
Algorithm_6964_I
### Coding Assessment: Genetic Algorithm for TSP #### Problem Statement You are provided with an implementation of a Genetic Algorithm (GA) for the Traveling Salesman Problem (TSP). Your task is to implement a similar optimization algorithm but for a multi-objective optimization problem. #### Objectives 1. Implement ...
import random from typing import List, Callable, Any, Tuple class MultiObjectiveProblem: def __init__(self, objectives: List[Callable], population: List[Any], mutation_rate: float, crossover_rate: float): self.objectives = objectives self.population = population self.mutation_rate = mutatio...
import pytest def test_multiobjective_genetic_algorithm(): def objective1(solution): return sum(x**2 for x in solution) def objective2(solution): return sum((x - 2)**2 for x in solution) initial_population = [[random.uniform(-10, 10) for _ in range(3)] for _ in range(50)] multi_obj_p...
[]
[ 0, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Callable, Tuple, Any\n\nclass MultiObjectiveProblem:\n def __init__(self, objectives: List[Callable], population: List...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000006964", "row_id": 6964, "seed_ids": "[4933]" }
0.497073
Algorithm_6964
I
[ "dominates", "genetic_algorithm_multi_objective" ]
2
[ [ "genetic_algorithm_multi_objective", "dominates" ] ]
1
[]
false
[ "MultiObjectiveProblem" ]
true
pytest
false
[]
true
ee2b030b6323070ac4b00dfea651109f8ed7fc89
9e8119b4149ebfee11f91b559c99922d784f018a
v1.0
instruct
Algorithm
Algorithm_6972_I
### Conway's Game of Life with Custom Initial State You are given a skeleton code to simulate Conway's Game of Life, which is a cellular automaton where cells evolve based on their neighbors' states. The board is represented as a 2D grid of cells that are either alive (1) or dead (0). Cells evolve according to the fol...
def count_live_neighbors(board: list[list[int]], row: int, col: int) -> int: directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] live_neighbors = 0 for dr, dc in directions: rr = (row + dr) % len(board) cc = (col + dc) % len(board[0]) live_neighbors +=...
def test_next_generation(): # Block pattern (still life) initial_state = [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0] ] expected_next_state = [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0] ] assert next_generat...
[ { "docstring": null, "function_declaration": "def count_live_neighbors(board, row, col):", "function_name": "count_live_neighbors", "parameter_list": "(board, row, col)" }, { "docstring": null, "function_declaration": "def next_generation(board):", "function_name": "next_generation",...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def count_live_neighbors(board, row, col):\n directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n live_neighbors = 0\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000006972", "row_id": 6972, "seed_ids": "[4787]" }
0.58554
Algorithm_6972
I
[ "count_live_neighbors", "next_generation", "initialize_board" ]
3
[ [ "next_generation", "count_live_neighbors" ] ]
1
[]
false
[]
false
pytest
false
[]
true
906f649c2f08427695e08ecfdd08fad373b70574
efd1fb54657f0d48deb74fa1e1b53e98fc619dc3
v1.0
instruct
Algorithm
Algorithm_6989_I
### Question: Extract and Display Weather Information You are tasked with creating a program that fetches and displays current weather information using the OpenWeatherMap API. Your program should include the following functionalities: 1. **Get current weather by city name**: Access the appropriate endpoint to get th...
import requests # Remember to replace 'your_api_key' with your actual OpenWeatherMap API key. API_KEY = 'your_api_key' BASE_URL = 'http://api.openweathermap.org/data/2.5/weather' def get_weather_by_city(city_name: str) -> dict: try: response = requests.get( BASE_URL, params={'q': c...
import pytest from unittest.mock import patch from solution import get_weather_by_city, get_weather_for_cities @patch('solution.requests.get') def test_get_weather_by_city(mock_get): mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = { 'weather': [{'description': 'clear ...
[ { "docstring": null, "function_declaration": "def get_weather_by_city(city_name):", "function_name": "get_weather_by_city", "parameter_list": "(city_name)" }, { "docstring": null, "function_declaration": "def get_weather_for_cities(cities):", "function_name": "get_weather_for_cities"...
[ 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": "import requests\n\nAPI_KEY = 'your_api_key' # Replace this with your actual OpenWeatherMap API key\nBASE_URL = 'http://api.openweathermap.org/data/2.5/weather'\...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000006989", "row_id": 6989, "seed_ids": "[1924]" }
0.55499
Algorithm_6989
I
[ "get_weather_by_city", "get_weather_for_cities" ]
2
[ [ "get_weather_for_cities", "get_weather_by_city" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
1d14601f7308bc5e122f3950523b6d222e2b81c1
16272da5a5f5dc7eb7942dc8063752166452b5a6
v1.0
instruct
Algorithm
Algorithm_7003_I
### Question: You are tasked with implementing a function `find_largest_rectangle(matrix: List[List[int]]) -> int` that finds the area of the largest rectangle containing all 1's in a given binary matrix. To solve this, follow these instructions: 1. Define a helper function `largest_histogram_area(heights: List[int]...
from typing import List def largest_histogram_area(heights: List[int]) -> int: """ Helper function to compute the largest rectangle area in a histogram given the heights of the bars. """ stack = [] max_area = 0 index = 0 while index < len(heights): if not stack or heights[stack[-1]...
def test_largest_histogram_area(): assert largest_histogram_area([2, 1, 5, 6, 2, 3]) == 10 assert largest_histogram_area([6, 2, 5, 4, 5, 1, 6]) == 12 def test_find_largest_rectangle_empty_matrix(): assert find_largest_rectangle([]) == 0 def test_find_largest_rectangle_zero_matrix(): assert find_larges...
[ { "docstring": "Helper function to compute the largest rectangle area in a histogram given the heights of the bars.", "function_declaration": "def largest_histogram_area(heights):", "function_name": "largest_histogram_area", "parameter_list": "(heights)" }, { "docstring": "Function to find t...
[ 0, 1, 1, 0, 1, 0, 1, 0, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl", "solution_code": "from typing import List\n\ndef largest_histogram_area(heights: List[int]) -> int:\n stack = []\n max_area = 0\n index = 0\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007003", "row_id": 7003, "seed_ids": "[4750]" }
0.705511
Algorithm_7003
I
[ "largest_histogram_area", "find_largest_rectangle" ]
2
[ [ "find_largest_rectangle", "largest_histogram_area" ] ]
1
[]
false
[]
false
pytest
false
[]
true
5a3f10dfa56a4e2d2b159de76eedf09232477cc7
5da42fa6712fa74440d2997e2fb22c4a2f102f2d
v1.0
instruct
Algorithm
Algorithm_7009_I
### Implement A* Pathfinding Algorithm You are given an unweighted grid where `0` denotes a free path, and `1` denotes an obstacle. Your task is to find the shortest path between a start position and a goal position using the A* Pathfinding Algorithm. **Implement the function `astar_pathfinding(grid: List[List[int]],...
from typing import List, Tuple import heapq def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int: """Calculate the Manhattan distance between points a and b.""" return abs(a[0] - b[0]) + abs(a[1] - b[1]) def astar_pathfinding(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> Lis...
def test_astar_path_simple_grid(): grid = [ [0, 0, 0], [0, 1, 0], [0, 0, 0] ] start = (0, 0) goal = (2, 2) expected_path = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)] assert astar_pathfinding(grid, start, goal) == expected_path def test_astar_path_complex_grid(): grid =...
[ { "docstring": "Calculate the Manhattan distance between points a and b.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Find the shortest path in an unweighted grid using the A* algorithm.", "function_declarat...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nfrom heapq import heappop, heappush\n\ndef astar_pathfinding(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000007009", "row_id": 7009, "seed_ids": "[5186]" }
0.655073
Algorithm_7009
I
[ "heuristic", "astar_pathfinding" ]
2
[ [ "astar_pathfinding", "heuristic" ] ]
1
[]
false
[]
false
pytest
false
[]
true
8be2c15f4ee5690e9d5e4edc965faa4c20a40faf
eeb59ca3f6b6090e3a4f6da1727d3123d58f99cb
v1.0
instruct
Algorithm
Algorithm_7024_I
### Coding Assessment Question #### Context: You are tasked with improving the backend performance of a social media application by optimizing the way it handles user notifications. The current system delivers notifications sequentially, causing delays. To offer a better user experience, the notification delivery syst...
import aiohttp import asyncio async def notify_user(user_id, message): url = f"http://notification.service/send?user={user_id}&message={message}" async with aiohttp.ClientSession() as session: for attempt in range(3): # up to 2 retries try: async with session.get(url) as re...
import pytest from unittest.mock import patch, AsyncMock import asyncio from solution import send_notifications @pytest.mark.asyncio async def test_send_notifications_all_success(): users = [1, 2, 3] message = "Test Message" with patch('solution.notify_user', AsyncMock(return_value='success')): ...
[]
[ 0, 0, 1, 1, 1, 1, 0, 0, 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 asyncio\nimport aiohttp\nfrom aiohttp import ClientResponseError\n\nasync def send_notification(user, message):\n \"\"\"\n Simulate the notification...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000007024", "row_id": 7024, "seed_ids": "[1990]" }
0.557681
Algorithm_7024
I
[ "notify_user", "send_notifications" ]
2
[ [ "send_notifications", "notify_user" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
9644e76bf96fe42c4a3c27f81b47360d61a66665
9b1d69f9f601c3490660c647cee9c4d27121a5a2
v1.0
instruct
Algorithm
Algorithm_7028_I
### Binary Search Tree Median You are tasked with writing a function to find the median value in a Binary Search Tree (BST). A BST is a tree structure where each node has at most two children, and for every node, the left subtree's values are less than the node's value, and the right subtree's values are greater than ...
class TreeNode: def __init__(self, value: int) -> None: self.value = value self.left = None self.right = None def inorder_traversal(root: TreeNode) -> list: """ Perform an in-order traversal of the BST and return the elements in sorted order. """ if not root: return ...
from solution import TreeNode, find_bst_median def test_find_bst_median_odd_nodes(): root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(6) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(5) root.right.right = TreeNode(7) assert fi...
[]
[ 1, 0, 1, 1, 1, 1, 0, 0, 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": "class TreeNode:\n def __init__(self, value: int) -> None:\n self.value = value\n self.left = None\n self.right = None\n\ndef inorder_trav...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000007028", "row_id": 7028, "seed_ids": "[3293]" }
0.63214
Algorithm_7028
I
[ "inorder_traversal", "find_bst_median" ]
2
[ [ "find_bst_median", "inorder_traversal" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
4c425ff62c160940a2a600549ea52da356c5a617
ddebc0a526a6a9ed231be079e1da19c3ce37a392
v1.0
instruct
Algorithm
Algorithm_7042_I
### Coding Assessment Question You are tasked with implementing a basic version of the A* search algorithm to find the shortest path between two nodes in a given weighted grid. The goal is to navigate through a `m x n` grid where some cells can have varying weights, representing different terrains or obstacles. ### R...
import heapq from typing import List, Tuple, Dict def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int: """ Calculate the Manhattan distance heuristic for A* search. """ return abs(a[0] - b[0]) + abs(a[1] - b[1]) def a_star_search(grid: List[List[int]], start: Tuple[int, int], end: Tuple[int, ...
from solution import a_star_search def test_a_star_search_basic(): grid = [ [1, 1, 1, 1], [1, 9, 9, 1], [1, 1, 1, 1], ] start = (0, 0) end = (2, 3) assert a_star_search(grid, start, end) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3)] def test_a_star_search_no_path(): ...
[ { "docstring": "Calculate the Manhattan distance heuristic for A* search.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Implements the A* search algorithm to find the shortest path in a weighted grid.", "func...
[ 0, 0, 1, 0, 0, 0, 0, 1, 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 heapq\nfrom typing import List, Tuple\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007042", "row_id": 7042, "seed_ids": "[4394]" }
0.580463
Algorithm_7042
I
[ "heuristic", "a_star_search" ]
2
[ [ "a_star_search", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0c8ec86d9f5364b10262f95cb157f7f8449138cb
fdd3ea1ba1dcf19dcbd5a686becd5b41c522f066
v1.0
instruct
Algorithm
Algorithm_7120_I
### Problem Statement: Least Common Multiple (LCM) of Multiple Numbers Context: Calculating the Least Common Multiple (LCM) of two numbers is a common task in programming. This problem extends that concept to finding the LCM of multiple numbers. The LCM of a set of integers is the smallest positive integer that is eve...
from typing import List import math from functools import reduce def lcm(a, b): return abs(a * b) // math.gcd(a, b) def find_lcm(numbers: List[int]) -> int: return reduce(lcm, numbers)
from solution import find_lcm def test_find_lcm_simple_case(): assert find_lcm([4, 6, 8]) == 24 def test_find_lcm_prime_numbers(): assert find_lcm([2, 5, 7, 11]) == 770 def test_find_lcm_multiples(): assert find_lcm([10, 20, 30, 40]) == 120 def test_find_lcm_consecutive_numbers(): assert find_lcm([1...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def find_lcm(numbers):", "function_name": "find_lcm", "parameter_list": "(numbers)" } ]
[ 0, 1, 0, 1, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport math\nfrom functools import reduce\n\ndef find_lcm(numbers: List[int]) -> int:\n \"\"\"\n Calculates the LCM of a list of i...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007120", "row_id": 7120, "seed_ids": "[3425]" }
0.709117
Algorithm_7120
I
[ "lcm", "find_lcm" ]
2
[ [ "find_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4e18b481aeef96acc10d3f66e66741421f2cca1c
2adac921fee21d172f8859c44be60a4aedbe34f7
v1.0
instruct
Algorithm
Algorithm_7121_I
### Question: Calculate Loan Repayment Details You are asked to write three functions to calculate different aspects of loan repayment: monthly payment, total payment over the loan term, and the breakdown of interest paid vs. principal repaid in each payment. Each function should handle various input validations and r...
def monthly_payment(principal: float, annual_interest_rate: float, loan_term_years: float) -> float: """ Calculate the monthly loan payment. :param principal: The initial amount of the loan. :param annual_interest_rate: The annual interest rate as a percentage. :param loan_term_years: The duration ...
import pytest from solution import monthly_payment, total_payment, repayment_schedule def test_monthly_payment(): assert pytest.approx(monthly_payment(100000, 5, 30), 0.01) == 536.82 assert pytest.approx(monthly_payment(200000, 3.5, 15), 0.01) == 1427.53 assert pytest.approx(monthly_payment(150000, 0, 30),...
[ { "docstring": "Calculate the monthly loan payment.\n\n:param principal: The initial amount of the loan.\n:param annual_interest_rate: The annual interest rate as a percentage.\n:param loan_term_years: The duration of the loan in years.\n:return: The monthly payment amount.", "function_declaration": "def mo...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef monthly_payment(principal: float, annual_interest_rate: float, loan_term_years: float) -> float:\n if principal <= 0 or ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000007121", "row_id": 7121, "seed_ids": "[5350]" }
0.512824
Algorithm_7121
I
[ "monthly_payment", "total_payment", "repayment_schedule" ]
3
[ [ "repayment_schedule", "monthly_payment" ], [ "total_payment", "monthly_payment" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c8522bb6f7f9a4a0bb55758a32a34bd21d2f0d74
aecaa78c863d1f3d220091753e3430ff89b64672
v1.0
instruct
Algorithm
Algorithm_7147_I
### Question You 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. #### Dataset Preparation 1. Download the dataset from the link: [Mall Customer Segmentation Data](https://www....
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": "", "prompt_id": "0000007147", "row_id": 7147, "seed_ids": "[4718]" }
0.652097
Algorithm_7147
I
[ "k_means_clustering", "plot_elbow_method", "plot_clusters" ]
3
[ [ "plot_elbow_method", "k_means_clustering" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
203505f3581621ee4db4d61c560de67f791932e6
75d6b5b25e568900500b12d726dc283fecb72742
v1.0
instruct
Algorithm
Algorithm_7163_I
### Problem Statement You are tasked to enhance a weather forecasting application by integrating a real-time weather API. The application should fetch the 7-day weather forecast for a given city and ensure the data is accurate and readily available. ### Objective Implement a function `get_weekly_forecast` that: 1. Fet...
import aiohttp import asyncio API_KEY = 'your_api_key_here' # Replace with your API key BASE_URL = 'https://api.openweathermap.org/data/2.5/onecall' async def fetch_forecast(session, lat, lon): params = { 'lat': lat, 'lon': lon, 'exclude': 'current,minutely,hourly,alerts', 'units'...
import pytest import asyncio from unittest.mock import patch, AsyncMock from solution import get_weekly_forecast # Sample data for testing sample_coords_response = [{'lat': 40.712776, 'lon': -74.005974}] sample_forecast_response = { 'daily': [ {'dt': '2023-10-01', 'temp': {'day': 18}, 'weather': [{'descri...
[]
[ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\n\nAPI_KEY = 'your_api_key' # Replace with a valid API key\nBASE_URL = 'http://api.openweathermap.org/data/2.5/forecast/daily'\n\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007163", "row_id": 7163, "seed_ids": "[2277]" }
0.596039
Algorithm_7163
I
[ "fetch_forecast", "get_coordinates", "get_weekly_forecast" ]
3
[ [ "get_weekly_forecast", "fetch_forecast" ], [ "get_weekly_forecast", "get_coordinates" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
314db2525d15b0809eb76908035e8251282a8573
8dfa5df94b181f1e49c14c2750ff7edd1bf787ff
v1.0
instruct
Algorithm
Algorithm_7208_I
### Problem Statement A Fibonacci prime is a Fibonacci number that is also a prime number. The Fibonacci sequence is defined as follows: \[ F_0 = 0, \quad F_1 = 1, \quad F_n = F_{n-1} + F_{n-2} \quad \text{for} \quad n \geq 2 \] Write a function to find the \(N\)-th Fibonacci prime number. ### Requirements 1. Implemen...
def generate_fibonacci(): """ A generator to yield Fibonacci numbers. """ a, b = 0, 1 while True: yield a a, b = b, a + b def is_prime(n: int) -> bool: """ Check if a number is prime. """ if n < 2: return False if n == 2: return True if n % 2 ...
from solution import is_prime, nth_fibonacci_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-3) == False def test_nth_fibonacci_...
[ { "docstring": "A generator to yield Fibonacci numbers.", "function_declaration": "def generate_fibonacci():", "function_name": "generate_fibonacci", "parameter_list": "()" }, { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "...
[ 0, 0, 1, 0, 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": "def is_prime(n: int) -> bool:\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007208", "row_id": 7208, "seed_ids": "[2946]" }
0.843521
Algorithm_7208
I
[ "generate_fibonacci", "is_prime", "nth_fibonacci_prime" ]
3
[ [ "nth_fibonacci_prime", "generate_fibonacci" ], [ "nth_fibonacci_prime", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
247a9028b1f125e02a0deae227e261e9e164e171
df1c1a2705db82d1d270c105e79010e27b6641cc
v1.0
instruct
Algorithm
Algorithm_7269_I
### Problem Statement You have been tasked with enhancing the current algorithm used to analyze and summarize movie reviews. The existing implementation reads reviews from a text file, processes the content, and generates a summary. Your goal is to optimize this process by leveraging concurrency to handle multiple revi...
import asyncio from concurrent.futures import ProcessPoolExecutor import os def process_review(review): """ A mock function to process individual reviews. In a real scenario, this function would have a more complex implementation to create a summary. """ return review.strip().split()[0] # just a ...
import pytest import asyncio import os from solution import summarize_movie_reviews @pytest.fixture(scope="module") def sample_reviews(tmpdir_factory): reviews = [ "This is the first review.\nIt's quite informative.", "Second review here.\nIt is more concise.", "Here is the third review.\n...
[ { "docstring": "A mock function to process individual reviews. In a real scenario, \nthis function would have a more complex implementation to create a summary.", "function_declaration": "def process_review(review):", "function_name": "process_review", "parameter_list": "(review)" } ]
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiofiles\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef summarize_review(review):\n \"\"\"\n This is a placeholder for th...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000007269", "row_id": 7269, "seed_ids": "[2277]" }
0.539311
Algorithm_7269
I
[ "process_review", "read_reviews", "summarize_movie_reviews" ]
3
[ [ "summarize_movie_reviews", "process_review" ], [ "summarize_movie_reviews", "read_reviews" ] ]
2
[]
false
[]
false
pytest
true
[]
true
39ed607bb360bacc3aaaa7c01d3e11ef7f9115e8
28c4582fed036274ccdcb0700d4bdbfe1c8a73d9
v1.0
instruct
Algorithm
Algorithm_7274_I
### Concurrent Prime Number Generator You 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 of `n`. #### Function Specifi...
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": "", "prompt_id": "0000007274", "row_id": 7274, "seed_ids": "[4273]" }
0.616594
Algorithm_7274
I
[ "is_prime", "worker", "generate_primes" ]
3
[ [ "worker", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a5514a5d4f6f2db7ca6f97f76be86776035c9bdc
1e0e70ec4ae60c9019fb2d2a46f60ec02612e4be
v1.0
instruct
Algorithm
Algorithm_7276_I
### Context: You need to implement a feature in a file synchronization program to ensure that a directory's content is up-to-date with a source directory. The program should compare files based on their last modified timestamps and update the target directory with the newest files from the source directory. Additional ...
import os import shutil import logging from datetime import datetime # Setting up logging configuration logging.basicConfig(filename='sync_log.log', level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') def compare_and_sync(source, target): """ Compare and s...
import os import pytest import shutil from datetime import datetime, timedelta from solution import compare_and_sync, log_sync_event def setup_test_directories(source_structure, target_structure): """ Helper function to set up test directories based on given structures. """ for root, files in source_st...
[ { "docstring": "Compare and synchronize target directory to match source directory.", "function_declaration": "def compare_and_sync(source, target):", "function_name": "compare_and_sync", "parameter_list": "(source, target)" }, { "docstring": "Log the synchronization event.", "function_d...
[ 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import os\nimport shutil\nimport logging\nfrom datetime import datetime\n\n# Setting up logging configuration\nlogging.basicConfig(filename='sync_log.log', level...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000007276", "row_id": 7276, "seed_ids": "[4235]" }
0.557447
Algorithm_7276
I
[ "compare_and_sync", "log_sync_event", "example" ]
3
[ [ "compare_and_sync", "log_sync_event" ], [ "example", "compare_and_sync" ] ]
2
[]
false
[]
false
pytest
true
[]
true
09166da3a4bc29bfc049c28a95be59debb70d331
cccb1af90949cb7038115eb53974adf2c17b8eb3
v1.0
instruct
Algorithm
Algorithm_7288_I
### Coding Question #### Context Sorting arrays is a fundamental task in computer science. One of the commonly used algorithms for sorting is the Merge Sort algorithm, which follows a divide-and-conquer approach to sort elements efficiently. Merge Sort works by: 1. Dividing the unsorted list into `n` sublists, each c...
def merge_sort(arr: list[int]) -> list[int]: """ Sorts a list 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 merge(lef...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_list(): assert merge_...
[ { "docstring": "Sorts a list 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, 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 merge_sort(arr: list[int]) -> list[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n rig...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007288", "row_id": 7288, "seed_ids": "[620]" }
0.697506
Algorithm_7288
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
31b42213d34ddf1922ec8fd634a6582a534077dc
c77e338f5ce0fc6e930a9bbec1c3013199e3d9c8
v1.0
instruct
Algorithm
Algorithm_7304_I
### Coding Assessment Question As a software engineer at a company that maintains historical weather data, you are required to improve the current system to provide enhanced weather insights. Your task involves fetching data from an archival weather API and performing various operations to ensure data accuracy and inc...
import requests import json import logging from datetime import datetime from dateutil.parser import parse as parse_date from statistics import mean from time import sleep # Setup logging logging.basicConfig(level=logging.INFO) def fetch_weather_data(retry_limit=3, url="https://archive-weather-api.com/data"): ret...
import pytest from solution import fetch_weather_data, display_weather, days_between_dates # Mocking requests to prevent actual API call from unittest.mock import patch sample_response = { "temperature": 25.3, "humidity": 80, "precipitation": 5.0, "historical_temperatures": [ {"date": "2023-01...
[ { "docstring": null, "function_declaration": "def fetch_weather_data(retry_limit=3, url='https://archive-weather-api.com/data'):", "function_name": "fetch_weather_data", "parameter_list": "(retry_limit=3, url='https://archive-weather-api.com/data')" }, { "docstring": null, "function_decl...
[ 0, 0, 1, 1, 0, 1, 1, 0, 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 requests\nfrom datetime import datetime\nimport logging\nfrom statistics import mean\n\n# Logging configuration\nlogging.basicConfig(filename='weather.log...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007304", "row_id": 7304, "seed_ids": "[2421]" }
0.472011
Algorithm_7304
I
[ "fetch_weather_data", "display_weather", "calculate_and_display_trends", "days_between_dates" ]
4
[ [ "display_weather", "calculate_and_display_trends" ], [ "display_weather", "fetch_weather_data" ] ]
2
[]
false
[]
false
pytest
true
[ "dateutil", "requests" ]
false
885e8cc569d35947725609ce9a197a4da5b0a3d1
ea3384e191f9046c72af3d5ee92246b9b33a58b2
v1.0
instruct
Algorithm
Algorithm_7422_I
### Matrix Determinant and Inverse Calculation You are required to implement functions to calculate the determinant and the inverse of a given square matrix. Ensure that your functions handle edge cases appropriately, such as non-invertible matrices. ### Matrix Determinant Implement a function `determinant(mat: list[...
def determinant(mat): """ Calculates the determinant of a square matrix. """ n = len(mat) if not all(len(row) == n for row in mat): raise ValueError("Matrix is not square") if n == 1: return mat[0][0] elif n == 2: return mat[0][0] * mat[1][1] - mat[0][1] * mat[1]...
from solution import determinant, inverse def test_determinant_2x2(): assert determinant([[1, 2], [3, 4]]) == -2 assert determinant([[4, 7], [2, 6]]) == 10 def test_determinant_3x3(): matrix = [ [6, 1, 1], [4, -2, 5], [2, 8, 7] ] assert determinant(matrix) == -306 def test...
[ { "docstring": "Calculates the determinant of a square matrix.", "function_declaration": "def determinant(mat):", "function_name": "determinant", "parameter_list": "(mat)" }, { "docstring": "Calculates the inverse of a square matrix.", "function_declaration": "def inverse(mat):", "fu...
[ 0, 1, 1, 0, 1, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def determinant(mat):\n \"\"\"\n Calculates the determinant of a given square matrix.\n \n :param mat: List of lists representing a square matrix.\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007422", "row_id": 7422, "seed_ids": "[5156]" }
0.498589
Algorithm_7422
I
[ "determinant", "inverse" ]
2
[ [ "inverse", "determinant" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0c306d2fa211858a5caa5d5349bd0fce1daf35ea
eb05ad13cc0aae33b8295d438423df923a9af864
v1.0
instruct
Algorithm
Algorithm_7423_I
### Question Write a function `convert_to_balanced_bst` that takes a sorted singly linked list representing the in-order traversal of a binary search tree (BST) and returns the root of a new BST that is height-balanced. **Function Signature**: ```python def convert_to_balanced_bst(head: ListNode) -> TreeNode: ``` **I...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def sorted_list_to_array(head: ListNode) -> list: array = [] ...
from solution import ListNode, TreeNode, convert_to_balanced_bst, inorder_traversal def test_convert_sorted_linked_list_to_balanced_bst(): # Linked list: -10 -> -3 -> 0 -> 5 -> 9 head = ListNode(-10, next=ListNode(-3, next=ListNode(0, next=ListNode(5, next=ListNode(9))))) root = convert_to_balanced_bst(hea...
[]
[ 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": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass TreeNode:\n def __init__(self, val=0, le...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007423", "row_id": 7423, "seed_ids": "[5042]" }
0.662616
Algorithm_7423
I
[ "sorted_list_to_array", "sorted_array_to_bst", "convert_to_balanced_bst", "inorder_traversal" ]
4
[ [ "convert_to_balanced_bst", "sorted_array_to_bst" ], [ "convert_to_balanced_bst", "sorted_list_to_array" ] ]
2
[]
false
[ "ListNode", "TreeNode" ]
true
pytest
true
[]
true
fbf64364494860d2ef0b6822c10e269177d3d051
bd6d0605e2ec4ed8011fdadd2051c36732e55a5c
v1.0
instruct
Algorithm
Algorithm_7442_I
### Coding Assessment Question **Problem Statement**: A hexagonal number is a figurate number of a hexagon. The nth hexagonal number \(H(n)\) is given by the formula `H(n) = n(2n - 1)`. The first few hexagonal numbers are: 1, 6, 15, 28, 45, 66, 91, 120, 153, 190, ... Interestingly, some hexagonal numbers are also tri...
def is_triangular(number: int) -> bool: # A number is triangular if and only if 8*number + 1 is a perfect square import math x = 8 * number + 1 sqrt_x = int(math.isqrt(x)) return sqrt_x * sqrt_x == x def find_triangular_hexagonal_numbers(n: int) -> list: result = [] index = 1 while...
from solution import find_triangular_hexagonal_numbers, is_triangular def test_single_triangular_hexagonal_number(): assert find_triangular_hexagonal_numbers(1) == [1] def test_three_triangular_hexagonal_numbers(): assert find_triangular_hexagonal_numbers(3) == [1, 6, 15] def test_five_triangular_hexagonal_n...
[ { "docstring": null, "function_declaration": "def is_triangular(number):", "function_name": "is_triangular", "parameter_list": "(number)" }, { "docstring": null, "function_declaration": "def find_triangular_hexagonal_numbers(n):", "function_name": "find_triangular_hexagonal_numbers",...
[ 1, 0, 1, 1, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def find_triangular_hexagonal_numbers(n: int) -> list:\n \"\"\"\n Find the first n hexagonal numbers that are also triangular numbers.\n Returns these n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000007442", "row_id": 7442, "seed_ids": "[2951]" }
0.725464
Algorithm_7442
I
[ "is_triangular", "find_triangular_hexagonal_numbers" ]
2
[ [ "find_triangular_hexagonal_numbers", "is_triangular" ] ]
1
[]
false
[]
false
pytest
true
[]
true
51db92b6881908b72eee3f50b3de5f89fbb22bc2
975428760bf90520dbcaa3c99c54495dd89f19ec
v1.0
instruct
Algorithm
Algorithm_7450_I
**Problem Statement:** You are given a singly linked list where each node contains an integer value. Your task is to implement a function that sorts the list using merge sort. The linked list should be sorted in non-decreasing order. ### Function Signature ```python class ListNode: def __init__(self, val=0, next=...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge_sort(head: ListNode) -> ListNode: if not head or not head.next: return head def split_list(node): slow = node fast = node.next while fast and fast.next: ...
from solution import ListNode, sort_linked_list def create_linked_list(arr): if not arr: return None head = ListNode(arr[0]) current = head for val in arr[1:]: current.next = ListNode(val) current = current.next return head def linked_list_to_list(head): result = [] ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef sort_linked_list(head: ListNode) -> ListNode:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007450", "row_id": 7450, "seed_ids": "[1125]" }
0.512863
Algorithm_7450
I
[ "merge_sort", "sort_linked_list" ]
2
[ [ "sort_linked_list", "merge_sort" ] ]
1
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
91789aa7c9326619efe34488c76d99b7b12dd54a
843ca9a2dc0c99e4dcd041e1c1eae0872e3cf5b4
v1.0
instruct
Algorithm
Algorithm_7460_I
### Problem Statement: You are given a string containing a sentence. Your task is to implement the following functions: 1. **`word_count`**: Compute the number of words in the sentence. 2. **`frequency_distribution`**: Calculate the frequency of each word in the sentence. 3. **`most_frequent_word`**: Identify the wor...
def word_count(sentence: str) -> int: """ Compute the number of words in the sentence. """ return len(sentence.split()) def frequency_distribution(sentence: str) -> dict: """ Calculate the frequency of each word in the sentence. """ words = sentence.split() freq = {} for word in...
from solution import word_count, frequency_distribution, most_frequent_word, reverse_sentence, capitalize_alternate_words def test_word_count(): assert word_count("the quick brown fox jumps over the lazy dog") == 9 assert word_count("hello world") == 2 assert word_count("one") == 1 def test_frequency_dist...
[ { "docstring": "Compute the number of words in the sentence.", "function_declaration": "def word_count(sentence):", "function_name": "word_count", "parameter_list": "(sentence)" }, { "docstring": "Calculate the frequency of each word in the sentence.", "function_declaration": "def freque...
[ 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 word_count(sentence: str) -> int:\n \"\"\"\n Compute the number of words in the sentence.\n \"\"\"\n words = sentence.split()\n return len(wor...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007460", "row_id": 7460, "seed_ids": "[3298]" }
0.730983
Algorithm_7460
I
[ "word_count", "frequency_distribution", "most_frequent_word", "reverse_sentence", "capitalize_alternate_words" ]
5
[ [ "most_frequent_word", "frequency_distribution" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5b9e7dc6388f7cd9d34e63256a50a3b459a13238
5173e7a0c4875ae87aa3d6cbac7fef54cd911e71
v1.0
instruct
Algorithm
Algorithm_7465_I
### Finding the Closest Pair of Points Given a list of points in a 2D plane, write a Python function to find the closest pair of points and return the distance between them. Implement the solution using an efficient divide-and-conquer algorithm. #### Function Signature ```python def closest_pair_of_points(points: Lis...
from typing import List, Tuple import math def euclidean_distance(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def closest_pair_of_points(points: List[Tuple[int, int]]) -> float: def closest_pair_recursive(px, py): if len(px) <= 3: return brute_force_closest_pair(...
from solution import closest_pair_of_points def test_closest_pair_basic(): points = [(1, 2), (3, 4), (5, 6), (7, 8)] assert closest_pair_of_points(points) == 2.828427 def test_closest_pair_with_duplicate_points(): points = [(1, 1), (4, 4), (7, 7), (1, 2)] assert closest_pair_of_points(points) == 1.000...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def closest_pair_of_points(points):", "function_name": "closest_pair_of_points", "p...
[ 1, 0, 0, 0, 1, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom typing import List, Tuple\n\ndef _euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\"\"\n Calculate the...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000007465", "row_id": 7465, "seed_ids": "[3432]" }
0.682375
Algorithm_7465
I
[ "euclidean_distance", "closest_pair_of_points" ]
2
[ [ "closest_pair_of_points", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eec2879531606846d636aa12950a88704c2037d2
2add3feb6a8895f80305806bf03c9c3904c63f26
v1.0
instruct
Algorithm
Algorithm_7515_I
### Classification Using Natural Language Processing (NLP) You are given a dataset containing customer reviews about a product along with their corresponding sentiment labels (positive or negative). Implement a function using Natural Language Processing (NLP) techniques to classify the sentiment of the reviews. Your t...
import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_pipeline from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score def preprocess...
from solution import nlp_sentiment_analysis import numpy as np def test_nlp_sentiment_analysis(): data = { "reviews": [ "This product is excellent! It exceeded my expectations.", "Awful experience. The product broke after two days.", "I am very happy with this purchase. ...
[ { "docstring": null, "function_declaration": "def preprocess_reviews(reviews):", "function_name": "preprocess_reviews", "parameter_list": "(reviews)" }, { "docstring": null, "function_declaration": "def nlp_sentiment_analysis(data):", "function_name": "nlp_sentiment_analysis", "p...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000007515", "row_id": 7515, "seed_ids": "[446]" }
0.704099
Algorithm_7515
I
[ "preprocess_reviews", "nlp_sentiment_analysis" ]
2
[ [ "nlp_sentiment_analysis", "preprocess_reviews" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
e90629c4506b5b89208a72f3c4e1925ec72e1de4
179ee6ecb20c3830c34b2d2eb89dc9c97a482e6a
v1.0
instruct
Algorithm
Algorithm_7522_I
### Question: You are provided with an implementation of a Segment Tree that supports range minimum queries. Your objective is to extend this data structure by adding a new method that counts the number of prime numbers within a specified subarray range. **Function Signature**: ```python def count_primes(node: Node |...
class Node: def __init__(self, start, end): self.start = start self.end = end self.minimum = float('inf') self.left = None self.right = None self.prime_count = 0 def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0...
from solution import build_segment_tree, count_primes def test_prime_in_full_range(): root = build_segment_tree([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 0, 18) assert count_primes(root, 0, 18) == 8 def test_prime_in_partial_range(): root = build_segment_tree([2, 3, 4, 5, 6, 7,...
[]
[ 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class SegmentTreeNode:\n def __init__(self, start, end, primes_count):\n self.start = start\n self.end = end\n self.primes_count = primes...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000007522", "row_id": 7522, "seed_ids": "[1913]" }
0.68334
Algorithm_7522
I
[ "is_prime", "build_segment_tree", "count_primes" ]
3
[ [ "build_segment_tree", "is_prime" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
c91b4181e0f31c881fc171ab61edbd5e683fe73e
2535b2bf04844de29e438f833b167719ae015f82
v1.0
instruct
Algorithm
Algorithm_7530_I
### Coding Assessment Question **Objective**: Implement a function to reverse a linked list in blocks of size `k`. **Scenario**: You are given a singly linked list and an integer `k`. Your task is to reverse the linked list in blocks of size `k` using the function `reverse_in_blocks_of_k`. If the number of nodes is n...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverse_linked_list(head: ListNode, k: int) -> ListNode: prev, current = None, head while current and k > 0: nxt = current.next current.next = prev prev = current curren...
import pytest from solution import ListNode, reverse_in_blocks_of_k def list_to_linkedlist(items): if not items: return None head = ListNode(items[0]) current_node = head for item in items[1:]: current_node.next = ListNode(item) current_node = current_node.next return head ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef reverse_in_blocks_of_k(head: ListNode, k: int...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007530", "row_id": 7530, "seed_ids": "[3642]" }
0.592238
Algorithm_7530
I
[ "reverse_linked_list", "reverse_in_blocks_of_k" ]
2
[ [ "reverse_in_blocks_of_k", "reverse_linked_list" ] ]
1
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
b2fd5cc3cda8a7d43c197b354b5c41ca2aa141b4
e0b6ee226072ec0918ceaba68e7a50c6687c95d8
v1.0
instruct
Algorithm
Algorithm_7578_I
### Question: Implement a Matrix Rotation Checker You are given two NxN 2D matrices (lists of lists) of integers, `matrix1` and `matrix2`. Write a function to determine if `matrix2` is a rotation of `matrix1`. The matrix can be rotated by 90 degrees clockwise any number of times (0 to 3). ### Input * Two matrices `ma...
def rotate_matrix_90(matrix): """ Rotates the given NxN matrix by 90 degrees clockwise. """ N = len(matrix) return [[matrix[N - 1 - j][i] for j in range(N)] for i in range(N)] def is_matrix_rotation(matrix1, matrix2): """ Checks if matrix2 is a rotation of matrix1 by 0, 90, 180, or 270 degr...
from solution import is_matrix_rotation def test_same_matrix(): matrix1 = [ [1, 2], [3, 4] ] matrix2 = [ [1, 2], [3, 4] ] assert is_matrix_rotation(matrix1, matrix2) == True def test_90_degree_rotation(): matrix1 = [ [1, 2], [3, 4] ] matr...
[ { "docstring": "Rotates the given NxN matrix by 90 degrees clockwise.", "function_declaration": "def rotate_matrix_90(matrix):", "function_name": "rotate_matrix_90", "parameter_list": "(matrix)" }, { "docstring": "Checks if matrix2 is a rotation of matrix1 by 0, 90, 180, or 270 degrees.", ...
[ 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 rotate_matrix_90(matrix):\n \"\"\"\n Rotates the given NxN matrix by 90 degrees clockwise.\n \"\"\"\n N = len(matrix)\n return [[matrix[N - 1 ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000007578", "row_id": 7578, "seed_ids": "[2736]" }
0.521932
Algorithm_7578
I
[ "rotate_matrix_90", "is_matrix_rotation" ]
2
[ [ "is_matrix_rotation", "rotate_matrix_90" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d813de060edcd36bd388179e818c7f78b0e459f9
392e128c0867dc6e5366967ce26f84fad2077c75
v1.0
instruct
Algorithm
Algorithm_7624_I
You've implemented the radix sort algorithm for sorting a list of non-negative integers. However, there is a twist. Instead of using base 10 (decimal system), the algorithm needs to adapt to an arbitrary base `b` (where 2 ≤ `b` ≤ 512). Write a Python function to perform radix sort on a given list of non-negative intege...
from typing import List def get_digit(number, base, digit_index): return (number // base ** digit_index) % base def radix_sort(arr: List[int], b: int) -> List[int]: if not arr: return [] max_num = max(arr) max_digits = 0 while max_num > 0: max_digits += 1 max_num //= b ...
from solution import radix_sort def test_radix_sort_base_10(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66], 10) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_base_2(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66], 2) == [2, 24, 45, 66, 75, 90, 170, 802] def test_radix_sort_base_512(...
[ { "docstring": null, "function_declaration": "def get_digit(number, base, digit_index):", "function_name": "get_digit", "parameter_list": "(number, base, digit_index)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, b):", "function_name": "radix_sort", "param...
[ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef counting_sort(arr, exp, base):\n n = len(arr)\n output = [0] * n\n count = [0] * base\n \n for i in range(n):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007624", "row_id": 7624, "seed_ids": "[2266]" }
0.614988
Algorithm_7624
I
[ "get_digit", "radix_sort" ]
2
[ [ "radix_sort", "get_digit" ] ]
1
[]
false
[]
false
pytest
true
[]
true
41f4c5eca5329686736d7dd0d4b77ee578746f80
6198afe1e7b6d98be2709f9f382732e472b04629
v1.0
instruct
Algorithm
Algorithm_7681_I
### Question: Find Minimum Platforms **Problem Description:** Given the arrival and departure times of trains on a single day at a railway station, your task is to write a function `find_minimum_platforms(arrivals: List[str], departures: List[str]) -> int` that determines the minimum number of platforms required to a...
from typing import List def convert_time_to_minutes(time: str) -> int: """Convert HH:MM time format to minutes since midnight.""" hours, minutes = map(int, time.split(':')) return hours * 60 + minutes def find_minimum_platforms(arrivals: List[str], departures: List[str]) -> int: n = len(arrivals) ...
def test_find_minimum_platforms_sample1(): arrivals = ["09:00", "09:40", "09:50", "11:00", "15:00", "18:00"] departures = ["09:10", "12:00", "11:20", "11:30", "19:00", "20:00"] assert find_minimum_platforms(arrivals, departures) == 3 def test_find_minimum_platforms_sample2(): arrivals = ["09:00", "09:1...
[ { "docstring": "Convert HH:MM time format to minutes since midnight.", "function_declaration": "def convert_time_to_minutes(time):", "function_name": "convert_time_to_minutes", "parameter_list": "(time)" }, { "docstring": null, "function_declaration": "def find_minimum_platforms(arrivals...
[ 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": "from typing import List\n\ndef find_minimum_platforms(arrivals: List[str], departures: List[str]) -> int:\n def time_to_minutes(time: str) -> int:\n ho...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007681", "row_id": 7681, "seed_ids": "[2269]" }
0.649361
Algorithm_7681
I
[ "convert_time_to_minutes", "find_minimum_platforms" ]
2
[ [ "find_minimum_platforms", "convert_time_to_minutes" ] ]
1
[]
false
[]
false
pytest
false
[]
true
85d262c715caefdd08b57820a39c4ee52e498d6c
90d37adf6537b3c96f9257c728ed99a619d3cb2a
v1.0
instruct
Algorithm
Algorithm_7699_I
### String Pattern Matching Assessment String 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 to locate substrings. #### Pa...
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": "", "prompt_id": "0000007699", "row_id": 7699, "seed_ids": "[4941]" }
0.632078
Algorithm_7699
I
[ "build_kmp_table", "kmp_search" ]
2
[ [ "kmp_search", "build_kmp_table" ] ]
1
[]
false
[]
false
pytest
true
[]
true
12a54c1ab0c39676f51f667fa02d3904fce737b7
bf76af7fcb81e772de64c57d30bb59e3761f0b6c
v1.0
instruct
Algorithm
Algorithm_7737_I
### Palindromic Primes #### Context: A palindromic prime is a prime number that remains the same when its digits are reversed. In other words, it is both a palindrome and a prime number. To determine whether a number is a palindromic prime, you need to check that it is a prime number and that it reads the same forward...
from typing import List def is_prime(num: int) -> bool: """ Check if a given number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) =...
from solution import palindromic_primes def test_palindromic_primes_within_1_to_100(): assert palindromic_primes(1, 100) == [2, 3, 5, 7, 11] def test_palindromic_primes_within_101_to_200(): assert palindromic_primes(101, 200) == [101, 131, 151, 181, 191] def test_palindromic_primes_with_large_range(): re...
[ { "docstring": "Check if a given number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Check if a given number is a palindrome.", "function_declaration": "def is_palindrome(num):", "function_name": "...
[ 1, 0, 1, 0, 1, 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": "from typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 =...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007737", "row_id": 7737, "seed_ids": "[3867]" }
0.615928
Algorithm_7737
I
[ "is_prime", "is_palindrome", "palindromic_primes" ]
3
[ [ "palindromic_primes", "is_palindrome" ], [ "palindromic_primes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3a8d89e94ca45bc15ca26bc80021bad39b009e70
0f4c6fbd3c8de0cf301f9185140fdbdbf0a6cfd2
v1.0
instruct
Algorithm
Algorithm_7739_I
### Objective Implement and validate the provided temperature and unit conversion functions with a focus on ensuring both correctness in conversions and handling edge cases effectively. ### Question You are tasked to implement three functions: `celsius_to_fahrenheit`, `fahrenheit_to_celsius`, and `temperature_conver...
def celsius_to_fahrenheit(celsius: float) -> float: """ Converts a temperature from Celsius to Fahrenheit. """ return (celsius * 9/5) + 32 def fahrenheit_to_celsius(fahrenheit: float) -> float: """ Converts a temperature from Fahrenheit to Celsius. """ return (fahrenheit - 32) * 5/9 de...
from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, temperature_converter def test_celsius_to_fahrenheit(): assert celsius_to_fahrenheit(0) == 32.0 assert celsius_to_fahrenheit(100) == 212.0 assert celsius_to_fahrenheit(-40) == -40.0 assert celsius_to_fahrenheit(37) == 98.6 def test_fah...
[ { "docstring": "Converts a temperature from Celsius to Fahrenheit.", "function_declaration": "def celsius_to_fahrenheit(celsius):", "function_name": "celsius_to_fahrenheit", "parameter_list": "(celsius)" }, { "docstring": "Converts a temperature from Fahrenheit to Celsius.", "function_de...
[ 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 celsius_to_fahrenheit(celsius: float) -> float:\n \"\"\"\n Converts a temperature from Celsius to Fahrenheit.\n \n Parameters:\n celsius (floa...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007739", "row_id": 7739, "seed_ids": "[5093]" }
0.513274
Algorithm_7739
I
[ "celsius_to_fahrenheit", "fahrenheit_to_celsius", "temperature_converter" ]
3
[ [ "temperature_converter", "celsius_to_fahrenheit" ], [ "temperature_converter", "fahrenheit_to_celsius" ] ]
2
[]
false
[]
false
pytest
true
[]
true
47c436350d4a4a05df858795ab00e39fdec63d11
f2da662a1d667f406a9790bbf8bfcf87f9a91c7a
v1.0
instruct
Algorithm
Algorithm_7752_I
### Fibonacci Sequence Generator with Caching You are tasked with creating a function that efficiently generates a list of the first `n` Fibonacci numbers using caching to improve performance. The function must utilize a caching mechanism (such as `functools.lru_cache` or a dictionary) to store previously computed valu...
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) def cached_fibonacci(n: int) -> list[int]: if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer") result = [] ...
from solution import cached_fibonacci import pytest def test_cached_fibonacci_general_cases(): assert cached_fibonacci(5) == [0, 1, 1, 2, 3] assert cached_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] def test_cached_fibonacci_edge_cases(): assert cached_fibonacci(0) == [] assert cached_fibonacci...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def cached_fibonacci(n):", "function_name": "cached_fibonacci", "parameter_list": "(n)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from functools import lru_cache\n\ndef cached_fibonacci(n: int) -> list[int]:\n # Check for invalid input\n if not isinstance(n, int) or n < 0:\n ra...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007752", "row_id": 7752, "seed_ids": "[3503]" }
0.740821
Algorithm_7752
I
[ "fibonacci", "cached_fibonacci" ]
2
[ [ "cached_fibonacci", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
22dcd3f87f76564deca24abaa555f8f5fc033b92
04f117101776a629b583f3bb23f0274a086f7cee
v1.0
instruct
Algorithm
Algorithm_7781_I
### Rotated Prime Identification and Sum Calculation #### Context A rotated number is formed by rotating the digits of a number in any order. A number is considered a rotated prime if all of its rotations are prime numbers. #### Task 1. Implement a function, `is_rotated_prime(num: int) -> bool` that checks if the inp...
def is_prime(n: int) -> bool: if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def is_rotated_prime(num: int) -> bool: if num <= 0: raise ValueError("Input number must be a positive integer.") if not is_prime...
from solution import is_rotated_prime, sum_of_rotated_primes def test_is_rotated_prime(): assert is_rotated_prime(197) == True # Rotations: 197, 971, 719 assert is_rotated_prime(23) == False # Rotations: 23, 32 (32 is not prime) assert is_rotated_prime(2) == True # Single digit prime assert is_rot...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_rotated_prime(num):", "function_name": "is_rotated_prime", "parameter_list": "(num)" }, { "docstri...
[ 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 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 return False\n i = 5\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000007781", "row_id": 7781, "seed_ids": "[3645]" }
0.610088
Algorithm_7781
I
[ "is_prime", "is_rotated_prime", "sum_of_rotated_primes" ]
3
[ [ "is_rotated_prime", "is_prime" ], [ "sum_of_rotated_primes", "is_rotated_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9236362d67afe803167c8f503776503b51ff54e5
335addd12ed84423dfce0d6fdfcacdddad058b37
v1.0
instruct
Algorithm
Algorithm_7910_I
### Problem Statement You are tasked with writing a function that compresses a given string using a basic Run-Length Encoding (RLE) technique and then decompresses the encoded string back to its original form. ### Function to Implement Implement the function `rle_encode_decode(operations: List[str], values: List[str]...
from typing import List def rle_encode(s: str) -> str: if not s: return "" encoded = [] i = 0 while i < len(s): count = 1 while i + 1 < len(s) and s[i] == s[i + 1]: i += 1 count += 1 encoded.append(f"{count}{s[i]}") i += 1 ...
def test_rle_encode(): assert rle_encode('aaabbccc') == '3a2b3c' assert rle_encode('a') == '1a' assert rle_encode('') == '' assert rle_encode('abc') == '1a1b1c' assert rle_encode('aabbaa') == '2a2b2a' def test_rle_decode(): assert rle_decode('3a2b3c') == 'aaabbccc' assert rle_decode('1a') =...
[ { "docstring": null, "function_declaration": "def rle_encode(s):", "function_name": "rle_encode", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def rle_decode(s):", "function_name": "rle_decode", "parameter_list": "(s)" }, { "docstring": null, ...
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rle_encode(s: str) -> str:\n if not s:\n return \"\"\n \n encoded_str = []\n count = 1\n\n for i in range(1,...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000007910", "row_id": 7910, "seed_ids": "[439]" }
0.707582
Algorithm_7910
I
[ "rle_encode", "rle_decode", "rle_encode_decode" ]
3
[ [ "rle_encode_decode", "rle_decode" ], [ "rle_encode_decode", "rle_encode" ] ]
2
[]
false
[]
false
pytest
false
[]
true
7e13c4cdebb8f26fd69fd5bab4c900475d8feb86
065571d297f388bc14ea567ad6e7081a2a524ee3
v1.0
instruct
Algorithm
Algorithm_7953_I
### Question: Implement an Optimized Pancake Sort The goal is to improve the efficiency of the Pancake Sort algorithm. Your task is to combine the basic idea of Pancake Sort with some optimization techniques to reduce the number of flips performed and improve performance. #### Requirements: * Implement a hybrid sorti...
def pancake_flip(arr, k): """ Perform a flip on the first k elements of the array. :param arr: List of elements to flip. :param k: The number of elements to flip. """ arr[:k] = arr[:k][::-1] def find_max_index(arr, end): """ Find the index of the maximum element in the array up to ...
from solution import hybrid_pancake_sort def test_hybrid_pancake_sort_with_duplicates(): assert hybrid_pancake_sort([0, 5, 3, 2, 2]) == [0, 2, 2, 3, 5] def test_hybrid_pancake_sort_with_negative_numbers(): assert hybrid_pancake_sort([-2, 5, 0, -45]) == [-45, -2, 0, 5] def test_hybrid_pancake_sort_single_elem...
[ { "docstring": "Perform a flip on the first k elements of the array.\n\n:param arr: List of elements to flip.\n:param k: The number of elements to flip.", "function_declaration": "def pancake_flip(arr, k):", "function_name": "pancake_flip", "parameter_list": "(arr, k)" }, { "docstring": "Fin...
[ 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": "def pancake_flip(arr, k):\n \"\"\"\n Reverses the order of the first k elements in the list.\n \n :param arr: List of elements to flip.\n :param k...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000007953", "row_id": 7953, "seed_ids": "[991]" }
0.729905
Algorithm_7953
I
[ "pancake_flip", "find_max_index", "hybrid_pancake_sort" ]
3
[ [ "hybrid_pancake_sort", "find_max_index" ], [ "hybrid_pancake_sort", "pancake_flip" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8ff1f7032021da2958773d2d985f8169ec012a1b
813b0f0102b0d47d55bf0f99691ff80e78dbc72e
v1.0
instruct
Algorithm
Algorithm_8022_I
### Sorting an Array Using Merge Sort #### Context You are asked to implement the merge sort algorithm to sort an array of integers. Merge sort is a classical divide-and-conquer algorithm that divides the array into halves, recursively sorts each half, and then merges the sorted halves back together. #### Requirement...
from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left: List[int], right: List[int]) -> List[int]: so...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reversed_list(): assert merge...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008022", "row_id": 8022, "seed_ids": "[1593]" }
0.699317
Algorithm_8022
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
07131ae09e5a52ffcfdd55798cb8775a88437bce
5cb8890a27cfd3bfe8b6a936d752d0eadde7b34e
v1.0
instruct
Algorithm
Algorithm_8027_I
**Question: Inorder Successor in a Binary Search Tree** You are given a Binary Search Tree (BST) where each node contains an integer key. Implement a function `find_inorder_successor(root: Node, target: int) -> Optional[Node]`: that finds the Inorder Successor of a given target node in the BST. ### Function Signature...
class Node: def __init__(self, key: int): self.key = key self.left = None self.right = None def find_inorder_successor(root: Node, target: int) -> Node: """ Finds the inorder successor of the given target key in a BST. Args: root: Node - the root of the binary search tr...
def test_find_inorder_successor(): root = Node(20) root.left = Node(10) root.right = Node(30) root.left.left = Node(5) root.left.right = Node(15) root.right.left = Node(25) root.right.right = Node(35) # Testing the example cases assert find_inorder_successor(root, 10).key == 15 ...
[]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, key: int):\n self.key = key\n self.left = None\n self.right = None\n\ndef find_inorder_successor(root: N...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000008027", "row_id": 8027, "seed_ids": "[1978]" }
0.517439
Algorithm_8027
I
[ "find_inorder_successor", "find_node", "find_min" ]
3
[ [ "find_inorder_successor", "find_min" ], [ "find_inorder_successor", "find_node" ] ]
2
[]
false
[ "Node" ]
true
pytest
false
[]
true
e0002378c570a93c652fc6ce159b442b505685f0
1c0c42f18f36081609763e8e731417aca486c786
v1.0
instruct
Algorithm
Algorithm_8067_I
Palindrome Partitioning You are tasked with implementing a function that partitions a given string into the minimum number of palindromic substrings. A palindromic substring is a substring that reads the same backward as forward. To achieve this, you will write several helper functions and the main function `min_pal...
def is_palindrome(s, start, end): """ Check if the substring s[start:end+1] is a palindrome. """ while start < end: if s[start] != s[end]: return False start += 1 end -= 1 return True def min_cuts(s, start, end): """ Compute the minimum cuts needed to par...
from solution import is_palindrome, min_cuts, min_palindrome_partitions def test_is_palindrome(): assert is_palindrome("racecar", 0, 6) == True assert is_palindrome("racecar", 0, 3) == False assert is_palindrome("level", 0, 4) == True assert is_palindrome("level", 1, 3) == True assert is_palindrome...
[ { "docstring": "Check if the substring s[start:end+1] is a palindrome.", "function_declaration": "def is_palindrome(s, start, end):", "function_name": "is_palindrome", "parameter_list": "(s, start, end)" }, { "docstring": "Compute the minimum cuts needed to partition the substring s[start:en...
[ 0, 1, 0, 1, 0, 0, 1, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_palindrome(s, start, end):\n \"\"\"\n Checks if the substring s[start:end+1] is a palindrome.\n \"\"\"\n while start < end:\n if s[star...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000008067", "row_id": 8067, "seed_ids": "[3890]" }
0.799324
Algorithm_8067
I
[ "is_palindrome", "min_cuts", "min_palindrome_partitions" ]
3
[ [ "min_cuts", "is_palindrome" ], [ "min_palindrome_partitions", "min_cuts" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2fd07da9e1708551e401eaf26d2c0c4c79fdebcc
827b19ddf5489733e5fc138ce2b6a4bb4b6c0070
v1.0
instruct
Algorithm
Algorithm_8082_I
***Graph Traversal and Shortest Path*** ### Context In this challenge, you will implement a solution for finding the shortest path in a weighted graph. The graph is represented as an adjacency matrix where the value at cell `(i, j)` represents the weight of the edge from node `i` to node `j`. If there is no edge betwe...
import heapq def initialize_graph(n: int) -> list[list[float]]: """ Initialize an n x n adjacency matrix for the graph with float('inf') representing no direct edge. """ return [[float('inf')] * n for _ in range(n)] def add_edge(graph: list[list[float]], u: int, v: int, weight: float) -> None: """...
from solution import initialize_graph, add_edge, dijkstra, shortest_path def test_initialize_graph(): graph = initialize_graph(3) assert graph == [[float('inf'), float('inf'), float('inf')], [float('inf'), float('inf'), float('inf')], [float('inf'), float('inf'), float...
[ { "docstring": "Initialize an n x n adjacency matrix for the graph with float('inf') representing no direct edge.", "function_declaration": "def initialize_graph(n):", "function_name": "initialize_graph", "parameter_list": "(n)" }, { "docstring": "Add or update an edge between node u and nod...
[ 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": "import heapq\n\ndef initialize_graph(n: int) -> list:\n \"\"\"\n Initialize an n x n adjacency matrix for the graph with `float('inf')` representing no dir...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000008082", "row_id": 8082, "seed_ids": "[325]" }
0.71409
Algorithm_8082
I
[ "initialize_graph", "add_edge", "dijkstra", "shortest_path" ]
4
[ [ "shortest_path", "dijkstra" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a72aeee0288a9012c3018d061ea3e414eed74b80
50847b6ac06896abdf64be57879b95705443c4db
v1.0
instruct
Algorithm
Algorithm_8115_I
### Problem Description You are given an unsorted list of `n` integers `arr` and an integer `k`. Your task is to implement the Quickselect algorithm to find the `k`-th smallest element in the list. If `k` is out of the bounds of the list, return `None`. ### Implementation Details 1. **Function Signature**: ```py...
from typing import List, Union def partition(arr: List[int], low: int, high: int) -> int: pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 d...
import pytest from solution import quickselect def test_quickselect_basic(): assert quickselect([3, 2, 1, 5, 4], 1) == 1 assert quickselect([3, 2, 1, 5, 4], 3) == 3 assert quickselect([3, 2, 1, 5, 4], 5) == 5 assert quickselect([3, 2, 1, 5, 4], 6) == None def test_quickselect_more_cases(): assert ...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quickselect_helper(arr, low, high, k):", "function_name": "quickselect_helper", "...
[ 1, 0, 1, 0, 1, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Union\n\ndef partition(arr: List[int], left: int, right: int, pivot_index: int) -> int:\n pivot_value = arr[pivot_index]\n arr[piv...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008115", "row_id": 8115, "seed_ids": "[4849]" }
0.569371
Algorithm_8115
I
[ "partition", "quickselect_helper", "quickselect" ]
3
[ [ "quickselect", "quickselect_helper" ], [ "quickselect_helper", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8e6e1b5573533b377836224f09ec213f375723c5
c4f50fedd62b97383fe3a47961dc9905fd1c600e
v1.0
instruct
Algorithm
Algorithm_8129_I
### Problem Statement: You are given a list of integer data points and a number `k`. Your task is to implement the following functions: 1. **`moving_average`**: Compute the simple moving average of the data points with a window size of `k`. 2. **`exponential_moving_average`**: Calculate the exponential moving average...
def moving_average(data_points, k): """ Computes the simple moving average of data points with a window size of k. """ if k <= 0: raise ValueError("Window size k must be greater than 0") n = len(data_points) if k > n: raise ValueError("Window size k must be less than or equa...
from solution import moving_average, exponential_moving_average, macd def test_moving_average_basic(): data_points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] k = 3 result = moving_average(data_points, k) assert result == [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] def test_moving_average_single_element(): dat...
[ { "docstring": "Computes the simple moving average of data points with a window size of k.", "function_declaration": "def moving_average(data_points, k):", "function_name": "moving_average", "parameter_list": "(data_points, k)" }, { "docstring": "Calculates the exponential moving average (EM...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def moving_average(data_points, k):\n \"\"\"\n Computes the simple moving average of the data points with a window size of `k`.\n \"\"\"\n if k <= 0 ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000008129", "row_id": 8129, "seed_ids": "[3298]" }
0.574983
Algorithm_8129
I
[ "moving_average", "exponential_moving_average", "macd" ]
3
[ [ "macd", "exponential_moving_average" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f35c52851db4e87cc90e15700a8d814c25cb389a
6a6fbc6c28e559bcdc3ff005f4765e8ffdd443a5
v1.0
instruct
Algorithm
Algorithm_8171_I
### CODING ASSESSMENT QUESTION #### Introduction You 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 frequency of the PWM signal is fixe...
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": "", "prompt_id": "0000008171", "row_id": 8171, "seed_ids": "[1100]" }
0.456677
Algorithm_8171
I
[ "compute_pwm_duty_cycle", "set_brightness_level" ]
2
[ [ "set_brightness_level", "compute_pwm_duty_cycle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff7f2c4c442f5de1fb90ebc93acb6734429bca36
3cdb4f19469adcb694f399c6084338661c14eab8
v1.0
instruct
Algorithm
Algorithm_8174_I
### Question: Determine the Least Common Multiple (LCM) of Multiple Integers #### Background The least common multiple (LCM) of two or more integers is the smallest positive integer that is divisible by each of them. It is a commonly used concept in number theory and has applications in solving problems involving sync...
from math import gcd from functools import reduce from typing import List def lcm(a: int, b: int) -> int: """ Helper function to calculate the least common multiple (LCM) of two numbers a and b. """ return abs(a * b) // gcd(a, b) def lcm_multiple(nums: List[int]) -> int: """ Returns the least ...
from solution import lcm_multiple def test_lcm_multiple_two_numbers(): assert lcm_multiple([4, 6]) == 12 def test_lcm_multiple_several_numbers(): assert lcm_multiple([1, 2, 3, 4, 5]) == 60 def test_lcm_multiple_with_common_factors(): assert lcm_multiple([5, 10, 15]) == 30 def test_lcm_multiple_multiples...
[ { "docstring": "Helper function to calculate the least common multiple (LCM) of two numbers a and b.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of a list of integers.", "functio...
[ 1, 1, 0, 0, 1, 1, 1, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nfrom math import gcd\n\ndef lcm(a, b):\n \"\"\"\n Helper function to calculate LCM of two numbers.\n \"\"\"\n return a * b /...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000008174", "row_id": 8174, "seed_ids": "[4446]" }
0.717773
Algorithm_8174
I
[ "lcm", "lcm_multiple" ]
2
[ [ "lcm_multiple", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d78e087b7fd39df7119416cc2a5962e3e31386fc
f47d02addeae240bb5a0f9868ecb17086996f7c3
v1.0
instruct
Algorithm
Algorithm_8194_I
### Visitor Log System #### Context In a private library, you are responsible for keeping a log of visitors' check-ins and check-outs. Each visitor's entry and exit times must be recorded, and at the end of the day, a report summarizing the total time each visitor spent in the library is generated. You need to implem...
from collections import defaultdict # Store the check-in and check-out times visitor_log = defaultdict(list) def check_in(visitor_name, check_in_time): """ Log the check-in time for a visitor. Args: visitor_name (str): Name of the visitor. check_in_time (int): Check-in time in minutes since m...
import pytest from solution import check_in, check_out, total_time_spent, generate_report, visitor_log def setup_function(): global visitor_log visitor_log.clear() def test_check_in_and_out(): setup_function() check_in("Alice", 480) check_out("Alice", 1020) assert visitor_log == {"Alice": [(48...
[ { "docstring": "Log the check-in time for a visitor.\n\nArgs:\nvisitor_name (str): Name of the visitor.\ncheck_in_time (int): Check-in time in minutes since midnight.", "function_declaration": "def check_in(visitor_name, check_in_time):", "function_name": "check_in", "parameter_list": "(visitor_name...
[ 1, 0, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import defaultdict\n\n# Store the check-in and check-out times\nvisitor_log = defaultdict(list)\n\ndef check_in(visitor_name, check_in_time):\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000008194", "row_id": 8194, "seed_ids": "[1136]" }
0.51893
Algorithm_8194
I
[ "check_in", "check_out", "total_time_spent", "generate_report" ]
4
[ [ "generate_report", "total_time_spent" ] ]
1
[]
false
[]
false
pytest
true
[]
true
68fc0330c924c31b02f3047236c26e9d4c0a8371
df03356d9151aa7eefeadfaeae20be867610c93c
v1.0
instruct
Algorithm
Algorithm_8244_I
### Question #### Scenario You work for a logistics company that needs to optimize their vehicle routing system to ensure timely deliveries. Each delivery point is represented by its coordinates, and you need to find the shortest path that visits each delivery point once and returns to the starting point (Traveling Sa...
import math def calculate_distance(point1, point2): """Helper function to calculate the Euclidean distance between two points.""" return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) def approximate_tsp(points): """ Finds an approximate solution to the TSP using the Nearest Ne...
from solution import approximate_tsp def test_approximate_tsp_simple_case(): points = [(0, 0), (1, 1), (1, 0), (0, 1)] result = approximate_tsp(points) # Since there can be multiple valid TSP solutions, just check it starts with the first point and contains all points. assert result[0] == (0, 0) as...
[ { "docstring": "Helper function to calculate the Euclidean distance between two points.", "function_declaration": "def calculate_distance(point1, point2):", "function_name": "calculate_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Finds an approximate solution to the TSP...
[ 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": "import math\n\ndef distance(point1, point2):\n \"\"\"\n Helper function to calculate the Euclidean distance between two points.\n \"\"\"\n return mat...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008244", "row_id": 8244, "seed_ids": "[626]" }
0.571661
Algorithm_8244
I
[ "calculate_distance", "approximate_tsp" ]
2
[ [ "approximate_tsp", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
428be751b142177f04d36efd3065d587224062b5
04d2816dd55b49d4a2bfad7f2003cfb729d61530
v1.0
instruct
Algorithm
Algorithm_8273_I
### Problem Statement You 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 on a set of given support ticket...
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": "", "prompt_id": "0000008273", "row_id": 8273, "seed_ids": "[640]" }
0.614228
Algorithm_8273
I
[ "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
bf2af84c0b1d2393b04c3bbc02bff7866dab8e02
fe1a1b40fe0ca38b7e5fc802953425f690d4c40d
v1.0
instruct
Algorithm
Algorithm_8350_I
### Building and Deploying a Simple Graphical User Interface (GUI) **Context**: Your task is to create a simple Graphical User Interface (GUI) using Tkinter, a built-in Python library. The GUI will have several widgets, including labels, entry boxes, buttons, and a text display area. Upon pressing the button, the GUI ...
import tkinter as tk def reverse_words(sentence: str) -> str: return ' '.join(sentence.split()[::-1]) def create_gui(): def on_button_click(): input_text = entry.get() reversed_text = reverse_words(input_text) text_display.delete(1.0, tk.END) text_display.insert(tk.END, reverse...
import pytest from solution import reverse_words, create_gui # Unit tests for the reverse_words function def test_reverse_words(): assert reverse_words("hello world") == "world hello" assert reverse_words("The quick brown fox") == "fox brown quick The" assert reverse_words("") == "" assert reverse_word...
[ { "docstring": null, "function_declaration": "def reverse_words(sentence):", "function_name": "reverse_words", "parameter_list": "(sentence)" }, { "docstring": null, "function_declaration": "def create_gui():", "function_name": "create_gui", "parameter_list": "()" }, { "d...
[ 1, 0, 0, 1, 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 tkinter as tk\n\ndef reverse_words(sentence: str) -> str:\n return ' '.join(sentence.split()[::-1])\n\ndef create_gui():\n def on_button_click():\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000008350", "row_id": 8350, "seed_ids": "[1858]" }
0.456593
Algorithm_8350
I
[ "reverse_words", "create_gui" ]
2
[ [ "create_gui", "reverse_words" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9fd326fa1f251554255d3e1e4686ec7202f2e32d
e64ee8a29cf1d276c489100d0074838e08ad047d
v1.0
instruct
Algorithm
Algorithm_8359_I
### Unique Words Counter You are given a function that deals with counting unique words in a given text: 1. `count_unique_words(text: str) -> int`: This function takes a string input `text` and returns the number of unique words in it. Words are defined as sequences of characters separated by whitespace and are consi...
import re from collections import Counter def count_unique_words(text: str) -> int: """ Returns the number of unique words in the given text. Words are considered case insensitive and any character sequences separated by white space. """ words = re.findall(r'\b\w+\b', text.lower()) return len(s...
from solution import unique_words_report def test_unique_words_single_paragraph(): assert unique_words_report(["This is a test."]) == {0: 4} def test_unique_words_multiple_paragraphs(): assert unique_words_report(["This is a test.", "This test is a Test."]) == {0: 4, 1: 4} def test_unique_words_case_insensit...
[ { "docstring": "Returns the number of unique words in the given text.\nWords are considered case insensitive and any character sequences separated by white space.", "function_declaration": "def count_unique_words(text):", "function_name": "count_unique_words", "parameter_list": "(text)" }, { ...
[ 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": "def count_unique_words(text: str) -> int:\n \"\"\"\n Returns the number of unique words in the given text.\n Words are considered case insensitive.\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008359", "row_id": 8359, "seed_ids": "[4108]" }
0.795514
Algorithm_8359
I
[ "count_unique_words", "unique_words_report" ]
2
[ [ "unique_words_report", "count_unique_words" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a63c2c98bb8726ccc115cba529e3381f55feac6
91696ddde564fdf2527f3ad81a9f453e6e388e4c
v1.0
instruct
Algorithm
Algorithm_8372_I
### Logistic Regression for Binary Classification You are required to implement a logistic regression model from scratch using batch gradient descent for optimization. Your goal is to: 1. Load and preprocess a given dataset. 2. Implement the logistic regression algorithm using gradient descent to update weights. 3. Ev...
import numpy as np import pandas as pd from urllib.request import urlopen def load_dataset(): """ Reads and processes the dataset from the URL. Returns a numpy matrix of the dataset. """ url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv" df = pd.read_csv(url) ...
import numpy as np from solution import load_dataset, sigmoid, logistic_gradient_descent, predict, evaluate_model def test_load_dataset(): data = load_dataset() assert data.shape[0] > 0 # Ensure that data has been loaded assert data.shape[1] == 2 # Ensure there are two columns (feature and label) def te...
[ { "docstring": "Reads and processes the dataset from the URL.\nReturns a numpy matrix of the dataset.", "function_declaration": "def load_dataset():", "function_name": "load_dataset", "parameter_list": "()" }, { "docstring": "Computes sigmoid function.", "function_declaration": "def sigm...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\n\ndef load_dataset():\n \"\"\"\n Load the dataset from the provided URL and preprocess it.\n Returns the datase...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000008372", "row_id": 8372, "seed_ids": "[681]" }
0.678924
Algorithm_8372
I
[ "load_dataset", "sigmoid", "logistic_gradient_descent", "predict", "evaluate_model", "main" ]
6
[ [ "logistic_gradient_descent", "sigmoid" ], [ "predict", "sigmoid" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
b46ea02406867f505b91bd54f7309661d917cdd7
86ce5dec32cc8d90b8ba58a26515e0473b0666da
v1.0
instruct
Algorithm
Algorithm_8373_I
### Data Compression Using Huffman Encoding #### Problem Description: You need to implement a Huffman encoding algorithm for compressing and decompressing text data. The Huffman encoding process involves creating a binary tree where the most frequent characters have the shortest binary codes, and the least frequent c...
import heapq import os from collections import defaultdict, Counter class TreeNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(fr...
from solution import huffman_encode_and_write, huffman_read_and_decode def test_simple_text(): input_text = "hello" with open('test_input.txt', 'w') as file: file.write(input_text) encoded_content = huffman_encode_and_write('test_input.txt', 'test_encoded.txt') assert huffman_read_and_deco...
[]
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nimport os\nfrom collections import defaultdict, Counter\nimport json\n\nclass HuffmanNode:\n def __init__(self, char, freq, left=None, right=Non...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000008373", "row_id": 8373, "seed_ids": "[460]" }
0.52033
Algorithm_8373
I
[ "build_huffman_tree", "build_codes", "huffman_encode_and_write", "huffman_read_and_decode" ]
4
[ [ "huffman_encode_and_write", "build_codes" ], [ "huffman_encode_and_write", "build_huffman_tree" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
efd6c5827b054096140945c6f1f0ff3a84b6fe48
995aaf7ac12582429805df2a1c0487755d671da8
v1.0
instruct
Algorithm
Algorithm_8376_I
### Sum of Digits in an Integer #### Context In certain applications, it may be necessary to calculate the sum of the digits of an integer for validation or analysis purposes. Your task is to write functions that: 1. Calculate the sum of the digits of a given integer. 2. Check if the calculated sum of the digits equal...
def sum_of_digits(n): """ Returns the sum of the digits of a non-negative integer n. """ return sum(int(digit) for digit in str(n)) def is_valid_sum(number, target_sum): """ Checks if the sum of the digits of the given number equals the target sum. """ return sum_of_digits(number) == ta...
import pytest from solution import sum_of_digits, is_valid_sum, convert_to_integer def test_sum_of_digits(): assert sum_of_digits(1234) == 10 assert sum_of_digits(9876) == 30 assert sum_of_digits(0) == 0 assert sum_of_digits(1001) == 2 def test_is_valid_sum(): assert is_valid_sum(1234, 10) == True...
[ { "docstring": "Returns the sum of the digits of a non-negative integer n.", "function_declaration": "def sum_of_digits(n):", "function_name": "sum_of_digits", "parameter_list": "(n)" }, { "docstring": "Checks if the sum of the digits of the given number equals the target sum.", "functio...
[ 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 sum_of_digits(n):\n \"\"\"\n Returns the sum of the digits of the given non-negative integer n.\n \"\"\"\n return sum(int(digit) for digit in str...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008376", "row_id": 8376, "seed_ids": "[1136]" }
0.717223
Algorithm_8376
I
[ "sum_of_digits", "is_valid_sum", "convert_to_integer" ]
3
[ [ "is_valid_sum", "sum_of_digits" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3ba9130d018f40f9e99149ed9bb8736529b4db22
adc6b7b2910f59cdc757cc5b56a87e6c0e35aa46
v1.0
instruct
Algorithm
Algorithm_8397_I
### Question: Graph Isomorphism Detection #### Problem Description: You are given two undirected graphs represented as adjacency lists. Your task is to write a Python function `are_isomorphic(graph1, graph2)` that determines whether the two graphs are isomorphic. Two graphs are isomorphic if one can be transformed int...
from collections import defaultdict def build_degree_sequence(graph): """ Builds the degree sequence count from an adjacency list representation of a graph. :param graph: A dictionary representing the graph :return: A sorted list of degree counts """ degree_sequence = defaultdict(int) for n...
from solution import are_isomorphic def test_example_1(): graph1 = { 'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['A', 'B'] } graph2 = { 1: [2, 3], 2: [1, 3], 3: [1, 2] } assert are_isomorphic(graph1, graph2) == True def test_example_2(): graph1 = { ...
[ { "docstring": "Builds the degree sequence count from an adjacency list representation of a graph.\n:param graph: A dictionary representing the graph\n:return: A sorted list of degree counts", "function_declaration": "def build_degree_sequence(graph):", "function_name": "build_degree_sequence", "par...
[ 0, 0, 1, 1, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import networkx as nx\n\ndef are_isomorphic(graph1: dict, graph2: dict) -> bool:\n \"\"\"\n Determine if two given graphs are isomorphic.\n \n :param...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008397", "row_id": 8397, "seed_ids": "[4535]" }
0.645657
Algorithm_8397
I
[ "build_degree_sequence", "are_isomorphic" ]
2
[ [ "are_isomorphic", "build_degree_sequence" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fae606f62995402c387ba0a75f771e020dcd287a
c378698c5a872667ada3f36cdea71fbf1d4d69a8
v1.0
instruct
Algorithm
Algorithm_8449_I
## Problem Statement You 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 the garden. ### Requirements ...
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": "", "prompt_id": "0000008449", "row_id": 8449, "seed_ids": "[640]" }
0.521825
Algorithm_8449
I
[ "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
cc5788302285155a3a416db1809cc3b0ea568396
39a606f08d9c475aae71112606bb5cff713c7695
v1.0
instruct
Algorithm
Algorithm_8485_I
### Coding Challenge You are developing a recommendation system for a movie streaming service. The system should recommend movies based on users' viewing history and the ratings of other similar users using three different approaches, and ensure that the recommended movies are suitable for the users based on their age...
def collaborative_filtering_recommendation(viewing_history, movie_details): """ Recommend movies based on collaborative filtering. This is a placeholder implementation. """ all_movies = list(movie_details.keys()) recommended_movies = list(set(all_movies) - set(viewing_history))[:5] return re...
import pytest from solution import collaborative_filtering_recommendation, content_based_recommendation, hybrid_recommendation from solution import age_group_suitability_checker, recommendation_suitability_checker from solution import recommend_movies # Sample data for testing purposes viewing_history = [101, 102, 103...
[ { "docstring": "Recommend movies based on collaborative filtering.\nThis is a placeholder implementation.", "function_declaration": "def collaborative_filtering_recommendation(viewing_history, movie_details):", "function_name": "collaborative_filtering_recommendation", "parameter_list": "(viewing_hi...
[ 0, 1, 1, 1, 0, 1, 1, 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": "def collaborative_filtering_recommendation(viewing_history, movie_details):\n \"\"\"\n Placeholder function for collaborative filtering recommendation.\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000008485", "row_id": 8485, "seed_ids": "[716]" }
0.480804
Algorithm_8485
I
[ "collaborative_filtering_recommendation", "content_based_recommendation", "hybrid_recommendation", "age_group_suitability_checker", "recommendation_suitability_checker", "recommend_movies" ]
6
[ [ "recommend_movies", "hybrid_recommendation" ], [ "recommend_movies", "recommendation_suitability_checker" ], [ "recommendation_suitability_checker", "age_group_suitability_checker" ] ]
3
[]
false
[]
false
pytest
true
[]
true
cf77322457aea2b390923a5f682afae3cf4e000f
ba5575c39ad0ec589ec1c145e03f0f53df3dee5b
v1.0
instruct
Algorithm
Algorithm_8523_I
### Rabin-Karp Algorithm for Substring Search You 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. ### Task 1. Implement a function `hash_function` to compute t...
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": "", "prompt_id": "0000008523", "row_id": 8523, "seed_ids": "[34]" }
0.591241
Algorithm_8523
I
[ "hash_function", "rabin_karp" ]
2
[ [ "rabin_karp", "hash_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
84dbcc61bc5d2b472bca401f8ab53fcd933a14f1
e4ae2c517969230a8f446205aeeeba13d2b21103
v1.0
instruct
Algorithm
Algorithm_8527_I
### Question: You are given a binary tree represented by a list in level-order traversal format where `None` indicates missing nodes. Implement the function `check_balanced_binary_tree(tree: List[Optional[int]]) -> bool` that returns `True` if the binary tree is height-balanced, and `False` otherwise. A height-balanced...
from typing import List, Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def list_to_tree(lst: List[Optional[int]], index: int = 0) -> Optional[TreeNode]: if index >= len(lst) or lst[index] is None: r...
from solution import check_balanced_binary_tree def test_balanced_tree(): tree = [1, 2, 3, 4, 5, None, 6] assert check_balanced_binary_tree(tree) == True def test_unbalanced_tree(): tree = [1, 2, 3, 4, None, None, 7, 8] assert check_balanced_binary_tree(tree) == False def test_single_node_tree(): ...
[]
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000008527", "row_id": 8527, "seed_ids": "[637]" }
0.801586
Algorithm_8527
I
[ "list_to_tree", "check_balanced_binary_tree" ]
2
[ [ "check_balanced_binary_tree", "list_to_tree" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
9e9715f5110cbba3ace8db2ca8f3ea716c2137e7
8f0efd6c0d882fecf2f6f17702e446be0c603c78
v1.0
instruct
Algorithm
Algorithm_8534_I
**Scenario**: You are developing a delivery routing system for an e-commerce platform. The system needs to determine the optimal delivery route that minimizes the total travel distance while visiting a given set of locations starting and ending at the warehouse. **Problem Statement**: Write a function `optimal_deliver...
import itertools import math def calculate_distance(p1, p2): """ Calculates the Euclidean distance between two points p1 and p2. """ return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def total_route_distance(route): """ Calculates the total distance of the given route returning to ...
from solution import optimal_delivery_route def test_empty_locations(): assert optimal_delivery_route([], (0, 0)) == [(0, 0), (0, 0)] def test_single_location(): assert optimal_delivery_route([(5, 5)], (3, 3)) == [(3, 3), (5, 5), (3, 3)] def test_three_locations(): result = optimal_delivery_route([(1, 2)...
[ { "docstring": "Calculates the Euclidean distance between two points p1 and p2.", "function_declaration": "def calculate_distance(p1, p2):", "function_name": "calculate_distance", "parameter_list": "(p1, p2)" }, { "docstring": "Calculates the total distance of the given route returning to th...
[ 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": "from itertools import permutations\nimport math\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000008534", "row_id": 8534, "seed_ids": "[1272]" }
0.637027
Algorithm_8534
I
[ "calculate_distance", "total_route_distance", "optimal_delivery_route" ]
3
[ [ "optimal_delivery_route", "total_route_distance" ], [ "total_route_distance", "calculate_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a82664660d94ef93f82eef972af17da2d26e2255
27b37131733f2921888fd4d85cef369bd16ca41d
v1.0
instruct
Algorithm
Algorithm_8605_I
### Coding Assessment Question In this assessment, you need to enhance a basic file processing script to handle CSV files with varying delimiters and manage large file sizes efficiently. The exercise is designed to test your understanding of file I/O, string manipulation, and memory management in Python. #### Your Ta...
import csv def detect_delimiter(file_path: str) -> str: """ Detect the delimiter used in the CSV file. It should be one of the following characters: comma, semicolon, tab, pipe. Args: - file_path (str): Path to the CSV file. Returns: - str: The detected delimiter. """ del...
import os import pytest from solution import detect_delimiter, add_row_numbers, process_large_csv def test_detect_delimiter(): with open('test_comma.csv', 'w') as f: f.write("Name,Age,Country\nJohn Doe,28,USA\n") assert detect_delimiter('test_comma.csv') == ',' with open('test_semicolon.csv', ...
[ { "docstring": "Detect the delimiter used in the CSV file. It should be one of the following \ncharacters: comma, semicolon, tab, pipe.\n\nArgs:\n- file_path (str): Path to the CSV file.\n\nReturns:\n- str: The detected delimiter.", "function_declaration": "def detect_delimiter(file_path):", "function_n...
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import csv\n\ndef detect_delimiter(file_path: str) -> str:\n # Read the first line of the file to detect the delimiter\n with open(file_path, 'r') as file:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008605", "row_id": 8605, "seed_ids": "[427]" }
0.614421
Algorithm_8605
I
[ "detect_delimiter", "add_row_numbers", "process_large_csv" ]
3
[ [ "process_large_csv", "add_row_numbers" ], [ "process_large_csv", "detect_delimiter" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1a8c15e2c41e30139ed89f5bcc45506fba60a853
5f56a2a10868ec48c37fdf5ccf898ff9f057078d
v1.0
instruct
Algorithm
Algorithm_8609_I
**Scenario:** You work at a company that designs custom calendar applications for clients. The company needs a system that can identify dates for important holidays automatically. These holidays could be fixed (like Christmas) or variable (like Easter or Thanksgiving). Your task is to develop a robust system that calc...
import datetime def calculate_holiday(holiday: str, year: int) -> str: """ Computes the date of the specified holiday for the given year. :param holiday: Name of the holiday to compute. :param year: Integer representing the year for which to calculate the holiday date. :return: The holiday dat...
from solution import calculate_holiday, calculate_easter, calculate_thanksgiving def test_calculate_christmas(): assert calculate_holiday("Christmas", 2023) == "2023-12-25" def test_calculate_new_year(): assert calculate_holiday("New Year's Day", 2023) == "2023-01-01" def test_calculate_easter(): assert ...
[ { "docstring": "Computes the date of the specified holiday for the given year.\n\n:param holiday: Name of the holiday to compute.\n:param year: Integer representing the year for which to calculate the holiday date.\n:return: The holiday date in the format \"YYYY-MM-DD\".\n:raises ValueError: If the specified ho...
[ 1, 1, 1, 1, 1, 1, 1, 0, 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": "from datetime import date, timedelta\nimport calendar\n\ndef calculate_holiday(holiday: str, year: int) -> str:\n \"\"\"\n Computes the date of the specifi...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000008609", "row_id": 8609, "seed_ids": "[4440]" }
0.727685
Algorithm_8609
I
[ "calculate_holiday", "calculate_easter", "calculate_thanksgiving" ]
3
[ [ "calculate_holiday", "calculate_easter" ], [ "calculate_holiday", "calculate_thanksgiving" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d8773b7d5e446c3ac929ee008c27eec6bd3afc14
b5a81641e4c274152f9f86571d8ff8ecf2684381
v1.0
instruct
Algorithm
Algorithm_8705_I
### Scenario You are developing a news aggregator program that consolidates the titles of news articles from various feeds and needs to handle word frequency analysis. Your task is to create functions to count the frequency of words and identify the most frequent word(s). ### Task Write two functions to count the freq...
import re from collections import defaultdict def word_frequency(titles): """ Counts the frequency of words in a list of news article titles. :param titles: List of strings representing the titles of news articles :return: Dictionary where keys are words and values are their respective frequencies...
from solution import word_frequency, most_frequent_words def test_word_frequency(): titles = [ "New vaccine shows promise", "Climate change impacts more severe", "New species discovered in rainforest", "Climate change policy adopted" ] expected = { "new": 2, ...
[ { "docstring": "Counts the frequency of words in a list of news article titles.\n\n:param titles: List of strings representing the titles of news articles\n:return: Dictionary where keys are words and values are their respective frequencies", "function_declaration": "def word_frequency(titles):", "funct...
[ 0, 1, 1, 1, 1, 0, 0, 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 re\nfrom collections import Counter\n\ndef word_frequency(titles):\n \"\"\"\n Counts the frequency of words in a list of news article titles.\n \...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000008705", "row_id": 8705, "seed_ids": "[2813]" }
0.711541
Algorithm_8705
I
[ "word_frequency", "most_frequent_words" ]
2
[ [ "most_frequent_words", "word_frequency" ] ]
1
[]
false
[]
false
pytest
true
[]
true
815cf270e1c3c42f5fd881e42648e08818b37111
940ea914eb58146b2471834871658af847e6a020
v1.0
instruct
Algorithm
Algorithm_8724_I
### Question: You are tasked with implementing a function `find_combinations(target: int, numbers: list) -> list` that finds all unique combinations of numbers in a list where the chosen numbers sum to a target value. Each number from the list can be used an unlimited number of times. To solve this problem, follow th...
def combination_sum(target, numbers, start, combination, result): """ Uses backtracking to find combinations of numbers that add up to the target sum. """ if target == 0: result.append(list(combination)) return elif target < 0: return for i in range(start, len(number...
from solution import find_combinations def test_find_combinations_example_1(): assert find_combinations(7, [2, 3, 6, 7]) == [[2, 2, 3], [7]] def test_find_combinations_example_2(): assert find_combinations(8, [2, 3, 5]) == [[2, 2, 2, 2], [2, 3, 3], [3, 5]] def test_find_combinations_example_3(): assert f...
[ { "docstring": "Uses backtracking to find combinations of numbers that add up to the target sum.", "function_declaration": "def combination_sum(target, numbers, start, combination, result):", "function_name": "combination_sum", "parameter_list": "(target, numbers, start, combination, result)" }, ...
[ 1, 0, 0, 0, 1, 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": "def combination_sum(target, numbers, start, combination, result):\n # Base case: if the target is 0, we found a valid combination\n if target == 0:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008724", "row_id": 8724, "seed_ids": "[4750]" }
0.713902
Algorithm_8724
I
[ "combination_sum", "find_combinations" ]
2
[ [ "find_combinations", "combination_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a6061a9a21e20e2b419d8a3d913cf592781a1228
320541270e15a5694bfb774d861240a36d13d187
v1.0
instruct
Algorithm
Algorithm_8727_I
### Coding Assessment: Implementing K-Nearest Neighbors (KNN) **Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. You will use the provided KNN model and utility functions as a reference to create new components to demonstrate your understanding. ### Problem Statement Give...
import math from collections import Counter def fit_knn_model(features, labels, k): """ Fits a KNN model. :param features: List[List[float]]: The feature vectors. :param labels: List[int]: The corresponding labels. :param k: int: The number of neighbors to consider. :return: dict: The mode...
from solution import fit_knn_model, predict_instances, calculate_accuracy def test_fit_knn_model(): features = [ [5.1, 3.5], [4.9, 3.0], [7.0, 3.2], [6.4, 3.2], ] labels = [0, 0, 1, 1] k = 3 model = fit_knn_model(features, labels, k) assert model == {"features": ...
[ { "docstring": "Fits a KNN model.\n\n:param features: List[List[float]]: The feature vectors.\n:param labels: List[int]: The corresponding labels.\n:param k: int: The number of neighbors to consider.\n:return: dict: The model containing the features, labels, and k value.", "function_declaration": "def fit_k...
[ 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 collections import Counter\n\ndef fit_knn_model(features, labels, k):\n \"\"\"\n Fit a K-Nearest Neighbors model using the provided featu...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008727", "row_id": 8727, "seed_ids": "[468]" }
0.561749
Algorithm_8727
I
[ "fit_knn_model", "euclidean_distance", "predict_instances", "calculate_accuracy" ]
4
[ [ "predict_instances", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
788fd90ed16f4c3e1dbfa5b4e59c39683ef98e4a
c2a2f3880fe6cecbc63cda087883090a0f5af800
v1.0
instruct
Algorithm
Algorithm_8745_I
### Coding Assessment Question #### Scenario In this task, you are required to work with a series of numbers and manipulate their mathematical properties. Specifically, you will be exploring properties related to prime numbers and Fibonacci sequences. #### Problem Statement Implement a function `is_prime_fibonacci(n:...
def is_prime(n): """ Check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def is_fibonacci(n): """ ...
from solution import is_prime_fibonacci def test_is_prime_fibonacci_with_prime_fibonacci_numbers(): assert is_prime_fibonacci(2) == True # 2 is both prime and Fibonacci assert is_prime_fibonacci(3) == True # 3 is both prime and Fibonacci assert is_prime_fibonacci(5) == True # 5 is both prime and Fibonac...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Check if a number is in the Fibonacci sequence.", "function_declaration": "def is_fibonacci(n):", "function_name": "is_fib...
[ 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 math\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000008745", "row_id": 8745, "seed_ids": "[4012]" }
0.775176
Algorithm_8745
I
[ "is_prime", "is_fibonacci", "is_prime_fibonacci" ]
3
[ [ "is_prime_fibonacci", "is_fibonacci" ], [ "is_prime_fibonacci", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d759fd287de869f59123e9fe88b134c9930774bb
d6dd68a40cd785f28deb309fbcb5e9c49e7fb2e3
v1.0
instruct
Algorithm
Algorithm_8794_I
### String Pattern Matching Using KMP Algorithm #### Problem Statement You are tasked with implementing the Knuth-Morris-Pratt (KMP) algorithm for string pattern matching. The KMP algorithm searches for occurrences of a "pattern" within a main "text" by employing the observation that when a mismatch occurs, the next ...
def build_lps(pattern: str) -> list: """ Constructs the Longest Prefix Suffix (LPS) array used in the KMP algorithm. :param pattern: The substring pattern for which the LPS array is to be constructed. :return: The LPS array. """ lps = [0] * len(pattern) length = 0 i = 1 while i < len...
from solution import build_lps, kmp_search def test_build_lps_basic(): assert build_lps("ABABCABAB") == [0, 0, 1, 2, 0, 1, 2, 3, 4] def test_build_lps_no_repeats(): assert build_lps("ABCDE") == [0, 0, 0, 0, 0] def test_build_lps_all_repeats(): assert build_lps("AAAAAA") == [0, 1, 2, 3, 4, 5] def test_km...
[ { "docstring": "Constructs the Longest Prefix Suffix (LPS) array used in the KMP algorithm.\n:param pattern: The substring pattern for which the LPS array is to be constructed.\n:return: The LPS array.", "function_declaration": "def build_lps(pattern):", "function_name": "build_lps", "parameter_list...
[ 0, 1, 0, 0, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def build_lps(pattern: str) -> list:\n \"\"\"\n Constructs the Longest Prefix Suffix (LPS) array used in the KMP algorithm.\n :param pattern: The substr...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000008794", "row_id": 8794, "seed_ids": "[3747]" }
0.639559
Algorithm_8794
I
[ "build_lps", "kmp_search" ]
2
[ [ "kmp_search", "build_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
576951a55867bf8948a3950d56403565ead4f086
bfeb390b55e7288b0fb0c2f90f40dd777fc380f0
v1.0
instruct
Algorithm
Algorithm_8800_I
### Coding Challenge: Stock Price Insights Aggregator Your task is to develop a Python script to aggregate stock price data from two different APIs: Alpha Vantage and IEX Cloud. You are required to implement error handling, optimize data retrieval, and handle different edge cases effectively. #### Function Signature ...
import requests import concurrent.futures # Put your API key(s) here ALPHA_VANTAGE_API_KEY = "your_alpha_vantage_api_key" IEX_CLOUD_API_KEY = "your_iex_cloud_api_key" ALPHA_VANTAGE_URL_BASE = "https://www.alphavantage.co/query" IEX_CLOUD_URL_BASE = "https://cloud.iexapis.com/stable/stock" def fetch_alpha_vantage_dat...
from unittest.mock import patch import pytest from solution import get_stock_data @patch('solution.fetch_alpha_vantage_data') @patch('solution.fetch_iex_cloud_data') def test_get_stock_data_success(mock_iex, mock_alpha): mock_alpha.return_value = { 'current_price': 150.00, 'volume': 1000000, ...
[ { "docstring": null, "function_declaration": "def fetch_alpha_vantage_data(symbol):", "function_name": "fetch_alpha_vantage_data", "parameter_list": "(symbol)" }, { "docstring": null, "function_declaration": "def fetch_iex_cloud_data(symbol):", "function_name": "fetch_iex_cloud_data"...
[ 0, 0, 1, 1, 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 requests\nimport concurrent.futures\nfrom typing import Tuple\n\n# API keys (assuming valid ones are provided)\nALPHA_VANTAGE_API_KEY = \"your_alpha_vanta...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000008800", "row_id": 8800, "seed_ids": "[2556]" }
0.471957
Algorithm_8800
I
[ "fetch_alpha_vantage_data", "fetch_iex_cloud_data", "get_stock_data" ]
3
[ [ "get_stock_data", "fetch_alpha_vantage_data" ], [ "get_stock_data", "fetch_iex_cloud_data" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
d7a2d72fca7945dd77b7c5614a9b57f7a97bef60
ba6973923df5e9306aa0307e0f2be5ad11fd8caa
v1.0
instruct
Algorithm
Algorithm_8837_I
### Celebrity Identification Challenge You are tasked to implement a system to identify the celebrity at a party. A celebrity is a person who is known by everyone but knows no one. Your task is to identify this celebrity, if they exist, using efficient algorithms. #### 1. Helper Function First, implement a helper fun...
from typing import List def knows(a: int, b: int, matrix: List[List[int]]) -> bool: """ Parameters: a (int): An integer representing a person. b (int): An integer representing another person. matrix (List[List[int]]): A 2D list where matrix[i][j] is 1 if person i knows person j, else 0....
from solution import knows, find_celebrity def test_knows(): matrix = [ [0, 1, 0], [0, 0, 1], [1, 0, 0] ] assert knows(0, 1, matrix) == True assert knows(1, 0, matrix) == False assert knows(2, 0, matrix) == True def test_find_celebrity_no_celebrity(): n = 3 matrix =...
[ { "docstring": "Parameters:\n a (int): An integer representing a person.\n b (int): An integer representing another person.\n matrix (List[List[int]]): A 2D list where matrix[i][j] is 1 if person i knows person j, else 0.\nReturns:\n bool: True if person 'a' knows person 'b', otherwise False.", ...
[ 0, 1, 1, 0, 0, 0, 0, 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": "def knows(a: int, b: int, matrix):\n \"\"\"\n Parameters:\n a (int): An integer representing a person.\n b (int): An integer representing ano...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000008837", "row_id": 8837, "seed_ids": "[236]" }
0.538158
Algorithm_8837
I
[ "knows", "find_celebrity" ]
2
[ [ "find_celebrity", "knows" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7466abb70c2d210e60b7d91130d4b886a5908bb3
4ab452c6179616ade43945772eab8c603a745a03
v1.0
instruct
Algorithm
Algorithm_8840_I
### Coding Assessment Question You 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, ensuring a seamless transitio...
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": "", "prompt_id": "0000008840", "row_id": 8840, "seed_ids": "[2421]" }
0.461759
Algorithm_8840
I
[ "get_flight_details", "calculate_duration", "display_flights", "main" ]
4
[ [ "display_flights", "calculate_duration" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
72dc3974acdbc07a935b7ad5a706328d5a83f8ce
71a8f6de08e08bb9c714cd3bb0fe5df8ada516eb