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_20748_I
Coding Question #### Objective Write a function `next_prime` that finds the closest prime number greater than a given input integer. The function should accept an integer and return the next prime number. #### Function Signature ```python def next_prime(n: int) -> int: pass ``` #### Input * `n`: An integer, repr...
def is_prime(num): """ Helper function to check if a number is prime. """ if num <= 1: return False if num == 2: return True if num % 2 == 0: return False p = 3 while p * p <= num: if num % p == 0: return False p += 2 return True d...
from solution import next_prime def test_next_prime_immediate(): assert next_prime(10) == 11 def test_next_prime_non_immediate(): assert next_prime(15) == 17 def test_next_prime_large(): assert next_prime(50) == 53 def test_next_prime_single_digit(): assert next_prime(2) == 3 assert next_prime(3...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns the closest prime number greater than the given input integer n.", "function_declaration": "def...
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000020748", "row_id": 20748, "seed_ids": "[600]" }
0.700227
Algorithm_20748
I
[ "is_prime", "next_prime" ]
2
[ [ "next_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4309c2c37d6902b15b1dabd7caa959858dbf32af
8044e1d9e4fc2ed8d0bef94fbdbe4dafd48d91fc
v1.0
instruct
Algorithm
Algorithm_20786_I
### Logistic Regression from Scratch Your task is to implement logistic regression by defining the necessary functions for model training and prediction. The provided snippets include partial implementations of the functions required. ### Function Descriptions 1. **sigmoid(z: np.ndarray) -> np.ndarray** * Compute...
import numpy as np def sigmoid(z: np.ndarray) -> np.ndarray: """ Compute the sigmoid function for the input z, which could be a numpy array or a scalar. """ return 1 / (1 + np.exp(-z)) def train_logistic_regression(x_train: np.ndarray, y_train: np.ndarray, learning_rate: float, epochs: int) -> np.ndar...
from solution import sigmoid, train_logistic_regression, predict_logistic_regression import numpy as np def test_sigmoid(): assert np.allclose(sigmoid(np.array([0])), np.array([0.5])) assert np.allclose(sigmoid(np.array([1])), np.array([0.73105857863]), rtol=1e-5) assert np.allclose(sigmoid(np.array([-1]))...
[ { "docstring": "Compute the sigmoid function for the input z, which could be a numpy array or a scalar.", "function_declaration": "def sigmoid(z):", "function_name": "sigmoid", "parameter_list": "(z)" }, { "docstring": "Train the logistic regression model using the provided training data x_t...
[ 0, 1, 1, 1, 0, 0, 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": "import numpy as np\n\ndef sigmoid(z: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute the sigmoid function for the input z.\n \n Parameters:\n z (np....
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020786", "row_id": 20786, "seed_ids": "[770]" }
0.718094
Algorithm_20786
I
[ "sigmoid", "train_logistic_regression", "predict_logistic_regression" ]
3
[ [ "predict_logistic_regression", "sigmoid" ], [ "train_logistic_regression", "sigmoid" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
99219f085f5eee595fb16f06934a9ee4bd850b00
7c537e9600887934b93540da079f4f4ae101275b
v1.0
instruct
Algorithm
Algorithm_20862_I
### Coding Challenge: Palindrome Pairs ### Context: A palindrome is a word, phrase, or sequence of characters that reads the same backward as forward. Finding palindrome pairs in a list of words is a common problem that involves checking if the concatenation of two words results in a palindrome. ### Task: You need to...
from typing import List, Tuple def is_palindrome(word: str) -> bool: """ Helper function to check if a given word is a palindrome. """ return word == word[::-1] def palindrome_pairs(words: List[str]) -> List[Tuple[int, int]]: """ Finds all unique pairs of indices (i, j) where the concatenation...
from solution import palindrome_pairs def test_palindrome_pairs_example1(): assert sorted(palindrome_pairs(["bat", "tab", "cat"])) == sorted([(0, 1), (1, 0)]) def test_palindrome_pairs_example2(): assert sorted(palindrome_pairs(["abcd", "dcba", "lls", "s", "sssll"])) == sorted([(0, 1), (1, 0), (3, 2), (2, 4)]...
[ { "docstring": "Helper function to check if a given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Finds all unique pairs of indices (i, j) where the concatenation of words[i] + words...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef is_palindrome(s: str) -> bool:\n \"\"\"\n Helper function to determine if a string is a palindrome.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000020862", "row_id": 20862, "seed_ids": "[1142]" }
0.746669
Algorithm_20862
I
[ "is_palindrome", "palindrome_pairs" ]
2
[ [ "palindrome_pairs", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8652de000252e599a3163bf287c56300fbe34be8
7635499836c3c33d88600bb6ad53020dec356f85
v1.0
instruct
Algorithm
Algorithm_20909_I
## New Question ### Question: Implement a Stock Price Simulator and Anomaly Detector Your task is to implement a function that simulates stock prices based on historical daily percentage changes using different provided models (Simple Moving Average, Exponential Moving Average, and Monte Carlo Simulation). Then, dete...
from typing import List, Tuple import numpy as np def calculate_sma(prices: List[float], window: int) -> List[float]: return [np.mean(prices[i:i + window]) for i in range(len(prices) - window + 1)] def calculate_ema(prices: List[float], window: int) -> List[float]: ema = [] k = 2 / (window + 1) ema.ap...
from solution import stock_price_simulator def test_stock_price_simulator_basic(): train_dates = ["2023-01-01", "2023-01-02", "2023-01-03", "2023-01-04"] train_prices = [100, 102, 105, 107] test_dates = ["2023-01-05", "2023-01-06"] predictions, anomalies = stock_price_simulator(train_dates, train_pric...
[ { "docstring": null, "function_declaration": "def calculate_sma(prices, window):", "function_name": "calculate_sma", "parameter_list": "(prices, window)" }, { "docstring": null, "function_declaration": "def calculate_ema(prices, window):", "function_name": "calculate_ema", "param...
[ 1, 1, 0, 0, 1, 0, 0, 0 ]
3
medium
0.375
{ "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 calculate_sma(prices, window):\n \"\"\"Calculates the Simple Moving Average (SMA) for given prices and window s...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000020909", "row_id": 20909, "seed_ids": "[722]" }
0.604023
Algorithm_20909
I
[ "calculate_sma", "calculate_ema", "monte_carlo_simulation", "stock_price_simulator" ]
4
[ [ "stock_price_simulator", "calculate_ema" ], [ "stock_price_simulator", "calculate_sma" ], [ "stock_price_simulator", "monte_carlo_simulation" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
3c8934d36cfe6b0641d39737c35688d0cf073ba8
8bb233ab753989354075c7ddc71b36ca80325416
v1.0
instruct
Algorithm
Algorithm_20935_I
### Problem Statement: You are tasked with generating a sequence of numbers where each number is the sum of digital roots of all numbers from 1 up to that number (inclusive). The digital root of a number is the single digit obtained by an iterative process of summing digits, on each step using the result from the prev...
def digital_root(n): """ Returns the digital root of n. """ if n == 0: return 0 else: return (n - 1) % 9 + 1 def digital_root_sum_sequence(n): """ Returns a list of length n where the i-th element is the sum of digital roots of integers from 1 to i+1. """ sequen...
from solution import digital_root_sum_sequence def test_digital_root_sum_sequence_start(): assert digital_root_sum_sequence(1) == [1] def test_digital_root_sum_sequence_small(): assert digital_root_sum_sequence(5) == [1, 3, 6, 10, 15] def test_digital_root_sum_sequence_medium(): assert digital_root_sum_s...
[ { "docstring": "Returns the digital root of n.", "function_declaration": "def digital_root(n):", "function_name": "digital_root", "parameter_list": "(n)" }, { "docstring": "Returns a list of length n where the i-th element is the sum of \ndigital roots of integers from 1 to i+1.", "funct...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def digital_root(x):\n \"\"\"\n Return the digital root of x.\n The digital root is the single digit obtained by an \n iterative process of summing d...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000020935", "row_id": 20935, "seed_ids": "[3586]" }
0.60016
Algorithm_20935
I
[ "digital_root", "digital_root_sum_sequence" ]
2
[ [ "digital_root_sum_sequence", "digital_root" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f161fe2224d25f39e398c5535db984c4ac7606e7
741d382e24976bc8a6558725099bdd4b009e34e7
v1.0
instruct
Algorithm
Algorithm_20955_I
## Problem Statement You are tasked with writing a function that calculates the least common multiple (LCM) of an array of integers. The least common multiple of a set of positive integers is the smallest positive integer that is divisible by each of them. ### Function Signature ```python def find_lcm(arr: List[int]) ...
from math import gcd from functools import reduce from typing import List def lcm(a: int, b: int) -> int: """ Helper function to find the LCM of two numbers. """ return a * b // gcd(a, b) def find_lcm(arr: List[int]) -> int: """ Returns the LCM of an array of integers. """ return reduc...
from solution import find_lcm def test_find_lcm_single_element(): assert find_lcm([1]) == 1 assert find_lcm([4]) == 4 def test_find_lcm_two_elements(): assert find_lcm([2, 3]) == 6 assert find_lcm([6, 8]) == 24 def test_find_lcm_multiple_elements(): assert find_lcm([2, 7, 3]) == 42 assert fin...
[ { "docstring": "Helper function to find the LCM of two numbers.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the LCM of an array of integers.", "function_declaration": "def find_lcm(arr):", "function_name": ...
[ 1, 0, 1, 1, 0, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import gcd\nfrom functools import reduce\nfrom typing import List\n\ndef find_lcm(arr: List[int]) -> int:\n \"\"\"\n Returns the least common mul...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000020955", "row_id": 20955, "seed_ids": "[3511]" }
0.699324
Algorithm_20955
I
[ "lcm", "find_lcm" ]
2
[ [ "find_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4ea0322449cba1f5fbc25004eba4182f1e4d29e4
f94ccd2b122ac3fdb7bed8eeb6f738bee2541dc3
v1.0
instruct
Algorithm
Algorithm_20977_I
### Coding Assessment Question #### Scenario You are working on enhancing the functionality of a statistical library by adding robust algorithms for data clustering. To evaluate the students' grasp of clustering algorithms, you want to test their ability to implement an optimized version of the k-means clustering algo...
import random from typing import List, Tuple import math def euclidean_distance(point1, point2): return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2))) def initialize_centroids(points, k): centroids = [] centroids.append(random.choice(points)) while len(centroids) < k: distances =...
from solution import optimized_k_means def test_optimized_k_means_simple_dataset(): points = [ [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], [9.0, 3.0] ] labels, centroids = optim...
[ { "docstring": null, "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": null, "function_declaration": "def initialize_centroids(points, k):", "function_name": "initialize_cen...
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1: List[float], point2: List[float]) -> float:\n return math.sqrt(su...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000020977", "row_id": 20977, "seed_ids": "[4358]" }
0.707468
Algorithm_20977
I
[ "euclidean_distance", "initialize_centroids", "assign_points_to_centroids", "compute_centroids", "optimized_k_means" ]
5
[ [ "assign_points_to_centroids", "euclidean_distance" ], [ "initialize_centroids", "euclidean_distance" ], [ "optimized_k_means", "assign_points_to_centroids" ], [ "optimized_k_means", "compute_centroids" ], [ "optimized_k_means", "euclidean_distance" ], [ ...
6
[]
false
[]
false
pytest
true
[]
true
bfc9aa4034ea8d8acbab120c784f927dd38edbdd
195729d7cac11e328bdbe9a7c12d011aa1d9e663
v1.0
instruct
Algorithm
Algorithm_20990_I
### Coding Challenge Question: Secure File Duplicate Remover **Context**: File duplicate removal is a common operation to save storage space. The task involves implementing a function that finds duplicate files in a directory based on their contents and removes them securely. File integrity and performance are crucial...
import os import hashlib def compute_file_hash(file_path): """Compute the SHA-256 hash of the file content.""" hash_func = hashlib.sha256() with open(file_path, 'rb') as f: while chunk := f.read(8192): hash_func.update(chunk) return hash_func.hexdigest() def remove_duplicates(direc...
import os import tempfile from solution import remove_duplicates def create_temp_file(directory, content): """Helper function to create a temporary file with specified content.""" fd, temp_path = tempfile.mkstemp(dir=directory) with os.fdopen(fd, 'w') as tmp: tmp.write(content) return temp_path...
[ { "docstring": "Compute the SHA-256 hash of the file content.", "function_declaration": "def compute_file_hash(file_path):", "function_name": "compute_file_hash", "parameter_list": "(file_path)" }, { "docstring": "Removes duplicate files in the directory based on their contents.\n\nArgs:\n ...
[ 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": "import os\nimport hashlib\n\ndef hash_file(file_path, chunk_size=1024):\n hash_func = hashlib.sha256()\n with open(file_path, 'rb') as f:\n for chun...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020990", "row_id": 20990, "seed_ids": "[3136]" }
0.613417
Algorithm_20990
I
[ "compute_file_hash", "remove_duplicates" ]
2
[ [ "remove_duplicates", "compute_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d29d49fe67fb4a781575bb7ed45ffc01ae96153c
105db9c94f1ab3b10a18a0124273b1d5768a9ba4
v1.0
instruct
Algorithm
Algorithm_21024_I
### Scenario You are a software developer for an online bookstore. One of your tasks is to implement a recommendation system that helps users discover new books based on their reading history and ratings. The system uses a collaborative filtering algorithm to suggest new books to users. ### Task Write a function `reco...
from typing import Dict, List from collections import defaultdict import math def cosine_similarity(user_ratings1: Dict[str, int], user_ratings2: Dict[str, int]) -> float: common_books = set(user_ratings1.keys()).intersection(set(user_ratings2.keys())) if not common_books: return 0.0 sum1 = su...
from solution import recommend_books def test_recommend_books_example1(): user_ratings = { 'user1': {'book1': 5, 'book2': 3, 'book3': 4}, 'user2': {'book1': 4, 'book2': 5, 'book3': 3}, 'user3': {'book1': 2, 'book2': 5, 'book3': 5}, 'user4': {'book4': 4, 'book5': 3} } recomme...
[ { "docstring": null, "function_declaration": "def cosine_similarity(user_ratings1, user_ratings2):", "function_name": "cosine_similarity", "parameter_list": "(user_ratings1, user_ratings2)" }, { "docstring": null, "function_declaration": "def recommend_books(user_ratings, target_user, nu...
[ 1, 0, 0, 1, 1, 0, 0, 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 Dict, List, Tuple\nimport math\nfrom collections import defaultdict\n\ndef cosine_similarity(user1_ratings: Dict[str, int], user2_ratings: Dic...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000021024", "row_id": 21024, "seed_ids": "[300]" }
0.66783
Algorithm_21024
I
[ "cosine_similarity", "recommend_books" ]
2
[ [ "recommend_books", "cosine_similarity" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4f3ce1fafbc7110716ec5050fe6515b0861d6c1b
63bbea76a63cc400b1f1fba292e693374b9fd414
v1.0
instruct
Algorithm
Algorithm_21073_I
### Problem Statement You are tasked with determining if the given number is a special type of number known as a 'Palindromic Prime'. A Palindromic Prime is a number that is both prime and reads the same forwards and backwards, such as 131 or 727. ### Function Requirements You need to implement the following functio...
def is_prime(n: int) -> bool: """ Returns True if n is a prime number, else False. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return Fa...
from solution import is_prime, is_palindrome, palindromic_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(131) == True assert is_prime(133) == False assert is_prime(1) == False assert is_prime(0) == False asser...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns True if n is a palindrome, else False.", "function_declaration": "def is_palindrome(n):", "fu...
[ 0, 1, 1, 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": "def is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is a prime number.\n :param n: Integer to check for primality.\n :return: True if n is pri...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000021073", "row_id": 21073, "seed_ids": "[2765]" }
0.713391
Algorithm_21073
I
[ "is_prime", "is_palindrome", "palindromic_prime" ]
3
[ [ "palindromic_prime", "is_palindrome" ], [ "palindromic_prime", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f471bfecd8b0cbc34f90d5c08878a07e689a0787
8f33731388125529ef54e0ee773ea5ac6cf59d87
v1.0
instruct
Algorithm
Algorithm_21129_I
### Problem Statement: You're required to create a function that computes the minimum total cost to connect all points in a 2D plane. Each point is represented by its coordinates `(x, y)`. Connecting any two points `(xi, yi)` and `(xj, yj)` incurs a cost given by the Manhattan distance between them, which is defined as...
from heapq import heappop, heappush from typing import List, Tuple def manhattan_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> int: """ Calculate the manhattan distance between two points. """ return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) def min_cost_connect_points(points: List[Tuple[int, in...
from solution import min_cost_connect_points def test_example_cases(): assert min_cost_connect_points([(0, 0), (2, 2), (3, 10), (5, 2), (7, 0)]) == 20 assert min_cost_connect_points([(3, 12), (-2, 5), (-4, 1)]) == 18 def test_single_point(): assert min_cost_connect_points([(0, 0)]) == 0 def test_two_poin...
[ { "docstring": "Calculate the manhattan distance between two points.", "function_declaration": "def manhattan_distance(p1, p2):", "function_name": "manhattan_distance", "parameter_list": "(p1, p2)" }, { "docstring": "Returns the minimum cost to connect all points in a 2D plane using the mini...
[ 1, 1, 0, 0, 0, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\n\ndef manhattan_distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n\ndef min_cost_connect_points(points):\n n = len(points)\...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000021129", "row_id": 21129, "seed_ids": "[2785]" }
0.650063
Algorithm_21129
I
[ "manhattan_distance", "min_cost_connect_points" ]
2
[ [ "min_cost_connect_points", "manhattan_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6f3718a65e8b9b6b53b2abdf86175377c2766bfc
48061269d09bc2c23a6746350c0ea845289d2c6c
v1.0
instruct
Algorithm
Algorithm_21208_I
### Prime Anagrams #### Scenario: You are working as a software developer at a cybersecurity firm. One of your tasks is to implement a function to determine special properties of numbers, which can aid in cryptographic algorithms. A particular property of interest is identifying prime anagrams. An anagram of a number ...
def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def is_anagram(n1, n2): return sorted(str(n1)) == sorted(str(n2)) def are_prime_...
from solution import are_prime_anagrams, is_prime, is_anagram def test_are_prime_anagrams(): assert are_prime_anagrams(13, 31) == True assert are_prime_anagrams(13, 37) == False assert are_prime_anagrams(17, 71) == True assert are_prime_anagrams(23, 32) == False assert are_prime_anagrams(113, 131) ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_anagram(n1, n2):", "function_name": "is_anagram", "parameter_list": "(n1, n2)" }, { "docstring": n...
[ 1, 0, 1, 0, 0, 1, 1, 0, 0 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise returns False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000021208", "row_id": 21208, "seed_ids": "[1849]" }
0.590534
Algorithm_21208
I
[ "is_prime", "is_anagram", "are_prime_anagrams" ]
3
[ [ "are_prime_anagrams", "is_anagram" ], [ "are_prime_anagrams", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
32b54d75f7e51284f97f6ecc674d03c6a394ac23
c02449c8d10acf16c7e3ecfe2622aafbf5a8ba56
v1.0
instruct
Algorithm
Algorithm_21229_I
### Question: Implementing an Efficient Sorting Algorithm with Threading **Context**: Sorting is a fundamental task in computer science. Your task is to implement an efficient sorting algorithm that leverages the power of multithreading to enhance performance. The algorithm should be a multi-threaded version of QuickS...
from concurrent.futures import ThreadPoolExecutor from typing import List def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] ...
from solution import multi_threaded_quick_sort def test_empty_list(): assert multi_threaded_quick_sort([]) == [] def test_single_element(): assert multi_threaded_quick_sort([1]) == [1] def test_sorted_list(): assert multi_threaded_quick_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_reverse_sorted_li...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quicksort(arr, low, high):", "function_name": "quicksort", "parameter_list": "(ar...
[ 0, 0, 1, 1, 0, 0, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\n\ndef quick_sort(arr, low, high):\n if low < high:\n p = part...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000021229", "row_id": 21229, "seed_ids": "[4018]" }
0.475789
Algorithm_21229
I
[ "partition", "quicksort", "threaded_quicksort", "multi_threaded_quick_sort" ]
4
[ [ "multi_threaded_quick_sort", "threaded_quicksort" ], [ "quicksort", "partition" ], [ "threaded_quicksort", "partition" ], [ "threaded_quicksort", "quicksort" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7e456aa8fb61b1694ea53f6169eaff337b6ebc47
d47efae1f9c28d456612559e0476c328800e23e1
v1.0
instruct
Algorithm
Algorithm_21265_I
## Problem Statement You are given a non-negative integer `n`. Your task is to implement a function that calculates the n-th Fibonacci number using matrix exponentiation. Additionally, implement a function that calculates the n-th Fibonacci number modulo `m`. ### Function Signature ```python def fibonacci_matrix(n: in...
def matrix_mult(A, B): return [ [A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[0][1]*B[1][1]], [A[1][0]*B[0][0] + A[1][1]*B[1][0], A[1][0]*B[0][1] + A[1][1]*B[1][1]] ] def matrix_mult_mod(A, B, m): return [ [(A[0][0]*B[0][0] + A[0][1]*B[1][0]) % m, (A[0][0]*B[0][1] + A[0][1...
from solution import fibonacci_matrix, fibonacci_matrix_mod def test_fibonacci_matrix(): assert fibonacci_matrix(0) == 0 assert fibonacci_matrix(1) == 1 assert fibonacci_matrix(2) == 1 assert fibonacci_matrix(3) == 2 assert fibonacci_matrix(4) == 3 assert fibonacci_matrix(5) == 5 assert fib...
[ { "docstring": null, "function_declaration": "def matrix_mult(A, B):", "function_name": "matrix_mult", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def matrix_mult_mod(A, B, m):", "function_name": "matrix_mult_mod", "parameter_list": "(A, B, m)" }...
[ 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": "def matrix_mult(A, B, mod=None):\n \"\"\"\n Multiplies two 2x2 matrices A and B, with optional modulus.\n \"\"\"\n if mod:\n return [[(A[0][0]...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000021265", "row_id": 21265, "seed_ids": "[3596]" }
0.703188
Algorithm_21265
I
[ "matrix_mult", "matrix_mult_mod", "matrix_pow", "matrix_pow_mod", "fibonacci_matrix", "fibonacci_matrix_mod" ]
6
[ [ "fibonacci_matrix", "matrix_pow" ], [ "fibonacci_matrix_mod", "matrix_pow_mod" ], [ "matrix_pow", "matrix_mult" ], [ "matrix_pow_mod", "matrix_mult_mod" ] ]
4
[]
false
[]
false
pytest
true
[]
true
bbd466dbf91d3de0a6e88fe0a15f5ce4ef4cfa4f
0a81c5e38fdcb31ba2f3c136c4b1d4f20f50cd97
v1.0
instruct
Algorithm
Algorithm_21327_I
### Coding Assessment Question: Implementing K-Nearest Neighbors (K-NN) from Scratch #### Objective Implement the K-Nearest Neighbors (K-NN) algorithm from scratch to classify data into categories. This problem will test your understanding of distance metrics, sorting, and the concept of nearest neighbors in a dataset...
import numpy as np from collections import Counter def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float: """ Computes the Euclidean distance between two points. Parameters: - point1: np.ndarray - point2: np.ndarray Returns: - float: Euclidean distance. """ ...
import numpy as np from solution import euclidean_distance, k_nearest_neighbors def test_euclidean_distance_same_point(): point1 = np.array([1.0, 2.0]) point2 = np.array([1.0, 2.0]) assert euclidean_distance(point1, point2) == 0.0 def test_euclidean_distance_different_points(): point1 = np.array([1.0,...
[ { "docstring": "Computes the Euclidean distance between two points.\n\nParameters:\n- point1: np.ndarray\n- point2: np.ndarray\n\nReturns:\n- float: Euclidean distance.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(poi...
[ 1, 0, 1, 1, 0, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float:\n \"\"\"\n Computes the Euc...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000021327", "row_id": 21327, "seed_ids": "[399]" }
0.690868
Algorithm_21327
I
[ "euclidean_distance", "k_nearest_neighbors" ]
2
[ [ "k_nearest_neighbors", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
d9d69762c95e8547640df506dcc9a470bf738e5f
2f8542dc5aa9f4e447ed925479c4edb13df9b052
v1.0
instruct
Algorithm
Algorithm_21354_I
### Problem Statement You are to implement a genetic algorithm (GA) to solve the OneMax problem, where the objective is to maximize the number of ones in a binary string. Write a function `evolve` that evolves a population of binary strings to find the optimal string consisting entirely of ones. ### Input Format The...
import random def initialize_population(population_size, chromosome_length): return [''.join(random.choice('01') for _ in range(chromosome_length)) for _ in range(population_size)] def fitness(chromosome): return chromosome.count('1') def select_parents(population, fitnesses): total_fitness = sum(fitness...
from solution import evolve def test_max_fitness_chromosome_length_10(): max_fitness, best_chromosome = evolve(10, 10, 0.01, 100) assert max_fitness == 10 assert best_chromosome == '1111111111' def test_max_fitness_chromosome_length_20(): max_fitness, best_chromosome = evolve(20, 20, 0.01, 200) as...
[ { "docstring": null, "function_declaration": "def initialize_population(population_size, chromosome_length):", "function_name": "initialize_population", "parameter_list": "(population_size, chromosome_length)" }, { "docstring": null, "function_declaration": "def fitness(chromosome):", ...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\n\ndef initialize_population(population_size, chromosome_length):\n population = []\n for _ in range(population_size):\n chromosome = ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000021354", "row_id": 21354, "seed_ids": "[5082]" }
0.505017
Algorithm_21354
I
[ "initialize_population", "fitness", "select_parents", "crossover", "mutate", "evolve" ]
6
[ [ "evolve", "crossover" ], [ "evolve", "fitness" ], [ "evolve", "initialize_population" ], [ "evolve", "mutate" ], [ "evolve", "select_parents" ] ]
5
[]
false
[]
false
pytest
true
[]
true
8ef51b1bab7526150a51de3291af9fd910353f8f
7385a5e8ab9f6392a7526f4389e4c0382c58698c
v1.0
instruct
Algorithm
Algorithm_21391_I
### Coding Question #### Introduction: Sorting algorithms are fundamental to computer science and numerous applications depend on their efficiency. Merge Sort is a classic divide-and-conquer algorithm that reliably sorts data in O(n log n) time. In this task, you will implement the Merge Sort algorithm to sort an inpu...
from typing import List def merge_sort(numbers: List[int]) -> List[int]: if len(numbers) <= 1: return numbers # Base case: a list of one element is inherently sorted # Recursive case: divide the list into halves and sort each half middle = len(numbers) // 2 left_half = merge_sort(numbers[:midd...
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_sorted_list(): ...
[ { "docstring": null, "function_declaration": "def merge_sort(numbers):", "function_name": "merge_sort", "parameter_list": "(numbers)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 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": "from typing import List\n\ndef merge_sort(numbers: List[int]) -> List[int]:\n if len(numbers) <= 1:\n return numbers\n \n mid = len(numbers) // 2...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000021391", "row_id": 21391, "seed_ids": "[4233]" }
0.64895
Algorithm_21391
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
128cf14927f4a4aaee7d0e3614ed8434a5f3da16
f046ff4ea26885a970dc9b3a0c46274f96127f82
v1.0
instruct
Algorithm
Algorithm_21394_I
### Coding Assessment Question Write a function `find_kth_smallest_unsorted` that finds the k-th smallest element in an unsorted array using the Quickselect algorithm. Quickselect is a selection algorithm to find the k-th smallest (or largest) element in an unordered list. It is related to the quicksort sorting algorit...
def partition(arr, left, right, pivot_index): pivot_value = arr[pivot_index] # Move pivot to the end arr[pivot_index], arr[right] = arr[right], arr[pivot_index] store_index = left # Move all elements smaller than pivot_value to the left for i in range(left, right): if arr[i] < pivot...
from solution import find_kth_smallest_unsorted def test_find_kth_smallest_unsorted(): assert find_kth_smallest_unsorted([3, 1, 2, 4, 5], 2) == 2 assert find_kth_smallest_unsorted([7, 10, 4, 3, 20, 15], 3) == 7 assert find_kth_smallest_unsorted([100, 90, 80, 70], 4) == 100 assert find_kth_smallest_unso...
[ { "docstring": null, "function_declaration": "def partition(arr, left, right, pivot_index):", "function_name": "partition", "parameter_list": "(arr, left, right, pivot_index)" }, { "docstring": null, "function_declaration": "def quickselect(arr, left, right, k):", "function_name": "q...
[ 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 random\n\ndef partition(arr, left, right, pivot_index):\n pivot_value = arr[pivot_index]\n # Move pivot to end\n arr[pivot_index], arr[right] = a...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000021394", "row_id": 21394, "seed_ids": "[3197]" }
0.584716
Algorithm_21394
I
[ "partition", "quickselect", "find_kth_smallest_unsorted" ]
3
[ [ "find_kth_smallest_unsorted", "quickselect" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2e00a1f62fce7d45f173b58a7bcfe0e6a252c818
eab98d11b6f82f9a5a44a8e2482b5928249b4850
v1.0
instruct
Algorithm
Algorithm_21438_I
### Context A delivery company needs to optimize its route planning software to minimize the travel distance for its drivers. They have a list of delivery locations and need to determine the optimal sequence of deliveries to minimize the total travel distance, starting and ending at the main distribution center. ### ...
from typing import List, Tuple import math def euclidean_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float: """ Calculate the Euclidean distance between two points p1 and p2. """ return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def optimal_delivery_route(locations: List[Tuple[in...
from solution import optimal_delivery_route def test_simple_case(): assert optimal_delivery_route([(1, 1)], (0, 0)) == [(0, 0), (1, 1), (0, 0)] def test_multiple_locations(): result = optimal_delivery_route([(1, 1), (2, 2), (3, 3)], (0, 0)) expected = [(0, 0), (1, 1), (2, 2), (3, 3), (0, 0)] assert re...
[ { "docstring": "Calculate the Euclidean distance between two points p1 and p2.", "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": "Finds the optimal route to visit all given locations exactly once...
[ 1, 0, 1, 0, 0, 1, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n return math.sqrt((point1[0...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000021438", "row_id": 21438, "seed_ids": "[5357]" }
0.687613
Algorithm_21438
I
[ "euclidean_distance", "optimal_delivery_route" ]
2
[ [ "optimal_delivery_route", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bab47d61a9645b8d513851a1cd7627f1d6bdb243
13b68c648fb12edd86ff4bf5a63f5fe7bed96456
v1.0
instruct
Algorithm
Algorithm_21473_I
### Decision Tree Classifier Implementation **Problem Statement**: Implement a Decision Tree classifier from scratch in Python. Your task is to understand and implement the key components and functionalities of the Decision Tree algorithm as provided in the code snippets. Demonstrate your coding proficiency by writing...
import numpy as np def entropy(y): """ Calculate the entropy of label array y. """ hist = np.bincount(y) ps = hist / len(y) return -np.sum([p * np.log2(p) for p in ps if p > 0]) def split(X, y, feature, threshold): """ Split the dataset X, y based on a feature and a feature value thres...
import pytest import numpy as np from solution import entropy, split, information_gain, build_tree def test_entropy(): assert entropy(np.array([0, 0, 0, 1, 1, 1])) == 1.0 assert np.isclose(entropy(np.array([0, 1])), 1.0) assert np.isclose(entropy(np.array([0, 0, 0, 1])), 0.8112781244591328, atol=1e-6) def...
[ { "docstring": "Calculate the entropy of label array y.", "function_declaration": "def entropy(y):", "function_name": "entropy", "parameter_list": "(y)" }, { "docstring": "Split the dataset X, y based on a feature and a feature value threshold", "function_declaration": "def split(X, y, f...
[ 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 numpy as np\n\ndef entropy(y):\n \"\"\"\n Calculate the entropy of a list of labels.\n \"\"\"\n unique_labels, counts = np.unique(y, return_co...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000021473", "row_id": 21473, "seed_ids": "[385]" }
0.611189
Algorithm_21473
I
[ "entropy", "split", "information_gain", "best_split", "build_tree" ]
5
[ [ "best_split", "information_gain" ], [ "best_split", "split" ], [ "build_tree", "best_split" ], [ "build_tree", "split" ], [ "information_gain", "entropy" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
5745821995f297720864d044e59577a28d94efe9
d411526e6fd62f7a5fc18c87c34b585da4e492ec
v1.0
instruct
Algorithm
Algorithm_21635_I
Warehouse Robot Path Planning You are tasked with implementing a simple path planning algorithm for a warehouse robot. The warehouse is represented as a 2D grid where each cell can be either empty, an obstacle, or the destination. The robot starts at a given position on the grid and must find the shortest path to the ...
import heapq from typing import List, Tuple, Optional 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 find_path(grid: List[List[int]], start: Tuple[int, int], destination: Tupl...
from solution import find_path def test_simple_path(): grid = [ [0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 1, 1, 0], [2, 0, 0, 0, 0] ] start = (0, 0) destination = (4, 0) expected_path = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)] assert find_...
[ { "docstring": "Calculate the Manhattan distance between points a and b.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Finds the shortest path in a 2D grid from start to destination avoiding obstacles. Uses A* al...
[ 0, 0, 1, 0, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nfrom typing import List, Tuple, Optional\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:\n \"\"\"\n Calculate the Manhattan ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000021635", "row_id": 21635, "seed_ids": "[1724]" }
0.613491
Algorithm_21635
I
[ "heuristic", "find_path" ]
2
[ [ "find_path", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6617dcad688c0a4e2469b4d252f2ebbb42ac4237
6dc69c76e08b5d481ad2cd7c838c4ab9de268241
v1.0
instruct
Algorithm
Algorithm_21686_I
### Question You are tasked with developing a function that detects and corrects common spelling errors in a given document. The typical spelling errors include the following types: 1. Single-character insertion (e.g., "speling" should be corrected to "spelling"). 2. Single-character deletion (e.g., "speling" should be...
from typing import List, Dict def levenshtein_distance(word1: str, word2: str) -> int: """Calculate the Levenshtein distance between two words.""" m, n = len(word1), len(word2) if m < n: word1, word2 = word2, word1 m, n = n, m previous_row = range(n + 1) for i, c1 in enumerate(word...
from solution import correct_spelling def test_correct_spelling_with_typical_errors(): text = "I have just finised readng a book caled The Art of Spelking Correction" dictionary = ["I", "have", "just", "finished", "reading", "a", "book", "called", "The", "Art", "of", "Spelling", "Correction"] expected_outp...
[ { "docstring": "Calculate the Levenshtein distance between two words.", "function_declaration": "def levenshtein_distance(word1, word2):", "function_name": "levenshtein_distance", "parameter_list": "(word1, word2)" }, { "docstring": "Correct misspelled words in the text based on the provided...
[ 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 typing import List, Dict\nimport numpy as np\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n \"\"\"\n Calculate the Levenshtein distance betwe...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000021686", "row_id": 21686, "seed_ids": "[4160]" }
0.519551
Algorithm_21686
I
[ "levenshtein_distance", "correct_spelling" ]
2
[ [ "correct_spelling", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
02e957af99c08d91c4e4d9e02aeeecf7eeb515da
d3746064c285cda171f09b62da772ab2eaaa3b53
v1.0
instruct
Algorithm
Algorithm_21710_I
Coding Assessment Question #### Context: You are required to implement a function that calculates the maximum flow in a given flow network using the Ford-Fulkerson algorithm with the Edmonds-Karp implementation. This algorithm finds the maximal flow from a source vertex to a sink vertex in a flow network. #### Task: ...
from typing import List from collections import deque def bfs(rGraph: List[List[int]], s: int, t: int, parent: List[int]) -> bool: """ Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path. """ visited = [False] * len(rGraph) queue ...
from solution import max_flow def test_example_case(): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] source = 0 sink = 5 assert max_flow(graph, source, sink) ==...
[ { "docstring": "Returns true if there is a path from source 's' to sink 't' in residual graph.\nAlso fills parent[] to store the path.", "function_declaration": "def bfs(rGraph, s, t, parent):", "function_name": "bfs", "parameter_list": "(rGraph, s, t, parent)" }, { "docstring": "Returns the...
[ 1, 1, 0, 0, 1, 1, 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": "from collections import deque\n\ndef bfs(graph, residual_graph, source, sink, parent):\n visited = [False] * len(graph)\n queue = deque([source])\n visi...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000021710", "row_id": 21710, "seed_ids": "[3864]" }
0.613344
Algorithm_21710
I
[ "bfs", "max_flow" ]
2
[ [ "max_flow", "bfs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fff41293479e506abd387141b45445d66237eaa1
a99856b7358220eb45cace2acf1688a4b919e015
v1.0
instruct
Algorithm
Algorithm_21776_I
### Lieferkette Routing Optimization using Dijkstra's Algorithm **Background**: A logistics company needs to optimize the routes for its delivery trucks. The company wants to ensure quick delivery times by finding the shortest paths between distribution centers in a network of cities. You are tasked with implementing ...
import heapq def dijkstra_algorithm(graph, start): """ Implements Dijkstra's algorithm to find the shortest path from the start node to all other nodes. Args: graph (dict): a dictionary representing the weighted graph. start (str): the starting node. Returns: dict: a dictionary wi...
from solution import find_shortest_paths def test_find_shortest_paths(): graph = { 'A': {'B': 1, 'C': 4}, 'B': {'C': 2, 'D': 5}, 'C': {'D': 1}, 'D': {} } start = 'A' result = find_shortest_paths(graph, start) expected = {'A': 0, 'B': 1, 'C': 3, 'D': 4} assert res...
[ { "docstring": "Implements Dijkstra's algorithm to find the shortest path from the start node to all other nodes.\n\nArgs:\ngraph (dict): a dictionary representing the weighted graph.\nstart (str): the starting node.\n\nReturns:\ndict: a dictionary with the shortest distance from the start node to every other n...
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\n\ndef find_shortest_paths(graph, start):\n \"\"\"\n Implements Dijkstra's algorithm to find the shortest path from start city to all other ci...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000021776", "row_id": 21776, "seed_ids": "[579]" }
0.666171
Algorithm_21776
I
[ "dijkstra_algorithm", "find_shortest_paths" ]
2
[ [ "find_shortest_paths", "dijkstra_algorithm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ee36e702fcc3be61a3380fdfe5df3b785c7229eb
75d4c5f224906a6511b0c7772141e1b0ee0da938
v1.0
instruct
Algorithm
Algorithm_21853_I
### Coding Assessment Question You are tasked with writing a Python function that processes a list of given date strings, formats them into a standard representation, and sorts them in chronological order. **Function Description:** Write a function `process_and_sort_dates(dates: List[str]) -> List[str]` that proces...
from typing import List from datetime import datetime def convert_to_standard_date_format(date_str: str) -> str: """ Converts a date string in a specific format to the standard YYYY-MM-DD format. """ for fmt in ("%d/%m/%Y", "%m-%d-%Y", "%Y.%m.%d"): try: return datetime.strptime(date...
from solution import process_and_sort_dates def test_process_and_sort_dates(): input_dates = [ "25/12/2020", "01-01-2021", "2020.11.20" ] expected_output = [ "2020-11-20", "2020-12-25", "2021-01-01" ] assert process_and_sort_dates(input_dates) == expe...
[ { "docstring": "Converts a date string in a specific format to the standard YYYY-MM-DD format.", "function_declaration": "def convert_to_standard_date_format(date_str):", "function_name": "convert_to_standard_date_format", "parameter_list": "(date_str)" }, { "docstring": "Processes a list of...
[ 0, 1, 1, 1, 1, 0, 0, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nfrom datetime import datetime\n\ndef convert_to_standard_format(date: str) -> str:\n \"\"\"\n Converts a date string of various fo...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000021853", "row_id": 21853, "seed_ids": "[4408]" }
0.600829
Algorithm_21853
I
[ "convert_to_standard_date_format", "process_and_sort_dates" ]
2
[ [ "process_and_sort_dates", "convert_to_standard_date_format" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab83387a8d983eb17fa1894a7cd2eaad4424106d
187e285e0a87c5b32ceb841979c8b7825c559882
v1.0
instruct
Algorithm
Algorithm_21858_I
### Coding Assessment Question #### Scenario: Parallel Matrix Multiplication You are tasked with optimizing a matrix multiplication operation to leverage the parallel processing capabilities of a multi-core processor to speed up computations. Specifically, you will implement a parallel matrix multiplication function ...
from typing import List from multiprocessing import Pool def parallel_worker(args): A_row, B, col_idx = args value = sum(A_row[k] * B[k][col_idx] for k in range(len(A_row))) return value def parallel_matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: if not A or not B or...
from solution import parallel_matrix_multiplication import pytest def test_parallel_matrix_multiplication_basic(): A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] result = parallel_matrix_multiplication(A, B) expected = [ [19, 22], [43, 50] ] ...
[ { "docstring": null, "function_declaration": "def parallel_worker(args):", "function_name": "parallel_worker", "parameter_list": "(args)" }, { "docstring": null, "function_declaration": "def parallel_matrix_multiplication(A, B):", "function_name": "parallel_matrix_multiplication", ...
[ 0, 0, 0, 0, 0, 1, 0, 1, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport multiprocessing\n\ndef matrix_multiply_worker(A, B, result, row, col):\n \"\"\"\n Helper function to compute a single eleme...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000021858", "row_id": 21858, "seed_ids": "[898]" }
0.567269
Algorithm_21858
I
[ "parallel_worker", "parallel_matrix_multiplication" ]
2
[ [ "parallel_matrix_multiplication", "parallel_worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5cb710dece7616527ab2cca91a66565ddcaa242d
b03e0863de0fe64f46a76e073a07d7fb9caca6ea
v1.0
instruct
Algorithm
Algorithm_21871_I
### Matrix Rotation Checker **Problem Statement**: You need to implement a function that determines if a given matrix can be rotated 90 degrees clockwise multiple times to become equal to another given matrix. Your task is to write a function `can_rotate_to_match` to check if the transformation is possible. **Functio...
def rotate_90_clockwise(mat): """ Rotate the given matrix 90 degrees clockwise. """ n = len(mat) return [[mat[n - j - 1][i] for j in range(n)] for i in range(n)] def can_rotate_to_match(mat1, mat2): """ Returns whether mat1 can be rotated to match mat2. """ if len(mat1) != len(mat2)...
from solution import can_rotate_to_match def test_match_after_0_degrees(): mat1 = [[1, 2], [3, 4]] mat2 = [[1, 2], [3, 4]] assert can_rotate_to_match(mat1, mat2) == True def test_match_after_90_degrees(): mat1 = [[1, 2], [3, 4]] mat2 = [[3, 1], [4, 2]] assert can_rotate_to_match(mat1, mat2) ==...
[ { "docstring": "Rotate the given matrix 90 degrees clockwise.", "function_declaration": "def rotate_90_clockwise(mat):", "function_name": "rotate_90_clockwise", "parameter_list": "(mat)" }, { "docstring": "Returns whether mat1 can be rotated to match mat2.", "function_declaration": "def ...
[ 1, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rotate_90_clockwise(mat: List[List[int]]) -> List[List[int]]:\n \"\"\"Returns the matrix rotated 90 degrees clockwise.\"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000021871", "row_id": 21871, "seed_ids": "[3359]" }
0.528977
Algorithm_21871
I
[ "rotate_90_clockwise", "can_rotate_to_match" ]
2
[ [ "can_rotate_to_match", "rotate_90_clockwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4adbe7fa6109d6b68defbfd547aff8440e4e263b
27eb8d221a2627176f00564ce7527109bf50b7c9
v1.0
instruct
Algorithm
Algorithm_21873_I
### Image Processing using K-means Clustering **Context**: You are asked to perform image compression using the K-means clustering algorithm. K-means clustering is an unsupervised learning algorithm that partitions data into K number of clusters. By representing the image using fewer colors than the original, we can a...
import numpy as np def initialize_centroids(image: np.ndarray, k: int) -> np.ndarray: """ Randomly pick k unique pixels from the image as the initial centroids. :param image: np.ndarray :param k: int :return: np.ndarray """ flat_image = image.reshape(-1, 3) indices = np.random.choi...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, kmeans_compression def test_initialize_centroids(): image = np.array([[[10, 10, 10], [20, 20, 20]], [[30, 30, 30], [40, 40, 40]]]) k = 2 centroids = initialize_centroids(image, k) ass...
[ { "docstring": "Randomly pick k unique pixels from the image as the initial centroids.\n\n:param image: np.ndarray\n:param k: int\n:return: np.ndarray", "function_declaration": "def initialize_centroids(image, k):", "function_name": "initialize_centroids", "parameter_list": "(image, k)" }, { ...
[ 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef initialize_centroids(image: np.ndarray, k: int) -> np.ndarray:\n \"\"\"\n Randomly initialize k centroids from the image's pixel ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000021873", "row_id": 21873, "seed_ids": "[5321]" }
0.78797
Algorithm_21873
I
[ "initialize_centroids", "assign_clusters", "update_centroids", "kmeans_compression" ]
4
[ [ "kmeans_compression", "assign_clusters" ], [ "kmeans_compression", "initialize_centroids" ], [ "kmeans_compression", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
1ac3ce6d39822e9504ba14e07051dfe83d19b959
608e5bb91b8c97afb6e50eb4cc284dfb068f1e76
v1.0
instruct
Algorithm
Algorithm_21880_I
### Matrix Diagonal Sum Calculation **Context**: Matrix operations are foundational in various fields including computer graphics, machine learning, and scientific computing. One common task is to calculate sums of elements along the diagonals of a matrix. In this exercise, you will implement functions to compute the ...
def primary_diagonal_sum(matrix: list[list[int]]) -> int: """ Computes the sum of the primary diagonal of a square matrix. Args: matrix (list[list[int]]): A square matrix. Returns: int: The sum of the primary diagonal. Raises: ValueError: If the input is not a square matri...
import pytest from solution import primary_diagonal_sum, secondary_diagonal_sum, diagonal_sums def test_primary_diagonal_sum(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] assert primary_diagonal_sum(matrix) == 15 def test_secondary_diagonal_sum(): matrix = [ [1, 2, 3]...
[ { "docstring": "Computes the sum of the primary diagonal of a square matrix.\n\nArgs:\nmatrix (list[list[int]]): A square matrix.\n\nReturns:\nint: The sum of the primary diagonal.\n\nRaises:\nValueError: If the input is not a square matrix.", "function_declaration": "def primary_diagonal_sum(matrix):", ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def primary_diagonal_sum(matrix: list[list[int]]) -> int:\n \"\"\"\n Computes the sum of the primary diagonal of a square matrix.\n :param matrix: A lis...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000021880", "row_id": 21880, "seed_ids": "[3866]" }
0.546311
Algorithm_21880
I
[ "primary_diagonal_sum", "secondary_diagonal_sum", "diagonal_sums" ]
3
[ [ "diagonal_sums", "primary_diagonal_sum" ], [ "diagonal_sums", "secondary_diagonal_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cb10f58324576baa33c8e439d5470418c5cd0315
70ccc0b28878d6cdd40e8fddc46ad1cd75a7e3e5
v1.0
instruct
Algorithm
Algorithm_21917_I
### Problem Statement You are designing a backend system for managing membership subscriptions to an online service. Your task is to implement a function that identifies overlapping memberships from the subscription data. ### Requirements Write a function `detect_overlaps(subscriptions: List[Tuple[str, str, str]]) -...
from typing import List, Tuple from datetime import datetime def parse_date(date_str: str) -> datetime: return datetime.strptime(date_str, "%Y-%m-%d") def detect_overlaps(subscriptions: List[Tuple[str, str, str]]) -> List[Tuple[str, str]]: overlaps = [] n = len(subscriptions) for i in range(n): ...
from solution import detect_overlaps def test_no_overlap(): assert detect_overlaps([ ("alice", "2023-01-01", "2023-02-01"), ("bob", "2023-03-01", "2023-04-01") ]) == [] def test_single_overlap(): assert detect_overlaps([ ("alice", "2023-01-01", "2023-02-01"), ("bob", "2023-...
[ { "docstring": null, "function_declaration": "def parse_date(date_str):", "function_name": "parse_date", "parameter_list": "(date_str)" }, { "docstring": null, "function_declaration": "def detect_overlaps(subscriptions):", "function_name": "detect_overlaps", "parameter_list": "(s...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nfrom datetime import datetime\n\ndef detect_overlaps(subscriptions: List[Tuple[str, str, str]]) -> List[Tuple[str, str]]:\n \"...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000021917", "row_id": 21917, "seed_ids": "[1422]" }
0.563886
Algorithm_21917
I
[ "parse_date", "detect_overlaps" ]
2
[ [ "detect_overlaps", "parse_date" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d8ecbcc92e8b291a13fb3e364ce598bd0e76a108
ae535b2a9fc0f92a8a41b5ffa10c186996392de7
v1.0
instruct
Algorithm
Algorithm_21938_I
### Neural Network Binary Classifier #### Context Neural networks have become a dominant methodology for a wide range of applications, from image classification to natural language processing. Implementing a simple neural network from scratch can help in understanding the underlying mechanics and gradient-based optimi...
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1 - x) def relu(x): return np.maximum(0, x) def relu_derivative(x): return np.where(x > 0, 1, 0) def train_neural_network(X, y, hidden_size, learning_rate, epochs): np.random.seed(42) inpu...
import numpy as np from solution import train_neural_network def test_train_neural_network_shapes(): X = np.array([[0.1, 0.2], [0.4, 0.5], [0.7, 0.8]]) y = np.array([0, 1, 1]) hidden_size = 4 learning_rate = 0.01 epochs = 1000 trained_weights = train_neural_network(X, y, hidden_size, learn...
[ { "docstring": null, "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def sigmoid_derivative(x):", "function_name": "sigmoid_derivative", "parameter_list": "(x)" }, { "docstring...
[ 0, 1, 0, 1, 0, 1, 1, 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 numpy as np\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef sigmoid_derivative(z):\n return z * (1 - z)\n\ndef relu(z):\n return np.maxim...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000021938", "row_id": 21938, "seed_ids": "[4181]" }
0.59819
Algorithm_21938
I
[ "sigmoid", "sigmoid_derivative", "relu", "relu_derivative", "train_neural_network" ]
5
[ [ "train_neural_network", "relu" ], [ "train_neural_network", "relu_derivative" ], [ "train_neural_network", "sigmoid" ], [ "train_neural_network", "sigmoid_derivative" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy" ]
false
dc29b54eebca13366577efb95f8f9c641b812d05
aba3ccc1ccf756de167302b739d652405b421de6
v1.0
instruct
Algorithm
Algorithm_21945_I
### Coding Assessment Question: You are given a list of integers. Your task is to implement the Merge Sort algorithm to sort the list in ascending order. Write a function `merge_sort(arr)` that takes a list of integers `arr` and sorts it using the Merge Sort algorithm. #### Input: * A list of integers `arr` (1 ≤ len(...
def merge_sort(arr): """ Sorts the list arr using the Merge Sort algorithm. Parameters: arr (list): List of integers to sort. Returns: list: Sorted list in ascending order. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) r...
from solution import merge_sort def test_merge_sort_basic(): assert merge_sort([4, 2, 5, 3, 0, 1]) == [0, 1, 2, 3, 4, 5] def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([2]) == [2] def test_merge_sort_presorted(): assert merge_sort([1,...
[ { "docstring": "Sorts the list arr using the Merge Sort algorithm.\n\nParameters:\narr (list): List of integers to sort.\n\nReturns:\nlist: Sorted list in ascending order.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstri...
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half = merge_sort(arr[:mid])\n right_half = merge_sor...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000021945", "row_id": 21945, "seed_ids": "[911]" }
0.674145
Algorithm_21945
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
13358ebc0596a9b1408d664ec9205c276c44f6c6
4eaff50af8ef5d9d1c8b5da7bc7692de42cb913c
v1.0
instruct
Algorithm
Algorithm_21951_I
### User Account Registration System Design and implement a user account registration system. The system should be able to create new user accounts, including necessary validation for user input. Each user account should have a unique username and password which satisfies specific security requirements. #### Function...
# Dictionary to simulate in-memory storage of user accounts user_database = {} def is_valid_username(username: str) -> bool: if 3 <= len(username) <= 20 and username.isalnum(): return True return False def is_valid_password(password: str) -> bool: if len(password) < 8: return False if ...
import pytest from solution import register_user, user_database def setup_function(): # Clean up user_database before each test global user_database user_database.clear() def test_successful_registration(): assert register_user("JohnDoe", "Password1") == 0 assert "JohnDoe" in user_database def te...
[ { "docstring": null, "function_declaration": "def is_valid_username(username):", "function_name": "is_valid_username", "parameter_list": "(username)" }, { "docstring": null, "function_declaration": "def is_valid_password(password):", "function_name": "is_valid_password", "paramet...
[ 1, 1, 1, 0, 0, 0, 0, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "users_db = {}\n\ndef register_user(username: str, password: str) -> int:\n \"\"\"\n Registers a new user with the given username and password.\n \"\"\"\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000021951", "row_id": 21951, "seed_ids": "[4193]" }
0.537005
Algorithm_21951
I
[ "is_valid_username", "is_valid_password", "register_user" ]
3
[ [ "register_user", "is_valid_password" ], [ "register_user", "is_valid_username" ] ]
2
[]
false
[]
false
pytest
true
[]
true
314745fadcf68322541aeea6fa3986d7267f0fe5
93fe99d9a900ed0d80a0c71f7eedc1b2c45b5cec
v1.0
instruct
Algorithm
Algorithm_21991_I
### Question: Matrix Rotation Checker #### Context: A common operation in image processing and computer graphics is rotating a matrix. While you can rotate a matrix by 90, 180, or 270 degrees clockwise, it is often necessary to validate if a given matrix can be transformed into another matrix by any of these rotations...
def rotate_90_degrees(matrix): return [list(row) for row in zip(*matrix[::-1])] def rotate_180_degrees(matrix): return [row[::-1] for row in matrix[::-1]] def rotate_270_degrees(matrix): return [list(row) for row in zip(*matrix)][::-1] def can_rotate_to(original: list[list[int]], target: list[list[int]])...
def test_can_rotate_to_90_degrees(): original = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] target = [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] assert can_rotate_to(original, target) == True def test_can_rotate_to_180_degrees(): original = [ [1, 2, 3], ...
[ { "docstring": null, "function_declaration": "def rotate_90_degrees(matrix):", "function_name": "rotate_90_degrees", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def rotate_180_degrees(matrix):", "function_name": "rotate_180_degrees", "parameter_l...
[ 0, 1, 1, 1, 1, 1, 0, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def can_rotate_to(original: list[list[int]], target: list[list[int]]) -> bool:\n def rotate_90(matrix):\n return [list(row) for row in zip(*matrix[::-1...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000021991", "row_id": 21991, "seed_ids": "[1510]" }
0.637991
Algorithm_21991
I
[ "rotate_90_degrees", "rotate_180_degrees", "rotate_270_degrees", "can_rotate_to" ]
4
[ [ "can_rotate_to", "rotate_180_degrees" ], [ "can_rotate_to", "rotate_270_degrees" ], [ "can_rotate_to", "rotate_90_degrees" ] ]
3
[]
false
[]
false
pytest
false
[]
true
de2eddad4ae65496682aecc414d9eff713e12c19
b6403706e73a54e02c41016474cfd6e7924725c9
v1.0
instruct
Algorithm
Algorithm_22024_I
**Context**: As a software developer for an e-commerce platform, you are tasked with creating an efficient algorithm for recommending products based on user behavior and product attributes. The goal is to suggest products that are similar to those the user has interacted with recently, using their browsing history and...
from typing import List import math def cosine_similarity(vec1: List[float], vec2: List[float]) -> float: """ Computes the cosine similarity between two vectors. """ dot_product = sum(a * b for a, b in zip(vec1, vec2)) magnitude1 = math.sqrt(sum(a * a for a in vec1)) magnitude2 = math.sqrt(sum(...
import pytest from solution import recommend_similar_products, cosine_similarity def test_cosine_similarity(): assert pytest.approx(cosine_similarity([1, 0, 0], [0, 1, 0]), 0.0001) == 0.0 assert pytest.approx(cosine_similarity([1, 0, 0], [1, 0, 0]), 0.0001) == 1.0 assert pytest.approx(cosine_similarity([1,...
[ { "docstring": "Computes the cosine similarity between two vectors.", "function_declaration": "def cosine_similarity(vec1, vec2):", "function_name": "cosine_similarity", "parameter_list": "(vec1, vec2)" }, { "docstring": "Recommends `n` products from the catalog based on cosine similarity wi...
[ 0, 1, 1, 1, 0, 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": "from typing import List\nimport math\n\ndef cosine_similarity(vec1: List[float], vec2: List[float]) -> float:\n dot_product = sum(a * b for a, b in zip(vec1, ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022024", "row_id": 22024, "seed_ids": "[1052]" }
0.519122
Algorithm_22024
I
[ "cosine_similarity", "recommend_similar_products" ]
2
[ [ "recommend_similar_products", "cosine_similarity" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b2f7fe8a830b4219457ab94c46f60a560bbfba49
bce28382e432200f40e9e0445f81f59e0b304b21
v1.0
instruct
Algorithm
Algorithm_22122_I
Sure, here is an additional question following the guidelines provided: --- ### Coding Assessment Question **Title**: Develop a Sentiment Analysis Classifier using NLP Techniques **Task**: Using the provided text data and Natural Language Processing (NLP) methods, construct a function to preprocess the dataset, tra...
import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, f1_score from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_p...
from solution import evaluate_sentiment_classifier def test_evaluate_sentiment_classifier_valid_data(capsys): reviews_data = ["Great movie", "Horrible movie", "It was okay", "Loved it", "Worst film ever"] reviews_labels = [1, 0, 1, 1, 0] evaluate_sentiment_classifier(reviews_data, reviews_labels, 0.2) ...
[ { "docstring": null, "function_declaration": "def preprocess_text(data):", "function_name": "preprocess_text", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def train_classifier(features, target):", "function_name": "train_classifier", "parameter_lis...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000022122", "row_id": 22122, "seed_ids": "[506]" }
0.69108
Algorithm_22122
I
[ "preprocess_text", "train_classifier", "evaluate_sentiment_classifier" ]
3
[ [ "evaluate_sentiment_classifier", "preprocess_text" ], [ "evaluate_sentiment_classifier", "train_classifier" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
08849784c1bd0e3475e60b84e3f2acae5e9d62b2
4ecf966d244b8dbce4b786b828cf3e15f5ffc0d9
v1.0
instruct
Algorithm
Algorithm_22127_I
## Problem: Image Pixel Manipulation In computer graphics and image processing, manipulating image pixels is a common task. In this problem, you are required to adjust the brightness of an image by modifying the RGB values of its pixels. ### Input 1. An integer **M** (1 <= M <= 1000) representing the number of rows ...
from typing import List, Tuple def clamp(value: int) -> int: """Clamp the value to be within the range of 0 to 255.""" return max(0, min(255, value)) def adjust_brightness(image: List[List[Tuple[int, int, int]]], k: int) -> List[List[Tuple[int, int, int]]]: result = [] for row in image: new_ro...
from solution import adjust_brightness def test_increase_brightness(): image = [ [(10, 20, 30), (40, 50, 60)], [(70, 80, 90), (100, 110, 120)] ] k = 20 expected = [ [(30, 40, 50), (60, 70, 80)], [(90, 100, 110), (120, 130, 140)] ] assert adjust_brightness(image, ...
[ { "docstring": "Clamp the value to be within the range of 0 to 255.", "function_declaration": "def clamp(value):", "function_name": "clamp", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def adjust_brightness(image, k):", "function_name": "adjust_bright...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef adjust_brightness(image: List[List[Tuple[int, int, int]]], k: int) -> List[List[Tuple[int, int, int]]]:\n def clamp(valu...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022127", "row_id": 22127, "seed_ids": "[412]" }
0.589634
Algorithm_22127
I
[ "clamp", "adjust_brightness" ]
2
[ [ "adjust_brightness", "clamp" ] ]
1
[]
false
[]
false
pytest
true
[]
true
815bd3b72b190326f88bea1e01936a9361d824f0
a19a8870e98315eab160243ac5a9cd82fee97b2d
v1.0
instruct
Algorithm
Algorithm_22134_I
### Problem Statement Given a list of integers, your task is to write a function that filters out all elements that are prime numbers and returns a new list with the remaining integers. You should also write a separate function that returns the sum of all the prime numbers that were filtered out. ### Constraints 1. Th...
def is_prime(n: int) -> bool: """ Check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 ...
from solution import is_prime, filter_non_primes, sum_of_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(10) == False assert is_prime(11) == True assert is_prime(1) == False assert i...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Filters out all prime numbers from the input list and returns a new list with the remaining integers.", "function_declaration"...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022134", "row_id": 22134, "seed_ids": "[1371]" }
0.667916
Algorithm_22134
I
[ "is_prime", "filter_non_primes", "sum_of_primes" ]
3
[ [ "filter_non_primes", "is_prime" ], [ "sum_of_primes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b7c9f7490be975620e129c6a8a70b5be76cf0448
5d0138a85aaf9f42ea08c935ec02d50937dff98e
v1.0
instruct
Algorithm
Algorithm_22191_I
### Coding Challenge: Efficient Substring Search Given a function that searches for a substring within a given text using a naive approach, optimize the function to use the Knuth-Morris-Pratt (KMP) algorithm for better performance, especially for large strings. ### Task Optimize the `find_substring` function to utili...
def compute_lps(pattern): length = 0 i = 1 lps = [0] * len(pattern) while i < len(pattern): if pattern[i] == pattern[length]: length += 1 lps[i] = length i += 1 else: if length != 0: length = lps[length - 1] ...
from solution import find_substring def test_find_substring_example(): assert find_substring("ABABDABACDABABCABAB", "ABABCABAB") == 10 def test_find_substring_multiple_occurrences(): assert find_substring("hello world", "world") == 6 def test_find_substring_not_found(): assert find_substring("a quick bro...
[ { "docstring": null, "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": null, "function_declaration": "def find_substring(text, pattern):", "function_name": "find_substring", "parameter_list": "(tex...
[ 1, 1, 1, 0, 0, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def compute_lps(pattern: str) -> list:\n \"\"\"\n Computes the Longest Prefix which is also Suffix (LPS) array for the given pattern.\n \"\"\"\n lps ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022191", "row_id": 22191, "seed_ids": "[4248]" }
0.616444
Algorithm_22191
I
[ "compute_lps", "find_substring" ]
2
[ [ "find_substring", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
72424873a1c289063bca17cd878a13900c4b36cd
ae7a3d94c8b60408b77aa8c51e2f0cc6576dc722
v1.0
instruct
Algorithm
Algorithm_22204_I
### Rebalanced Binary Search Tree You are given a `BSTNode` class for a Binary Search Tree (BST), which stores integer values and has pointers to its left and right children. Your task is to implement a function `insert_and_rebalance` that inserts a new value into the BST and then rebalances the tree to ensure it rema...
class BSTNode: def __init__(self, value: int): self.value = value self.left = None self.right = None # Helper Functions def height(node: BSTNode) -> int: if not node: return 0 return max(height(node.left), height(node.right)) + 1 def balance_factor(node: BSTNode) -> int: ...
import pytest from solution import BSTNode, insert_and_rebalance def test_insert_and_rebalance_single_node(): root = BSTNode(10) root = insert_and_rebalance(root, 20) assert root.value == 10 assert root.right.value == 20 assert root.left is None def test_insert_and_rebalance_multiple_left_rotation...
[]
[ 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": "class BSTNode:\n def __init__(self, value: int):\n self.value = value\n self.left = None\n self.right = None\n\n# Helper Functions\ndef h...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000022204", "row_id": 22204, "seed_ids": "[1672]" }
0.669877
Algorithm_22204
I
[ "height", "balance_factor", "rotate_left", "rotate_right", "insert_and_rebalance" ]
5
[ [ "balance_factor", "height" ], [ "insert_and_rebalance", "balance_factor" ], [ "insert_and_rebalance", "rotate_left" ], [ "insert_and_rebalance", "rotate_right" ] ]
4
[]
false
[ "BSTNode" ]
true
pytest
true
[]
true
33ff44d3bb6586ae08962ab9b4071ae6dac07d2d
384682578444ded42d43a241ea19d131886c9e3f
v1.0
instruct
Algorithm
Algorithm_22234_I
### Meeting Scheduler You need to implement a function that finds all possible meeting time slots from a list of participants' availability. Each participant provides a list of their available time slots, and you need to determine the slots where all participants are available for a meeting. Each time slot is represe...
from typing import List def time_to_minutes(time: str) -> int: """Convert time in "HH:MM" format to minutes since 00:00.""" hours, minutes = map(int, time.split(":")) return hours * 60 + minutes def minutes_to_time(minutes: int) -> str: """Convert minutes since 00:00 to time in "HH:MM" format.""" ...
from solution import find_common_slots def test_example_1(): participants = [ ["09:00-10:00", "10:30-12:00", "14:00-16:00"], ["09:30-10:30", "11:30-12:30", "14:00-15:00"], ["08:00-09:00", "10:00-11:00", "14:00-15:30"] ] assert find_common_slots(participants) == ["14:00-15:00"] def ...
[ { "docstring": "Convert time in \"HH:MM\" format to minutes since 00:00.", "function_declaration": "def time_to_minutes(time):", "function_name": "time_to_minutes", "parameter_list": "(time)" }, { "docstring": "Convert minutes since 00:00 to time in \"HH:MM\" format.", "function_declarat...
[ 0, 1, 1, 0, 1, 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": "from typing import List\n\ndef parse_time_slot(slot):\n start, end = slot.split('-')\n start_hours, start_minutes = map(int, start.split(':'))\n end_hou...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000022234", "row_id": 22234, "seed_ids": "[2542]" }
0.596968
Algorithm_22234
I
[ "time_to_minutes", "minutes_to_time", "find_common_slots" ]
3
[ [ "find_common_slots", "minutes_to_time" ], [ "find_common_slots", "time_to_minutes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1085e1c8f75213ce8ed964893ad3cb88619d95b7
26802c6fe9a871ad6a5b83af3da77bca34eaa50e
v1.0
instruct
Algorithm
Algorithm_22289_I
### Problem Statement Consider a series of numbers where the next number in the series is generated by reversing the order of the digits of the current number and then adding it to the original number. This series always ends in either: 1. A palindrome (a number that reads the same backward as forward). 2. A pre-defin...
def reverse_number(n): """ Reverses the digits of a given number. """ return int(str(n)[::-1]) def is_palindrome(n): """ Checks if a given number is a palindrome. """ return str(n) == str(n)[::-1] def count_palindrome_numbers(max_start: int = 1000, max_iterations: int = 50) -> int: ...
from solution import count_palindrome_numbers def test_within_one_thousand(): result = count_palindrome_numbers(1000, 50) assert result > 0, "Expected some count of palindromic sequences within 1000." def test_smaller_range(): result = count_palindrome_numbers(10, 50) assert result > 0, "Expected some...
[ { "docstring": "Reverses the digits of a given number.", "function_declaration": "def reverse_number(n):", "function_name": "reverse_number", "parameter_list": "(n)" }, { "docstring": "Checks if a given number is a palindrome.", "function_declaration": "def is_palindrome(n):", "funct...
[ 1, 0, 1, 0, 0, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def reverse_number(n: int) -> int:\n \"\"\"\n Returns the number obtained by reversing the digits of n.\n \"\"\"\n return int(str(n)[::-1])\n\ndef is...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000022289", "row_id": 22289, "seed_ids": "[2936]" }
0.688079
Algorithm_22289
I
[ "reverse_number", "is_palindrome", "count_palindrome_numbers" ]
3
[ [ "count_palindrome_numbers", "is_palindrome" ], [ "count_palindrome_numbers", "reverse_number" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c642a538cb3a1f6928b7a57f32a47bcd98b7a438
8f1a637f2703fe9d90c866bc1cc4443e416eb2a2
v1.0
instruct
Algorithm
Algorithm_22302_I
### Maximum Twin Number Finder **Context**: A twin number is defined as a number that, when reversed, forms itself. For example, 121 and 12321 are twin numbers because reversing them results in 121 and 12321 respectively. **Objective**: Write a function that finds the largest twin number within a specified range. ##...
def is_twin_number(n: int) -> bool: """ Checks if a number is a twin number (i.e., palindrome). """ return str(n) == str(n)[::-1] def max_twin_number(upper_limit: int) -> int: """ Finds the largest twin number less than or equal to the upper_limit. """ for number in range(upper_limit, -...
from solution import is_twin_number, max_twin_number def test_is_twin_number(): assert is_twin_number(121) == True assert is_twin_number(12321) == True assert is_twin_number(1234567) == False assert is_twin_number(0) == True assert is_twin_number(1) == True def test_max_twin_number(): assert m...
[ { "docstring": "Checks if a number is a twin number (i.e., palindrome).", "function_declaration": "def is_twin_number(n):", "function_name": "is_twin_number", "parameter_list": "(n)" }, { "docstring": "Finds the largest twin number less than or equal to the upper_limit.", "function_decla...
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_twin_number(n: int) -> bool:\n \"\"\"\n Checks if a number is a twin number (i.e., palindrome).\n \"\"\"\n return str(n) == str(n)[::-1]\n\nde...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000022302", "row_id": 22302, "seed_ids": "[2212]" }
0.596603
Algorithm_22302
I
[ "is_twin_number", "max_twin_number" ]
2
[ [ "max_twin_number", "is_twin_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be8adccf716359c9e4192e6d8eb7c73b671bbeba
b639019c3f256c309d3939baee9164891b5d3c70
v1.0
instruct
Algorithm
Algorithm_22310_I
### Weather Data Analyzer You are provided with a function to analyze weather data fetched from an API. This function should: 1. Fetch the weather data for a specified location. 2. Parse the JSON response to extract relevant weather information. 3. Calculate and display the average temperature for the next 7 days. 4....
import requests def fetch_weather_data(location): """ Fetches the weather data for the specified location. Args: location (str): The location (city name). Returns: dict: The weather data in JSON format. """ API_KEY = 'your_api_key_here' # Replace with your actual API key BASE_URL...
import pytest from unittest.mock import patch, Mock from solution import fetch_weather_data, analyze_weather_data def test_fetch_weather_data_success(): with patch('solution.requests.get') as mock_get: mock_response = Mock() expected_data = { 'list': [ {'dt': 1634140800,...
[ { "docstring": "Fetches the weather data for the specified location.\n\nArgs:\nlocation (str): The location (city name).\n\nReturns:\ndict: The weather data in JSON format.", "function_declaration": "def fetch_weather_data(location):", "function_name": "fetch_weather_data", "parameter_list": "(locat...
[ 1, 0, 0, 0, 1, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nimport json\n\ndef fetch_weather_data(location):\n \"\"\"\n Fetch weather data for the specified location from a mock API.\n \"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000022310", "row_id": 22310, "seed_ids": "[2300]" }
0.622064
Algorithm_22310
I
[ "fetch_weather_data", "analyze_weather_data" ]
2
[ [ "analyze_weather_data", "fetch_weather_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
0c81411a4afc6f3cf14f153d20529d122695a049
ddbc2797719b129fba8ccbf5aba4114d49a595d1
v1.0
instruct
Algorithm
Algorithm_22473_I
### Question: File Directory Size Summarizer You have been provided with a function that calculates the total size of files in a directory. Your task is to enhance this function to include the following features: file filtering, concurrent size computation, and improved error handling. **Task** 1. Modify the `directo...
import os import asyncio import logging async def file_size(file_path): try: return os.path.getsize(file_path) except Exception as e: logging.error(f"Error reading file {file_path}: {e}") return 0 async def directory_size(path: str, extension_filter: list[str]) -> int: total_size =...
import os import asyncio from solution import directory_size def create_test_files(base_dir): os.makedirs(base_dir, exist_ok=True) test_files = [ ("file1.txt", 100), ("file2.pdf", 200), ("file3.jpg", 300), ] for filename, size in test_files: with open(os.path.join(base_d...
[]
[ 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 os\nimport asyncio\nimport concurrent.futures\nimport logging\n\nlogging.basicConfig(level=logging.ERROR)\n\nasync def directory_size(path: str, extension...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000022473", "row_id": 22473, "seed_ids": "[1953]" }
0.664027
Algorithm_22473
I
[ "file_size", "directory_size" ]
2
[ [ "directory_size", "file_size" ] ]
1
[]
false
[]
false
pytest
true
[]
true
40f419f9725588169873b2564588facc58b47ed1
f4454bdb7c0bb7130977a89985fa6993cc3dd367
v1.0
instruct
Algorithm
Algorithm_22514_I
### Problem Statement Sorting algorithms are foundational in computer science for organizing data. One commonly used sorting algorithm is Merge Sort, which uses a divide-and-conquer strategy to sort elements. #### Task Your task is to implement the `merge_sort` function that sorts an array of integers in non-decreasin...
def merge_sort(arr): """ Sorts an array of integers in non-decreasing order using merge sort. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): """ M...
from solution import merge_sort, merge def test_merge_sort_sorted(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_unsorted(): assert merge_sort([5, 2, 4, 6, 1, 3]) == [1, 2, 3, 4, 5, 6] def test_merge_sort_negatives(): assert merge_sort([-5, -1, -20, -3, -4, 0]) == [-...
[ { "docstring": "Sorts an array of integers in non-decreasing order using merge sort.", "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 ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts the input list of integers in non-decreasing order using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022514", "row_id": 22514, "seed_ids": "[570]" }
0.676918
Algorithm_22514
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
32c34b0f35c12f3e738715ab951e38847f866f6f
037652be622a0777e8c65c8234c8283224723e57
v1.0
instruct
Algorithm
Algorithm_22568_I
### Validate and Calculate Factorial Sum #### Context Understanding factorials and their applications is fundamental in fields like combinatorics and analysis. This exercise will test your ability to calculate factorials and perform basic summation operations programmatically. #### Task Write a function `factorial_su...
from typing import List def factorial(n: int) -> int: """ Helper function to compute the factorial of a positive integer n. """ if n == 0 or n == 1: return 1 result = 1 for i in range(2, n+1): result *= i return result def factorial_sum(numbers: List[int]) -> int: """ ...
from solution import factorial_sum def test_factorial_sum_basic(): assert factorial_sum([1, 2, 3]) == 9 # 1! + 2! + 3! = 1 + 2 + 6 = 9 assert factorial_sum([4, 5]) == 144 # 4! + 5! = 24 + 120 = 144 def test_factorial_sum_empty_list(): assert factorial_sum([]) == 0 def test_factorial_sum_single_element(...
[ { "docstring": "Helper function to compute the factorial of a positive integer n.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Computes the sum of factorials of the input positive integers.", "function_declaration...
[ 1, 1, 1, 0, 1, 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": "from typing import List\n\ndef factorial(n: int) -> int:\n \"\"\"\n Computes the factorial of a given number n.\n \"\"\"\n if n == 0 or n == 1:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022568", "row_id": 22568, "seed_ids": "[4397]" }
0.735921
Algorithm_22568
I
[ "factorial", "factorial_sum" ]
2
[ [ "factorial_sum", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
afcf4346f08a3c42a89bab259ffa89146afcfa01
c5b6a8442e5c9d3cc7ec3c89d920b41a965fb92a
v1.0
instruct
Algorithm
Algorithm_22573_I
### Rot13 Encoder/Decoder With Error Handling In this task, you need to implement a Rot13 encoder and decoder that can handle various input scenarios, including edge cases. Rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. Note that only letters should b...
def rot13_encode(data: str) -> str: """ Encode the given string using ROT13. Only alphabet characters are transformed. Other characters remain unchanged. """ def encode_char(c): if 'a' <= c <= 'z': return chr((ord(c) - ord('a') + 13) % 26 + ord('a')) elif 'A' <= c <= ...
from solution import rot13_encode, rot13_decode def test_rot13_with_letters(): assert rot13_encode("Hello, World!") == "Uryyb, Jbeyq!" assert rot13_decode("Uryyb, Jbeyq!") == "Hello, World!" def test_rot13_with_empty_string(): assert rot13_encode("") == "" assert rot13_decode("") == "" def test_rot13...
[ { "docstring": "Encode the given string using ROT13.\nOnly alphabet characters are transformed.\nOther characters remain unchanged.", "function_declaration": "def rot13_encode(data):", "function_name": "rot13_encode", "parameter_list": "(data)" }, { "docstring": "Decode the given string usin...
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rot13_transform(char):\n \"\"\"\n Helper function to transform a single character using ROT13 substitution.\n \"\"\"\n if char.isalpha():\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000022573", "row_id": 22573, "seed_ids": "[430]" }
0.648185
Algorithm_22573
I
[ "rot13_encode", "rot13_decode" ]
2
[ [ "rot13_decode", "rot13_encode" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c797952e7bb005bb9508b90962ad953c57df8c76
bf71128ea7ce5f714bb46515c17a0ddd8cc0d050
v1.0
instruct
Algorithm
Algorithm_22618_I
### K-Means Clustering Implementation with Optimal 'K' **Context**: You are given a dataset containing geolocation information of various incidents such as emergency service calls within a city. You aim to cluster these incidents into different regions using the K-Means clustering algorithm. However, determining the o...
import numpy as np import matplotlib.pyplot as plt import requests def collect_dataset(url): response = requests.get(url, timeout=10) lines = response.text.splitlines() data = [] for item in lines[1:]: # Skip the header item = item.split(",") data.append([float(coord) for coord in item...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, compute_inertia, kmeans, elbow_method def test_initialize_centroids(): data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]) centroids = initialize_centroids(data, 2) assert centroids.shape == (2, 2) a...
[ { "docstring": null, "function_declaration": "def collect_dataset(url):", "function_name": "collect_dataset", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def initialize_centroids(dataset, k):", "function_name": "initialize_centroids", "parameter_lis...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport requests\n\ndef collect_dataset(url):\n response = requests.get(url, timeout=10)\n lines = resp...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000022618", "row_id": 22618, "seed_ids": "[786]" }
0.729973
Algorithm_22618
I
[ "collect_dataset", "initialize_centroids", "assign_clusters", "update_centroids", "compute_inertia", "kmeans", "elbow_method", "plot_clusters", "main" ]
9
[ [ "elbow_method", "compute_inertia" ], [ "elbow_method", "kmeans" ], [ "kmeans", "assign_clusters" ], [ "kmeans", "initialize_centroids" ], [ "kmeans", "update_centroids" ] ]
5
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "requests" ]
false
302cf309e510540ffee27519f6d2501ec602ede7
b59a04dc687c14075919862d0061f25b85c67fcd
v1.0
instruct
Algorithm
Algorithm_22622_I
**Question 2**: Implementing Merge Sort You are tasked with implementing the Merge Sort algorithm to sort a list of integers in ascending order. ### Problem Statement Given a list of integers, you need to sort the list using the Merge Sort algorithm and return the sorted list. ### Input Format - A list of integers \...
def merge_sort(arr): """ Sorts a list of integers using the Merge Sort algorithm. :param arr: List of integers to sort :return: Sorted list of integers """ if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) ...
from solution import merge_sort def test_merge_sort_with_positive_numbers(): assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62] def test_merge_sort_with_negative_numbers(): assert merge_sort([3, -1, 0, -5, 12, 8]) == [-5, -1, 0, 3, 8, 12] def test_merge_sort_with_mixed_numbers(): assert ...
[ { "docstring": "Sorts a list of integers using the Merge Sort algorithm.\n\n:param arr: List of integers to sort\n:return: Sorted list of integers", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted l...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr: [int]) -> [int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n right = mer...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022622", "row_id": 22622, "seed_ids": "[3667]" }
0.584973
Algorithm_22622
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b686a32e6ff7e2bb205ea23567ec206b68e94a0f
f9489bbb3273128dbdde914b0442fe2a376a46bd
v1.0
instruct
Algorithm
Algorithm_22679_I
### Coding Assessment Question #### Problem Statement You are given an implementation of the k-Nearest Neighbors (k-NN) classifier. Your task is to write a function that will apply this classifier to various input scenarios and compare the classification results with those obtained from the `scikit-learn` library to ...
import numpy as np from sklearn.neighbors import KNeighborsClassifier def knn_classifier(train_data: np.ndarray, train_labels: np.ndarray, test_data: np.ndarray, k: int = 3) -> np.ndarray: """ A simple k-Nearest Neighbors classifier. Parameters: - train_data: A 2D numpy array of shape (num_train_sampl...
import numpy as np from solution import validate_knn_classifier def test_validate_knn_classifier_basic(): train_data = np.array([[1, 2], [2, 3], [8, 9], [5, 6], [3, 3]]) train_labels = np.array([0, 0, 1, 1, 0]) test_data = np.array([[2, 2], [6, 5]]) test_labels = np.array([0, 1]) assert valida...
[ { "docstring": "A simple k-Nearest Neighbors classifier.\n\nParameters:\n- train_data: A 2D numpy array of shape (num_train_samples, num_features).\n- train_labels: A 1D numpy array of shape (num_train_samples,).\n- test_data: A 2D numpy array of shape (num_test_samples, num_features).\n- k: Number of neighbors...
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 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 Tuple\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\n\ndef knn_classifier(\n train_data: np.ndarray,\n train_l...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000022679", "row_id": 22679, "seed_ids": "[3982]" }
0.608595
Algorithm_22679
I
[ "knn_classifier", "validate_knn_classifier" ]
2
[ [ "validate_knn_classifier", "knn_classifier" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
9ad3d6bf3b69f5e3dd3ceaade162c6bb14b01845
1dbe43d276d06a9e1709343a6fbaee9bb00a21e5
v1.0
instruct
Algorithm
Algorithm_22689_I
### Problem Statement: You are tasked with developing a simple inventory system for a small bookstore. The inventory system should allow you to add, remove, and search for books using their unique identifiers (ISBN numbers). Additionally, the system should support bulk operations to add and remove books effectively. ...
inventory = {} def add_book(isbn: str, title: str, author: str, quantity: int) -> None: if isbn not in inventory: inventory[isbn] = {'title': title, 'author': author, 'quantity': quantity} else: inventory[isbn]['quantity'] += quantity def remove_book(isbn: str, quantity: int) -> None: if i...
from solution import add_book, remove_book, search_book, bulk_add_books, bulk_remove_books, inventory def setup_function(): # Reset the inventory before each test inventory.clear() def test_add_book(): setup_function() add_book("978-3-16-148410-0", "The Great Gatsby", "F. Scott Fitzgerald", 30) as...
[ { "docstring": null, "function_declaration": "def add_book(isbn, title, author, quantity):", "function_name": "add_book", "parameter_list": "(isbn, title, author, quantity)" }, { "docstring": null, "function_declaration": "def remove_book(isbn, quantity):", "function_name": "remove_b...
[ 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": "class BookstoreInventory:\n def __init__(self):\n self.inventory = {}\n \n def add_book(self, isbn, title, author, quantity):\n if isbn in...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022689", "row_id": 22689, "seed_ids": "[2819]" }
0.583304
Algorithm_22689
I
[ "add_book", "remove_book", "search_book", "bulk_add_books", "bulk_remove_books" ]
5
[ [ "bulk_add_books", "add_book" ], [ "bulk_remove_books", "remove_book" ] ]
2
[]
false
[]
false
pytest
true
[]
true
21c7c759626fcd1f149f8410ab33f5e4df378597
db03c4606715424fbe1c1a70dc254f1aa6443e33
v1.0
instruct
Algorithm
Algorithm_22789_I
### Coding Assessment Question: Implementing Dynamic Word Counter #### Context: A social media platform wants to add a feature to dynamically count specific words in user-generated posts. This feature would assist in generating real-time statistics about how often specific terms are mentioned. Your task is to help the...
from typing import List, Dict import re def sanitize_text(text: str) -> str: """ Sanitizes the input text by converting to lowercase and removing non-alphanumeric characters. :param text: The text to sanitize. :return: A sanitized string. """ return re.sub(r'[^a-z0-9\s]', '', text.lower())...
from solution import dynamic_word_counter def test_dynamic_word_counter_with_simple_post(): post = "This social platform is great! I love this platform." keywords = ["social", "platform", "love"] expected_output = {'social': 1, 'platform': 2, 'love': 1} assert dynamic_word_counter(post, keywords) == ex...
[ { "docstring": "Sanitizes the input text by converting to lowercase and removing non-alphanumeric characters.\n\n:param text: The text to sanitize.\n:return: A sanitized string.", "function_declaration": "def sanitize_text(text):", "function_name": "sanitize_text", "parameter_list": "(text)" }, ...
[ 0, 1, 1, 1, 0, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\nfrom typing import List, Dict\n\ndef sanitize_text(text: str) -> str:\n \"\"\"\n Sanitizes the text by converting it to lowercase and\n remov...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022789", "row_id": 22789, "seed_ids": "[1451]" }
0.699689
Algorithm_22789
I
[ "sanitize_text", "dynamic_word_counter" ]
2
[ [ "dynamic_word_counter", "sanitize_text" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e0c31b33c462d0f85e5013488f78cd6f04abe223
3ba8e0a301a49140322a9c06a23c2f7505bdaba7
v1.0
instruct
Algorithm
Algorithm_22833_I
### Prime Number Position Calculator You need to write a function that calculates the position of a given prime number in the sequence of prime numbers. For example, the prime number 2 is the 1st prime number, 3 is the 2nd prime number, 5 is the 3rd prime number, and so on. Write a function `prime_position(prime_numb...
import math def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def prime_position(p...
from solution import prime_position, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(1) == False def test_prime_position_valid_cases(): assert prime_posi...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def prime_position(prime_number):", "function_name": "prime_position", "parameter_list": "(prime_number)" } ]
[ 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 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_9
{ "original_instruction": "", "prompt_id": "0000022833", "row_id": 22833, "seed_ids": "[3994]" }
0.731183
Algorithm_22833
I
[ "is_prime", "prime_position" ]
2
[ [ "prime_position", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9eeccb71d59ab159ea581d7731857352f4c864da
248c39012269666781cf3d159d9a6939d360a60e
v1.0
instruct
Algorithm
Algorithm_22854_I
### Order Calculation Problem You are tasked with implementing functions in Python to calculate order totals for an e-commerce platform. Your platform sells items with bulk discount offers, and you need to compute the order total after applying the discounts, if applicable. Each item has a regular price and may be su...
from typing import List, Tuple def apply_discount(price: float, discount: float, minimum_quantity: int, quantity: int) -> float: """ Compute the total cost after applying a bulk discount if the quantity meets the threshold. :param price: Regular price per unit. :param discount: Discounted bulk pri...
import pytest from solution import apply_discount, calculate_order_total def test_apply_discount_regular_price(): assert apply_discount(25.0, 20.0, 5, 4) == 100.0 # 4 * 25.0 def test_apply_discount_bulk_price(): assert apply_discount(10.0, 8.0, 10, 12) == 96.0 # 12 * 8.0 def test_apply_discount_edge_case()...
[ { "docstring": "Compute the total cost after applying a bulk discount if the quantity meets the threshold.\n\n:param price: Regular price per unit.\n:param discount: Discounted bulk price per unit.\n:param minimum_quantity: The minimum quantity required to get the bulk discount.\n:param quantity: The number of ...
[ 1, 0, 0, 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": "from typing import List, Tuple\n\ndef calculate_order_total(items: List[Tuple[str, float, float, int, int]]) -> float:\n \"\"\"\n Computes the total cost o...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022854", "row_id": 22854, "seed_ids": "[605]" }
0.584018
Algorithm_22854
I
[ "apply_discount", "calculate_order_total" ]
2
[ [ "calculate_order_total", "apply_discount" ] ]
1
[]
false
[]
false
pytest
true
[]
true
993a154a9f7551535c2ec1d0c211f38e8d5d6bee
82fa9e9562383476c7cf9afb5b04eba0b71e0b5d
v1.0
instruct
Algorithm
Algorithm_22877_I
### Question: Implement an A* Search Algorithm with Custom Heuristic You are assigned to implement the A* Search Algorithm to find the shortest path from a start node to a goal node in a given weighted graph. Additionally, the algorithm should accept a custom heuristic function to potentially improve the efficiency of...
import heapq class Graph: def __init__(self): self.edges = {} def add_edge(self, node1, node2, weight): if node1 not in self.edges: self.edges[node1] = [] if node2 not in self.edges: self.edges[node2] = [] self.edges[node1].append((node2, weight)) ...
from solution import Graph, a_star_search def simple_heuristic(node, goal): return abs(ord(goal) - ord(node)) def test_path_exists(): graph = Graph() graph.add_edge('A', 'B', 1) graph.add_edge('B', 'C', 2) graph.add_edge('A', 'D', 4) graph.add_edge('C', 'D', 1) graph.add_edge('C', 'E', 3) ...
[]
[ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\n\nclass Graph:\n def __init__(self):\n self.edges = {}\n \n def add_edge(self, node1, node2, weight):\n if node1 not in self...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022877", "row_id": 22877, "seed_ids": "[5342]" }
0.554335
Algorithm_22877
I
[ "a_star_search", "reconstruct_path" ]
2
[ [ "a_star_search", "reconstruct_path" ] ]
1
[]
false
[ "Graph" ]
true
pytest
true
[]
true
b8446400d6d24283072e0a2d30c009d82c827dee
6c854a664242ee4c2e78125689c722f5154985f5
v1.0
instruct
Algorithm
Algorithm_22881_I
### Fibonacci Palindrome Checker Students are required to write a function that checks if a number is both a Fibonacci number and a palindrome. ### Task: Write a function `fibonacci_palindrome(number)` that checks if the given `number` is both a Fibonacci number and a palindrome. If it is, return `'Yes'`, otherwise r...
def is_fibonacci(number): """ Helper function to check if a number is a Fibonacci number. """ if number == 0 or number == 1: return True a, b = 0, 1 while b < number: a, b = b, a + b return b == number def is_palindrome(number): """ Helper function to check if a num...
def test_fibonacci_palindrome(): # Positive tests assert fibonacci_palindrome(0) == 'Yes' # 0 is a Fibonacci number and a palindrome. assert fibonacci_palindrome(1) == 'Yes' # 1 is a Fibonacci number and a palindrome. # Fibonacci numbers that are palindromes assert fibon...
[ { "docstring": "Helper function to check if a number is a Fibonacci number.", "function_declaration": "def is_fibonacci(number):", "function_name": "is_fibonacci", "parameter_list": "(number)" }, { "docstring": "Helper function to check if a number is a palindrome.", "function_declaratio...
[ 0, 1, 1, 0, 1, 0, 0, 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": "def fibonacci_palindrome(number):\n def is_fibonacci(n):\n if n == 0 or n == 1:\n return True\n a, b = 0, 1\n while b < n:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022881", "row_id": 22881, "seed_ids": "[4852]" }
0.628713
Algorithm_22881
I
[ "is_fibonacci", "is_palindrome", "fibonacci_palindrome" ]
3
[ [ "fibonacci_palindrome", "is_fibonacci" ], [ "fibonacci_palindrome", "is_palindrome" ] ]
2
[]
false
[]
false
pytest
false
[]
true
f17dc70ebba479d61f30f10bef2469211b3cea5c
57fedb0c12721b8c70d627a75a8d7c5434436a0b
v1.0
instruct
Algorithm
Algorithm_22895_I
### Question: Implement and Compare Sorting Algorithms You are provided with two well-known sorting algorithms: Merge Sort and Quick Sort. Your task is to implement an additional sorting algorithm (like Heap Sort) and benchmark its performance against the two provided algorithms on the same list of integers. **Functi...
from typing import List def heap_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the Heap Sort algorithm. """ n = len(arr) # Build a maxheap for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n-1, 0...
from solution import heap_sort, merge_sort, quick_sort def test_heap_sort(): assert heap_sort([37, 25, 21, 58, 0, -5]) == [-5, 0, 21, 25, 37, 58] assert heap_sort([10, 5, 2, 3]) == [2, 3, 5, 10] assert heap_sort([4, 1, 3, -2, 0]) == [-2, 0, 1, 3, 4] assert heap_sort([5, 1, 6, 2, 3, 4]) == [1, 2, 3, 4, ...
[ { "docstring": "Sorts a list of integers using the Heap Sort algorithm.", "function_declaration": "def heap_sort(arr):", "function_name": "heap_sort", "parameter_list": "(arr)" }, { "docstring": "To heapify a subtree rooted with node i which is an index in arr[].\nn is size of heap", "fu...
[ 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 heapq\nfrom typing import List\nimport timeit\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n mid = len(ar...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022895", "row_id": 22895, "seed_ids": "[4788]" }
0.627573
Algorithm_22895
I
[ "heap_sort", "heapify", "merge_sort", "merge", "quick_sort" ]
5
[ [ "heap_sort", "heapify" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
371aaf056ab0f839560a3a3f90878588a424425a
081e534ca4fb693d5792b72b40c7286538a6c78c
v1.0
instruct
Algorithm
Algorithm_22924_I
### Question: Implementing K-means Clustering You are given a dataset where each instance has a number of features. Your task is to implement the K-means algorithm to cluster the dataset into `K` clusters. #### Function Signature ```python def kmeans_clustering(data: list[list[float]], k: int, max_iterations: int) ->...
import random from copy import deepcopy from math import sqrt def euclidean_distance(point1, point2): return sqrt(sum((coord1 - coord2) ** 2 for coord1, coord2 in zip(point1, point2))) def compute_centroids(data, assignments, k): clusters = [[] for _ in range(k)] for index, point in enumerate(data): ...
from solution import kmeans_clustering def test_kmeans_basic(): data = [ [1.0, 2.0], [2.0, 3.0], [1.1, 1.9], [10.0, 10.0], [10.1, 10.1], [9.9, 9.8] ] k = 2 max_iterations = 100 result = kmeans_clustering(data, k, max_iterations) assert result...
[ { "docstring": null, "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": null, "function_declaration": "def compute_centroids(data, assignments, k):", "function_name": "comput...
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\nfrom copy import deepcopy\n\ndef kmeans_clustering(data, k, max_iterations):\n \"\"\"\n Perform k-means clustering on the given dataset.\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000022924", "row_id": 22924, "seed_ids": "[629]" }
0.80379
Algorithm_22924
I
[ "euclidean_distance", "compute_centroids", "kmeans_clustering" ]
3
[ [ "kmeans_clustering", "compute_centroids" ], [ "kmeans_clustering", "euclidean_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5b68e0941f91f60552330b5567ac75df2acdc0aa
fcc6dfd7367319d351cea85941dc134d276ed9a9
v1.0
instruct
Algorithm
Algorithm_22933_I
### Coding Assessment Question You are asked to implement two functions that involve examining and working with prime numbers and their sums. You need to validate if a number can be expressed as a sum of exactly two prime numbers, and compute the sum of unique prime factors of a given number. #### Task **Function 1:...
def is_prime(num): if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 return True def is_sum_of_two_primes(n: in...
from solution import is_sum_of_two_primes, sum_of_unique_prime_factors def test_is_sum_of_two_primes_true_cases(): assert is_sum_of_two_primes(10) == True # 3 + 7 or 5 + 5 assert is_sum_of_two_primes(4) == True # 2 + 2 def test_is_sum_of_two_primes_false_cases(): assert is_sum_of_two_primes(11) == Fals...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def is_sum_of_two_primes(n):", "function_name": "is_sum_of_two_primes", "parameter_list": "(n)" }, { ...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000022933", "row_id": 22933, "seed_ids": "[4198]" }
0.654022
Algorithm_22933
I
[ "is_prime", "is_sum_of_two_primes", "prime_factors", "sum_of_unique_prime_factors" ]
4
[ [ "is_sum_of_two_primes", "is_prime" ], [ "sum_of_unique_prime_factors", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
fd410f8786ad2a79281e2ce9f858fde928c08b8f
7a3f58672d9599d3a44ec4efbce5d429ca373a55
v1.0
instruct
Algorithm
Algorithm_22936_I
**Context**: In the realm of algorithmic challenges, it is often useful to evaluate a function by its ability to handle strings and numerical operations efficiently. This problem involves encoding a sequence of lowercase English letters with each letter replaced by its position in the alphabet, concatenated together wi...
def letter_to_number(letter: str) -> int: """ Convert a single lowercase letter to its position in the alphabet (a=1, b=2, ..., z=26). """ return ord(letter) - ord('a') + 1 def encode_string(s: str) -> str: """ Encode the string s by replacing each letter with its position in the alphabet and c...
from solution import letter_to_number, encode_string def test_letter_to_number(): assert letter_to_number('a') == 1 assert letter_to_number('b') == 2 assert letter_to_number('z') == 26 assert letter_to_number('m') == 13 def test_encode_string_basic(): assert encode_string('abc') == '123' asser...
[ { "docstring": "Convert a single lowercase letter to its position in the alphabet (a=1, b=2, ..., z=26).", "function_declaration": "def letter_to_number(letter):", "function_name": "letter_to_number", "parameter_list": "(letter)" }, { "docstring": "Encode the string s by replacing each lette...
[ 0, 0, 1, 1, 1, 1, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def letter_to_number(letter: str) -> int:\n \"\"\"\n Convert a single lowercase letter to its corresponding position in the alphabet.\n \"\"\"\n retu...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000022936", "row_id": 22936, "seed_ids": "[2670]" }
0.692789
Algorithm_22936
I
[ "letter_to_number", "encode_string" ]
2
[ [ "encode_string", "letter_to_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4c8aa31ff9bb238f245947e073f985b2b5659bbe
a7456ddab13b25d1eaee2ecd4e8318694f9bb74b
v1.0
instruct
Algorithm
Algorithm_23044_I
### Problem Statement Write a Python function `bitwise_left_rotate` that performs a left rotation on a given 8-bit integer. A left rotation by one position shifts each bit to the left by one place, with the leftmost bit wrapping around to the rightmost position. Additionally, write a `bitwise_operations_summary` funct...
def bitwise_left_rotate(num: int, shift: int) -> int: """ Returns the result of left rotating an 8-bit integer `num` by `shift` positions. """ shift %= 8 # In case shift is greater than 7, it wraps around return ((num << shift) & 0xFF) | (num >> (8 - shift)) def bitwise_operations_summary(num: int...
def test_bitwise_left_rotate(): assert bitwise_left_rotate(13, 1) == 26 assert bitwise_left_rotate(13, 2) == 52 assert bitwise_left_rotate(13, 3) == 104 assert bitwise_left_rotate(255, 1) == 255 assert bitwise_left_rotate(128, 1) == 1 assert bitwise_left_rotate(128, 8) == 128 assert bitwise_...
[ { "docstring": "Returns the result of left rotating an 8-bit integer `num` by `shift` positions.", "function_declaration": "def bitwise_left_rotate(num, shift):", "function_name": "bitwise_left_rotate", "parameter_list": "(num, shift)" }, { "docstring": "Generates a summary of bitwise operat...
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def bitwise_left_rotate(num: int, shift: int) -> int:\n \"\"\"\n Performs a left rotation on a given 8-bit integer by the given number of positions.\n \...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023044", "row_id": 23044, "seed_ids": "[4194]" }
0.618874
Algorithm_23044
I
[ "bitwise_left_rotate", "bitwise_operations_summary" ]
2
[ [ "bitwise_operations_summary", "bitwise_left_rotate" ] ]
1
[]
false
[]
false
pytest
false
[]
true
23d09a09d324071bc4eef234fd9ea9e2dc9dcb9a
ef81a05d1a46f8f4294f1e0de8f5648063e7a9fa
v1.0
instruct
Algorithm
Algorithm_23082_I
### Problem Description You are given an array `arr` of positive integers. Your task is to find the smallest positive integer that is a multiple of all the numbers in the array. Write a function `find_lcm` that: - Takes `arr` as an input list of positive integers. - Returns the smallest positive integer that is the ...
import math from functools import reduce def lcm(a, b): """ Helper function to find the Least Common Multiple (LCM) of two numbers. """ return abs(a * b) // math.gcd(a, b) def find_lcm(arr): """ Returns the Least Common Multiple (LCM) of all the numbers in the array. """ return reduce(...
from solution import find_lcm def test_lcm_of_array_elements(): assert find_lcm([1, 2, 3, 4, 5]) == 60 assert find_lcm([2, 7, 3, 9, 4]) == 252 assert find_lcm([5, 10, 20]) == 20 assert find_lcm([12, 15, 25]) == 300 assert find_lcm([2]) == 2 assert find_lcm([100, 200, 300]) == 600 assert fin...
[ { "docstring": "Helper function to find the Least Common Multiple (LCM) of two numbers.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the Least Common Multiple (LCM) of all the numbers in the array.", "function_d...
[ 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": "import math\nfrom functools import reduce\n\ndef find_lcm(arr):\n \"\"\"\n Returns the least common multiple (LCM) of all the positive integers in the arra...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023082", "row_id": 23082, "seed_ids": "[2735]" }
0.659909
Algorithm_23082
I
[ "lcm", "find_lcm" ]
2
[ [ "find_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f8fd721856e6fdf8759b4b7b134de6f78f55c151
12d2d3464bceaa502c61d708c0c05195c5d5ce27
v1.0
instruct
Algorithm
Algorithm_23088_I
### Maximum Subarray Sum using Divide and Conquer #### Objective You are given an integer array. Your task is to implement a function that finds the sum of the maximum sum subarray using the divide-and-conquer approach. #### Function Signature ```python def max_subarray_sum(arr: List[int]) -> int: pass ``` #### ...
from typing import List def max_crossing_sum(arr: List[int], left: int, mid: int, right: int) -> int: left_sum = float('-inf') curr_sum = 0 for i in range(mid, left - 1, -1): curr_sum += arr[i] if curr_sum > left_sum: left_sum = curr_sum right_sum = float('-inf') curr_s...
def test_max_subarray_sum(): assert max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6 assert max_subarray_sum([1, 2, 3, 4, 5]) == 15 assert max_subarray_sum([-1, -2, -3, -4]) == -1 assert max_subarray_sum([3, -2, 5, -1]) == 6 assert max_subarray_sum([1, -3, 2, 1, -1]) == 3 assert max_subarr...
[ { "docstring": null, "function_declaration": "def max_crossing_sum(arr, left, mid, right):", "function_name": "max_crossing_sum", "parameter_list": "(arr, left, mid, right)" }, { "docstring": null, "function_declaration": "def max_subarray_sum_recursive(arr, left, right):", "function...
[ 1, 1, 1, 1, 1, 0, 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": "from typing import List\n\ndef max_crossing_sum(arr: List[int], left: int, mid: int, right: int) -> int:\n # Include elements on left of mid.\n left_sum = ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023088", "row_id": 23088, "seed_ids": "[4824]" }
0.769468
Algorithm_23088
I
[ "max_crossing_sum", "max_subarray_sum_recursive", "max_subarray_sum" ]
3
[ [ "max_subarray_sum", "max_subarray_sum_recursive" ], [ "max_subarray_sum_recursive", "max_crossing_sum" ] ]
2
[]
false
[]
false
pytest
false
[]
true
0d40041b00eeb2e01fa4c6eb080bfed8dbc1768b
1fb551fcc60a3f103a17605467ddfc50d319ca29
v1.0
instruct
Algorithm
Algorithm_23157_I
### Assignment: Implement a Basic Multi-threaded Web Server You will be creating a simple multi-threaded web server that can handle multiple client requests concurrently. This will involve setting up a basic server, using threads to manage different client connections, and sending appropriate HTTP responses. ### Task...
import socket import threading def start_server(port): """ Starts a multi-threaded web server that listens on the specified port. Parameters: port (int): The port number on which the server will listen. Returns: None """ server_socket = socket.socket(socket.AF_INET, socket.SOC...
import socket import threading import time from contextlib import closing import pytest from solution import start_server, generate_response @pytest.fixture(scope='module') def server(): port = 8080 server_thread = threading.Thread(target=start_server, args=(port,), daemon=True) server_thread.start() ...
[ { "docstring": "Starts a multi-threaded web server that listens on the specified port.\n\nParameters:\nport (int): The port number on which the server will listen.\n\nReturns:\nNone", "function_declaration": "def start_server(port):", "function_name": "start_server", "parameter_list": "(port)" }, ...
[ 1, 1, 1, 0, 0, 1, 0, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import socket\nimport threading\n\ndef start_server(port):\n \"\"\"\n Starts a multi-threaded web server that listens on the specified port.\n \n Par...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000023157", "row_id": 23157, "seed_ids": "[347]" }
0.627139
Algorithm_23157
I
[ "start_server", "handle_client", "generate_response" ]
3
[ [ "handle_client", "generate_response" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e0325c39e1190b4f45068ea5ad57aba3df9b127e
9ca5b2e488519591e4a49d79aa579a78e3e100ba
v1.0
instruct
Algorithm
Algorithm_23222_I
### Question: You are provided with an implementation of the Segment Tree data structure, which allows for efficient range queries and updates on an array. Your task is to extend this data structure by adding a new method to compute the second minimum value in a specified subarray range. **Function Signature**: ```p...
class Node: def __init__(self, start, end, min_val, second_min_val): self.start = start self.end = end self.min_val = min_val self.second_min_val = second_min_val self.left = None self.right = None def build_segment_tree(arr): def build(start, end): if st...
def test_build_segment_tree(): root = build_segment_tree([1, 3, 2, 7, 5, 4]) assert root.min_val == 1 assert root.second_min_val == 2 def test_second_min_single_element(): root = build_segment_tree([1, 3, 2, 7, 5, 4]) assert second_min(root, 1, 1) == -1 def test_second_min_entire_range(): root...
[]
[ 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": "class SegmentTreeNode:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.min_val = float('inf')\n sel...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000023222", "row_id": 23222, "seed_ids": "[1913]" }
0.571929
Algorithm_23222
I
[ "build_segment_tree", "second_min_query", "second_min" ]
3
[ [ "second_min", "second_min_query" ] ]
1
[]
false
[ "Node" ]
true
pytest
false
[]
true
ba8ae92ceec108f8c50bd1a67b5a57627985755d
0480df549c17ae84aacd0e974cd8bfabd6958bf3
v1.0
instruct
Algorithm
Algorithm_23234_I
### Multi-threaded Summation Multi-threading is a common technique to optimize performance by allowing concurrent execution of code. Each thread can run a part of the function simultaneously, making efficient use of multi-core processors. **Your task** is to implement multi-threaded functions in Python to compute the...
from threading import Thread def sum_range(start: int, end: int) -> int: """ Compute the sum of the integers in the range [start, end). """ return sum(range(start, end)) def worker(start: int, end: int, result: list, index: int): """ Compute the sum for a subrange and store it in the `result` ...
def test_sum_range(): assert sum_range(1, 101) == 5050 assert sum_range(1, 11) == 55 assert sum_range(1, 2) == 1 assert sum_range(50, 100) == sum(range(50, 100)) assert sum_range(1, 1) == 0 def test_multi_threaded_sum(): # Basic sums assert multi_threaded_sum(100, 4) == 5050 assert mult...
[ { "docstring": "Compute the sum of the integers in the range [start, end).", "function_declaration": "def sum_range(start, end):", "function_name": "sum_range", "parameter_list": "(start, end)" }, { "docstring": "Compute the sum for a subrange and store it in the `result` list at the given `...
[ 1, 0, 0, 0, 0, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import threading\n\ndef sum_range(start: int, end: int) -> int:\n \"\"\"\n Returns the sum of integers in the range [start, end)\n \"\"\"\n return su...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023234", "row_id": 23234, "seed_ids": "[297]" }
0.609983
Algorithm_23234
I
[ "sum_range", "worker", "multi_threaded_sum" ]
3
[ [ "worker", "sum_range" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b94950dd7b15950b406a0af24f8d3b708d0e173d
609189f9a24e724def381dddea04f90ec00367f6
v1.0
instruct
Algorithm
Algorithm_23272_I
### Real-Time Stock Price Monitoring App You are tasked with creating a real-time stock price monitoring application that connects to a stock price data provider and periodically fetches and displays the latest price of a given stock. The application must also handle network errors gracefully and retry fetching the pr...
import asyncio import signal import random import logging # Setup logging logging.basicConfig(level=logging.INFO) # Simulated stock price data provider async def fetch_stock_price(stock_symbol): """ Simulates fetching the stock price for a given symbol. Randomly raises ConnectionError to simulate network ...
from solution import monitor_stock_price, fetch_stock_price import asyncio import pytest # Test the mocked fetch_stock_price function def test_fetch_stock_price(): stock_symbol = "AAPL" prices = [] for _ in range(100): try: price = asyncio.run(fetch_stock_price(stock_symbol)) ...
[ { "docstring": null, "function_declaration": "def signal_handler():", "function_name": "signal_handler", "parameter_list": "()" } ]
[ 1, 1, 1, 0, 0, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\nimport random\nimport logging\n\n# Setup logging\nlogging.basicConfig(level=logging.INFO)\n\n# Simulated stock price data provider...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000023272", "row_id": 23272, "seed_ids": "[4273]" }
0.513625
Algorithm_23272
I
[ "fetch_stock_price", "monitor_stock_price" ]
2
[ [ "monitor_stock_price", "fetch_stock_price" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c7e0577e24ad775c2462dd1857d653ec1399d346
65f653c13151cb12b769b09d61245875b27bb366
v1.0
instruct
Algorithm
Algorithm_23292_I
**Binary Search Tree Operations** You are given the root node of a binary search tree (BST). Implement a series of functions to perform various operations on the BST. Implement the functions as described below: #### Function Definitions: 1. **`bst_insert(root: TreeNode, val: int) -> TreeNode`** - **Input**: root:...
from __future__ import annotations from typing import Optional, List class TreeNode: def __init__(self, val: int = 0, left: Optional[TreeNode] = None, right: Optional[TreeNode] = None): self.val = val self.left = left self.right = right def bst_insert(root: TreeNode, val: int) -> TreeNode:...
from solution import TreeNode, bst_insert, bst_search, bst_delete, bst_inorder_traversal def test_bst_insert(): root = TreeNode(8) bst_insert(root, 3) bst_insert(root, 10) bst_insert(root, 1) bst_insert(root, 6) bst_insert(root, 14) bst_insert(root, 4) bst_insert(root, 7) bst_insert...
[]
[ 1, 1, 1, 0, 0, 1, 1, 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": "from typing import Optional, List\n\nclass TreeNode:\n def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None)...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000023292", "row_id": 23292, "seed_ids": "[1475]" }
0.568327
Algorithm_23292
I
[ "bst_insert", "bst_search", "bst_delete", "get_min", "bst_inorder_traversal" ]
5
[ [ "bst_delete", "get_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
c408eb8ccc651ec6c3515b4154bf4ef66695a800
9b0029d06f64f56c98a0d724c7f5e5b18c451f46
v1.0
instruct
Algorithm
Algorithm_23357_I
### Context: You are working on the implementation of a text processing module for a natural language processing (NLP) pipeline. Part of your task is to create a function that can extract and analyze particular text features. ### Task: 1. **Implement Custom Text Processing Functions**: - Implement a function `count...
import re import numpy as np from collections import Counter def count_words(text): """ Counts the number of occurrences of each word in the given text. :param text: A string of text. :return: A dictionary where keys are unique words, and values are their counts. """ # Convert text to lowercas...
from solution import count_words, sentence_length_statistics def test_count_words_single_sentence(): text = "Hello world, hello!" expected = {'hello': 2, 'world': 1} assert count_words(text) == expected def test_count_words_multiple_sentences(): text = "This is a test. This test is simple. Simple is g...
[ { "docstring": "Counts the number of occurrences of each word in the given text.\n\n:param text: A string of text.\n:return: A dictionary where keys are unique words, and values are their counts.", "function_declaration": "def count_words(text):", "function_name": "count_words", "parameter_list": "(...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\nimport numpy as np\nfrom collections import Counter\n\ndef count_words(text):\n \"\"\"\n Count the occurrences of each word in the given text.\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000023357", "row_id": 23357, "seed_ids": "[4235]" }
0.647011
Algorithm_23357
I
[ "count_words", "sentence_length_statistics", "example" ]
3
[ [ "example", "count_words" ], [ "example", "sentence_length_statistics" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
bef1fc89a31616001a12ce374668baa8236d1c74
c57b516d75574206ec410cd20ddac0712d34cbf4
v1.0
instruct
Algorithm
Algorithm_23368_I
### Background In order to compare the efficiency and performance of various sorting algorithms, you need to write a program that can execute different sorting techniques on a given list of integers. To provide a comprehensive comparison, your task involves implementing specific sorting algorithms with a performance me...
import time def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[m...
from solution import compare_sorting_algorithms def test_compare_sorting_algorithms(): import time # Test with unsorted list arr = [64, 34, 25, 12, 22, 11, 90] result = compare_sorting_algorithms(arr) assert 'bubble_sort' in result assert 'merge_sort' in result assert 'quick_sort' in result...
[ { "docstring": null, "function_declaration": "def bubble_sort(arr):", "function_name": "bubble_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import time\n\ndef compare_sorting_algorithms(arr: list) -> dict:\n def bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023368", "row_id": 23368, "seed_ids": "[2403]" }
0.572898
Algorithm_23368
I
[ "bubble_sort", "merge_sort", "quick_sort", "compare_sorting_algorithms" ]
4
[ [ "compare_sorting_algorithms", "bubble_sort" ], [ "compare_sorting_algorithms", "merge_sort" ], [ "compare_sorting_algorithms", "quick_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
1bb71d84aa079db43334f3bd9e81dfa4c1273ea5
f332960ecd48b0a239d14e3990b4c3b07f0410a5
v1.0
instruct
Algorithm
Algorithm_23380_I
### Prime Number Rearrangement **Objective**: Assess the student's ability to work with number theory concepts and practice their sorting and list manipulation skills within a programming context. **Task**: Write a Python function `rearrange_primes` that takes a list of integers, identifies all prime numbers within t...
from typing import List def is_prime(n: int) -> bool: """Helper function to check if a number is prime.""" if n <= 1: return False if n == 2: return True # 2 is the only even prime number if n % 2 == 0: return False # No other even number can be a prime for i in range(3, i...
def test_no_primes(): assert rearrange_primes([1, 4, 6, 8, 10]) == [1, 4, 6, 8, 10] def test_all_primes(): assert rearrange_primes([2, 3, 5, 7, 11]) == [11, 7, 5, 3, 2] def test_mixed_numbers(): assert rearrange_primes([10, 7, 2, 11, 4, 5, 8, 13]) == [10, 13, 11, 7, 4, 5, 8, 2] def test_single_prime(): ...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Rearranges primes in a list in descending order while keeping non-primes in the same positions.", "function...
[ 1, 1, 0, 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": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if an integer is a prime number.\n \"\"\"\n if n <= ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000023380", "row_id": 23380, "seed_ids": "[4124]" }
0.626663
Algorithm_23380
I
[ "is_prime", "rearrange_primes" ]
2
[ [ "rearrange_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
false
[]
true
257609f4f8be0cc883bd4f971e90ea7f5b90551c
7eae099c1cb7cb366d4da021944e755d52ca752a
v1.0
instruct
Algorithm
Algorithm_23466_I
You are tasked with writing a function that searches for the smallest factorial number that is also a palindrome. ### Task Write a function `find_palindromic_factorial() -> int` that finds the smallest factorial number which is a palindrome. A number is a palindrome if it reads the same backwards as forwards. ### In...
def is_palindrome(num): """ Check if a given number is a palindrome. """ return str(num) == str(num)[::-1] def factorial(n): """ Calculate the factorial of a given number n. """ if n == 0 or n == 1: return 1 result = 1 for i in range(2, n + 1): result *= i re...
from solution import find_palindromic_factorial, is_palindrome, factorial def test_find_palindromic_factorial(): assert find_palindromic_factorial() == 1 def test_is_palindrome(): assert is_palindrome(121) == True assert is_palindrome(123) == False assert is_palindrome(1331) == True assert is_pali...
[ { "docstring": "Check if a given number is a palindrome.", "function_declaration": "def is_palindrome(num):", "function_name": "is_palindrome", "parameter_list": "(num)" }, { "docstring": "Calculate the factorial of a given number n.", "function_declaration": "def factorial(n):", "fu...
[ 1, 0, 0, 1, 1, 0, 1, 0, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_palindrome(num):\n \"\"\"\n Helper function to check if a given number is a palindrome.\n \"\"\"\n return str(num) == str(num)[::-1]\n\ndef fi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023466", "row_id": 23466, "seed_ids": "[3026]" }
0.723835
Algorithm_23466
I
[ "is_palindrome", "factorial", "find_palindromic_factorial" ]
3
[ [ "find_palindromic_factorial", "factorial" ], [ "find_palindromic_factorial", "is_palindrome" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e3e69054e90779b624eead893265667d1d97a7a2
59a4ef0cb5cb39bc809d57b317ec42fdeefe0c23
v1.0
instruct
Algorithm
Algorithm_23473_I
### Problem Statement You have been tasked with creating a function to encode and decode messages using a simple numerical cipher. This cipher shifts the letters in the message by a given number of positions in the alphabet. For example, with a shift of 3, 'a' would become 'd', and 'z' would wrap around to become 'c'....
def encode_message(message: str, shift: int) -> str: """ Encodes a message by shifting its letters by the specified number of positions in the alphabet. """ def shift_char(c, shift): if 'a' <= c <= 'z': return chr((ord(c) - ord('a') + shift) % 26 + ord('a')) elif 'A' <= c <= ...
def test_encode_message_with_shift_3(): assert encode_message("Hello World!123", 3) == "Khoor Zruog!123" def test_decode_message_with_shift_3(): assert decode_message("Khoor Zruog!123", 3) == "Hello World!123" def test_encode_message_with_shift_5(): assert encode_message("Python 3.8", 5) == "Udymts 3.8" ...
[ { "docstring": "Encodes a message by shifting its letters by the specified number of positions in the alphabet.", "function_declaration": "def encode_message(message, shift):", "function_name": "encode_message", "parameter_list": "(message, shift)" }, { "docstring": "Decodes a message that w...
[ 1, 0, 1, 1, 1, 0, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def encode_message(message: str, shift: int) -> str:\n def shift_char(c, shift):\n if 'a' <= c <= 'z':\n return chr((ord(c) - ord('a') + shi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023473", "row_id": 23473, "seed_ids": "[4479]" }
0.670655
Algorithm_23473
I
[ "encode_message", "decode_message" ]
2
[ [ "decode_message", "encode_message" ] ]
1
[]
false
[]
false
pytest
false
[]
true
d25399494faddfe90dc212019acabbc89aaff267
35d4f9ec285586f0609ca39e014671bc9c08d208
v1.0
instruct
Algorithm
Algorithm_23638_I
### Air Quality Index Prediction with Linear Regression #### Context You are a data analyst working for an environmental organization. Your task is to predict the Air Quality Index (AQI) based on various air pollutant levels. You choose to use Linear Regression for this purpose. #### Objective Implement a Linear Regr...
import numpy as np def expand_polynomial_features(X, degree): """ Expand the input features X to include polynomial features up to the specified degree. """ from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree) return poly.fit_transform(X) def normalize_feature...
import numpy as np from solution import linear_regression_polynomial, expand_polynomial_features, normalize_features, compute_cost def test_expand_polynomial_features(): X = np.array([[1, 2], [3, 4]]) degree = 2 expected_shape = (2, 6) # 1, X1, X2, X1^2, X1*X2, X2^2 X_poly = expand_polynomial_features...
[ { "docstring": "Expand the input features X to include polynomial features up to the specified degree.", "function_declaration": "def expand_polynomial_features(X, degree):", "function_name": "expand_polynomial_features", "parameter_list": "(X, degree)" }, { "docstring": "Normalize the featu...
[ 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 numpy as np\nfrom itertools import combinations_with_replacement\n\ndef add_polynomial_features(X, degree):\n \"\"\"\n Returns a new feature matrix ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023638", "row_id": 23638, "seed_ids": "[503]" }
0.64756
Algorithm_23638
I
[ "expand_polynomial_features", "normalize_features", "compute_cost", "gradient_descent", "linear_regression_polynomial" ]
5
[ [ "gradient_descent", "compute_cost" ], [ "linear_regression_polynomial", "expand_polynomial_features" ], [ "linear_regression_polynomial", "gradient_descent" ], [ "linear_regression_polynomial", "normalize_features" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
668666ed7be17ef936dc16a9e3e4d4f246ffe59a
208a6036bf81f485079083d0ffc5f8cc9b87a2d8
v1.0
instruct
Algorithm
Algorithm_23647_I
### Coding Assessment Question #### Context You're developing a logistics planning tool for a delivery service company. The company needs to efficiently schedule deliveries each day based on the provided delivery windows and the distances between delivery points. The aim is to minimize total travel distance while ensu...
from typing import List, Tuple import math def distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float: """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) def schedule_deliveries( delivery_p...
def test_example_case(): delivery_points = [ (2.3, 3.5), (3.1, 4.2), (4.0, 5.1), (4.5, 5.8) ] delivery_windows = [ (8, 10), (9, 12), (11, 15), (13, 16) ] start_point = (1.0, 1.0) result = schedule_deliveries(delivery_points, de...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def distance(point1, point2):", "function_name": "distance", "parameter_list": "(point1, point2)" }, { "docstring": "Schedules the deliveries for a given set of delivery points and their time wind...
[ 0, 1, 0, 1, 0, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport math\nimport heapq\n\ndef calculate_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:\n \"\"...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023647", "row_id": 23647, "seed_ids": "[517]" }
0.66066
Algorithm_23647
I
[ "distance", "schedule_deliveries" ]
2
[ [ "schedule_deliveries", "distance" ] ]
1
[]
false
[]
false
pytest
false
[]
true
5750ab6c5f120b4c400b385e725bd0e01aa45c32
23f6f55b6ba8c001aa33a7eed1f8a5f4cab2619c
v1.0
instruct
Algorithm
Algorithm_23670_I
### Problem Statement You are given an integer array `nums` and an integer `k`. Your task is to implement a function to find the k-th smallest element in the array using the Quickselect algorithm. The Quickselect algorithm is an efficient selection algorithm based on the partitioning logic used in QuickSort. ### Input...
from typing import List def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] < pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quickselect(arr, low, high,...
from solution import find_kth_smallest def test_example1(): nums = [3, 2, 1, 5, 6, 4] k = 2 assert find_kth_smallest(nums, k) == 2 def test_example2(): nums = [7, 10, 4, 3, 20, 15] k = 3 assert find_kth_smallest(nums, k) == 7 def test_example3(): nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] k =...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quickselect(arr, low, high, k):", "function_name": "quickselect", "parameter_list...
[ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_kth_smallest(nums: List[int], k: int) -> int:\n def partition(left, right, pivot_index):\n pivot_value = nums[pivot...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023670", "row_id": 23670, "seed_ids": "[147]" }
0.627156
Algorithm_23670
I
[ "partition", "quickselect", "find_kth_smallest" ]
3
[ [ "find_kth_smallest", "quickselect" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
15a66ebedabb5d36f158447d4c59da309c1620fd
576b8ed1d2d923ea935480851a427cda68293823
v1.0
instruct
Algorithm
Algorithm_23701_I
### Sorting an Array Using Merge Sort You are tasked with implementing the merge sort algorithm to sort an array of integers. ### Problem Statement Write a function `merge_sort(arr: list[int]) -> list[int]` that: - **Input**: - `arr`: A list of integers which needs to be sorted. - **Output**: - Returns a sorted ...
def merge_sort(arr: list[int]) -> list[int]: if len(arr) <= 1: return arr # Split the array into two halves mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) # Merge the sorted halves return merge(left_half, right_half) def merge(left...
from solution import merge_sort def test_merge_sort_example_1(): arr = [38, 27, 43, 3, 9, 82, 10] assert merge_sort(arr) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_example_2(): arr = [5, 2, 9, 1, 5, 6] assert merge_sort(arr) == [1, 2, 5, 5, 6, 9] def test_merge_sort_example_3(): arr = [0, ...
[ { "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, 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": "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_8
{ "original_instruction": "", "prompt_id": "0000023701", "row_id": 23701, "seed_ids": "[4038]" }
0.665042
Algorithm_23701
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6daff45b8f184417c4af3ce70a708c1b6b72f16d
5c125567e7bd56b0dcf00e76aafb1ef513eaf506
v1.0
instruct
Algorithm
Algorithm_23715_I
### Problem Statement **Game of Sequences** is a game where players take turns constructing a sequence of numbers based on a specific rule. The rule is to add the number of divisors of each element to the sequence as its next element. Initially, the sequence starts with a given integer `a1`. For example, if the seque...
from typing import List def number_of_divisors(x: int) -> int: """ Helper function to return the number of divisors of x. """ count = 0 for i in range(1, int(x**0.5) + 1): if x % i == 0: count += 1 if i != x // i: # To account for both divisors when i is not the squ...
from solution import game_of_sequences, number_of_divisors def test_number_of_divisors(): assert number_of_divisors(1) == 1 assert number_of_divisors(2) == 2 assert number_of_divisors(3) == 2 assert number_of_divisors(4) == 3 assert number_of_divisors(6) == 4 assert number_of_divisors(12) == 6 ...
[ { "docstring": "Helper function to return the number of divisors of x.", "function_declaration": "def number_of_divisors(x):", "function_name": "number_of_divisors", "parameter_list": "(x)" }, { "docstring": "Generates a sequence of numbers based on the rule provided.\n\n:param a1: The initi...
[ 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 number_of_divisors(x: int) -> int:\n count = 0\n for i in range(1, x + 1):\n if x % i == 0:\n count += 1\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023715", "row_id": 23715, "seed_ids": "[2299]" }
0.728215
Algorithm_23715
I
[ "number_of_divisors", "game_of_sequences" ]
2
[ [ "game_of_sequences", "number_of_divisors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d92a78a358d3cde2f3af7d6c7baec0e41945454b
6e7e4cf99a31869a5632a6710fa9db95db409072
v1.0
instruct
Algorithm
Algorithm_23734_I
### Longest Common Substring Using Suffix Array and LCP Array #### Background Scenario Finding the longest common substring between two strings efficiently is a common problem in bioinformatics and text processing. One method to solve this involves using suffix arrays and longest common prefix (LCP) arrays. You are ta...
from typing import List, Tuple def construct_suffix_array(text: str) -> List[int]: """ Constructs a suffix array for the given text. Parameters: text (str): The text for which to construct the suffix array. Returns: List[int]: The constructed suffix array. """ suffixes = [(tex...
from solution import construct_suffix_array, construct_lcp_array, find_longest_common_substring def test_construct_suffix_array(): assert construct_suffix_array("banana") == [5, 3, 1, 0, 4, 2] assert construct_suffix_array("abcde") == [0, 1, 2, 3, 4] def test_construct_lcp_array(): text = "banana" suf...
[ { "docstring": "Constructs a suffix array for the given text.\n\nParameters:\n text (str): The text for which to construct the suffix array.\n\nReturns:\n List[int]: The constructed suffix array.", "function_declaration": "def construct_suffix_array(text):", "function_name": "construct_suffix_arra...
[ 0, 0, 0, 1, 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\n\ndef construct_suffix_array(text: str) -> List[int]:\n n = len(text)\n suffixes = sorted((text[i:], i) for i in range(n))\n re...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023734", "row_id": 23734, "seed_ids": "[1752]" }
0.755995
Algorithm_23734
I
[ "construct_suffix_array", "construct_lcp_array", "find_longest_common_substring" ]
3
[ [ "find_longest_common_substring", "construct_lcp_array" ], [ "find_longest_common_substring", "construct_suffix_array" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e631eb3947d96e06bd63b1c3abf7acaabca8b552
7b3c8ecd0143ed236dbf471af1479d98f516caf8
v1.0
instruct
Algorithm
Algorithm_23777_I
### Question **Context**: You are a software engineer working on a project requiring quick access and manipulation of specific elements within a large dataset. A common data structure used for such purposes is a binary search tree (BST). Your task is to implement a function that will efficiently delete nodes from a BS...
class TreeNode: def __init__(self, key: int): self.key = key self.left = None self.right = None def delete_node(root: TreeNode, key: int) -> TreeNode: if not root: return root if key < root.key: root.left = delete_node(root.left, key) elif key > root.key: ...
from solution import TreeNode, delete_node def create_bst_from_sorted_list(arr): if not arr: return None mid = len(arr) // 2 root = TreeNode(arr[mid]) root.left = create_bst_from_sorted_list(arr[:mid]) root.right = create_bst_from_sorted_list(arr[mid+1:]) return root def test_delete_le...
[]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
8
easy
0.889
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, key: int):\n self.key = key\n self.left = None\n self.right = None\n\ndef d...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000023777", "row_id": 23777, "seed_ids": "[558]" }
0.602316
Algorithm_23777
I
[ "delete_node", "find_min" ]
2
[ [ "delete_node", "find_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
ab113ba0f2dd75fe6919a02c8f7b95674f3ba934
9c2d871a405ff9c02a94c02cf0f09d104eb25617
v1.0
instruct
Algorithm
Algorithm_23787_I
### Question: Implement a Merge Sort Function You are required to implement the merge sort algorithm due to its importance in reducing time complexity for sorting huge datasets. This algorithm uses the divide and conquer method to recursively sort and merge elements. #### Task Implement the function `merge_sort(arr:...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using 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_hal...
from solution import merge_sort def test_merge_sort(): assert merge_sort([3, 7, 1, 5]) == [1, 3, 5, 7] assert merge_sort([9, 8, 7, 6]) == [6, 7, 8, 9] assert merge_sort([0, -10, 5, 5, 1000000]) == [-10, 0, 5, 5, 1000000] assert merge_sort([1]) == [1] def test_merge_sort_empty(): assert merge_sort(...
[ { "docstring": "Sorts a list of integers using merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "pa...
[ 0, 1, 1, 1, 1, 1, 1, 1 ]
7
easy
0.875
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023787", "row_id": 23787, "seed_ids": "[340]" }
0.641916
Algorithm_23787
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0c6df1fa7886545e9d0d4c9a198e9f085a748813
a4c1eac800b37b3eee7c7789822324535fc0a1d6
v1.0
instruct
Algorithm
Algorithm_23802_I
### Question You are given an implementation of a matrix multiplication function in the `multiply_matrices` function. Your task is to write a function `matrix_multiplication_selector` that chooses an optimized matrix multiplication method based on the size of the matrices. Specifically: - If the number of rows in the ...
def standard_matrix_multiplication(A, B): """ Returns the product of matrices A and B using standard matrix multiplication. """ n, m, p = len(A), len(B), len(B[0]) C = [[0] * p for _ in range(n)] for i in range(n): for j in range(p): for k in range(m): C[...
import pytest def test_standard_multiplication(): A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]] result = matrix_multiplication_selector(A, B, 2) expected = [[19, 22], [43, 50]] assert result == expected def test_strassens_multiplication(): A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]] result =...
[ { "docstring": "Returns the product of matrices A and B using standard matrix multiplication.", "function_declaration": "def standard_matrix_multiplication(A, B):", "function_name": "standard_matrix_multiplication", "parameter_list": "(A, B)" }, { "docstring": "A simplistic implementation of...
[ 0, 1, 1, 0, 1, 0, 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 standard_matrix_multiplication(A, B):\n result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]\n for i in range(len(A)):\n for j in ran...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000023802", "row_id": 23802, "seed_ids": "[3592]" }
0.510303
Algorithm_23802
I
[ "standard_matrix_multiplication", "strassens_matrix_multiplication", "split_matrix", "add_matrices", "subtract_matrices", "combine_matrices", "matrix_multiplication_selector" ]
7
[ [ "matrix_multiplication_selector", "standard_matrix_multiplication" ], [ "matrix_multiplication_selector", "strassens_matrix_multiplication" ], [ "strassens_matrix_multiplication", "add_matrices" ], [ "strassens_matrix_multiplication", "combine_matrices" ], [ "st...
6
[]
false
[]
false
pytest
false
[]
true
bcc4b1d24e4d43cea5c621c746b396f7f646ca3a
3f761683b3a57b5b021e53a4406665779e5ac679
v1.0
instruct
Algorithm
Algorithm_23811_I
### Problem Description You are given an unsorted list of `n` integers `arr`. Your task is to implement the Radix Sort algorithm to sort the list in ascending order. ### Implementation Details 1. **Function Signature**: ```python def radix_sort(arr: List[int]) -> List[int]: ``` 2. **Input**: - `arr`...
from typing import List def counting_sort(arr: List[int], exp: int) -> List[int]: n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = abs(arr[i]) // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] for i in range(n-1, -1...
from solution import radix_sort def test_radix_sort_example_cases(): assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802] assert radix_sort([3, 10, 2, 8, 6, 7, 5]) == [2, 3, 5, 6, 7, 8, 10] assert radix_sort([5]) == [5] assert radix_sort([]) == [] assert radix_s...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp):", "function_name": "counting_sort", "parameter_list": "(arr, exp)" }, { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_sort", "parameter_list": "(arr)" } ]
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef counting_sort_for_radix(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n \n count = [0] * 10\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000023811", "row_id": 23811, "seed_ids": "[4849]" }
0.634552
Algorithm_23811
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
02f094db22568de2de9786842d5a1805fb2e4f1d
bb9eccd4d7dedbc9d30b8c3df65c50d8c62a395e
v1.0
instruct
Algorithm
Algorithm_23886_I
### Scenario: You are in charge of developing an algorithm to generate the most efficient route for garbage collection trucks in a city. The city map is represented as a grid with certain cells marked as garbage dumps. ### Problem Description: Implement the function `shortestPathToCollectAllGarbage(grid)` which calcul...
from typing import List, Tuple from collections import deque from itertools import permutations def bfs(grid: List[List[str]], start: Tuple[int, int]) -> dict: q = deque([start]) visited = set([start]) distances = {start: 0} while q: x, y = q.popleft() for dx, dy in [(-1, 0), (1, 0), (0...
def test_no_garbage(): grid = [['.']] assert shortestPathToCollectAllGarbage(grid) == 0 def test_one_garbage(): grid = [['.', 'G']] assert shortestPathToCollectAllGarbage(grid) == 2 def test_two_garbage(): grid = [['.', 'G', '.'], ['.', 'X', 'G']] assert shortestPathToCollectAllGar...
[ { "docstring": null, "function_declaration": "def bfs(grid, start):", "function_name": "bfs", "parameter_list": "(grid, start)" }, { "docstring": null, "function_declaration": "def shortestPathToCollectAllGarbage(grid):", "function_name": "shortestPathToCollectAllGarbage", "param...
[ 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, Tuple\nfrom collections import deque\n\ndef shortestPathToCollectAllGarbage(grid: List[List[str]]) -> int:\n def bfs(start: Tuple[int...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000023886", "row_id": 23886, "seed_ids": "[4354]" }
0.639889
Algorithm_23886
I
[ "bfs", "shortestPathToCollectAllGarbage" ]
2
[ [ "shortestPathToCollectAllGarbage", "bfs" ] ]
1
[]
false
[]
false
pytest
false
[]
true
90854e73a276bb6920c91750a45e1fd92e51be26
6f77f1625bf13bbed63ec2ad65585a11dd11828e
v1.0
instruct
Algorithm
Algorithm_24006_I
### In-Place Merge Sort Implementation Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the two sorted halves. Traditionally, merge sort is not in-place and requires additional memory, but it can be adapted to work in-place with careful ...
def merge(arr, start, mid, end): start2 = mid + 1 if arr[mid] <= arr[start2]: # Already in place return while start <= mid and start2 <= end: if arr[start] <= arr[start2]: start += 1 else: value = arr[start2] index = start2 while in...
from solution import in_place_merge_sort def test_empty_array(): arr = [] in_place_merge_sort(arr) assert arr == [] def test_single_element_array(): arr = [1] in_place_merge_sort(arr) assert arr == [1] def test_sorted_array(): arr = [1, 2, 3, 4, 5] in_place_merge_sort(arr) assert ...
[ { "docstring": null, "function_declaration": "def merge(arr, start, mid, end):", "function_name": "merge", "parameter_list": "(arr, start, mid, end)" }, { "docstring": null, "function_declaration": "def in_place_merge_sort_helper(arr, l, r):", "function_name": "in_place_merge_sort_he...
[ 1, 0, 1, 1, 1, 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 in_place_merge_sort(arr: list[int]) -> None:\n def merge(arr, start, mid, end):\n start2 = mid + 1\n \n # If the direct merge is already ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024006", "row_id": 24006, "seed_ids": "[884]" }
0.667691
Algorithm_24006
I
[ "merge", "in_place_merge_sort_helper", "in_place_merge_sort" ]
3
[ [ "in_place_merge_sort", "in_place_merge_sort_helper" ], [ "in_place_merge_sort_helper", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f152561f2cc9595ebdcc279f88f502ee399db6ab
72fa096647eab05f3082243e44d3c99ac5e5b64f
v1.0
instruct
Algorithm
Algorithm_24023_I
### Matrix Multiplication Validator As part of a system that performs matrix operations, you have been asked to create a function that validates if two matrices can be multiplied and then performs the multiplication if valid. #### Task 1. Implement two functions: - `can_multiply_matrices(A: list, B: list) -> bool...
def can_multiply_matrices(A, B): """ Check if two matrices can be multiplied. Parameters: A (list of list of int): Matrix A B (list of list of int): Matrix B Returns: bool: True if matrices can be multiplied, otherwise False """ # Number of columns in A should be equal to t...
import pytest from solution import can_multiply_matrices, multiply_matrices def test_can_multiply_matrices_true(): assert can_multiply_matrices([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]]) == True assert can_multiply_matrices([[1, 2]], [[3, 4], [5, 6]]) == True assert can_multiply_matrices([[2]], ...
[ { "docstring": "Check if two matrices can be multiplied.\n\nParameters:\nA (list of list of int): Matrix A\nB (list of list of int): Matrix B\n\nReturns:\nbool: True if matrices can be multiplied, otherwise False", "function_declaration": "def can_multiply_matrices(A, B):", "function_name": "can_multipl...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def can_multiply_matrices(A, B):\n \"\"\"\n Check if the matrices A and B can be multiplied.\n \"\"\"\n if len(A[0]) == len(B):\n return True\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024023", "row_id": 24023, "seed_ids": "[4925]" }
0.565768
Algorithm_24023
I
[ "can_multiply_matrices", "multiply_matrices" ]
2
[ [ "multiply_matrices", "can_multiply_matrices" ] ]
1
[]
false
[]
false
pytest
true
[]
true
67ea2ea2bca0e5d00e611f7af7d1c452e717a2eb
0fd4ff477a2a06b0f584f95b6b207a96829338eb
v1.0
instruct
Algorithm
Algorithm_24059_I
### Problem Statement You are given an array of integers `arr` and an integer `k`. Your task is to split the array into `k` non-empty subarrays such that the largest sum among those subarrays is minimized. Return the minimized largest sum. ### Function Signature ```python def split_array_minimized_max_sum(arr: List[i...
from typing import List def can_partition(nums: List[int], k: int, max_sum: int) -> bool: current_sum = 0 count = 1 for num in nums: if current_sum + num > max_sum: count += 1 current_sum = num if count > k: return False else: ...
from solution import split_array_minimized_max_sum def test_example_1(): assert split_array_minimized_max_sum([7, 2, 5, 10, 8], 2) == 18 def test_example_2(): assert split_array_minimized_max_sum([1, 2, 3, 4, 5], 2) == 9 def test_example_3(): assert split_array_minimized_max_sum([1, 4, 4], 3) == 4 def t...
[ { "docstring": null, "function_declaration": "def can_partition(nums, k, max_sum):", "function_name": "can_partition", "parameter_list": "(nums, k, max_sum)" }, { "docstring": null, "function_declaration": "def split_array_minimized_max_sum(arr, k):", "function_name": "split_array_mi...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef split_array_minimized_max_sum(arr: List[int], k: int) -> int:\n def can_split(max_sum):\n count, subarray_sum = 1, 0\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000024059", "row_id": 24059, "seed_ids": "[209]" }
0.772174
Algorithm_24059
I
[ "can_partition", "split_array_minimized_max_sum" ]
2
[ [ "split_array_minimized_max_sum", "can_partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
19b46e2078d75178e67a655a0a3a5c2e2a991c0b
3407b06d6bf66ef51ae7b9afdf5864d65208adc1
v1.0
instruct
Algorithm
Algorithm_24157_I
### Objective Given a set of students with their grades in different subjects, write a function to calculate each student's GPA and the class average GPA. Assume each subject carries the same weight. ### Function Implementation #### Function 1: Calculate Student GPA - **Function Name**: `student_gpa` - **Input**: ...
from typing import List def student_gpa(grades: List[float]) -> float: if not grades: raise ValueError("Grades list cannot be empty.") for grade in grades: if not 0.0 <= grade <= 4.0: raise ValueError(f"Grade {grade} is out of acceptable range 0.0 to 4.0.") return sum(grades) / ...
def test_student_gpa(): assert student_gpa([3.5, 2.7, 4.0, 3.8]) == 3.5 assert student_gpa([4.0, 4.0, 4.0, 4.0]) == 4.0 assert student_gpa([0.0, 0.0, 0.0, 0.0]) == 0.0 assert student_gpa([3.0, 3.0, 3.0]) == 3.0 def test_student_gpa_invalid_grades(): try: student_gpa([4.5]) except ValueE...
[ { "docstring": null, "function_declaration": "def student_gpa(grades):", "function_name": "student_gpa", "parameter_list": "(grades)" }, { "docstring": null, "function_declaration": "def class_average_gpa(all_grades):", "function_name": "class_average_gpa", "parameter_list": "(al...
[ 0, 1, 0, 1, 0, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef student_gpa(grades: List[float]) -> float:\n if not grades:\n raise ValueError(\"Grades list cannot be empty.\")\n \n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000024157", "row_id": 24157, "seed_ids": "[734]" }
0.732582
Algorithm_24157
I
[ "student_gpa", "class_average_gpa" ]
2
[ [ "class_average_gpa", "student_gpa" ] ]
1
[]
false
[]
false
pytest
false
[]
true
302c7969b6cc157f5ce64e5a2ddf4e712642419f
2db12976af82fbdd300bb5a80bc46b7e8435d643
v1.0
instruct
Algorithm
Algorithm_24158_I
### Data Structure Comparison: Sorting Algorithm Efficiency #### Context: As a software engineer, you are tasked with optimizing a data processing pipeline. You need to compare the efficiencies of different sorting algorithms on various types of input data. Your goal is to implement a function that, given an unsorted ...
from typing import List, Tuple import time def merge_sort(data: List[int]) -> List[int]: if len(data) <= 1: return data mid = len(data) // 2 left = merge_sort(data[:mid]) right = merge_sort(data[mid:]) return merge(left, right) def merge(left: List[int], right: List[int]) -> List[int]: ...
from solution import sort_comparison def test_sort_comparison_empty_list(): merge_time, quick_time = sort_comparison([]) assert merge_time >= 0 assert quick_time >= 0 def test_sort_comparison_single_element(): data = [1] merge_time, quick_time = sort_comparison(data) assert merge_time >= 0 ...
[ { "docstring": null, "function_declaration": "def merge_sort(data):", "function_name": "merge_sort", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "doc...
[ 1, 1, 1, 1, 1, 0, 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, Tuple\nimport time\n\ndef merge_sort(data: List[int]) -> List[int]:\n if len(data) <= 1:\n return data\n mid = len(data) //...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024158", "row_id": 24158, "seed_ids": "[1694]" }
0.578877
Algorithm_24158
I
[ "merge_sort", "merge", "quick_sort", "sort_comparison" ]
4
[ [ "merge_sort", "merge" ], [ "sort_comparison", "merge_sort" ], [ "sort_comparison", "quick_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
e08bb7de59668dc5287c3e2dc67ef205c6cf7dcd
18201ac3c13e20b0e7026458aca56e0bdb5fc53b
v1.0
instruct
Algorithm
Algorithm_24165_I
### Stock Price Alert System You are tasked with creating a system that monitors stock prices and sends an alert when the price of a specified stock crosses a certain threshold. The system will have to retrieve the current stock price from a provided URL and compare it to a given target price. Implement the following...
import requests def get_stock_price(url): """ Fetch the current stock price from a given URL. Args: - url (str): The URL from which to fetch the stock price. Returns: - float: The current stock price. """ try: response = requests.get(url, timeout=10) response.r...
from solution import get_stock_price, check_stock_price from unittest.mock import patch, MagicMock def test_get_stock_price_success(): with patch('solution.requests.get') as mock_get: mock_response = MagicMock() mock_response.json.return_value = {'price': '200.0'} mock_get.return_value = mo...
[ { "docstring": "Fetch the current stock price from a given URL.\n\nArgs:\n- url (str): The URL from which to fetch the stock price.\n\nReturns:\n- float: The current stock price.", "function_declaration": "def get_stock_price(url):", "function_name": "get_stock_price", "parameter_list": "(url)" },...
[ 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nfrom requests.exceptions import Timeout, RequestException\n\ndef get_stock_price(url):\n \"\"\"\n Fetch the current price of a stock from ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024165", "row_id": 24165, "seed_ids": "[2361]" }
0.497406
Algorithm_24165
I
[ "get_stock_price", "check_stock_price" ]
2
[ [ "check_stock_price", "get_stock_price" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
2deacc1b0c77da8d1ed44d555987bf0d19d3eb0b
06d652c780312f02e8bdb7f909d6f9ad49011510
v1.0
instruct
Algorithm
Algorithm_24202_I
### Question: Smallest Multiple of Consecutive Numbers **Problem Description:** You are tasked with writing a function `smallest_multiple(n: int) -> int` that finds the smallest positive number that is evenly divisible by all of the numbers from 1 to `n`. **Function Signature:** ```python def smallest_multiple(n: in...
import math def lcm(a, b): """Helper function to calculate Least Common Multiple (LCM) of two numbers""" return abs(a*b) // math.gcd(a, b) def smallest_multiple(n: int) -> int: """Function to find the smallest positive number that is evenly divisible by all numbers from 1 to n""" answer = 1 for i ...
from solution import smallest_multiple def test_smallest_multiple_basic_cases(): assert smallest_multiple(1) == 1 assert smallest_multiple(2) == 2 assert smallest_multiple(3) == 6 assert smallest_multiple(4) == 12 assert smallest_multiple(5) == 60 def test_smallest_multiple_larger_cases(): ass...
[ { "docstring": "Helper function to calculate Least Common Multiple (LCM) of two numbers", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Function to find the smallest positive number that is evenly divisible by all numbers from...
[ 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 gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return a * b // gcd(a, b)\n\ndef smallest_multiple(n):\n result = 1...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024202", "row_id": 24202, "seed_ids": "[2269]" }
0.646996
Algorithm_24202
I
[ "lcm", "smallest_multiple" ]
2
[ [ "smallest_multiple", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0c14730c6c7a2b5beb2217649802528d5c3a288c
261107ae44924b2455bb681d0554d1d201ba1c09
v1.0
instruct
Algorithm
Algorithm_24282_I
### Problem Statement You are tasked with writing functionalities related to matrices and linear algebra. These concepts are critical in various domains including computer graphics, engineering, and data science. ### Your Task 1. **Calculate Determinant of a 2x2 Matrix**: Implement a function that calculates the ...
def determinant_2x2(matrix): """ Calculate the determinant of a 2x2 matrix. matrix: list of lists, a 2x2 matrix [[a, b], [c, d]] Returns: float: the determinant of the matrix """ if len(matrix) != 2 or any(len(row) != 2 for row in matrix): raise ValueError("Input must be a ...
import pytest from solution import determinant_2x2, is_singular def test_determinant_positive_numbers(): assert determinant_2x2([[1, 2], [3, 4]]) == -2.0 def test_determinant_negative_numbers(): assert determinant_2x2([[-1, -2], [-3, -4]]) == -2.0 def test_determinant_with_zero(): assert determinant_2x2(...
[ { "docstring": "Calculate the determinant of a 2x2 matrix.\n\nmatrix: list of lists, a 2x2 matrix [[a, b], [c, d]]\n\nReturns:\nfloat: the determinant of the matrix", "function_declaration": "def determinant_2x2(matrix):", "function_name": "determinant_2x2", "parameter_list": "(matrix)" }, { ...
[ 1, 0, 1, 1, 0, 0, 0, 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 determinant_2x2(matrix):\n \"\"\"\n Calculate the determinant of a 2x2 matrix.\n \n Parameters:\n matrix (list of list of int/float): A 2x2 ma...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024282", "row_id": 24282, "seed_ids": "[782]" }
0.493107
Algorithm_24282
I
[ "determinant_2x2", "is_singular" ]
2
[ [ "is_singular", "determinant_2x2" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4b0221785d8643b53eb821817eada50ddda91e52
1a71926b5416620152832ac03adbed8aed7d20fd
v1.0
instruct
Algorithm
Algorithm_24293_I
## Question: Implement the Knuth-Morris-Pratt (KMP) Algorithm for Pattern Matching **Problem Statement**: You are given two strings, `text` and `pattern`. Your task is to implement the Knuth-Morris-Pratt (KMP) algorithm to find all occurrences of the `pattern` in the `text`. ### Function Signature ```python def KMP_s...
from typing import List def compute_LPS_array(pattern: str) -> List[int]: """ This function computes the Longest Prefix Suffix (LPS) array, also known as the "partial match" table, which will be used to skip unnecessary comparisons in the KMP algorithm. """ m = len(pattern) lps = [0] * m ...
from solution import KMP_search def test_KMP_basic(): text = "ababcabcabababd" pattern = "ababd" assert KMP_search(text, pattern) == [10] def test_KMP_multiple_occurrences(): text = "ababcababcababc" pattern = "abc" assert KMP_search(text, pattern) == [2, 7, 12] def test_KMP_pattern_in_text()...
[ { "docstring": "This function computes the Longest Prefix Suffix (LPS) array, also known as\nthe \"partial match\" table, which will be used to skip unnecessary comparisons\nin the KMP algorithm.", "function_declaration": "def compute_LPS_array(pattern):", "function_name": "compute_LPS_array", "para...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_lps_array(pattern: str) -> List[int]:\n \"\"\"\n Helper function to compute the Longest Prefix Suffix (LPS) array.\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000024293", "row_id": 24293, "seed_ids": "[4545]" }
0.576342
Algorithm_24293
I
[ "compute_LPS_array", "KMP_search" ]
2
[ [ "KMP_search", "compute_LPS_array" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f14ff38db305628cab1f6fafc3161aa5c4b96d4e
4a6feae21a687cc56c8931f5e801424193e59f30
v1.0
instruct
Algorithm
Algorithm_24319_I
### Coding Question: Matrix Rotation and Daylight Cycles You are required to implement a function that simulates the rotation of a square matrix representing a cityscape over one full daylight cycle. The matrix elements can be `U` for buildings, `D` for gardens, or `P` for parks. The matrix should rotate 90 degrees cl...
def rotate_90_clockwise(matrix): """ Rotates the given n x n matrix 90 degrees clockwise. """ n = len(matrix) new_matrix = [[''] * n for _ in range(n)] for i in range(n): for j in range(n): new_matrix[j][n - 1 - i] = matrix[i][j] return new_matrix def simulate_...
from solution import simulate_daylight def test_simulate_daylight_2x2(): matrix = [ ['U', 'D'], ['P', 'U'] ] expected = [ ['U', 'D'], ['P', 'U'] ] assert simulate_daylight(matrix) == expected def test_simulate_daylight_3x3(): matrix = [ ['U', 'D', 'P'], ...
[ { "docstring": "Rotates the given n x n matrix 90 degrees clockwise.", "function_declaration": "def rotate_90_clockwise(matrix):", "function_name": "rotate_90_clockwise", "parameter_list": "(matrix)" }, { "docstring": "Simulates the rotation of the square matrix over one full daylight cycle ...
[ 1, 1, 0, 0, 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": "from typing import List\n\ndef rotate_90_clockwise(matrix: List[List[str]]) -> List[List[str]]:\n \"\"\"Helper function to rotate a matrix 90 degrees clockwis...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024319", "row_id": 24319, "seed_ids": "[3929]" }
0.468928
Algorithm_24319
I
[ "rotate_90_clockwise", "simulate_daylight" ]
2
[ [ "simulate_daylight", "rotate_90_clockwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
267e7b0c43bd3e7ecad185b116d1aacc0ee1941f
075fb918e86208213341060a06e26526ef28ae37
v1.0
instruct
Algorithm
Algorithm_24331_I
### Context You've been studying various sorting algorithms and understand the complexities involved in sorting large datasets. Now, you come across an efficient algorithm called Merge Sort, which is particularly useful for large lists of data because of its O(n log n) time complexity. ### Problem Implement the Merge ...
def merge_sort(arr, ascending=True): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid], ascending) right = merge_sort(arr[mid:], ascending) return merge(left, right, ascending) def merge(left, right, ascending): result = [] i = j = 0 while i < len(l...
from solution import merge_sort def test_merge_sort_ascending(): assert merge_sort([4, 2, 5, 3, 1, 6], ascending=True) == [1, 2, 3, 4, 5, 6] assert merge_sort([5, 3, 8, 6, 2], ascending=True) == [2, 3, 5, 6, 8] assert merge_sort([], ascending=True) == [] assert merge_sort([1], ascending=True) == [1] ...
[ { "docstring": null, "function_declaration": "def merge_sort(arr, ascending=True):", "function_name": "merge_sort", "parameter_list": "(arr, ascending=True)" }, { "docstring": null, "function_declaration": "def merge(left, right, ascending):", "function_name": "merge", "parameter...
[ 1, 1, 0, 1, 1, 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, ascending=True):\n if len(arr) <= 1:\n return arr\n\n def merge(left, right, ascending):\n merged = []\n while lef...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000024331", "row_id": 24331, "seed_ids": "[2982]" }
0.60504
Algorithm_24331
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5526f6eec91606ad3b18b947ecc05cc9c619d82d
3a8eeab8e658c732f0902bc5eaa0fa01db2629f6
v1.0
instruct
Algorithm
Algorithm_24364_I
Infix to Postfix Conversion You are provided with an implementation of an algorithm that converts infix expressions to postfix expressions using a stack. Your task is to extend this implementation by writing a function that can handle multiple expressions at once and returns a list of their corresponding postfix expre...
def precedence(op): if op == '+' or op == '-': return 1 if op == '*' or op == '/': return 2 return 0 def infix_to_postfix(expression): stack = [] postfix = [] tokens = expression.split() for token in tokens: if token.isalnum(): postfix.append(token) ...
import pytest from solution import convert_expressions def test_single_expression(): expressions = ["A + B"] assert convert_expressions(expressions) == ["A B +"] def test_multiple_expressions(): expressions = ["A + B", "A + B * C", "( A + B ) * C"] expected_results = ["A B +", "A B C * +", "A B + C *"...
[ { "docstring": null, "function_declaration": "def precedence(op):", "function_name": "precedence", "parameter_list": "(op)" }, { "docstring": null, "function_declaration": "def infix_to_postfix(expression):", "function_name": "infix_to_postfix", "parameter_list": "(expression)" ...
[ 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
8
easy
0.889
{ "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 infix_to_postfix(expression: str) -> str:\n \"\"\"\n Convert a single infix expression to postfix.\n \"\"\"\n preceden...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000024364", "row_id": 24364, "seed_ids": "[312]" }
0.594015
Algorithm_24364
I
[ "precedence", "infix_to_postfix", "convert_expressions" ]
3
[ [ "convert_expressions", "infix_to_postfix" ], [ "infix_to_postfix", "precedence" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b0c8727720d4475df469e5ac2e34ec9d38f0d636
65e0d14695272768d21670d0e25044a8f290d2bd
v1.0
instruct
Algorithm
Algorithm_24420_I
### Problem Statement You are given a 2D grid filled with integers where each cell is either land (`1`) or water (`0`). Your task is to find the size of the largest island of land. An island is a group of adjacent lands horizontally or vertically (not diagonally). You need to implement functions that identify each isla...
from typing import List def dfs(row: int, col: int, grid: List[List[int]], visited: List[List[bool]]) -> int: """ Perform a Depth-First Search to calculate the size of the island. """ # Check for bounds and if the cell is water or already visited if row < 0 or row >= len(grid) or col < 0 or col >= ...
def test_dfs_island_size(): grid = [ [1, 1, 0, 0, 0], [1, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1] ] visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))] assert dfs(0, 0, grid, visited) == 4 visited = [[False for _ in range(len(grid[0]))] fo...
[ { "docstring": "Perform a Depth-First Search to calculate the size of the island.", "function_declaration": "def dfs(row, col, grid, visited):", "function_name": "dfs", "parameter_list": "(row, col, grid, visited)" }, { "docstring": "Find the size of the largest island in the grid.", "fu...
[ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef dfs(row: int, col: int, grid: List[List[int]], visited: List[List[bool]]) -> int:\n # If we are out of bounds or at a cell that...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000024420", "row_id": 24420, "seed_ids": "[2226]" }
0.642063
Algorithm_24420
I
[ "dfs", "largest_island" ]
2
[ [ "largest_island", "dfs" ] ]
1
[]
false
[]
false
pytest
false
[]
true
345405a0562a15f6f67130af058c97ddedfc1487
bb67135a8b6daf86b6b71484e3a7f1ffaae4c92e
v1.0
instruct
Algorithm
Algorithm_24437_I
### Next Prime Number Finder #### Objective: Create a function that finds the next prime number greater than a given integer. The function should efficiently determine the smallest prime number that is strictly greater than the input number. #### Function Signature: ```python def next_prime(n: int) -> int: ... ``...
def is_prime(num): """Helper function to check if a number is a prime number.""" if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return Fa...
from solution import next_prime def test_next_prime_cases(): assert next_prime(3) == 5 assert next_prime(8) == 11 assert next_prime(14) == 17 assert next_prime(30) == 31 assert next_prime(99) == 101 assert next_prime(1000) == 1009 def test_next_prime_edge_cases(): assert next_prime(0) == 2...
[ { "docstring": "Helper function to check if a number is a prime number.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Finds the next prime number greater than a given integer n.", "function_declaration": "def nex...
[ 0, 0, 1, 0, 1, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000024437", "row_id": 24437, "seed_ids": "[3361]" }
0.712423
Algorithm_24437
I
[ "is_prime", "next_prime" ]
2
[ [ "next_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6423c9e98be7af0765e17d6029771a934785b75a
53b47ff4c32c2f95700dfdb1e0aeac3885a145d3
v1.0
instruct
Algorithm
Algorithm_24439_I
### Scenario You are required to develop a function that examines and filters a list based on specific criteria related to numeric properties. Specifically, the function should retain numbers that are prime and discard the rest. ### Problem Statement Write a function `filter_primes(numbers: List[int]) -> List[int]` th...
from typing import List def is_prime(n: int) -> bool: """ Determines if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: ...
from solution import filter_primes def test_filter_primes_with_mixed_numbers(): assert filter_primes([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7] def test_filter_primes_with_all_primes(): assert filter_primes([11, 13, 17, 19, 23, 24, 25, 29]) == [11, 13, 17, 19, 23, 29] def test_filter_primes_with_no_primes...
[ { "docstring": "Determines if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Filters and returns a list of prime numbers from the input list.", "function_declaration": "def filter_primes(numbers):",...
[ 1, 1, 0, 0, 1, 1, 0, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000024439", "row_id": 24439, "seed_ids": "[1202]" }
0.6241
Algorithm_24439
I
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6d30275865a968c428ee2cadd24dd0a0ccc06bc0
cd04db519053483712d6d402d71080d835943b65