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_39720_I | ### Problem Statement
You are given a string `s` and a pattern `p`. Your task is to implement a function that finds the starting index of the first occurrence of the pattern `p` in the string `s` using the Knuth-Morris-Pratt (KMP) algorithm. If the pattern is not found, return -1.
### Function Signature
```python
def... | def build_kmp_table(p):
"""
Build the KMP table for the given pattern.
"""
m = len(p)
kmp_table = [0] * m
j = 0
for i in range(1, m):
while j > 0 and p[i] != p[j]:
j = kmp_table[j - 1]
if p[i] == p[j]:
j += 1
kmp_table[i] = j
... | def test_kmp_search():
assert kmp_search("ababcababcabc", "abc") == 2
assert kmp_search("hello", "ll") == 2
assert kmp_search("aaaaaaa", "bba") == -1
assert kmp_search("mississippi", "issi") == 1
assert kmp_search("a", "a") == 0
assert kmp_search("abcdef", "def") == 3
assert kmp_search("abcd... | [
{
"docstring": "Build the KMP table for the given pattern.",
"function_declaration": "def build_kmp_table(p):",
"function_name": "build_kmp_table",
"parameter_list": "(p)"
},
{
"docstring": "Returns the starting index of the first occurrence of the pattern `p` in the string `s`.\nIf the patt... | [
1,
1,
1,
0,
0,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def kmp_search(s: str, p: str) -> int:\n \"\"\"\n KMP algorithm to find the first occurrence of the pattern `p` in the string `s`.\n Returns the startin... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039720",
"row_id": 39720,
"seed_ids": "[3544]"
} | 0.632044 | Algorithm_39720 | I | [
"build_kmp_table",
"kmp_search"
] | 2 | [
[
"kmp_search",
"build_kmp_table"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 70c7ff8877ab88511a553e0b8815de006997d0df | 8e6ec77df3cfb310519ecd01986fdb3a447aaa6e | |||
v1.0 | instruct | Algorithm | Algorithm_39817_I | ### Coding Question: Genetic Algorithm for String Mutation
**Scenario**:
You are tasked with evolving a string to match a target string using a genetic algorithm. A genetic algorithm is a search heuristic inspired by the process of natural selection. Your task is to implement the core part of this algorithm: the mutat... | import random
def fitness(candidate, target):
"""
Computes the fitness score of a candidate string compared to the target string.
"""
return sum(1 for a, b in zip(candidate, target) if a == b)
def mutate(candidate, mutation_rate):
"""
Mutates a candidate string based on the given mutation rate... | from solution import genetic_algorithm_string
def test_exact_match():
initial_population = ["hello", "hellz", "herlo"]
target = "hello"
mutation_rate = 0.05
max_generations = 1000
assert genetic_algorithm_string(initial_population, target, mutation_rate, max_generations) == "hello"
def test_evolut... | [
{
"docstring": "Computes the fitness score of a candidate string compared to the target string.",
"function_declaration": "def fitness(candidate, target):",
"function_name": "fitness",
"parameter_list": "(candidate, target)"
},
{
"docstring": "Mutates a candidate string based on the given mu... | [
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 random\n\ndef genetic_algorithm_string(initial_population, target, mutation_rate, max_generations):\n def fitness(candidate):\n return sum(c1 ==... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000039817",
"row_id": 39817,
"seed_ids": "[5314]"
} | 0.516384 | Algorithm_39817 | I | [
"fitness",
"mutate",
"crossover",
"genetic_algorithm_string"
] | 4 | [
[
"genetic_algorithm_string",
"crossover"
],
[
"genetic_algorithm_string",
"fitness"
],
[
"genetic_algorithm_string",
"mutate"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4afe42ab605d64f843f299e95505891c2188360f | 6fad79436803e183342baa5974e6e8f1869236af | |||
v1.0 | instruct | Algorithm | Algorithm_39832_I | ### Coding Assessment Question: Password Strength Validator
**Scenario**:
In the context of user authentication systems, it's crucial to ensure that users choose strong passwords to maintain their security. You'll implement an algorithm to validate password strength according to a set of predefined rules.
**Objectiv... | import re
def contains_uppercase(password: str) -> bool:
"""
Checks if the password contains at least one uppercase letter.
"""
return any(char.isupper() for char in password)
def contains_lowercase(password: str) -> bool:
"""
Checks if the password contains at least one lowercase letter.
... | import pytest
from solution import validate_password, contains_uppercase, contains_lowercase, contains_digit, contains_special_char
def test_contains_uppercase():
assert contains_uppercase("Password") == True
assert contains_uppercase("password") == False
assert contains_uppercase("123456") == False
def t... | [
{
"docstring": "Checks if the password contains at least one uppercase letter.",
"function_declaration": "def contains_uppercase(password):",
"function_name": "contains_uppercase",
"parameter_list": "(password)"
},
{
"docstring": "Checks if the password contains at least one lowercase letter... | [
1,
0,
1,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef contains_uppercase(password: str) -> bool:\n \"\"\"\n Checks if the password contains at least one uppercase letter.\n \"\"\"\n retu... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039832",
"row_id": 39832,
"seed_ids": "[1197]"
} | 0.616003 | Algorithm_39832 | I | [
"contains_uppercase",
"contains_lowercase",
"contains_digit",
"contains_special_char",
"validate_password"
] | 5 | [
[
"validate_password",
"contains_digit"
],
[
"validate_password",
"contains_lowercase"
],
[
"validate_password",
"contains_special_char"
],
[
"validate_password",
"contains_uppercase"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 5f66e875e6a942a7cb462e7a3e5e664dfa9622f7 | 1210af7a1839733471727091f96dc29b463c8e60 | |||
v1.0 | instruct | Algorithm | Algorithm_39877_I | ### Coding Question: Merge Intervals in a List with a Custom Comparator
You need to implement a function that merges overlapping intervals in a list. Each interval is represented as a tuple containing two integer elements: the start and end of the interval.
However, instead of using the traditional less-than compara... | from typing import List, Tuple
import functools
def compare_intervals(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> int:
"""
Compare two intervals based on custom rules.
:param interval1: Tuple[int, int], the first interval.
:param interval2: Tuple[int, int], the second interval.
:retu... | from solution import compare_intervals, merge_intervals
# Tests for compare_intervals
def test_compare_intervals_different_lengths():
assert compare_intervals((1, 3), (2, 5)) == -1
assert compare_intervals((2, 6), (4, 5)) == 1
def test_compare_intervals_same_length_and_start():
assert compare_intervals((1... | [
{
"docstring": "Compare two intervals based on custom rules.\n:param interval1: Tuple[int, int], the first interval.\n:param interval2: Tuple[int, int], the second interval.\n:return: -1 if interval1 < interval2, 1 if interval1 > interval2, 0 if they are equal.",
"function_declaration": "def compare_interva... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport functools\n\ndef compare_intervals(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> int:\n \"\"\"\n Compar... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000039877",
"row_id": 39877,
"seed_ids": "[383]"
} | 0.626579 | Algorithm_39877 | I | [
"compare_intervals",
"merge_intervals"
] | 2 | [
[
"merge_intervals",
"compare_intervals"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fcf64210281a8eb60df857d451dc74da3d18fa1a | f96f038d856c2e6311122acfa356b9f1c1b4d432 | |||
v1.0 | instruct | Algorithm | Algorithm_39919_I | ### Matrix Transform Sum
**Context**:
Matrix manipulation is a key aspect of various algorithmic challenges. This problem involves performing a series of transformations on a matrix, followed by operations that sum specific elements based on given queries.
**Task**:
Write a program that performs multiple transformati... | def rotate_90_clockwise(matrix):
n = len(matrix)
new_matrix = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n-i-1] = matrix[i][j]
return new_matrix
def reflect_horizontally(matrix):
n = len(matrix)
new_matrix = [[0]*n for _ in range(n)]
fo... | from solution import matrix_transform_sum
def test_single_rotation_and_query():
n = 3
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
t = 1
transformations = ['R']
q = 1
queries = ['R 1']
result = matrix_transform_sum(n, matrix, t, transformations, q, queries)
a... | [
{
"docstring": null,
"function_declaration": "def rotate_90_clockwise(matrix):",
"function_name": "rotate_90_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def reflect_horizontally(matrix):",
"function_name": "reflect_horizontally",
"par... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_90_clockwise(matrix):\n return [list(x)[::-1] for x in zip(*matrix)]\n\ndef reflect_horizontally(matrix):\n return matrix[::-1]\n\ndef matrix_tr... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000039919",
"row_id": 39919,
"seed_ids": "[374]"
} | 0.5594 | Algorithm_39919 | I | [
"rotate_90_clockwise",
"reflect_horizontally",
"process_queries",
"matrix_transform_sum"
] | 4 | [
[
"matrix_transform_sum",
"process_queries"
],
[
"matrix_transform_sum",
"reflect_horizontally"
],
[
"matrix_transform_sum",
"rotate_90_clockwise"
]
] | 3 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | 0e919777d29fecbb30b7e5ddd58f4cd8474a372b | e1ff359ff7246577d1415748d0e3f33ae3699f06 | |||
v1.0 | instruct | Algorithm | Algorithm_39954_I | ### Radix Sort Algorithm Assessment
#### Context
You have been provided with a list of non-negative integers, and you need to sort the list in ascending order efficiently. Your task is to implement the radix sort algorithm to achieve this.
#### Task
Write a function `radix_sort` that takes in one parameter:
1. `unsor... | def radix_sort(unsorted_collection: list[int]) -> list[int]:
if len(unsorted_collection) == 0:
return unsorted_collection
# Find the maximum number to determine the maximum number of digits
max_number = max(unsorted_collection)
# Initialize the exponent to 1 (10^0)
exp = 1
while m... | from solution import radix_sort
def test_radix_sort_example():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_dup_numbers():
assert radix_sort([1, 4, 1, 2, 7, 5, 2]) == [1, 1, 2, 2, 4, 5, 7]
def test_radix_sort_large_numbers():
assert radix_s... | [
{
"docstring": null,
"function_declaration": "def radix_sort(unsorted_collection):",
"function_name": "radix_sort",
"parameter_list": "(unsorted_collection)"
},
{
"docstring": null,
"function_declaration": "def counting_sort(collection, exp):",
"function_name": "counting_sort",
"... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def radix_sort(unsorted_collection: list[int]) -> list[int]:\n RADIX = 10 # We are working with base 10 numbers\n \n # Find the maximum number to figur... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039954",
"row_id": 39954,
"seed_ids": "[5265]"
} | 0.624738 | Algorithm_39954 | I | [
"radix_sort",
"counting_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 22aeaa2b7bde0690a19c0098288fef6eca9e0de3 | 5301ef3d0bc1c3bfab5cfb61f2a2cf7fd4dd498e | |||
v1.0 | instruct | Algorithm | Algorithm_39994_I | ### Question: Implement Prime Number Vector Filter
In this task, you will write a function to filter out prime numbers from a given numpy array of integers. A prime number is defined as any integer greater than `1` that is not divisible by any integer other than `1` and itself. Your function should identify and retain... | import numpy as np
def is_prime(n):
"""Check if a number is a prime number."""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(np.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def filter_pr... | from solution import filter_primes
import numpy as np
def test_filter_primes_example():
vector = np.array([10, 15, 3, 7, 6, 11, 13, 20, 25])
result = filter_primes(vector)
expected = np.array([3, 7, 11, 13])
assert np.array_equal(result, expected)
def test_filter_primes_empty():
vector = np.array(... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filter out the prime numbers from a given numpy array of integers.\n\nArgs:\nvector (np.ndarray): Input numpy array of in... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039994",
"row_id": 39994,
"seed_ids": "[4086]"
} | 0.607377 | Algorithm_39994 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 2808ef85de3f1fe1d404a6e739f6b711195b0a23 | bd14bd85d5f0552f645e75ca072489a80d2b07b6 | |||
v1.0 | instruct | Algorithm | Algorithm_40007_I | ### Scenario:
You have been hired as a software developer by a logistics company to streamline their package delivery tracking system. They require a function to determine the shortest delivery route between different locations while considering some locations as mandatory stops.
### Task:
Implement a function that fi... | import heapq
from typing import List, Tuple
def dijkstra(graph: List[List[Tuple[int, int]]], start: int) -> List[int]:
"""
Implements Dijkstra's algorithm to find the shortest path from 'start' to all other nodes.
Parameters:
- graph: Adjacency list representation of the graph where graph[u] is a ... | def test_dijkstra_basic():
graph = [
[(1, 2), (2, 4)],
[(0, 2), (2, 1)],
[(0, 4), (1, 1)]
]
assert dijkstra(graph, 0) == [0, 2, 3]
assert dijkstra(graph, 1) == [2, 0, 1]
assert dijkstra(graph, 2) == [3, 1, 0]
def test_find_shortest_route_case1():
assert find_shortes... | [
{
"docstring": "Implements Dijkstra's algorithm to find the shortest path from 'start' to all other nodes.\n\nParameters:\n- graph: Adjacency list representation of the graph where graph[u] is a list of tuples (v, w)\n representing an edge from u to v with weight w.\n- start: The starting node.\n\nRetur... | [
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": "import heapq\nfrom typing import List, Tuple, Dict\n\ndef dijkstra(n: int, graph: Dict[int, List[Tuple[int, int]]], start: int) -> Dict[int, int]:\n # Initial... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000040007",
"row_id": 40007,
"seed_ids": "[612]"
} | 0.684874 | Algorithm_40007 | I | [
"dijkstra",
"find_shortest_route"
] | 2 | [
[
"find_shortest_route",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 4b00ec10d647dc38efd8cfb6b20b0890539a8c58 | 7d6b7b397e62457c4e5d5f1f5ec14f63132e0aab | |||
v1.0 | instruct | Algorithm | Algorithm_40043_I | **Context**:
Sorting algorithms are a fundamental topic in computer science, often used to arrange data in a specified order. One common sorting algorithm is Merge Sort, which employs a divide-and-conquer strategy to sort elements efficiently.
**Objective**:
Your task is to implement the Merge Sort algorithm. Given a... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in non-decreasing order using the Merge Sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
... | from solution import merge_sort
def test_merge_sort_with_multiple_elements():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_negative_elements():
assert merge_sort([-5, -10, 0, -3, 8, 5, -1, 10]) == [-10, -5, -3, -1, 0, 5, 8, 10]
def test_merge_sort_w... | [
{
"docstring": "Sorts an array of integers in non-decreasing order using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"fu... | [
1,
1,
0,
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": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \"\"\"\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040043",
"row_id": 40043,
"seed_ids": "[4068]"
} | 0.666308 | Algorithm_40043 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f83485aef9ac66d9a2545cfb844ecc6bf761e44 | 519cd3e5fcc8d172850afa228ea4144878266013 | |||
v1.0 | instruct | Algorithm | Algorithm_40065_I | ### Coding Assessment Question
#### Scenario: Optimizing a Text Data Processing System using Multiprocessing
You are enhancing a text data processing system by introducing parallel processing to handle large datasets efficiently. Your task is to implement a function that leverages multiprocessing to count the frequen... | import multiprocessing
from collections import Counter
import re
def process_chunk(chunk):
"""
Function to process each chunk of text, count the word frequencies,
and return a Counter object.
"""
# Convert to lower case and use regex to remove punctuation
clean_text = re.sub(r'[^\w\s]', '', chu... | import pytest
from solution import word_frequency_counter
import os
def create_test_file(file_path, content):
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
def test_word_frequency_counter():
test_content = """
The quick brown fox jumps over the lazy dog.
The quick br... | [
{
"docstring": "Function to process each chunk of text, count the word frequencies,\nand return a Counter object.",
"function_declaration": "def process_chunk(chunk):",
"function_name": "process_chunk",
"parameter_list": "(chunk)"
},
{
"docstring": "Function to yield chunks of text from the ... | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import multiprocessing\nfrom collections import Counter\nimport re\n\ndef process_chunk(chunk):\n \"\"\"\n Function to process each chunk of text, count th... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000040065",
"row_id": 40065,
"seed_ids": "[898]"
} | 0.6507 | Algorithm_40065 | I | [
"process_chunk",
"chunkify",
"word_frequency_counter"
] | 3 | [
[
"word_frequency_counter",
"chunkify"
],
[
"word_frequency_counter",
"process_chunk"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3507d7b447aa6d22d7f1f5048d7b5960a15d69a5 | ca383d07bb15cb4f32a9c2421611d4443d9336d9 | |||
v1.0 | instruct | Algorithm | Algorithm_40112_I | ### Implementing a Decision Tree from Scratch
You are required to write a function `custom_decision_tree` that builds a Decision Tree classifier for a given dataset. The function should include detailed logging for each step of the tree construction process and handle edge cases gracefully.
#### Function Signature
``... | import numpy as np
def gini_impurity(labels):
"""Calculate the Gini impurity for a list of labels."""
unique_labels, counts = np.unique(labels, return_counts=True)
probabilities = counts / len(labels)
gini = 1 - np.sum(probabilities ** 2)
return gini
def find_best_split(data, labels):
"""Find ... | import numpy as np
from solution import custom_decision_tree
def test_single_split():
data = np.array([
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6]
])
labels = np.array([0, 0, 1, 1, 1])
tree = custom_decision_tree(data, labels, max_depth=1)
assert tree == {'featur... | [] | [
0,
0,
1,
1,
0,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef calculate_gini(labels):\n \"\"\"\n Calculate the Gini impurity for a list of labels.\n \"\"\"\n if len(labels) == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000040112",
"row_id": 40112,
"seed_ids": "[382]"
} | 0.567529 | Algorithm_40112 | I | [
"gini_impurity",
"find_best_split",
"build_tree",
"custom_decision_tree"
] | 4 | [
[
"build_tree",
"find_best_split"
],
[
"custom_decision_tree",
"build_tree"
],
[
"find_best_split",
"gini_impurity"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 4f59a55238244962f591f2e4f4acd532ec647fc6 | 4d0c9a5cf879baacaa05c48c4b0a8f6ed6e1d90d | |||
v1.0 | instruct | Algorithm | Algorithm_40120_I | ### String Manipulation with Custom Format
You are tasked with implementing a text processing program that detects and transforms specific patterns in a string. Using Python, you will write functions to identify and modify occurrences of a specific format, then reverse the modifications.
#### Requirements:
1. **Patt... | def transform_text(original_text: str) -> str:
"""
Transforms occurrences of <tag> to [TAG] and </tag> to [/TAG] in the text.
"""
transformed_text = original_text.replace('<tag>', '[TAG]').replace('</tag>', '[/TAG]')
return transformed_text
def reverse_transform(transformed_text: str) -> str:
"... | from solution import transform_text, reverse_transform, apply_transformation_to_file, reverse_transformation_from_file
def test_transform_text():
original = "This is <tag>example</tag> text."
transformed = "This is [TAG]example[/TAG] text."
assert transform_text(original) == transformed
def test_reverse_t... | [
{
"docstring": "Transforms occurrences of <tag> to [TAG] and </tag> to [/TAG] in the text.",
"function_declaration": "def transform_text(original_text):",
"function_name": "transform_text",
"parameter_list": "(original_text)"
},
{
"docstring": "Reverts occurrences of [TAG] to <tag> and [/TAG... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef transform_text(original_text: str) -> str:\n \"\"\"\n Transforms occurrences of <tag>some_text</tag> to [TAG]some_text[/TAG].\n \"\"\"\... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000040120",
"row_id": 40120,
"seed_ids": "[308]"
} | 0.561279 | Algorithm_40120 | I | [
"transform_text",
"reverse_transform",
"apply_transformation_to_file",
"reverse_transformation_from_file"
] | 4 | [
[
"apply_transformation_to_file",
"transform_text"
],
[
"reverse_transformation_from_file",
"reverse_transform"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1ced4539f530197ddd710f72ed5d256ca39bb060 | 847dabc299bcd582c4bcd6b3333c831044e24307 | |||
v1.0 | instruct | Algorithm | Algorithm_40149_I | ### Secure Chat Server with Asynchronous IO and Authentication
You are required to build a secure chat server that allows multiple clients to connect and communicate with each other in a chat room. The server should use asynchronous I/O and implement basic user authentication.
#### Function Specification:
Implement t... | import asyncio
import logging
import signal
logging.basicConfig(level=logging.INFO)
CLIENTS = {}
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
logging.info(f"Connection from {addr}")
if not await authenticate_user(reader, writer):
logging.info(f"Authentica... | import asyncio
import pytest
from solution import handle_client, authenticate_user, broadcast_message
async def fake_writer(data: list):
class FakeStreamWriter:
def __init__(self):
self._data = data
def write(self, data):
self._data.append(data.decode())
async def d... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
0,
0,
1,
0,
0,
1,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nimport signal\n\nlogging.basicConfig(level=logging.INFO)\n\nclients = {}\n\ndef load_credentials(auth_file):\n credentials = {... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000040149",
"row_id": 40149,
"seed_ids": "[4273]"
} | 0.530269 | Algorithm_40149 | I | [
"handle_client",
"broadcast_message",
"authenticate_user",
"start_chat_server",
"main",
"shutdown"
] | 6 | [
[
"handle_client",
"authenticate_user"
],
[
"handle_client",
"broadcast_message"
],
[
"start_chat_server",
"handle_client"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a85769dce6379aca6f0a6efc23e189b7cd4edff5 | 529ac891b328d8acf1272c2bb660ab965ab7377b | |||
v1.0 | instruct | Algorithm | Algorithm_40197_I | ### Problem Statement
You are managing a logistics company and need to optimize the daily delivery route for a single delivery truck. The truck starts from the depot (origin point) and must visit all customer locations exactly once and then return to the depot. This problem is conceptually known as the Traveling Sales... | import math
from typing import List, Tuple
def calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def nearest_neighbor_tsp(locations: List[Tuple[int, int]]) -> List[int]:
n = len(locations)
if n == 1:... | from solution import nearest_neighbor_tsp
def test_single_location():
assert nearest_neighbor_tsp([(0, 0)]) == [0, 0]
def test_two_locations():
assert nearest_neighbor_tsp([(0, 0), (1, 1)]) == [0, 1, 0]
def test_three_locations():
assert nearest_neighbor_tsp([(0, 0), (2, 3), (5, 4)]) == [0, 1, 2, 0]
def... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def nearest_neighbor_tsp(locations):",
"function_name": "nearest_neighb... | [
0,
1,
1,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef nearest_neighbor_tsp(locations):\n def distance(p1, p2):\n return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)\n \n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000040197",
"row_id": 40197,
"seed_ids": "[890]"
} | 0.612847 | Algorithm_40197 | I | [
"calculate_distance",
"nearest_neighbor_tsp"
] | 2 | [
[
"nearest_neighbor_tsp",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9e30c917593fcdab88b3a9b96e27f497d5a19678 | d0461cff2380bf46e7dc6f010fab15db83a1883d | |||
v1.0 | instruct | Algorithm | Algorithm_40206_I | ### Question
Create a function that implements the merge sort algorithm to sort a list of integers. Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts both halves, and then merges them to create the final sorted list.
#### Specific Requirements:
1. **Function N... | def merge_sort(arr):
"""
Sorts a list of integers using the merge sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A new list of integers sorted in ascending order.
"""
if len(arr) <= 1:
return arr
# Divide the list into two h... | from solution import merge_sort
def test_merge_sort_basic():
assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62]
def test_merge_sort_with_negative_numbers():
assert merge_sort([-3, -1, -2, -4, -5]) == [-5, -4, -3, -2, -1]
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]... | [
{
"docstring": "Sorts a list of integers using the merge sort algorithm.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A new list of integers sorted in ascending order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Function to sort an array using the merge sort algorithm\n \"\"\"\n if len(arr) <= 1:\n return arr\n\n # Sp... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040206",
"row_id": 40206,
"seed_ids": "[1627]"
} | 0.645031 | Algorithm_40206 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbf0770361f6779da9f2e215a176e865398f6fdf | d1c51b2c8620cd849f04fae47eead7a36973fe16 | |||
v1.0 | instruct | Algorithm | Algorithm_40243_I | ### Mandelbrot Set Visualization
You are required to implement a Python function that visualizes the Mandelbrot set, a famous fractal. Your task is to enhance the provided algorithm by introducing parallel processing to speed up the calculation.
### Objective
Write a function `plot_mandelbrot_parallel` that improves ... | import numpy as np
from PIL import Image
import multiprocessing
def mandelbrot(c, max_iter):
z = c
for n in range(max_iter):
if abs(z) > 2:
return n
z = z*z + c
return max_iter
def calculate_mandelbrot(pixel_data):
x, y, width, height, max_iter, x_min, x_max, y_min, y_max =... | import pytest
import multiprocessing
from PIL import Image
from solution import plot_mandelbrot_parallel, mandelbrot, calculate_mandelbrot
def test_mandelbrot():
assert mandelbrot(complex(0, 0), 1000) == 1000
assert mandelbrot(complex(2, 2), 1000) < 1000
assert mandelbrot(complex(-2, -2), 1000) < 1000
def... | [
{
"docstring": null,
"function_declaration": "def mandelbrot(c, max_iter):",
"function_name": "mandelbrot",
"parameter_list": "(c, max_iter)"
},
{
"docstring": null,
"function_declaration": "def calculate_mandelbrot(pixel_data):",
"function_name": "calculate_mandelbrot",
"paramet... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom PIL import Image\nimport multiprocessing\n\ndef mandelbrot(c, max_iter):\n z = c\n for n in range(max_iter):\n if abs(z) > ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000040243",
"row_id": 40243,
"seed_ids": "[4823]"
} | 0.506006 | Algorithm_40243 | I | [
"mandelbrot",
"calculate_mandelbrot",
"plot_mandelbrot_parallel",
"main"
] | 4 | [
[
"calculate_mandelbrot",
"mandelbrot"
],
[
"plot_mandelbrot_parallel",
"calculate_mandelbrot"
]
] | 2 | [] | false | [] | false | pytest | true | [
"PIL",
"numpy"
] | false | 31a80262427114a09045660aa64d167d4016a39a | aa1b3d7091482bcb03dc6c97f62c3344943825ee | |||
v1.0 | instruct | Algorithm | Algorithm_40246_I | ### Coding Assessment Question
#### Context:
You have been working with search algorithms and their various implementations. Now, you'll be tasked with implementing an efficient search algorithm for a sorted dataset and comparing its performance with a linear search.
#### Task:
Implement the Binary Search algorithm. ... | from typing import List
def binary_search(arr: List[int], target: int) -> int:
"""
Perform a binary search to find the index of the target in the sorted list.
Args:
arr (List[int]): The sorted list of integers.
target (int): The integer to find in the array.
Returns:
int: The index of... | from solution import binary_search, linear_search, compare_search_performance
def test_binary_search():
assert binary_search([1, 2, 3, 4, 5, 6], 4) == 3
assert binary_search([1, 2, 3, 4, 5, 6], 6) == 5
assert binary_search([1, 2, 3, 4, 5, 6], 1) == 0
assert binary_search([1, 2, 3, 4, 5, 6], 7) == -1
... | [
{
"docstring": "Perform a binary search to find the index of the target in the sorted list.\n\nArgs:\narr (List[int]): The sorted list of integers.\ntarget (int): The integer to find in the array.\n\nReturns:\nint: The index of the target in the array if found, otherwise -1.",
"function_declaration": "def b... | [
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 binary_search(arr: List[int], target: int) -> int:\n \"\"\"\n Implements the binary search algorithm.\n \n Args:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040246",
"row_id": 40246,
"seed_ids": "[952]"
} | 0.663202 | Algorithm_40246 | I | [
"binary_search",
"linear_search",
"compare_search_performance"
] | 3 | [
[
"compare_search_performance",
"binary_search"
],
[
"compare_search_performance",
"linear_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 835b44aa6fce67492013bc63af4b03a3497025af | a7475682f931bb4aab6901242e304fca7d396bd1 | |||
v1.0 | instruct | Algorithm | Algorithm_40286_I | ### Coding Challenge: Balanced Parentheses Conversion
#### Problem Statement
You are given a text file containing a list of strings, where each string consists solely of parentheses `(` and `)`. Your task is to determine how many operations are required to convert each string into a balanced parentheses string. Each o... | def minimum_operations_to_balance(s: str) -> int:
open_count = 0
close_count = 0
for char in s:
if char == '(':
open_count += 1
elif char == ')':
if open_count > 0:
open_count -= 1
else:
close_count += 1
return open_co... | from solution import minimum_operations_to_balance, compute_total_operations
def test_minimum_operations_empty_string():
assert minimum_operations_to_balance("") == 0
def test_minimum_operations_all_open():
assert minimum_operations_to_balance("(((") == 3
def test_minimum_operations_all_close():
assert m... | [
{
"docstring": null,
"function_declaration": "def minimum_operations_to_balance(s):",
"function_name": "minimum_operations_to_balance",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def compute_total_operations(filename):",
"function_name": "compute_total_o... | [
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def minimum_operations_to_balance(s: str) -> int:\n open_count = 0\n close_count = 0\n\n for char in s:\n if char == '(':\n open_count... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000040286",
"row_id": 40286,
"seed_ids": "[2805]"
} | 0.729571 | Algorithm_40286 | I | [
"minimum_operations_to_balance",
"compute_total_operations"
] | 2 | [
[
"compute_total_operations",
"minimum_operations_to_balance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f5b6bf129e060219313a3829dee731e6701b7907 | b6c113d9696f6d8f5f5602c180cc0aabb63af053 | |||
v1.0 | instruct | Algorithm | Algorithm_40324_I | ### Question
**Context**:
A self-dividing number is a number that is divisible by every digit it contains without leaving a remainder. For instance, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. However, 26 is not a self-dividing number because 26 % 6 != 0.
**Task**:
You need to ... | from typing import List
def is_self_dividing(n: int) -> bool:
"""
Helper function to determine if a number is self-dividing
"""
original = n
while n > 0:
digit = n % 10
if digit == 0 or original % digit != 0:
return False
n = n // 10
return True
def self_div... | from solution import self_dividing_numbers
def test_small_range():
assert self_dividing_numbers(1, 22) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
def test_range_no_self_dividing_numbers():
assert self_dividing_numbers(21, 21) == []
assert self_dividing_numbers(24, 25) == [24]
def test_large_range_wit... | [
{
"docstring": "Helper function to determine if a number is self-dividing",
"function_declaration": "def is_self_dividing(n):",
"function_name": "is_self_dividing",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all self-dividing numbers in the range [left, right]",
"functi... | [
0,
1,
0,
0,
1,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef self_dividing_numbers(left: int, right: int) -> List[int]:\n def is_self_dividing(n: int) -> bool:\n original_n = n\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040324",
"row_id": 40324,
"seed_ids": "[3618]"
} | 0.605735 | Algorithm_40324 | I | [
"is_self_dividing",
"self_dividing_numbers"
] | 2 | [
[
"self_dividing_numbers",
"is_self_dividing"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1089416a508617ccdc70db7789c9cebd38736e88 | 43b219798f59e3e0be16862c0f338785683481a2 | |||
v1.0 | instruct | Algorithm | Algorithm_40334_I | ### Question
You are given three different implementations for calculating the factorial of an integer:
- An iterative approach (`factorial_iter`).
- A recursive approach (`factorial_recur`).
- A compact approach using Python's built-in `math.factorial` function (`factorial_builtin`).
Your task is to write a function... | def factorial_recur(n):
"""
Returns the factorial of n using recursion.
"""
if n <= 1:
return 1
else:
return n * factorial_recur(n - 1)
def factorial_iter(n):
"""
Returns the factorial of n using iteration.
"""
result = 1
for i in range(2, n + 1):
result ... | def test_factorial_factory():
# Testing thresholds
assert factorial_factory(5, 3) == 120 # Uses iterative
assert factorial_factory(3, 4) == 6 # Uses recursive
assert factorial_factory(0, 2) == 1 # Zero case
assert factorial_factory(-4, 2) == 1 # Negative case
assert factorial_factory(10, 5) ... | [
{
"docstring": "Returns the factorial of n using recursion.",
"function_declaration": "def factorial_recur(n):",
"function_name": "factorial_recur",
"parameter_list": "(n)"
},
{
"docstring": "Returns the factorial of n using iteration.",
"function_declaration": "def factorial_iter(n):",
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def factorial_iter(n: int) -> int:\n result = 1\n for i in range(1, n + 1):\n result *= i\n return result\n\ndef factorial_recur(n: int) -> int:\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040334",
"row_id": 40334,
"seed_ids": "[3592]"
} | 0.662465 | Algorithm_40334 | I | [
"factorial_recur",
"factorial_iter",
"factorial_factory"
] | 3 | [
[
"factorial_factory",
"factorial_iter"
],
[
"factorial_factory",
"factorial_recur"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9cbf5e51c18347b448cc1095d6fae0ba22204e0a | b3b1a4a9d72e8894dc29ff4ffa495ea068a0462b | |||
v1.0 | instruct | Algorithm | Algorithm_40339_I | ### Coding Question: Convert Roman Numerals to Integers
#### Context
In various applications, historical data is often represented in Roman numerals. Your task is to create a function that converts Roman numerals into their corresponding integer values. This can be particularly useful in software dealing with historic... | def roman_to_int(roman: str) -> int:
"""
Converts a Roman numeral string to an integer.
:param roman: A string representing a Roman numeral.
:return: An integer equivalent of the Roman numeral.
"""
if not isinstance(roman, str):
raise TypeError("input must be a string")
rom... | import pytest
from solution import roman_to_int
def test_roman_to_int_basic():
assert roman_to_int("I") == 1
assert roman_to_int("III") == 3
assert roman_to_int("IV") == 4
assert roman_to_int("IX") == 9
assert roman_to_int("LVIII") == 58
assert roman_to_int("MCMXCIV") == 1994
def test_roman_to... | [
{
"docstring": "Converts a Roman numeral string to an integer.\n\n:param roman: A string representing a Roman numeral.\n:return: An integer equivalent of the Roman numeral.",
"function_declaration": "def roman_to_int(roman):",
"function_name": "roman_to_int",
"parameter_list": "(roman)"
},
{
... | [
0,
1,
0,
1,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def roman_to_int(roman: str) -> int:\n \"\"\"\n Converts a Roman numeral string to an integer.\n \n Args:\n roman (str): A string representing a R... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000040339",
"row_id": 40339,
"seed_ids": "[5202]"
} | 0.76002 | Algorithm_40339 | I | [
"roman_to_int",
"int_to_roman"
] | 2 | [
[
"roman_to_int",
"int_to_roman"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0538aeebb536f9aba8bb7d6faacbfdaf0cb93891 | 72ff49f875474d910cba0b524be2d0da7b8c1778 | |||
v1.0 | instruct | Algorithm | Algorithm_40346_I | ### Array Rotation and Query
You are tasked with implementing an array rotation function and a querying function to evaluate the array after performing the specified rotations. This is useful in database management systems and data processing pipelines where rotational transformations and data retrieval are frequent t... | def rotate_array(arr: list, k: int) -> list:
"""
Rotates the array to the right by k positions.
Args:
arr (list): The input array to rotate.
k (int): The number of positions to rotate the array.
Returns:
list: The rotated array.
"""
n = len(arr)
k %= n # To handle cases where ... | from solution import rotate_array, query_element
def test_rotate_array():
assert rotate_array([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]
assert rotate_array([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]
assert rotate_array([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5] # Rotating by the array length should return the same a... | [
{
"docstring": "Rotates the array to the right by k positions.\n\nArgs:\narr (list): The input array to rotate.\nk (int): The number of positions to rotate the array.\n\nReturns:\nlist: The rotated array.",
"function_declaration": "def rotate_array(arr, k):",
"function_name": "rotate_array",
"parame... | [
0,
1,
1,
0,
1,
1,
0,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_array(arr: list, k: int) -> list:\n n = len(arr)\n k %= n # To handle cases where k >= n\n return arr[-k:] + arr[:-k]\n\ndef query_element(a... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040346",
"row_id": 40346,
"seed_ids": "[3602]"
} | 0.577535 | Algorithm_40346 | I | [
"rotate_array",
"query_element"
] | 2 | [
[
"query_element",
"rotate_array"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2356541cfe7222ea1d71737cf49ef1517dd3a47 | a1f779150d93f4acb94b1486a2bee2ae9b74ca2b | |||
v1.0 | instruct | Algorithm | Algorithm_40352_I | ### Question
Write a function that implements a basic K-Means clustering algorithm from scratch. This function should group a set of 2D points into k clusters based on their Euclidean distances. Additionally, visualize the clustered points after the algorithm has converged.
### Requirements:
- Do not use any clusterin... | import numpy as np
import random
from matplotlib import pyplot as plt
def euclidean_distance(point1: tuple, point2: tuple) -> float:
"""
Calculate the Euclidean distance between two 2D points.
"""
return np.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def k_means_clustering(points: li... | import pytest
from solution import k_means_clustering, euclidean_distance
def test_k_means_clustering():
points = [(2, 3), (3, 4), (5, 6), (8, 9), (1, 2), (7, 8)]
k = 2
clusters, centroids = k_means_clustering(points, k)
assert len(clusters) == k
assert len(centroids) == k
def test_k_means_differe... | [
{
"docstring": "Calculate the Euclidean distance between two 2D points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Implement K-Means clustering algorithm.",
"function_... | [
1,
0,
0,
1,
1,
1,
0,
1,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport random\nfrom matplotlib import pyplot as plt\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean dista... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000040352",
"row_id": 40352,
"seed_ids": "[710]"
} | 0.706559 | Algorithm_40352 | I | [
"euclidean_distance",
"k_means_clustering",
"plot_clusters"
] | 3 | [
[
"k_means_clustering",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 85c05f473a2e9a269a96cb128b183184d8fb1a6f | 452b7f7c46c405af32f4050f83d4521a56cad80e | |||
v1.0 | instruct | Algorithm | Algorithm_40369_I | **Scenario**: You are developing a library that needs functionality for producing concise, human-readable summaries of lists containing both numerical and string elements. This library will handle dynamic datasets where data representation is key to user engagement and quick understanding.
### Task
1. **Function to C... | def concatenate_strings(string_list):
"""
Concatenates a list of strings into a single string, separated by a comma and a space.
Args:
string_list (list): List of strings to concatenate.
Returns:
str: Concatenated string.
"""
return ', '.join(string_list)
def calculate_summary... | from solution import concatenate_strings, calculate_summary_statistics, produce_summary
def test_concatenate_strings():
assert concatenate_strings(["apple", "banana", "cherry"]) == "apple, banana, cherry"
assert concatenate_strings(["hello", "world"]) == "hello, world"
assert concatenate_strings(["a", "b",... | [
{
"docstring": "Concatenates a list of strings into a single string, separated by a comma and a space.\n\nArgs:\nstring_list (list): List of strings to concatenate.\n\nReturns:\nstr: Concatenated string.",
"function_declaration": "def concatenate_strings(string_list):",
"function_name": "concatenate_str... | [
0,
0,
0,
1,
1,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from statistics import mean, median, variance, stdev\n\ndef concatenate_strings(strings):\n \"\"\"\n Concatenates a list of strings into a single string, s... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040369",
"row_id": 40369,
"seed_ids": "[2922]"
} | 0.59609 | Algorithm_40369 | I | [
"concatenate_strings",
"calculate_summary_statistics",
"produce_summary"
] | 3 | [
[
"produce_summary",
"calculate_summary_statistics"
],
[
"produce_summary",
"concatenate_strings"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 972a672bd50fce8b164d52e5f438f5bad6f475af | c9e0fd03f7ef751dd83f85cf5ddda157e9dad726 | |||
v1.0 | instruct | Algorithm | Algorithm_40371_I | ### Problem Statement: Prime Factorization and Greatest Common Divisor
You are required to write a library that assists in computing prime factorizations of integers and using those factorizations to determine the greatest common divisor (GCD) of two numbers.
**Context and Functions:**
Prime factorization involves b... | from typing import Dict
import math
def prime_factorization(n: int) -> Dict[int, int]:
if n <= 1:
raise ValueError("Input must be a positive integer greater than 1")
factors = {}
# Check for number of twos in n and divide by two
while n % 2 == 0:
factors[2] = factors.get(2, 0) + 1
... | from solution import prime_factorization, gcd
def test_prime_factorization():
assert prime_factorization(18) == {2: 1, 3: 2}
assert prime_factorization(29) == {29: 1}
assert prime_factorization(24) == {2: 3, 3: 1}
assert prime_factorization(100) == {2: 2, 5: 2}
def test_prime_factorization_invalid... | [
{
"docstring": null,
"function_declaration": "def prime_factorization(n):",
"function_name": "prime_factorization",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Dict\n\ndef prime_factorization(n: int) -> Dict[int, int]:\n \"\"\"\n Computes the prime factorization of a given integer n.\n \n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040371",
"row_id": 40371,
"seed_ids": "[824]"
} | 0.72078 | Algorithm_40371 | I | [
"prime_factorization",
"gcd"
] | 2 | [
[
"gcd",
"prime_factorization"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10591de846821d5e76391f254ed3253a565fe2ab | df87219c166803cb50e20064c31302f901644706 | |||
v1.0 | instruct | Algorithm | Algorithm_40587_I | ### Scenario
An e-commerce platform wants to offer discount prices and calculate totals for orders placed by customers. The discount rules can be configured for different product categories.
### Task
1. **Function Requirement: `calculate_discount`**
- **Purpose**:
Create a function to calculate the discount ... | class InvalidPriceError(Exception):
"""Custom exception for invalid price values."""
pass
def calculate_discount(category, price):
"""
Returns the discounted price based on the category and original price.
"""
if price <= 0:
raise InvalidPriceError("Invalid price value. Price must be gr... | import pytest
from solution import calculate_discount, calculate_order_total, InvalidPriceError
def test_calculate_discount_electronics():
assert calculate_discount('electronics', 100.0) == 90.00
def test_calculate_discount_clothing():
assert calculate_discount('clothing', 50.0) == 40.00
def test_calculate_d... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\nclass InvalidPriceError(Exception):\n pass\n\ndef calculate_discount(category: str, price: float) -> float:\n \"\"\"\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000040587",
"row_id": 40587,
"seed_ids": "[2296]"
} | 0.551354 | Algorithm_40587 | I | [
"calculate_discount",
"calculate_order_total"
] | 2 | [
[
"calculate_order_total",
"calculate_discount"
]
] | 1 | [] | false | [
"InvalidPriceError"
] | true | pytest | true | [] | true | 643c95d779031e4ecefc82d67b80211ea83bada3 | 593eadf29c2e0a2f43ff2d568410a716ca6dd548 | |||
v1.0 | instruct | Algorithm | Algorithm_40653_I | ### Problem Statement
You are to implement a function to calculate the **Matrix Product** using the Strassen Algorithm, which is more efficient than the standard matrix multiplication approach for larger matrices.
### Requirements
Write a function `strassen_matrix_mult` that takes in two square matrices `A` and `B`,... | import numpy as np
def add_matrix(A, B):
"""
Adds two matrices A and B.
"""
return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
def subtract_matrix(A, B):
"""
Subtracts matrix B from matrix A.
"""
return [[A[i][j] - B[i][j] for j in range(len(A[0]))] for i in ... | def test_strassen_matrix_mult_2x2():
A = [
[1, 2],
[3, 4]
]
B = [
[5, 6],
[7, 8]
]
result = strassen_matrix_mult(A, B)
assert result == [
[19, 22],
[43, 50]
]
def test_strassen_matrix_mult_4x4():
C = [
[1, 2, 3, 4],
[5, 6, ... | [
{
"docstring": "Adds two matrices A and B.",
"function_declaration": "def add_matrix(A, B):",
"function_name": "add_matrix",
"parameter_list": "(A, B)"
},
{
"docstring": "Subtracts matrix B from matrix A.",
"function_declaration": "def subtract_matrix(A, B):",
"function_name": "subtr... | [
0,
0,
1,
0,
0,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def strassen_matrix_mult(A, B):\n def add_matrix(X, Y):\n size = len(X)\n return [[X[i][j] + Y[i][j] for j in range(size)] for i in range(size)]... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040653",
"row_id": 40653,
"seed_ids": "[3647]"
} | 0.515528 | Algorithm_40653 | I | [
"add_matrix",
"subtract_matrix",
"split_matrix",
"strassen_matrix_mult"
] | 4 | [
[
"strassen_matrix_mult",
"add_matrix"
],
[
"strassen_matrix_mult",
"split_matrix"
],
[
"strassen_matrix_mult",
"subtract_matrix"
]
] | 3 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | 1f930f2dc846612fc14ec767753740c075fbc1c1 | 7e2fb9b122d32d9cd4862d17d6fcad5367ca1096 | |||
v1.0 | instruct | Algorithm | Algorithm_40654_I | ### Question: Matrix Determinant Calculation
You are given a function `determinant(matrix)` that calculates the determinant of a 2x2 matrix. Your task is to implement an enhanced function `determinant_calculator` that reads a matrix input string, parses it into a 2x2 list structure, and computes its determinant.
### ... | def determinant(matrix):
"""
Calculates the determinant of a 2x2 matrix.
The matrix is expected to be a list of lists in the form:
[[a11, a12], [a21, a22]]
"""
[[a11, a12], [a21, a22]] = matrix
return a11 * a22 - a12 * a21
def determinant_calculator(input_str: str) -> int:
"""
Parse... | def test_determinant_calculator():
assert determinant_calculator("1,2;3,4") == -2
assert determinant_calculator("5,6;7,8") == -2
assert determinant_calculator("0,1;-1,0") == 1
assert determinant_calculator("-1,-2;-3,-4") == -2
assert determinant_calculator("2,3;5,7") == -1
assert determinant_cal... | [
{
"docstring": "Calculates the determinant of a 2x2 matrix.\nThe matrix is expected to be a list of lists in the form:\n[[a11, a12], [a21, a22]]",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Parses a matr... | [
0,
0,
0,
1,
1,
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": "def determinant_calculator(input_str: str) -> int:\n \"\"\"\n Parses a 2x2 matrix from input string and calculates its determinant.\n\n Args:\n i... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000040654",
"row_id": 40654,
"seed_ids": "[3698]"
} | 0.498925 | Algorithm_40654 | I | [
"determinant",
"determinant_calculator"
] | 2 | [
[
"determinant_calculator",
"determinant"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 86fb0da60c02c8dc0b765227097f8192b73b6d9e | 38489cb0adbfc803dbf4f4135e4b70ac1c3bb804 | |||
v1.0 | instruct | Algorithm | Algorithm_40665_I | ### Problem Statement
You are tasked with creating a scheduling system that checks for conflicts in a list of events and suggests optimal event slots based on given constraints. Each event has a start time, end time, and a unique identifier.
#### Function Descriptions
1. **parse_time(time_str: str) -> Tuple[int, int... | from typing import List, Tuple
def parse_time(time_str: str) -> Tuple[int, int]:
hours, minutes = map(int, time_str.split(':'))
return (hours, minutes)
def event_conflict(event1: Tuple[str, str, str], event2: Tuple[str, str, str]) -> bool:
_, start1, end1 = event1
_, start2, end2 = event2
start1_h... | def test_parse_time():
assert parse_time("14:30") == (14, 30)
assert parse_time("00:00") == (0, 0)
assert parse_time("23:59") == (23, 59)
assert parse_time("08:05") == (8, 5)
def test_event_conflict():
event1 = ("1", "09:00", "11:00")
event2 = ("2", "10:30", "12:00")
event3 = ("3", "11:00",... | [
{
"docstring": null,
"function_declaration": "def parse_time(time_str):",
"function_name": "parse_time",
"parameter_list": "(time_str)"
},
{
"docstring": null,
"function_declaration": "def event_conflict(event1, event2):",
"function_name": "event_conflict",
"parameter_list": "(ev... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef parse_time(time_str: str) -> Tuple[int, int]:\n hours, minutes = map(int, time_str.split(\":\"))\n return hours, minu... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000040665",
"row_id": 40665,
"seed_ids": "[495]"
} | 0.549483 | Algorithm_40665 | I | [
"parse_time",
"event_conflict",
"find_conflicts",
"suggest_time_slot"
] | 4 | [
[
"event_conflict",
"parse_time"
],
[
"find_conflicts",
"event_conflict"
],
[
"suggest_time_slot",
"parse_time"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 15d6b505c83efe9fa1ab806862ef7cac44a9b016 | 01e74bf8f1840f757565de92d11957781147e540 | |||
v1.0 | instruct | Algorithm | Algorithm_40709_I | ### Problem Statement
You are tasked with developing a basic encryption and decryption system using a simple substitution cipher. Each letter in the plaintext is 'shifted' a certain number of places down (or up) the alphabet. This is a variation of the Caesar cipher that needs to handle both uppercase and lowercase let... | def encrypt(text, shift):
"""
Encrypts the text by shifting alphabetical characters by a given shift amount.
"""
result = []
for char in text:
if char.isalpha():
if char.islower():
result.append(chr((ord(char) - ord('a') + shift) % 26 + ord('a')))
elif... | from solution import encrypt, decrypt
def test_encrypt_positive_shift():
assert encrypt("Hello, World!", 3) == "Khoor, Zruog!"
assert encrypt("abc", 1) == "bcd"
assert encrypt("XYZ", 3) == "ABC"
assert encrypt("hello123", 2) == "jgnnq123"
def test_encrypt_negative_shift():
assert encrypt("Hello, W... | [
{
"docstring": "Encrypts the text by shifting alphabetical characters by a given shift amount.",
"function_declaration": "def encrypt(text, shift):",
"function_name": "encrypt",
"parameter_list": "(text, shift)"
},
{
"docstring": "Decrypts the text by reversing the shift alphabetical charact... | [
0,
1,
1,
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": "def encrypt(text, shift):\n \"\"\"\n Encrypts text using a Caesar cipher with a given shift.\n \"\"\"\n result = []\n for char in text:\n i... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000040709",
"row_id": 40709,
"seed_ids": "[4158]"
} | 0.722544 | Algorithm_40709 | I | [
"encrypt",
"decrypt"
] | 2 | [
[
"decrypt",
"encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71cb495749624bfb5895e1872c2fd984c1972c1a | fc5d74cb0b687dd81e9c2cb5a58c7c11f68cede9 | |||
v1.0 | instruct | Algorithm | Algorithm_40741_I | **Question: Implement a Basic Text-Based Tic-Tac-Toe Game**
You are tasked with writing a simple text-based implementation of the Tic-Tac-Toe game where two players can play against each other in turns. Your implementation should handle the following:
1. **Game Board Display**: Implement a function to print the curre... | def print_board(board):
"""
Prints the current game board.
Arguments:
board -- list of 9 elements representing the tic-tac-toe board
"""
print(f"{board[0]} | {board[1]} | {board[2]}")
print("--+---+--")
print(f"{board[3]} | {board[4]} | {board[5]}")
print("--+---+--")
print(... | from solution import print_board, make_move, check_winner, is_draw
def test_print_board(capsys):
board = ['X', ' ', 'O', ' ', 'X', ' ', 'O', ' ', 'X']
print_board(board)
captured = capsys.readouterr()
assert captured.out == "X | | O\n--+---+--\n | X | \n--+---+--\nO | | X\n"
def test_make_move()... | [
{
"docstring": "Prints the current game board.\n\nArguments:\nboard -- list of 9 elements representing the tic-tac-toe board",
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": "Makes a move for the player on the ... | [
1,
0,
1,
1,
1,
0,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def print_board(board):\n \"\"\"\n Prints the current state of the game board.\n \"\"\"\n print(f\"{board[0]} | {board[1]} | {board[2]}\")\n print... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040741",
"row_id": 40741,
"seed_ids": "[231]"
} | 0.516178 | Algorithm_40741 | I | [
"print_board",
"make_move",
"check_winner",
"is_draw",
"play_game"
] | 5 | [
[
"play_game",
"check_winner"
],
[
"play_game",
"is_draw"
],
[
"play_game",
"make_move"
],
[
"play_game",
"print_board"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | d89e3b65ad28906946b38217eecb98588d883417 | 5ace6b979a84d0a03d2655dcee67c21607eb6436 | |||
v1.0 | instruct | Algorithm | Algorithm_40787_I | ### Context
Sorting algorithms are fundamental to computer science, and understanding how they work can elucidate deeper algorithmic concepts. Merge Sort is a classic divide-and-conquer algorithm that you are required to implement. Demonstrating your grasp of this algorithm will show your proficiency in recursion and ... | def merge_sort(arr):
"""
Implements the Merge Sort algorithm to sort a list of integers in non-decreasing order.
Parameters:
arr (list of int): List of integers to be sorted.
Returns:
list of int: Sorted list of integers.
"""
if len(arr) <= 1:
return arr
# Find... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3]) == [1, 2, 3]
def test_merge_sort_reverse_sorted():
assert merge_sort([3, 2, 1]) == [... | [
{
"docstring": "Implements the Merge Sort algorithm to sort a list of integers in non-decreasing order.\n\nParameters:\narr (list of int): List of integers to be sorted.\n\nReturns:\nlist of int: Sorted list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
... | [
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: list[int]) -> list[int]:\n \"\"\"\n Sorts a list of integers using the Merge Sort algorithm.\n Parameters:\n arr (list[int]):... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000040787",
"row_id": 40787,
"seed_ids": "[4614]"
} | 0.638623 | Algorithm_40787 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c64caae46c34ec64c4c7d867b701730b9d411c50 | 4340fca3df1c53a11cac972d7685120ad314d36f | |||
v1.0 | instruct | Algorithm | Algorithm_40805_I | ### Problem Statement:
You are assigned a task to identify the next largest prime within a certain range after a given number.
**Objective:**
Write a function `next_largest_prime(n: int, upper_bound: int) -> int` that returns the smallest prime number greater than `n` and less than or equal to `upper_bound`.
**Input... | def is_prime(num):
"""Helper function to check if a number is prime"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
... | from solution import next_largest_prime
def test_next_largest_prime_normal_cases():
assert next_largest_prime(10, 20) == 11
assert next_largest_prime(14, 30) == 17
assert next_largest_prime(30, 35) == 31
def test_next_largest_prime_no_prime_in_range():
assert next_largest_prime(13, 13) == -1
asser... | [
{
"docstring": "Helper function to check if a number is prime",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Finds the smallest prime number greater than n and less than or equal to upper_bound.",
"function_declar... | [
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(num):\n \"\"\"Returns True if num is a prime number, else False.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000040805",
"row_id": 40805,
"seed_ids": "[2613]"
} | 0.625359 | Algorithm_40805 | I | [
"is_prime",
"next_largest_prime"
] | 2 | [
[
"next_largest_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e587bff966b4be5315d5fa4e0c57fa46a7a548d8 | 4d7ec633b59a0950a07ae95cd61a8247ea947162 | |||
v1.0 | instruct | Algorithm | Algorithm_40825_I | ### Coding Assessment Question:
Imagine you are tasked with analyzing strings for symmetry and transformation patterns.
**Problem Statement:**
You are given a collection of strings. Your assignment is to identify all possible palindromic substrings within each string without transforming the string. After identifyin... | def is_palindrome(s: str) -> bool:
"""
Determines if the given string is a palindrome.
Parameters:
s (str): Input string to check for palindrome.
Returns:
bool: True if the input string is a palindrome, False otherwise.
"""
return s == s[::-1]
def find_longest_palindromes(stri... | from solution import is_palindrome, find_longest_palindromes
def test_is_palindrome():
assert is_palindrome("racecar") is True
assert is_palindrome("babad") is False
assert is_palindrome("civic") is True
assert is_palindrome("hello") is False
assert is_palindrome("noon") is True
assert is_palin... | [
{
"docstring": "Determines if the given string is a palindrome.\n\nParameters:\ns (str): Input string to check for palindrome.\n\nReturns:\nbool: True if the input string is a palindrome, False otherwise.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Returns True if the given string s is a palindrome, otherwise False.\n \"\"\"\n return s == s[::-1]\n\ndef find_long... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000040825",
"row_id": 40825,
"seed_ids": "[2456]"
} | 0.79189 | Algorithm_40825 | I | [
"is_palindrome",
"find_longest_palindromes"
] | 2 | [
[
"find_longest_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83077aad9776fceb62d416e4b41422517d1ea6d6 | a8ed2b10cf65019eb81e341f70d22517a60098eb | |||
v1.0 | instruct | Algorithm | Algorithm_40828_I | ### Employee Salary Calculator
You are asked to develop an employee salary calculator system that determines the monthly salary of employees based on their hourly rate and hours worked. The system should also compute overtime pay for hours worked beyond a specified threshold.
**Objectives**:
1. **Salary Calculation*... | def calculate_regular_salary(hours_worked: float, hourly_rate: float) -> float:
"""
Calculate the regular salary based on hourly rate and hours worked.
"""
if hours_worked < 0 or hourly_rate < 0:
raise ValueError("hours_worked and hourly_rate must be non-negative")
return hours_worked * hour... | import pytest
from solution import calculate_regular_salary, calculate_overtime_salary, calculate_total_salary
def test_calculate_regular_salary():
assert calculate_regular_salary(160, 20) == 3200.0
assert calculate_regular_salary(0, 20) == 0.0
assert calculate_regular_salary(160, 0) == 0.0
with pytest... | [
{
"docstring": "Calculate the regular salary based on hourly rate and hours worked.",
"function_declaration": "def calculate_regular_salary(hours_worked, hourly_rate):",
"function_name": "calculate_regular_salary",
"parameter_list": "(hours_worked, hourly_rate)"
},
{
"docstring": "Calculate ... | [
0,
1,
1,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate_regular_salary(hours_worked: float, hourly_rate: float) -> float:\n \"\"\"\n Calculate the regular salary based on hourly rate and hours work... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000040828",
"row_id": 40828,
"seed_ids": "[2974]"
} | 0.546012 | Algorithm_40828 | I | [
"calculate_regular_salary",
"calculate_overtime_salary",
"calculate_total_salary"
] | 3 | [
[
"calculate_total_salary",
"calculate_overtime_salary"
],
[
"calculate_total_salary",
"calculate_regular_salary"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1a3a16726daf414615e302b91bae5fdcba1425ef | 03fd98690a72f76336e4b782a10c0ed421f43fcf | |||
v1.0 | instruct | Algorithm | Algorithm_40887_I | ### Content Rebalancing and Sharding (Database Scaling)
The following set of functions implements a basic sharding mechanism for distributing and rebalancing data across multiple database shards. The specific focus is on distributing user data uniformly using consistent hashing.
You are required to implement the `reb... | import hashlib
from typing import List, Tuple, Any, Dict
def consistent_hash(key: str, num_shards: int) -> int:
"""
Consistently hash a given key to one of the available shards.
"""
return int(hashlib.md5(key.encode()).hexdigest(), 16) % num_shards
def rebalance(user_data: List[Tuple[str, Any]], num_s... | from solution import rebalance
def test_rebalance_even_distribution():
user_data = [
("user1", {"data": "value1"}),
("user2", {"data": "value2"}),
("user3", {"data": "value3"}),
("user4", {"data": "value4"})
]
num_shards = 2
sharded_data = rebalance(user_data, num_shards... | [
{
"docstring": "Consistently hash a given key to one of the available shards.",
"function_declaration": "def consistent_hash(key, num_shards):",
"function_name": "consistent_hash",
"parameter_list": "(key, num_shards)"
},
{
"docstring": "Rebalances the user data across the specified number o... | [
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": "import hashlib\n\ndef hash_user_id(user_id: str) -> int:\n return int(hashlib.md5(user_id.encode()).hexdigest(), 16)\n\ndef rebalance(user_data, num_shards):\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000040887",
"row_id": 40887,
"seed_ids": "[4854]"
} | 0.435933 | Algorithm_40887 | I | [
"consistent_hash",
"rebalance"
] | 2 | [
[
"rebalance",
"consistent_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2e4915f914eaa6249ec86bc56f1ce42f855f8687 | f4d853b800a44f726d4c069488f7aab2984fbf82 | |||
v1.0 | instruct | Algorithm | Algorithm_40992_I | ### Context
You are working on enhancing a spell-checking software by implementing a feature for suggesting corrections to misspelled words. The software needs to generate suggestions based on the edit distance, which measures the number of operations (insertions, deletions, or substitutions) required to transform one ... | def edit_distance(word1, word2):
"""Compute the edit distance between two words."""
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for i in range(len(word1) + 1):
for j in range(len(word2) + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
... | from solution import suggest_correction
def test_suggest_correction_example():
misspelled = "speling"
dictionary = ["spelling", "sphere", "selling", "spilling"]
assert suggest_correction(misspelled, dictionary) == "spelling"
def test_suggest_correction_tie():
misspelled = "teest"
dictionary = ["te... | [
{
"docstring": "Compute the edit distance between two words.",
"function_declaration": "def edit_distance(word1, word2):",
"function_name": "edit_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Suggest the best correction for a misspelled word from a dictionary.",
"funct... | [
1,
1,
1,
0,
1,
0,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def edit_distance(word1: str, word2: str) -> int:\n \"\"\"\n Computes the edit distance between two words using dynamic programming.\n \"\"\"\n m, n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000040992",
"row_id": 40992,
"seed_ids": "[2231]"
} | 0.638674 | Algorithm_40992 | I | [
"edit_distance",
"suggest_correction"
] | 2 | [
[
"suggest_correction",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85b0042e180354f31735342941ddca7117dd07fc | 0ffd32ff1deb7d93118b3a34bd176469456b01f3 | |||
v1.0 | instruct | Algorithm | Algorithm_41003_I | ### Question:
You are provided with a function `is_possible` that determines if it is possible to transform one string into another using a series of operations. Each operation can be one of the following:
- Insert a character at any position in the string.
- Delete a character from any position in the string.
- Repla... | def min_operations(str1: str, str2: str) -> int:
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j # str1 is empty, insert all characters of str2
elif j == 0:
... | from solution import min_operations, is_possible
def test_min_operations():
# Testing identical strings
assert min_operations("a", "a") == 0
assert min_operations("", "") == 0
# Testing insertions
assert min_operations("a", "ab") == 1
assert min_operations("", "abc") == 3
# Testin... | [
{
"docstring": null,
"function_declaration": "def min_operations(str1, str2):",
"function_name": "min_operations",
"parameter_list": "(str1, str2)"
},
{
"docstring": null,
"function_declaration": "def is_possible(str1, str2, k):",
"function_name": "is_possible",
"parameter_list":... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def min_operations(str1: str, str2: str) -> int:\n \"\"\"\n Returns the minimum number of operations required to transform str1 into str2.\n Operations:... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000041003",
"row_id": 41003,
"seed_ids": "[38]"
} | 0.706691 | Algorithm_41003 | I | [
"min_operations",
"is_possible"
] | 2 | [
[
"is_possible",
"min_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cc8921b241ddf2871e1d7b76a9df034655a577f4 | f8c10e7326518d1df069cac9f9521d07a0637364 | |||
v1.0 | instruct | Algorithm | Algorithm_41023_I | ### Coding Task: Enhanced GCD and LCM Calculator
**Objective**: Develop an advanced version of the Euclidean algorithm to calculate the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two given integers. Additionally, implement a function to calculate the GCD and LCM of a list of integers.
#### Funct... | def find_gcd(a, b):
"""
Returns the GCD of two integers a and b.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Both a and b must be integers.")
if a <= 0 or b <= 0:
raise ValueError("Both a and b must be greater than zero.")
while b:
a, b ... | def test_find_gcd():
assert find_gcd(54, 24) == 6
assert find_gcd(24, 54) == 6
assert find_gcd(7, 5) == 1
assert find_gcd(48, 180) == 12
def test_find_gcd_exceptions():
try:
find_gcd(-54, 24)
except ValueError as e:
assert str(e) == "Both a and b must be greater than zero."
... | [
{
"docstring": "Returns the GCD of two integers a and b.",
"function_declaration": "def find_gcd(a, b):",
"function_name": "find_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the LCM of two integers a and b.",
"function_declaration": "def find_lcm(a, b):",
"function_nam... | [
1,
1,
0,
1,
0,
0,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import gcd\nfrom functools import reduce\n\ndef find_gcd(a: int, b: int) -> int:\n \"\"\"\n Returns the GCD of two given integers a and b.\n \... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000041023",
"row_id": 41023,
"seed_ids": "[3559]"
} | 0.697749 | Algorithm_41023 | I | [
"find_gcd",
"find_lcm",
"gcd_list",
"lcm_list"
] | 4 | [
[
"find_lcm",
"find_gcd"
],
[
"gcd_list",
"find_gcd"
],
[
"lcm_list",
"find_lcm"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | d62b167f41379611a2b0668206632181b3e2b931 | 018a7c3d68e4feb0b1448c7a95fa0dd0bbcf18af | |||
v1.0 | instruct | Algorithm | Algorithm_41036_I | ### Problem Statement
Alex is learning about palindromic numbers and their interesting properties. A palindromic number is a number that remains the same when its digits are reversed. Alex wants to find the smallest palindromic number that is greater than a given integer `x`.
Your task is to implement a function `nex... | def is_palindromic(num):
"""
Helper function to check if a number is palindromic.
"""
str_num = str(num)
return str_num == str_num[::-1]
def next_palindrome(x):
"""
Returns the smallest palindromic number greater than x.
"""
x += 1 # Start checking from the next number
while no... | from solution import next_palindrome
def test_next_palindrome_basic():
assert next_palindrome(123) == 131
def test_next_palindrome_edge():
assert next_palindrome(999) == 1001
def test_next_palindrome_same_digits():
assert next_palindrome(888) == 898
def test_next_palindrome_large():
assert next_pali... | [
{
"docstring": "Helper function to check if a number is palindromic.",
"function_declaration": "def is_palindromic(num):",
"function_name": "is_palindromic",
"parameter_list": "(num)"
},
{
"docstring": "Returns the smallest palindromic number greater than x.",
"function_declaration": "de... | [
0,
0,
1,
0,
1,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(n: int) -> bool:\n \"\"\"\n Checks if the given number n is a palindrome.\n \"\"\"\n str_n = str(n)\n return str_n == str_n[::-1... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041036",
"row_id": 41036,
"seed_ids": "[2128]"
} | 0.834285 | Algorithm_41036 | I | [
"is_palindromic",
"next_palindrome"
] | 2 | [
[
"next_palindrome",
"is_palindromic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b3b6635aa15452de716b84d42d32033d46df598a | 4a81d48742dfc0f19a36ad2197a0aae31b431a9b | |||
v1.0 | instruct | Algorithm | Algorithm_41081_I | ### Problem Statement
You need to develop a program that calculates the sum of the first N prime numbers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
### Objectives
1. Write a function `is_prime(n: int) -> bool` that checks if a given integer `n` is a prime... | import math
def is_prime(n: int) -> bool:
"""
Check if a number n is prime.
Args:
n: int - Number to be checked
Returns:
bool - True if n is prime, False otherwise
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
r... | def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(13) == True
assert is_prime(17) == True
assert is_prime(20) == False
assert is_prime(29) == True
assert is_prime(1) == False
assert i... | [
{
"docstring": "Check if a number n is prime.\n\nArgs:\nn: int - Number to be checked\n\nReturns:\nbool - True if n is prime, False otherwise",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of the first n... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Checks if a given integer `n` is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000041081",
"row_id": 41081,
"seed_ids": "[2322]"
} | 0.747879 | Algorithm_41081 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6b554094e626e1242d50312a597afa0f8e2a73a4 | 137c57c367ff6abd14d7c3c9a2f29236087ad4c2 | |||
v1.0 | instruct | Algorithm | Algorithm_41093_I | ### Problem Statement
A tech company is developing a data processing module that deals with lists of integers. Your task is to implement a utility that performs specific operations on these lists. Users can input a list of integers and perform operations such as finding the second largest number, checking if the list ... | def second_largest(numbers):
if len(numbers) < 2:
raise ValueError("The list must contain at least two elements.")
unique_numbers = list(set(numbers))
if len(unique_numbers) < 2:
raise ValueError("The list must contain at least two unique elements.")
unique_numbers.sort(reverse=True)
... | from solution import second_largest, is_strictly_increasing, sum_of_squares_of_evens, list_operations_summary
def test_second_largest():
assert second_largest([1, 7, 3, 5, 9, 2]) == 7
assert second_largest([2, 2, 2, 4]) == 2
assert second_largest([5, 1]) == 1
import pytest
with pytest.raises(V... | [
{
"docstring": null,
"function_declaration": "def second_largest(numbers):",
"function_name": "second_largest",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def is_strictly_increasing(numbers):",
"function_name": "is_strictly_increasing",
"parame... | [
1,
1,
1,
1,
1,
0,
0,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef second_largest(numbers: List[int]) -> int:\n \"\"\"\n Returns the second largest number in the list.\n \"\"\"\n if len... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000041093",
"row_id": 41093,
"seed_ids": "[640]"
} | 0.623128 | Algorithm_41093 | I | [
"second_largest",
"is_strictly_increasing",
"sum_of_squares_of_evens",
"list_operations_summary"
] | 4 | [
[
"list_operations_summary",
"is_strictly_increasing"
],
[
"list_operations_summary",
"second_largest"
],
[
"list_operations_summary",
"sum_of_squares_of_evens"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f3ed404495bd249121926acd5786d066e4245db6 | ebaf09d7980c9da477823045ebfaaf3c9196f9c1 | |||
v1.0 | instruct | Algorithm | Algorithm_41109_I | ### Problem
You are given a log file containing multiple lines of user activities. Each line represents a single activity and contains a timestamp (in the format `YYYY-MM-DD HH:MM:SS`), a user ID, and an activity description. Your task is to write a function `parse_log_file` that reads and processes this log file to ex... | from collections import defaultdict
# Data structure to store parsed activities
activities = defaultdict(list)
def parse_log_file(filename: str) -> None:
"""
Reads the log file and stores the activities in a data structure.
"""
global activities
activities.clear()
with open(filename, 'r')... | from solution import parse_log_file, most_active_user, user_activity_count
def test_parse_log_file():
log_content = """2023-01-01 09:00:00 user1 Logged in
2023-01-01 09:05:00 user2 Viewed dashboard
2023-01-01 09:10:00 user1 Posted a comment
2023-01-01 09:15:00 user1 Logged out
2023-01-01 09:20:00 user3 Logged in""... | [
{
"docstring": "Reads the log file and stores the activities in a data structure.",
"function_declaration": "def parse_log_file(filename):",
"function_name": "parse_log_file",
"parameter_list": "(filename)"
},
{
"docstring": "Parses a single line of the log file.",
"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": "from collections import defaultdict\n\n# Data structure to store parsed activities\nactivities = defaultdict(list)\n\ndef parse_log_file(filename: str) -> None:\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041109",
"row_id": 41109,
"seed_ids": "[344]"
} | 0.568459 | Algorithm_41109 | I | [
"parse_log_file",
"parse_line",
"most_active_user",
"user_activity_count"
] | 4 | [
[
"parse_log_file",
"parse_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c5ff2ee24a088a2ce7f3a4f99ea10493a1141ea1 | 17a1bab931f01b6818b4aa0c963933ff28f72845 | |||
v1.0 | instruct | Algorithm | Algorithm_41134_I | ### Advanced Problem: Implementing a Multithreaded Web Crawler
#### Scenario
You are to design a multithreaded web crawler that can crawl a list of URLs concurrently. The crawler should avoid crawling the same URL multiple times and should handle potential errors such as timeouts or HTTP errors gracefully.
### Proble... | import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
def fetch_url(url):
try:
response = requests.get(url, timeout=5)
return url, response.status_code
except requests.RequestException as e:
return url, None
def multithreaded_web_crawler(urls,... | import pytest
from solution import multithreaded_web_crawler
def test_multithreaded_web_crawler():
urls = [
"http://httpbin.org/status/200",
"http://httpbin.org/status/404",
"http://httpbin.org/status/500"
]
num_threads = 3
result = multithreaded_web_crawler(urls, num_threads)
... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def multithreaded_web_crawler(urls, num_threads):",
"function_name": "multithreaded_web_crawler",
"paramete... | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import threading\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor\nfrom collections import defaultdict\nimport time\n\ndef fetch_url(url, resu... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000041134",
"row_id": 41134,
"seed_ids": "[900]"
} | 0.59179 | Algorithm_41134 | I | [
"fetch_url",
"multithreaded_web_crawler"
] | 2 | [
[
"multithreaded_web_crawler",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 5d72caf8378666f701e49393fa67e19254b27a21 | 1f5c90b7156e5cb59e7039f93237890d2ec1f55e | |||
v1.0 | instruct | Algorithm | Algorithm_41204_I | ### Coding Assessment Question:
You are tasked with managing a school system where students' grades need to be processed and analyzed.
**Problem Statement:**
You are provided with a list of students' grades for different subjects. Each student's record contains the student's name and a dictionary of subjects along w... | from typing import Dict, List, Any
def calculate_average(grades: Dict[str, int]) -> float:
"""
Calculate the average grade from a dictionary of subjects and grades.
Parameters:
grades (Dict[str, int]): Dictionary with subjects as keys and grades as values.
Returns:
float: The average ... | from solution import calculate_average, find_top_student
def test_calculate_average_single_subject():
assert calculate_average({"Math": 90}) == 90.0
def test_calculate_average_multiple_subjects():
assert calculate_average({"Math": 90, "Science": 85, "English": 95}) == 90.0
def test_calculate_average_zero_gra... | [
{
"docstring": "Calculate the average grade from a dictionary of subjects and grades.\n\nParameters:\ngrades (Dict[str, int]): Dictionary with subjects as keys and grades as values.\n\nReturns:\nfloat: The average grade.",
"function_declaration": "def calculate_average(grades):",
"function_name": "calcu... | [
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 Dict, List, Any\n\ndef calculate_average(grades: Dict[str, int]) -> float:\n \"\"\"\n Given a dictionary of subjects and grades, compute... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000041204",
"row_id": 41204,
"seed_ids": "[2456]"
} | 0.739485 | Algorithm_41204 | I | [
"calculate_average",
"find_top_student"
] | 2 | [
[
"find_top_student",
"calculate_average"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f58629e2d1b03999a2fe1eb4832993df45108a64 | 5d7b0f49f3539fe67fac6d8d0abdac5ec086d75e | |||
v1.0 | instruct | Algorithm | Algorithm_41205_I | ### Minimum Spanning Tree Problem
You are given an undirected graph with vertices connected by weighted edges. Your task is to find the sum of the weights for the Minimum Spanning Tree (MST) of the graph using Kruskal's algorithm.
**Problem**:
Write a function `mst_kruskal` that calculates the total weight of the Min... | from typing import List, Tuple
def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] ... | from solution import mst_kruskal
def test_mst_kruskal_basic():
vertices = 4
edges = [
(0, 1, 10),
(0, 2, 6),
(0, 3, 5),
(1, 3, 15),
(2, 3, 4)
]
assert mst_kruskal(vertices, edges) == 19
def test_mst_kruskal_disjoint_set():
vertices = 4
edges = [
... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
0,
1,
1,
0,
0,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\nclass UnionFind:\n def __init__(self, size):\n self.parent = list(range(size))\n self.rank = [0] * size\n \... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000041205",
"row_id": 41205,
"seed_ids": "[4534]"
} | 0.779598 | Algorithm_41205 | I | [
"find",
"union",
"mst_kruskal"
] | 3 | [
[
"mst_kruskal",
"find"
],
[
"mst_kruskal",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | eba5e342a4ae46f7fbf4992f0a3eea59ebb0d740 | 6860cae5260d06cb80882b7a0ba1cc930b348022 | |||
v1.0 | instruct | Algorithm | Algorithm_41275_I | Implement a file version management system that tracks changes to a text document. This system will involve versioning files, retrieving file contents for a specific version, and comparing different versions of the file to highlight differences.
### Objectives:
1. Write a function `init_system() -> None` to initialize... | from typing import List
import difflib
# Initialize a global variable to hold versions
versions = []
def init_system() -> None:
"""
Initializes the file version management system.
"""
global versions
versions = []
def add_version(content: str) -> int:
"""
Adds a new version of the file's ... | import pytest
from solution import init_system, add_version, get_version, compare_versions
def test_init_system():
init_system()
with pytest.raises(ValueError):
get_version(0)
def test_add_version():
init_system()
version0 = add_version("First version content.")
assert version0 == 0
ve... | [
{
"docstring": "Initializes the file version management system.",
"function_declaration": "def init_system():",
"function_name": "init_system",
"parameter_list": "()"
},
{
"docstring": "Adds a new version of the file's content.\n\nParameters:\ncontent (str): The content of the file to be add... | [
0,
0,
1,
1,
1,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "version_storage = {}\ncurrent_version = -1\n\ndef init_system() -> None:\n \"\"\"\n Initializes the version management system.\n \"\"\"\n global vers... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000041275",
"row_id": 41275,
"seed_ids": "[1830]"
} | 0.542319 | Algorithm_41275 | I | [
"init_system",
"add_version",
"get_version",
"compare_versions"
] | 4 | [
[
"compare_versions",
"get_version"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 33e5e98d2fdfa1ab8b14b1e21d30dc474c791a47 | a35c38f43766d946fe4531e9307741d6cc964e23 | |||
v1.0 | instruct | Algorithm | Algorithm_41294_I | ### Coding Assessment Question: Parallel Data Processing with MapReduce
#### Context:
You are given a large dataset stored as a list of strings. Each string represents a line in a document containing multiple words. Your task is to implement a function that uses the MapReduce programming model to count the occurrences... | import re
from collections import defaultdict
from functools import reduce
def map_function(document):
"""
The map function takes a document and returns a list of (word, 1) tuples.
"""
words = re.findall(r'\b\w+\b', document.lower())
return [(word, 1) for word in words]
def reduce_function(word_co... | from solution import map_reduce_word_count
def test_map_reduce_word_count_single_line():
documents = ["The quick brown fox"]
result = map_reduce_word_count(documents)
expected = {'the': 1, 'quick': 1, 'brown': 1, 'fox': 1}
assert result == expected
def test_map_reduce_word_count_multiple_lines():
... | [
{
"docstring": "The map function takes a document and returns a list of (word, 1) tuples.",
"function_declaration": "def map_function(document):",
"function_name": "map_function",
"parameter_list": "(document)"
},
{
"docstring": "The reduce function takes a list of (word, occurrences) tuples... | [
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": "import collections\nimport re\n\ndef mapper(document):\n \"\"\"\n Mapper function that takes a document (string) and maps it to a list of (word, 1) tuples.... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000041294",
"row_id": 41294,
"seed_ids": "[4966]"
} | 0.582725 | Algorithm_41294 | I | [
"map_function",
"reduce_function",
"map_reduce_word_count"
] | 3 | [
[
"map_reduce_word_count",
"map_function"
],
[
"map_reduce_word_count",
"reduce_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1389700809779b96c7fedab9786a1eed9e3654b9 | 8915fb129f479fbe21e688644c77e2f02f7a534f | |||
v1.0 | instruct | Algorithm | Algorithm_41324_I | ### Binary Search Tree Balancing
**Scenario**:
You are given a Binary Search Tree (BST) which might be unbalanced. The task is to implement a function to balance the BST to ensure runtime efficiencies for operations like search, insertion, and deletion. You will create a function that takes an unbalanced BST and retur... | class TreeNode:
def __init__(self, value: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None):
self.value = value
self.left = left
self.right = right
def inorder_traversal(root):
"""
Returns the inorder traversal of the BST as a list.
"""
return inorder_traversal(roo... | from solution import TreeNode, balance_bst, inorder_traversal
def tree_equals(t1, t2):
if not t1 and not t2:
return True
if t1 and t2 and t1.value == t2.value:
return tree_equals(t1.left, t2.left) and tree_equals(t1.right, t2.right)
return False
def test_empty_tree():
assert balance_bs... | [] | [
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": "class TreeNode:\n def __init__(self, value: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None):\n self.value = value\n self.left = left... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041324",
"row_id": 41324,
"seed_ids": "[485]"
} | 0.745859 | Algorithm_41324 | I | [
"inorder_traversal",
"sorted_array_to_bst",
"balance_bst"
] | 3 | [
[
"balance_bst",
"inorder_traversal"
],
[
"balance_bst",
"sorted_array_to_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8a6f26785080f79e708cdfa1dae44930a0798e36 | 434e9d8609fb95ed8bef0bdd95e996f3bec4c9f1 | |||
v1.0 | instruct | Algorithm | Algorithm_41344_I | ### Task
You need to implement the `run_kmeans_clustering` function to perform the k-means clustering algorithm on a set of 2D points. Given a number of clusters `k` and a list of points, your function should iteratively refine the clusters by updating the cluster centroids until convergence is reached. You will also ... | import random
import math
def euclidean_distance(p1, p2):
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def run_kmeans_clustering(points, k, tolerance=0.0001, max_iterations=100):
# Randomly initialize the cluster centroids
centroids = random.sample(points, k)
prev_centroids = centroid... | def test_euclidean_distance():
p1 = (0, 0)
p2 = (3, 4)
assert euclidean_distance(p1, p2) == 5
def test_run_kmeans_clustering():
points = [(1.5, 2.0), (3.0, 4.0), (5.0, 7.0), (8.0, 8.0), (3.5, 5.0), (4.5, 5.0), (3.5, 4.5)]
k = 2
tolerance = 0.0001
max_iterations = 100
# Check if the fun... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def run_kmeans_clustering(points, k, tolerance=0.0001, max_iterations=100):",
"function... | [
0,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\n\ndef run_kmeans_clustering(points, k, tolerance=0.0001, max_iterations=100):\n \"\"\"\n Perform k-means clustering on t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000041344",
"row_id": 41344,
"seed_ids": "[492]"
} | 0.759719 | Algorithm_41344 | I | [
"euclidean_distance",
"run_kmeans_clustering",
"test_kmeans_clustering"
] | 3 | [
[
"run_kmeans_clustering",
"euclidean_distance"
],
[
"test_kmeans_clustering",
"run_kmeans_clustering"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 6a7bf38a862e473353b3d1664f8615e296b1dc48 | dba8a9c60a31b071be993049a6e607a2a801d228 | |||
v1.0 | instruct | Algorithm | Algorithm_41395_I | ### Radix Sort Implementation
You are required to implement the `radix_sort` function to sort a list of non-negative integers using the radix sort algorithm. This sorting algorithm processes the integers digit by digit from the least significant to the most significant digit.
#### Function Signature
```python
def rad... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
w... | from solution import radix_sort
def test_radix_sort_normal_case():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_radix_so... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
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": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041395",
"row_id": 41395,
"seed_ids": "[3315]"
} | 0.670657 | Algorithm_41395 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 62430e02a0dcf2c3acf237aede500915c849fc4a | de6856cadf1595b99921e8919a371613e984b9cc | |||
v1.0 | instruct | Algorithm | Algorithm_41427_I | ### Question: Finding Steiner Tree Approximation in an Undirected Graph
The Steiner tree problem for a given graph and a set of required vertices can be seen as finding a minimal subgraph that spans all the given required vertices. In this task, you are required to implement an approximation algorithm for the Steiner ... | import heapq
from collections import defaultdict, deque
def dijkstra(graph, start):
"""Helper function to perform Dijkstra's algorithm to find shortest paths."""
distances = {node: float('infinity') for node in graph}
distances[start] = 0
priority_queue = [(0, start)]
predecessors = {node: None for... | from solution import approximate_steiner_tree
def test_approximate_steiner_tree_single_vertex():
graph = {
"1": ["2", "3"],
"2": ["1", "3", "4", "5"],
"3": ["1", "2", "5"],
"4": ["2"],
"5": ["2", "3"]
}
required_vertices = {"1"}
assert approximate_steiner_tree(gr... | [
{
"docstring": "Helper function to perform Dijkstra's algorithm to find shortest paths.",
"function_declaration": "def dijkstra(graph, start):",
"function_name": "dijkstra",
"parameter_list": "(graph, start)"
},
{
"docstring": "Helper function to reconstruct the shortest path from start to e... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(graph, start):\n \"\"\"\n Dijkstra's Algorithm to find shortest paths from start node to all other nodes.\n \"\"\"\n dis... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000041427",
"row_id": 41427,
"seed_ids": "[4649]"
} | 0.52441 | Algorithm_41427 | I | [
"dijkstra",
"get_shortest_path",
"approximate_steiner_tree"
] | 3 | [
[
"approximate_steiner_tree",
"dijkstra"
],
[
"approximate_steiner_tree",
"get_shortest_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 43d2b4c330108838e2f64d657660e23916e32875 | 86d1f96e7ad66290abdfa96b055b4b5e2208fa40 | |||
v1.0 | instruct | Algorithm | Algorithm_41478_I | ### Problem Description
You are working with a data processing system that processes numerical sensor data coming from various sensors in real time. Each sensor sends an array of measurements, and your task is to implement some basic statistical analysis on the sensor data.
#### Objective
Write two functions `mean` ... | from typing import List
import math
def mean(measurements: List[float]) -> float:
"""
Calculate the mean (average) of a list of measurements.
"""
if not measurements:
return 0.0
return sum(measurements) / len(measurements)
def standard_deviation(measurements: List[float]) -> float:
"""... | import pytest
from solution import mean, standard_deviation
def test_mean_with_positive_numbers():
assert mean([1, 2, 3, 4, 5]) == 3.0
def test_mean_with_empty_list():
assert mean([]) == 0.0
def test_mean_with_negative_numbers():
assert mean([-1, -2, -3, -4, -5]) == -3.0
def test_mean_with_mixed_nu... | [
{
"docstring": "Calculate the mean (average) of a list of measurements.",
"function_declaration": "def mean(measurements):",
"function_name": "mean",
"parameter_list": "(measurements)"
},
{
"docstring": "Calculate the standard deviation of a list of measurements.",
"function_declaration"... | [
0,
0,
1,
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": "from typing import List\nimport math\n\ndef mean(measurements: List[float]) -> float:\n \"\"\"\n Calculate the mean (average) of a list of measurements.\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041478",
"row_id": 41478,
"seed_ids": "[779]"
} | 0.656578 | Algorithm_41478 | I | [
"mean",
"standard_deviation"
] | 2 | [
[
"standard_deviation",
"mean"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b51ff44345f285a817f7e9cc6b9456be86e1a8ef | eec1ddfc782115c47008fce78929f59a96030ba6 | |||
v1.0 | instruct | Algorithm | Algorithm_41482_I | ### Trie - Auto-Complete System
#### Background:
A Trie (prefix tree) is a data structure used to efficiently store and retrieve keys in a dataset of strings. This problem extends the Trie data structure to implement an auto-complete feature useful for applications like search engines.
#### Task:
1. **Construct the T... | class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def build_trie(words):
root = TrieNode()
for word in words:
current = root
for letter in word:
if letter not in current.children:
current.children[letter] = TrieNod... | from solution import build_trie, autocomplete
def test_build_trie_and_autocomplete():
words = [
"apple",
"app",
"application",
"bat",
"ball",
"batman",
"ape"
]
trie_root = build_trie(words)
assert set(autocomplete("app", trie_root)) == {"appl... | [] | [
0,
1,
0,
0,
1,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\ndef build_trie(words):\n root = TrieNode()\n f... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041482",
"row_id": 41482,
"seed_ids": "[1333]"
} | 0.562734 | Algorithm_41482 | I | [
"build_trie",
"autocomplete",
"search_helper"
] | 3 | [
[
"autocomplete",
"search_helper"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 45f83b759ee73b37972742c9941900c72c27c4d4 | acbc45af49920cd58f8b76147a219fb0d8fade5f | |||
v1.0 | instruct | Algorithm | Algorithm_41484_I | ### Balanced Binary Search Tree Construction and Searching
You are tasked with creating a balanced Binary Search Tree (BST) structure for efficient insertion, deletion, and search operations. Implement the core functionalities from scratch.
Your task is to:
1. **Construct the BST** from a given set of nodes ensuring ... | class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def get_height(node):
if not node:
return 0
return node.height
def update_height(node):
if node:
node.height = 1 + max(get_height(node.left), get_h... | import pytest
def test_insert_and_search():
root = None
for value in [10, 20, 5, 6, 15, 30, 25]:
root = insert_node(root, value)
assert search_node(root, 10) == True
assert search_node(root, 20) == True
assert search_node(root, 5) == True
assert search_node(root, 6) == True
ass... | [] | [
1,
0,
1,
1,
1,
1,
0,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n\ndef get_he... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000041484",
"row_id": 41484,
"seed_ids": "[1745]"
} | 0.596136 | Algorithm_41484 | I | [
"get_height",
"update_height",
"get_balance",
"rotate_right",
"rotate_left",
"balance_tree",
"insert_node",
"search_node",
"get_min_value_node",
"delete_node"
] | 10 | [
[
"balance_tree",
"get_balance"
],
[
"balance_tree",
"rotate_left"
],
[
"balance_tree",
"rotate_right"
],
[
"balance_tree",
"update_height"
],
[
"delete_node",
"balance_tree"
],
[
"delete_node",
"get_min_value_node"
],
[
"get_balance",
... | 11 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | d36116ae6a26f744f33c615a03349fcaebd0293a | 0b416e3a6e8aa6b53c992005a82b5c4e1a4b7266 | |||
v1.0 | instruct | Algorithm | Algorithm_41575_I | ### Scenario
You are developing a library management system that manages book records. This system needs to categorize books according to their publication years and titles.
### Problem Statement
Write a function `classify_books(books: List[Dict[str, Union[str, int]]]) -> Dict[str, Union[List[str], Dict[str, List[st... | from typing import List, Dict, Union
def is_vowel(char: str) -> bool:
return char.lower() in 'aeiou'
def classify_books(books: List[Dict[str, Union[str, int]]]) -> Dict[str, Union[List[str], Dict[str, List[str]]]]:
categorized_books = {
"before_2000": [],
"from_2000": [],
"vowel_titles... | def test_classify_books():
books = [
{"title": "A Tale of Two Cities", "year": 1859},
{"title": "Effective Python", "year": 2015},
{"title": "To Kill a Mockingbird", "year": 1960},
{"title": "The Great Gatsby", "year": 1925},
{"title": "1984", "year": 1949},
{"title":... | [
{
"docstring": null,
"function_declaration": "def is_vowel(char):",
"function_name": "is_vowel",
"parameter_list": "(char)"
},
{
"docstring": null,
"function_declaration": "def classify_books(books):",
"function_name": "classify_books",
"parameter_list": "(books)"
}
] | [
1,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Union\n\ndef is_vowel(char: str) -> bool:\n return char.lower() in 'aeiou'\n\ndef classify_books(books: List[Dict[str, Union[st... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000041575",
"row_id": 41575,
"seed_ids": "[4377]"
} | 0.573863 | Algorithm_41575 | I | [
"is_vowel",
"classify_books"
] | 2 | [
[
"classify_books",
"is_vowel"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 84a24cfa4575c88a417ddedbbc295fccdc2de101 | 2148be6a24bf79f7b76f228b25aa6ac4978145a8 | |||
v1.0 | instruct | Algorithm | Algorithm_41619_I | ### Partitioning an Array to Minimize Maximum Subarray Sum
#### Problem Description:
You are tasked with partitioning an array into `k` or fewer non-empty continuous subarrays such that the maximum sum among these subarrays is minimized. Write two functions: one to implement this partitioning and another to help visu... | def partition_array(arr, k):
"""
Partitions an array into `k` or fewer non-empty continuous subarrays to minimize the maximum subarray sum.
Args:
- arr (List[int]): A list of integers representing the array to be partitioned.
- k (int): The maximum number of partitions allowed.
Returns... | import pytest
from solution import partition_array, visualize_partitions
def test_partition_array_example():
arr = [7, 2, 5, 10, 8]
k = 2
assert partition_array(arr, k) == 18
def test_partition_array_single_element():
arr = [10]
k = 1
assert partition_array(arr, k) == 10
def test_partition_ar... | [
{
"docstring": "Partitions an array into `k` or fewer non-empty continuous subarrays to minimize the maximum subarray sum.\n\nArgs:\n- arr (List[int]): A list of integers representing the array to be partitioned.\n- k (int): The maximum number of partitions allowed.\n\nReturns:\n- int: The minimized maximum sum... | [
0,
1,
0,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef partition_array(arr: List[int], k: int) -> int:\n def can_partition(mid: int) -> bool:\n current_sum = 0\n count ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000041619",
"row_id": 41619,
"seed_ids": "[460]"
} | 0.709592 | Algorithm_41619 | I | [
"partition_array",
"visualize_partitions"
] | 2 | [
[
"visualize_partitions",
"partition_array"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 29d736fa6c96d79a5f05d80a5132bad567fde4ee | a3d0a1d40d264daa2b35af3428c016977df41991 | |||
v1.0 | instruct | Algorithm | Algorithm_41631_I | ### Your Task
You need to implement a function that calculates the distance of a point from the origin in a 2D plane, and a function that sorts a list of such points based on their distance from the origin.
### Detailed Requirements
1. **Calculate Distance**:
* Implement the `distance_from_origin` function that ... | import math
from typing import List, Tuple
def distance_from_origin(x: int, y: int) -> float:
"""
Computes the Euclidean distance of a point (x, y) from the origin (0, 0).
:param x: int - The x-coordinate of the point
:param y: int - The y-coordinate of the point
:return: float - The distance ... | from solution import distance_from_origin, sort_points
# Unit tests for distance_from_origin
def test_distance_from_origin_positive_coords():
assert distance_from_origin(3, 4) == 5.0
def test_distance_from_origin_negative_coords():
assert distance_from_origin(-3, -4) == 5.0
def test_distance_from_origin_mixe... | [
{
"docstring": "Computes the Euclidean distance of a point (x, y) from the origin (0, 0).\n\n:param x: int - The x-coordinate of the point\n:param y: int - The y-coordinate of the point\n:return: float - The distance from the origin",
"function_declaration": "def distance_from_origin(x, y):",
"function_... | [
1,
1,
0,
1,
1,
0,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List, Tuple\n\ndef distance_from_origin(x: int, y: int) -> float:\n \"\"\"\n Computes the Euclidean distance of a point (x,... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041631",
"row_id": 41631,
"seed_ids": "[443]"
} | 0.696691 | Algorithm_41631 | I | [
"distance_from_origin",
"sort_points"
] | 2 | [
[
"sort_points",
"distance_from_origin"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8606dcc9bf6d4c384d1cfd5a99e2395282250c32 | c3da97a0cd43d56dd29e2dd9eedbbf044adf1a59 | |||
v1.0 | instruct | Algorithm | Algorithm_41663_I | ### Context:
Sorting algorithms are fundamental to computer science, and an understanding of different approaches to sorting is crucial. One of the popular sorting techniques is the merge sort, which utilizes a divide-and-conquer strategy.
### Problem Statement:
Implement the merge sort algorithm to sort a list of int... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Performs merge sort on a list of integers and returns a new sorted list.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return me... | from solution import merge_sort
def test_merge_sort_basic():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_duplicates():
assert merge_sort([4, 2, 7, 3, 2, 7, 10]) == [2, 2, 3, 4, 7, 7, 10]
def test_merge_sort_empty():
assert merge_sort([]) == []
def... | [
{
"docstring": "Performs merge sort on a list of integers and returns a new sorted list.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"function_declaratio... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge(left: List[int], right: List[int]) -> List[int]:\n result = []\n i = j = 0\n while i < len(left) and j < len(right)... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041663",
"row_id": 41663,
"seed_ids": "[3300]"
} | 0.632513 | Algorithm_41663 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3f17d27bba0a0e7c3cad7db5757596ab52d8c315 | 00b877407fd433a87f22f5a6182d3a311c4d17d8 | |||
v1.0 | instruct | Algorithm | Algorithm_41833_I | ### Coding Assessment Question
#### Problem Statement
You are given an array of integers and you need to form a list of all distinct subsets of this array. Your task is to implement a function that returns these subsets in lexicographical order.
#### Function Signature
```python
def find_subsets(arr):
"""
G... | def find_subsets(arr):
"""
Generates all distinct subsets of the given array in lexicographical order.
Parameters:
arr (List[int]): An array of integers.
Returns:
List[List[int]]: A list of lists where each list represents a subset of the input array.
"""
arr.sort()
res = []
df... | from solution import find_subsets
def test_find_subsets_example():
assert find_subsets([1, 2, 2]) == [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
def test_find_subsets_duplicates():
assert find_subsets([1, 1]) == [[], [1], [1, 1]]
def test_find_subsets_empty():
assert find_subsets([]) == [[]]
def test_find... | [
{
"docstring": "Generates all distinct subsets of the given array in lexicographical order.\n\nParameters:\narr (List[int]): An array of integers.\n\nReturns:\nList[List[int]]: A list of lists where each list represents a subset of the input array.",
"function_declaration": "def find_subsets(arr):",
"fu... | [
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 find_subsets(arr):\n \"\"\"\n Generates all distinct subsets of the given array in lexicographical order.\n\n Parameters:\n arr (List[int]): An a... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041833",
"row_id": 41833,
"seed_ids": "[3993]"
} | 0.558733 | Algorithm_41833 | I | [
"find_subsets",
"dfs"
] | 2 | [
[
"find_subsets",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 18a80e140ca5fe3a1daa9af8ae792496a9b161cc | 6bbcaff36af7a32c1e65ccd551c6b74f96df04e9 | |||
v1.0 | instruct | Algorithm | Algorithm_41835_I | ### Binary Search Tree (BST) Deletion
#### Objective:
Implement the delete operation in a Binary Search Tree (BST) and ensure the tree retains its properties after deletion.
### Task:
Write a function `delete_node` that deletes a node with a given value from a BST. Ensure that the tree remains a valid BST after the d... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node(root, key):
"""
Deletes the node with the given key from the BST and returns the new root.
"""
if not root: # base case
return root
... | import pytest
from solution import TreeNode, delete_node
def create_tree_from_list(values):
"""
Helper function to create a BST from a list of values.
Assumes the list is a level-order traversal of the BST.
"""
if not values:
return None
root = TreeNode(values[0])
queue = [root... | [] | [
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": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef delet... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000041835",
"row_id": 41835,
"seed_ids": "[4234]"
} | 0.621056 | Algorithm_41835 | I | [
"delete_node",
"get_min_node"
] | 2 | [
[
"delete_node",
"get_min_node"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 985be8976745408f5b81eb1e5cf06f6d35a4c797 | 60a1be0bf0dc42cd9ac3f876c8e7756113376b98 | |||
v1.0 | instruct | Algorithm | Algorithm_41880_I | ### Prime Number Partition Function
Implement a function that partitions a given list of integers into multiple sublists, such that each sublist only contains prime numbers, and the sum of each sublist is as close to an even split of the total sum as possible. Follow these steps:
1. **Prime Identification**: Create a... | from math import sqrt
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def partition_primes(nu... | from solution import is_prime, partition_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(29) == True
assert is_prime(35) == False
assert is_prime(1) == False
def test_partition_primes()... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def partition_primes(numbers, num_partitions):",
"function_name": "partition_primes",
"parameter_list": "(numbers... | [
0,
1,
1,
1,
0,
0,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import sqrt\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n r... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000041880",
"row_id": 41880,
"seed_ids": "[5085]"
} | 0.626033 | Algorithm_41880 | I | [
"is_prime",
"partition_primes"
] | 2 | [
[
"partition_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6687d285183fa60b50abade1d53f11d7b2082826 | 383a632fae2f420c4500ddd3a173d0bbdd51aca5 | |||
v1.0 | instruct | Algorithm | Algorithm_41892_I | ### Problem Statement
Given a list of integers, you need to implement a function to find the k-th smallest element in the list. The function should be able to handle large lists efficiently. This is to ensure your understanding of efficient selection algorithms like the Quickselect algorithm.
### Function to Implemen... | from typing import List
def quickselect(arr: List[int], left: int, right: int, k: int) -> int:
"""
Quickselect helper function to find k-th smallest element.
"""
if left == right:
return arr[left]
pivot_index = partition(arr, left, right)
if k == pivot_index:
return ar... | from solution import kth_smallest
def test_kth_smallest():
assert kth_smallest([3, 2, 1, 5, 4], 3) == 3
assert kth_smallest([1, 1, 1, 1], 2) == 1
assert kth_smallest([5, 4, 3, 2, 1], 1) == 1
assert kth_smallest([7, 10, 4, 3, 20, 15], 4) == 10
assert kth_smallest([-1, -2, -3, 0], 1) == -3
assert... | [
{
"docstring": "Quickselect helper function to find k-th smallest element.",
"function_declaration": "def quickselect(arr, left, right, k):",
"function_name": "quickselect",
"parameter_list": "(arr, left, right, k)"
},
{
"docstring": "Partition the array and return the pivot index.",
"fu... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef kth_smallest(arr: List[int], k: int) -> int:\n \"\"\"\n Returns the k-th smallest element in the array `arr`.\n Utilizes ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041892",
"row_id": 41892,
"seed_ids": "[4876]"
} | 0.637816 | Algorithm_41892 | I | [
"quickselect",
"partition",
"kth_smallest"
] | 3 | [
[
"kth_smallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 157323c2cb3b12ce36ae82ce17bad4c55c7499f8 | d9ebd2bb0842bfd56f7fe688932d8a2846738153 | |||
v1.0 | instruct | Algorithm | Algorithm_41907_I | ### Problem Statement
You are required to implement a function to generate a list of prime numbers up to a given integer `n`. Additionally, implement a function that identifies the two prime numbers whose sum equals a given even integer `m`. If multiple pairs are possible, return any one of them. If no such pair exists... | from typing import List, Tuple, Union
def generate_primes(n: int) -> List[int]:
"""
Generates a list of all prime numbers up to and including n.
Args:
n (int): The upper limit to generate prime numbers.
Returns:
List[int]: List of prime numbers.
"""
if n < 2:
return []... | def test_generate_primes():
assert generate_primes(1) == []
assert generate_primes(2) == [2]
assert generate_primes(10) == [2, 3, 5, 7]
assert generate_primes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_find_prime_sum_pair():
assert find_prime_sum_pair(4) == (2, 2)
result = find_prime_... | [
{
"docstring": "Generates a list of all prime numbers up to and including n.\n\nArgs:\nn (int): The upper limit to generate prime numbers.\n\nReturns:\nList[int]: List of prime numbers.",
"function_declaration": "def generate_primes(n):",
"function_name": "generate_primes",
"parameter_list": "(n)"
... | [
1,
1,
0,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple, Union\n\ndef generate_primes(n: int) -> List[int]:\n \"\"\"\n Generates a list of all prime numbers up to and including n.\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000041907",
"row_id": 41907,
"seed_ids": "[4103]"
} | 0.730965 | Algorithm_41907 | I | [
"generate_primes",
"find_prime_sum_pair"
] | 2 | [
[
"find_prime_sum_pair",
"generate_primes"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 76fa7681555b0887a994f63d0397e3882c7c5b93 | aaa0d50a52f0c5c12e4fe371ffc60aacae5f2346 | |||
v1.0 | instruct | Algorithm | Algorithm_41970_I | Sorting Algorithms - Merge Sort with Inversions Count
You are tasked to write a function that performs the merge sort algorithm on a list of integers and simultaneously counts the number of inversions required to sort the list. An inversion is a situation where a larger number precedes a smaller one in the list.
**Ta... | def merge_sort_and_count(arr):
"""
Sorts the array using merge sort algorithm and counts inversions.
Args:
arr (list[int]): The list of integers to be sorted and for which to count inversions.
Returns:
tuple: A tuple containing the sorted list and the total number of inversions.
"""
if... | from solution import merge_sort_and_count
def test_already_sorted():
arr = [1, 2, 3, 4, 5]
sorted_arr, inversions = merge_sort_and_count(arr)
assert sorted_arr == [1, 2, 3, 4, 5]
assert inversions == 0
def test_reverse_sorted():
arr = [5, 4, 3, 2, 1]
sorted_arr, inversions = merge_sort_and_cou... | [
{
"docstring": "Sorts the array using merge sort algorithm and counts inversions.\n\nArgs:\narr (list[int]): The list of integers to be sorted and for which to count inversions.\n\nReturns:\ntuple: A tuple containing the sorted list and the total number of inversions.",
"function_declaration": "def merge_so... | [
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 merge_sort_and_count(arr):\n \"\"\"\n Perform a merge sort and count the number of inversions required to sort the list.\n\n Args:\n arr (list[in... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000041970",
"row_id": 41970,
"seed_ids": "[3991]"
} | 0.656832 | Algorithm_41970 | I | [
"merge_sort_and_count",
"merge_and_count"
] | 2 | [
[
"merge_sort_and_count",
"merge_and_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ad40ba37d9f427a66354966a3e1aa385f7874bb | fea35a553ad73e3e919e91d7281282bb15cb8a7e | |||
v1.0 | instruct | Algorithm | Algorithm_42028_I | ### Coding Question
#### Context
Sorting algorithms are fundamental in computer science and have numerous applications. One commonly used sorting algorithm is Merge Sort, which employs a divide-and-conquer strategy to sort an array efficiently. This algorithm recursively divides the array into two halves, sorts each h... | def merge_sort(arr: list) -> list:
"""
Sort a list of integers using the merge sort algorithm.
"""
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: list, right: list) -... | from solution import merge_sort, merge
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_positive_numbers():
assert merge_sort([3, 5, 2, 9, 1]) == [1, 2, 3, 5, 9]
def test_merge_sort_negative_numbers():
as... | [
{
"docstring": "Sort a list of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge two sorted lists into a single sorted list.",
"function_declaration": "def merge(lef... | [
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: list) -> list:\n if len(arr) <= 1:\n return arr # Base case: list is already sorted if it has 1 or 0 elements\n\n mid = len(arr... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042028",
"row_id": 42028,
"seed_ids": "[620]"
} | 0.653658 | Algorithm_42028 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e65f6bf47bdc895bc24a6b5fe89ba6ac29a39eaa | eae6bda5eaa3d863670cef6667e6dfadb3ac902a | |||
v1.0 | instruct | Algorithm | Algorithm_42040_I | ### Problem Statement
You need to implement a system that calculates a unique series of numbers known as "Happy Primes." A number is considered a Happy Prime if it is both a happy number and a prime number.
A number is considered "happy" if repeatedly summing the squares of its digits eventually leads to the number 1... | import math
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, False otherwise.
"""
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:
... | def test_is_prime():
assert is_prime(13) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(10) == False
assert is_prime(23) == True
def test_is_happy():
assert is_happy(19... | [
{
"docstring": "Returns True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns True if n is a happy number, False otherwise.",
"function_declaration": "def is_happy(n):",
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"Returns True if n is a prime number, False otherwise.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return Tru... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042040",
"row_id": 42040,
"seed_ids": "[2765]"
} | 0.658663 | Algorithm_42040 | I | [
"is_prime",
"is_happy",
"next_happy_prime"
] | 3 | [
[
"next_happy_prime",
"is_happy"
],
[
"next_happy_prime",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | d7b869a5841a61310d85fdb39744c8ace734f73f | be25cf8dcaf9144b627d5d985c9906f2b1ad43c7 | |||
v1.0 | instruct | Algorithm | Algorithm_42062_I | ### Coding Assessment Question
As part of an automated health monitoring system, you are required to enhance a module that analyzes patient data to detect any health anomalies in real-time. Your task involves refactoring the existing system to ensure it is more efficient and capable of handling larger datasets.
Your ... | import requests
import logging
from typing import List, Dict
# Configure logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger()
# Define thresholds for anomalies
HEART_RATE_THRESHOLDS = (60, 100)
BLOOD_PRESSURE_THRESHOLDS = ((90, 140), (60, 90))
TEMPERATURE_THRESHOLDS = (36, 38)
# API endpoint... | from solution import fetch_patient_data, detect_anomalies, process_patient_data
import pytest
from unittest.mock import patch, Mock
def test_fetch_patient_data_success():
expected_data = [{"id": 1, "heart_rate": 72, "blood_pressure": {"systolic": 120, "diastolic": 80}, "temperature": 37}]
with patch('solution.... | [
{
"docstring": "Fetch patient data from the API with a specified limit for retries.\nReturns the patient data as a list of dictionaries.",
"function_declaration": "def fetch_patient_data(retry_limit):",
"function_name": "fetch_patient_data",
"parameter_list": "(retry_limit)"
},
{
"docstring"... | [
1,
1,
0,
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": "import requests\nimport logging\nimport pandas as pd\n\nlogging.basicConfig(level=logging.INFO)\n\ndef fetch_patient_data(api_url, retry_limit=3):\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042062",
"row_id": 42062,
"seed_ids": "[2421]"
} | 0.468719 | Algorithm_42062 | I | [
"fetch_patient_data",
"detect_anomalies",
"process_patient_data"
] | 3 | [
[
"process_patient_data",
"detect_anomalies"
],
[
"process_patient_data",
"fetch_patient_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 1d3c82a37b0967bccde375a2e9b228ee8b188ff1 | ebfd77ee3ac71713d87578d552f26c7a24649de9 | |||
v1.0 | instruct | Algorithm | Algorithm_42071_I | ### Summation of Prime Numbers in a Range
Given two integers `a` and `b` with `0 ≤ a ≤ b ≤ 10000`, write a function called `sum_primes(a: int, b: int) -> int` that returns the sum of all prime numbers in the inclusive range from `a` to `b`.
#### Core Functionality
- Determine all prime numbers between `a` and `b`.
- ... | def is_prime(num):
if num < 2:
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
def sum_primes(a, b):
return sum(num for num in range(a, b + 1) i... | from solution import sum_primes
def test_sum_primes_basic():
assert sum_primes(10, 20) == 60
def test_sum_primes_single():
assert sum_primes(2, 2) == 2
def test_sum_primes_no_primes():
assert sum_primes(14, 16) == 0
assert sum_primes(20, 20) == 0
def test_sum_primes_range_with_no_primes():
asser... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def sum_primes(a, b):",
"function_name": "sum_primes",
"parameter_list": "(a, b)"
}
] | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num < 2:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n p = 3\n whil... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000042071",
"row_id": 42071,
"seed_ids": "[1267]"
} | 0.658288 | Algorithm_42071 | I | [
"is_prime",
"sum_primes"
] | 2 | [
[
"sum_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6062d2e9133d696e14b2b0400c542fb106c36914 | 99b46cba129bbf10c23760d2c76fda4177daf869 | |||
v1.0 | instruct | Algorithm | Algorithm_42079_I | ### Coding Assessment Question
A critical aspect of data processing applications is to efficiently identify and extract prime numbers from a list of integers. Your task is to implement a function that accomplishes this efficiently, considering the constraints provided.
#### Function Definition
```python
def find_pri... | from typing import List
def is_prime(n: int) -> bool:
"""
Check if a given number n is a prime number.
Args:
n : int : the integer to be checked
Returns:
bool : True if n is a prime number, False otherwise
"""
if n <= 1:
return False
if n <= 3:
return True
if n... | from solution import find_prime_numbers, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(-1) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(29) ... | [
{
"docstring": "Check if a given number n is a prime number.\n\nArgs:\nn : int : the integer to be checked\n\nReturns:\nbool : True if n is a prime number, False otherwise",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Gi... | [
0,
1,
1,
1,
0,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n ret... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000042079",
"row_id": 42079,
"seed_ids": "[3219]"
} | 0.739596 | Algorithm_42079 | I | [
"is_prime",
"find_prime_numbers"
] | 2 | [
[
"find_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bcd26d29087d75f799605724af5d2b58b07d0194 | d28ee322b625759ab597e7c73514d90b82a9f4f8 | |||
v1.0 | instruct | Algorithm | Algorithm_42133_I | ### Question: Detecting Circular Primes
A **circular prime** is a prime number that remains prime under all rotations of its digits. For example, 197 is a circular prime because all rotations of its digits (197, 971, and 719) are themselves prime numbers.
#### Task
Write a function `find_circular_primes(limit)` that... | from typing import List
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:
retur... | from solution import find_circular_primes
def test_find_circular_primes_small_limit():
assert find_circular_primes(10) == [2, 3, 5, 7]
def test_find_circular_primes_medium_limit():
assert find_circular_primes(100) == [2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97]
def test_find_circular_primes_large_limit()... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Get all rotations of the digits of a number.",
"function_declaration": "def get_rotations(n):",
"function_name": "get_rota... | [
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": "from typing import List\nimport math\n\ndef is_prime(n: int) -> bool:\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n <= 1:\n re... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042133",
"row_id": 42133,
"seed_ids": "[3989]"
} | 0.611629 | Algorithm_42133 | I | [
"is_prime",
"get_rotations",
"find_circular_primes"
] | 3 | [
[
"find_circular_primes",
"get_rotations"
],
[
"find_circular_primes",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 23fc88a83d882eda348eeb3e4c5b4c322e94430f | 0320df2c5d0245539cc23f86e00343a1341a8a42 | |||
v1.0 | instruct | Algorithm | Algorithm_42210_I | ### Sum of Digits in Base Conversion Assessment
Your task is to implement functions to convert an integer to any given base (between 2 and 36) and calculate the sum of digits in the converted base.
#### Part 1: Base Conversion
Implement the function `convert_to_base(n: int, base: int) -> str` that takes an integer `... | def convert_to_base(n: int, base: int) -> str:
if n == 0:
return "0"
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ""
while n > 0:
result = digits[n % base] + result
n //= base
return result
def sum_of_digits_in_base(n: int, base: int) -> int:
c... | from solution import convert_to_base, sum_of_digits_in_base
def test_convert_to_base():
assert convert_to_base(255, 16) == 'FF'
assert convert_to_base(255, 2) == '11111111'
assert convert_to_base(0, 10) == '0'
assert convert_to_base(10, 10) == '10'
assert convert_to_base(10, 2) == '1010'
assert... | [
{
"docstring": null,
"function_declaration": "def convert_to_base(n, base):",
"function_name": "convert_to_base",
"parameter_list": "(n, base)"
},
{
"docstring": null,
"function_declaration": "def sum_of_digits_in_base(n, base):",
"function_name": "sum_of_digits_in_base",
"parame... | [
0,
1,
0,
0,
0,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def convert_to_base(n: int, base: int) -> str:\n \"\"\"\n Convert a given integer n to a string representation in the given base.\n \"\"\"\n if n == ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000042210",
"row_id": 42210,
"seed_ids": "[4941]"
} | 0.651306 | Algorithm_42210 | I | [
"convert_to_base",
"sum_of_digits_in_base"
] | 2 | [
[
"sum_of_digits_in_base",
"convert_to_base"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d8ac8c74ba8e0f5be93c62840b37e48eed1b02ac | 9bbb28f3b3133a35289fb12823c163ea9724b7af | |||
v1.0 | instruct | Algorithm | Algorithm_42287_I | ### Scenario
As a software developer, you are working on a project related to data privacy and encryption. One of the tasks involves encoding and decoding messages using a simple substitution cipher where each letter in the alphabet is shifted by a fixed number of positions. The encoding is done by moving each letter ... | def encode_message(message: str, shift: int) -> str:
def shift_char(c, shift):
if c.isalpha():
base = ord('A') if c.isupper() else ord('a')
return chr((ord(c) - base + shift) % 26 + base)
return c
return ''.join(shift_char(c, shift) for c in message)
def decode_message(... | from solution import encode_message, decode_message
def test_encode_message_positive_shift():
assert encode_message("Hello, World!", 5) == "Mjqqt, Btwqi!"
def test_decode_message_positive_shift():
assert decode_message("Mjqqt, Btwqi!", 5) == "Hello, World!"
def test_encode_message_negative_shift():
asser... | [
{
"docstring": null,
"function_declaration": "def encode_message(message, shift):",
"function_name": "encode_message",
"parameter_list": "(message, shift)"
},
{
"docstring": null,
"function_declaration": "def decode_message(encoded_message, shift):",
"function_name": "decode_message"... | [
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": "def encode_message(message: str, shift: int) -> str:\n def shift_char(c, shift):\n if c.isalpha():\n base = ord('A') if c.isupper() else ord... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000042287",
"row_id": 42287,
"seed_ids": "[959]"
} | 0.665315 | Algorithm_42287 | I | [
"encode_message",
"decode_message"
] | 2 | [
[
"decode_message",
"encode_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 311c3026d732cc8a67f795059d0d63e7150ff24f | e570e177ebc3f7d78cea7e79721ac88cbae196c2 | |||
v1.0 | instruct | Algorithm | Algorithm_42321_I | ### Coding Assessment Question
#### Task
Given a list of non-negative integers representing the amount of money of each house, where each house is arranged in a circular manner, determine the maximum amount of money you can rob tonight without alerting the police. If two adjacent houses are robbed, then the police wil... | from typing import List
def rob_linear_houses(nums: List[int]) -> int:
prev = curr = 0
for num in nums:
prev, curr = curr, max(curr, prev + num)
return curr
def rob_circular_houses(nums: List[int]) -> int:
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
... | from solution import rob_circular_houses
def test_empty_list():
assert rob_circular_houses([]) == 0
def test_single_house():
assert rob_circular_houses([5]) == 5
def test_two_houses():
assert rob_circular_houses([2, 3]) == 3
assert rob_circular_houses([3, 2]) == 3
def test_three_houses():
assert... | [
{
"docstring": null,
"function_declaration": "def rob_linear_houses(nums):",
"function_name": "rob_linear_houses",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def rob_circular_houses(nums):",
"function_name": "rob_circular_houses",
"parameter_list"... | [
0,
0,
0,
1,
0,
1,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rob_circular_houses(nums: List[int]) -> int:\n \"\"\"\n Returns the maximum amount of money that can be robbed without alert... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000042321",
"row_id": 42321,
"seed_ids": "[2390]"
} | 0.615604 | Algorithm_42321 | I | [
"rob_linear_houses",
"rob_circular_houses"
] | 2 | [
[
"rob_circular_houses",
"rob_linear_houses"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b5772216a67740ba680d0949c2b4d5e0c5169733 | c3c1524309ed3b642223f43c2c760b52aa895b47 | |||
v1.0 | instruct | Algorithm | Algorithm_42360_I | ### Coding Assessment Question
#### Objective
Write a function that determines the next leap year after a given year. A leap year occurs every 4 years, but years divisible by 100 are not leap years, unless they are also divisible by 400.
#### Background
Leap years help synchronize the calendar year with the solar yea... | def is_leap_year(year: int) -> bool:
"""
Determines if a given year is a leap year.
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return ... | from solution import is_leap_year, next_leap_year
def test_is_leap_year():
assert is_leap_year(2020) == True
assert is_leap_year(2021) == False
assert is_leap_year(1900) == False
assert is_leap_year(2000) == True
assert is_leap_year(2100) == False
assert is_leap_year(2400) == True
def test_nex... | [
{
"docstring": "Determines if a given year is a leap year.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"docstring": "Finds and returns the next leap year after the given year.",
"function_declaration": "def next_le... | [
0,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def next_leap_year(year):\n \"\"\"\n Determines the next leap year after a given year.\n \"\"\"\n def is_leap_year(y):\n if y % 4 == 0:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042360",
"row_id": 42360,
"seed_ids": "[4378]"
} | 0.688753 | Algorithm_42360 | I | [
"is_leap_year",
"next_leap_year"
] | 2 | [
[
"next_leap_year",
"is_leap_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 46770ba133c5596ab4fb4107fc7a597c8a84d7e1 | 0faf30fd9e655d089dffc99d42a128e8d303c83a | |||
v1.0 | instruct | Algorithm | Algorithm_42394_I | ### Problem Statement
You are tasked with creating a function that sums all prime-indexed elements of an integer array. Prime indices refer to positions in the array that are prime numbers. Your function should take a list of integers and return the sum of the elements at those prime indices.
### Requirements
1. Impl... | def is_prime(n):
"""Helper function to check if a number is prime."""
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 sum_of_prime_indices(ele... | from solution import sum_of_prime_indices
def test_sum_of_prime_indices_all_primes():
assert sum_of_prime_indices([10, 20, 30, 40, 50, 60]) == 130 # 30 (index 2) + 40 (index 3) + 60 (index 5)
def test_sum_of_prime_indices_mixed_elements():
assert sum_of_prime_indices([5, 15, 25, 35]) == 60 # 25 (index 2) + ... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Function to sum all elements in the list that are at prime indices.\n\nArgs:\nelements (list of int): List of i... | [
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": "def is_prime(n):\n \"\"\"\n Returns True if 'n' is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042394",
"row_id": 42394,
"seed_ids": "[1376]"
} | 0.694277 | Algorithm_42394 | I | [
"is_prime",
"sum_of_prime_indices"
] | 2 | [
[
"sum_of_prime_indices",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 46ccfbca1f955a0b6c95e8234932530bdf737921 | 22dbe1e652ea1efa98ae6b0e27f1ad2661f13590 | |||
v1.0 | instruct | Algorithm | Algorithm_42455_I | ### Coding Assessment Question: Implementing a Decision Tree for Classification
#### Context
You are working on a classification problem as part of a machine learning project. To solve this, you decide to implement a Decision Tree classifier from scratch. Decision Trees are effective for both classification and regres... | import numpy as np
def calculate_gini(labels):
"""
Function to compute the Gini impurity for a list of labels.
"""
_, label_counts = np.unique(labels, return_counts=True)
impurity = 1 - sum((count / len(labels)) ** 2 for count in label_counts)
return impurity
def split_dataset(dataset, labels,... | def test_calculate_gini():
assert np.isclose(calculate_gini([1, 1, 0, 0]), 0.5)
def test_split_dataset():
dataset = [[1, 2], [3, 4], [5, 6]]
labels = [1, 0, 1]
left_dataset, right_dataset, left_labels, right_labels = split_dataset(dataset, labels, 0, 2)
assert left_dataset == [[1, 2]]
assert ri... | [
{
"docstring": "Function to compute the Gini impurity for a list of labels.",
"function_declaration": "def calculate_gini(labels):",
"function_name": "calculate_gini",
"parameter_list": "(labels)"
},
{
"docstring": "Splits the dataset based on the given feature index and threshold.",
"fu... | [
0,
1,
0,
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": "class TreeNode:\n def __init__(self, gini, num_samples, num_samples_per_class, predicted_class):\n self.gini = gini\n self.num_samples = num_sam... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000042455",
"row_id": 42455,
"seed_ids": "[590]"
} | 0.568005 | Algorithm_42455 | I | [
"calculate_gini",
"split_dataset",
"calculate_best_split",
"build_decision_tree",
"classify",
"decision_tree_classifier"
] | 6 | [
[
"build_decision_tree",
"calculate_best_split"
],
[
"calculate_best_split",
"calculate_gini"
],
[
"calculate_best_split",
"split_dataset"
],
[
"decision_tree_classifier",
"build_decision_tree"
],
[
"decision_tree_classifier",
"classify"
]
] | 5 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | dfc9dae474dff1ca48e13c90a84a4d1c66565789 | 9d4d920fe1d0d40c8914785e1a3fd2c2d61b5906 | |||
v1.0 | instruct | Algorithm | Algorithm_42461_I | ### Sum of Digits in Large Numbers
**Objective**: In this task, you will implement a function that reads a file containing very large integers and calculates the sum of digits for each number provided, determining the maximum sum of digits among all numbers.
### Problem Statement:
You are given a text file with one t... | def sum_of_digits(number: str) -> int:
"""
Compute the sum of the digits of the provided large integer.
"""
return sum(int(digit) for digit in number)
def max_sum_of_digits(filename: str = "numbers.txt") -> int:
"""
Compute the maximum sum of digits among all numbers in the given file.
"""
... | from solution import sum_of_digits, max_sum_of_digits
import tempfile
def test_sum_of_digits():
assert sum_of_digits("123456789") == 45
assert sum_of_digits("987654321") == 45
assert sum_of_digits("1111111111111111111111111111111111") == 34
assert sum_of_digits("0") == 0
assert sum_of_digits("99999... | [
{
"docstring": "Compute the sum of the digits of the provided large integer.",
"function_declaration": "def sum_of_digits(number):",
"function_name": "sum_of_digits",
"parameter_list": "(number)"
},
{
"docstring": "Compute the maximum sum of digits among all numbers in the given file.",
... | [
1,
0,
1,
1,
1,
0,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def sum_of_digits(number: str) -> int:\n \"\"\"\n Compute the sum of the digits of the provided large integer.\n \"\"\"\n return sum(int(digit) for d... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000042461",
"row_id": 42461,
"seed_ids": "[2511]"
} | 0.654526 | Algorithm_42461 | I | [
"sum_of_digits",
"max_sum_of_digits"
] | 2 | [
[
"max_sum_of_digits",
"sum_of_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ec1270c1e5b1f7a0c6b00b68884f66b7d582319 | eef742e16b8243bbcc59876ed862652ddb11af94 | |||
v1.0 | instruct | Algorithm | Algorithm_42482_I | ### Coding Assessment Question
You are required to extend a program that processes and analyzes weather data. The existing implementation fetches current weather conditions from a public weather API and logs temperature changes over time. Now, extend the functionality to include fetching historical weather data for a ... | import requests
from datetime import datetime, timedelta
def get_historical_weather(api_key: str, location: str, date: str) -> dict:
"""
Fetch historical weather data for the given location and date from the weather API.
"""
url = f"https://api.weatherapi.com/v1/history.json"
params = {
"ke... | from solution import get_historical_weather, calculate_average_temperature
from unittest.mock import patch
def test_get_historical_weather_success():
mock_response = {
"forecast": {
"forecastday": [
{
"day": {
"avgtemp_c": 25.0,
... | [
{
"docstring": "Fetch historical weather data for the given location and date from the weather API.",
"function_declaration": "def get_historical_weather(api_key, location, date):",
"function_name": "get_historical_weather",
"parameter_list": "(api_key, location, date)"
},
{
"docstring": "Fe... | [
1,
0,
1,
0,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom datetime import datetime, timedelta\n\ndef get_historical_weather(api_key: str, location: str, date: str) -> dict:\n \"\"\"\n Fetch h... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042482",
"row_id": 42482,
"seed_ids": "[2092]"
} | 0.607264 | Algorithm_42482 | I | [
"get_historical_weather",
"calculate_average_temperature"
] | 2 | [
[
"calculate_average_temperature",
"get_historical_weather"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 1378b4e24f8c0b5b511694bd6b7187606028f23e | 9f0b3e8e3ef0ac445547ac28c7c2cc65ff75cf22 | |||
v1.0 | instruct | Algorithm | Algorithm_42484_I | ### Problem Statement: Logistic Regression Enhancement
You are provided with a basic implementation of logistic regression using gradient descent for binary classification. The current implementation uses a simple gradient descent algorithm with a fixed learning rate. Your task is to improve this implementation by add... | import numpy as np
def sigmoid(z: np.ndarray) -> np.ndarray:
"""
Apply the sigmoid function to the input array.
Parameters:
z (np.ndarray): Numpy array of input values.
Returns:
np.ndarray: Numpy array with sigmoid applied to each element.
"""
return 1 / (1 + np.exp(-z))
def initiali... | import numpy as np
from solution import sigmoid, initialize_weights, logistic_regression
def test_sigmoid():
z = np.array([0, 2])
expected_output = np.array([0.5, 0.88079708])
assert np.allclose(sigmoid(z), expected_output)
def test_initialize_weights():
n_features = 3
weights = initialize_weights... | [
{
"docstring": "Apply the sigmoid function to the input array.\n\nParameters:\nz (np.ndarray): Numpy array of input values.\n\nReturns:\nnp.ndarray: Numpy array with sigmoid applied to each element.",
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(z: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply the sigmoid function to the input array.\n\n Parameters:\n z (np.nda... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042484",
"row_id": 42484,
"seed_ids": "[541]"
} | 0.618691 | Algorithm_42484 | I | [
"sigmoid",
"initialize_weights",
"logistic_regression"
] | 3 | [
[
"logistic_regression",
"initialize_weights"
],
[
"logistic_regression",
"sigmoid"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 3486c8b8a5ff341220edd1152a7737674f15f3ef | 5568d00899b44571bb1bf526b1608a6173aeba53 | |||
v1.0 | instruct | Algorithm | Algorithm_42514_I | ### Hangman Game Implementation
Your task is to implement a simple Hangman game where the user attempts to guess a hidden word one letter at a time. The game continues until the user either guesses the word correctly or exceeds the allowed number of incorrect attempts.
#### Function Signatures:
1. `def display_word(w... | def display_word(word: str, guessed_letters: set) -> str:
"""
Returns the word with unguessed letters replaced by underscores and guessed letters revealed.
"""
return ''.join([letter if letter in guessed_letters else '_' for letter in word])
def guess_letter(word: str, guessed_letters: set, letter: str... | import pytest
def test_display_word():
assert display_word("python", set()) == "______"
assert display_word("python", {'p', 'y'}) == "py____"
assert display_word("python", {'p', 'y', 't', 'h', 'o', 'n'}) == "python"
def test_guess_letter():
guessed_letters, correct = guess_letter("python", set(), 'p')... | [
{
"docstring": "Returns the word with unguessed letters replaced by underscores and guessed letters revealed.",
"function_declaration": "def display_word(word, guessed_letters):",
"function_name": "display_word",
"parameter_list": "(word, guessed_letters)"
},
{
"docstring": "Updates the set ... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def display_word(word: str, guessed_letters: set) -> str:\n \"\"\"\n Returns the word with unguessed letters replaced by underscores and guessed letters re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000042514",
"row_id": 42514,
"seed_ids": "[4722]"
} | 0.558865 | Algorithm_42514 | I | [
"display_word",
"guess_letter",
"check_win",
"hangman"
] | 4 | [
[
"hangman",
"check_win"
],
[
"hangman",
"display_word"
],
[
"hangman",
"guess_letter"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | dd2951590a1aca6a89de49d25832bfc5da65840e | 4a25b2c89e231d8d2ec98257bff4566e36ac7342 | |||
v1.0 | instruct | Algorithm | Algorithm_42609_I | ### Problem Statement
You are given a function called `duration_between` that calculates the duration between two times represented in a 24-hour format ("HH:MM"). Your task is to expand the implementation to account for more complex time scenarios and edge cases.
You need to implement the following three functions:
1... | def is_valid_time(time_str: str) -> bool:
"""
Checks whether a given time string is in a valid "HH:MM" format.
Args:
time_str (str): The time string to validate.
Returns:
bool: True if the time string is valid, False otherwise.
"""
if len(time_str) != 5 or time_str[2] != ':':
... | import pytest
from solution import is_valid_time, minutes_since_midnight, duration_between
def test_is_valid_time():
assert is_valid_time("12:34") == True
assert is_valid_time("23:59") == True
assert is_valid_time("00:00") == True
assert is_valid_time("25:00") == False
assert is_valid_time("12:60")... | [
{
"docstring": "Checks whether a given time string is in a valid \"HH:MM\" format.\n\nArgs:\ntime_str (str): The time string to validate.\n\nReturns:\nbool: True if the time string is valid, False otherwise.",
"function_declaration": "def is_valid_time(time_str):",
"function_name": "is_valid_time",
... | [
0,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_valid_time(time_str: str) -> bool:\n \"\"\"\n Checks whether a given time string is in a valid \"HH:MM\" format.\n \n :param time_str: A strin... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000042609",
"row_id": 42609,
"seed_ids": "[3338]"
} | 0.608443 | Algorithm_42609 | I | [
"is_valid_time",
"minutes_since_midnight",
"duration_between"
] | 3 | [
[
"duration_between",
"minutes_since_midnight"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 32ce9d013d0e5e3c696ef6e4f5d1e5735d798148 | 44631c3275122ff11d0d368d3836a545f794fabd | |||
v1.0 | instruct | Algorithm | Algorithm_42619_I | Order Statistics: Kth Smallest Element
#### Background
Finding the k-th smallest element in a collection of elements is a classic problem in computer science known as order statistics. Various algorithms, including sorting, quickselect, and min-heaps, can solve this problem efficiently for different scenarios.
#### T... | def quickselect(arr, left, right, k):
"""
Helper function to perform the quickselect algorithm.
"""
if left == right:
return arr[left]
pivot_index = partition(arr, left, right)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, left, piv... | from solution import kth_smallest_element
import pytest
def test_kth_smallest_element_regular_case():
assert kth_smallest_element([7, 10, 4, 3, 20, 15], 3) == 7
def test_kth_smallest_element_single_element():
assert kth_smallest_element([1], 1) == 1
def test_kth_smallest_element_all_same_elements():
asse... | [
{
"docstring": "Helper function to perform the quickselect algorithm.",
"function_declaration": "def quickselect(arr, left, right, k):",
"function_name": "quickselect",
"parameter_list": "(arr, left, right, k)"
},
{
"docstring": "Helper function to partition the array.",
"function_declar... | [
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 kth_smallest_element(arr: list[int], k: int) -> int:\n \"\"\"\n Finds the k-th smallest element in an unsorted array using the quickselect algorithm.\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042619",
"row_id": 42619,
"seed_ids": "[3311]"
} | 0.651827 | Algorithm_42619 | I | [
"quickselect",
"partition",
"kth_smallest_element"
] | 3 | [
[
"kth_smallest_element",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | be1b173a24696a493331508dec9bc88aa0487b3d | 847b84998d266e2ff1bbe88a97fd8cb61401f17f | |||
v1.0 | instruct | Algorithm | Algorithm_42634_I | ### Question: Counting Valid Parentheses Strings
**Scenario:**
You are tasked with evaluating various strings to determine how many of them are valid parentheses strings. A valid parentheses string is defined by the following conditions:
1. An empty string is a valid parentheses string.
2. If "s" is a valid parenthese... | from typing import List
def is_valid_parentheses(s: str) -> bool:
"""
Helper function to determine if the given string is a valid parentheses string.
"""
stack = []
for char in s:
if char == '(':
stack.append('(')
elif char == ')':
if not stack:
... | def test_count_valid_parentheses():
assert count_valid_parentheses(["(", "()", "(())", "()", "(()"]) == 3, "Test Case 1 Failed"
assert count_valid_parentheses(["", "()", "()()", "(()())", "((()"]) == 4, "Test Case 2 Failed"
assert count_valid_parentheses([")", "((()())", "(()))", "()()()"]) == 1, "Test Case... | [
{
"docstring": "Helper function to determine if the given string is a valid parentheses string.",
"function_declaration": "def is_valid_parentheses(s):",
"function_name": "is_valid_parentheses",
"parameter_list": "(s)"
},
{
"docstring": "Counts the number of valid parentheses strings in the ... | [
0,
1,
1,
0,
1,
0,
1,
1,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_valid_parentheses_string(s: str) -> bool:\n stack = []\n for char in s:\n if char == '(':\n stack.appen... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000042634",
"row_id": 42634,
"seed_ids": "[3113]"
} | 0.766111 | Algorithm_42634 | I | [
"is_valid_parentheses",
"count_valid_parentheses"
] | 2 | [
[
"count_valid_parentheses",
"is_valid_parentheses"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ea6582ae69a58f063b75a4a020326f321e67ebda | b0004658768a54b3e2d2a8d8df7984f1b73a6a67 | |||
v1.0 | instruct | Algorithm | Algorithm_42666_I | ### Coding Question: Identify Rotated Array's Pivot Index
Given a rotated sorted array of unique integers, your task is to implement two functions to identify the pivot point (index) and determine whether a given target is present in the array.
1. **Function 1: `find_pivot_index(arr: list[int]) -> int`**:
* **Inp... | def find_pivot_index(arr):
"""
Finds the index of the smallest element (pivot) in the rotated sorted array.
"""
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] > arr[right]:
left = mid + 1
else:
right = mid
r... | def test_find_pivot_index():
assert find_pivot_index([4, 5, 6, 7, 0, 1, 2]) == 4
assert find_pivot_index([12, 15, 18, 2, 3, 6]) == 3
assert find_pivot_index([1]) == 0
assert find_pivot_index([1, 2, 3, 4, 5]) == 0
assert find_pivot_index([5, 1, 2, 3, 4]) == 1
def test_search_in_rotated_array():
... | [
{
"docstring": "Finds the index of the smallest element (pivot) in the rotated sorted array.",
"function_declaration": "def find_pivot_index(arr):",
"function_name": "find_pivot_index",
"parameter_list": "(arr)"
},
{
"docstring": "Searches for the target in the rotated sorted array and retur... | [
1,
1,
0,
1,
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": "def find_pivot_index(arr):\n \"\"\"\n Finds the index of the pivot (the smallest element) in the rotated sorted array.\n \"\"\"\n low, high = 0, len(... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000042666",
"row_id": 42666,
"seed_ids": "[3746]"
} | 0.600203 | Algorithm_42666 | I | [
"find_pivot_index",
"search_in_rotated_array"
] | 2 | [
[
"search_in_rotated_array",
"find_pivot_index"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 54085b955cef55dd353ba656ca9caf7d2d6c9a23 | fb095050f2e2604e5b40102f64c370157b17edc2 | |||
v1.0 | instruct | Algorithm | Algorithm_42720_I | ### Coding Question
#### Context
You are developing a library management system. One of the functionalities required is to recommend books based on the user's reading history and preferences. The system needs to process the user's reading data and return book titles that align with their interests.
#### Task
Write a ... | from typing import List, Dict
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
# Assume we have a database of books and their genres
BOOK_DATABASE = {
"Book D": "Fiction",
"Book E": "Mystery",
"Book F": "Sci-Fi",
"Book G": "Romance",
"Book H": "Fiction",
"Book I": "Sci-F... | from solution import recommend_books
def test_recommend_books_basic():
reading_history = ["Book A", "Book B", "Book C"]
preferences = {"Fiction": 5, "Mystery": 3, "Sci-Fi": 4}
recommendations = recommend_books(user_id=1, reading_history=reading_history, preferences=preferences)
assert sorted(recommenda... | [
{
"docstring": "Helper function to get books by genre",
"function_declaration": "def get_books_by_genre(genre):",
"function_name": "get_books_by_genre",
"parameter_list": "(genre)"
},
{
"docstring": "Recommend books to a user based on their reading history and preferences.",
"function_de... | [
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\nimport logging\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO)\n\n# Assume we have a database of books and their genr... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000042720",
"row_id": 42720,
"seed_ids": "[3948]"
} | 0.590219 | Algorithm_42720 | I | [
"get_books_by_genre",
"recommend_books"
] | 2 | [
[
"recommend_books",
"get_books_by_genre"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 214da5e959971d7c419f104252fe2d7ceed1600d | b199cbce4d31be5d5a866a1aa08d71c255334df3 | |||
v1.0 | instruct | Algorithm | Algorithm_42790_I | Custom K-Means Clustering Implementation and Analysis
You are tasked with implementing the K-Means clustering algorithm from scratch without using scikit-learn's `KMeans`. Your implementation will be applied to the provided Wine dataset. The task includes handling the data correctly, initializing centroids, assigning ... | import numpy as np
from sklearn.datasets import load_wine
from sklearn.metrics import silhouette_score
def data_preparation(data: dict) -> np.ndarray:
"""
Prepares the feature array from the input data dictionary.
Args:
data (dict): A dictionary containing 'data' with a feature array.
Ret... | import numpy as np
from solution import data_preparation, initialize_centroids, assign_clusters, update_centroids, kmeans_clustering, calculate_silhouette_score
from sklearn.datasets import load_wine
def test_data_preparation():
wine = load_wine()
features = data_preparation(wine)
assert isinstance(feature... | [
{
"docstring": "Prepares the feature array from the input data dictionary.\n\nArgs:\ndata (dict): A dictionary containing 'data' with a feature array.\n\nReturns:\nnp.ndarray: Numpy array containing the features.",
"function_declaration": "def data_preparation(data):",
"function_name": "data_preparation... | [
0,
1,
1,
0,
1,
1,
1,
1,
1
] | 7 | easy | 0.778 | {
"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.datasets import load_wine\nfrom sklearn.metrics import silhouette_score\n\ndef data_preparation(data: dict) -> np.ndarray:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042790",
"row_id": 42790,
"seed_ids": "[505]"
} | 0.79147 | Algorithm_42790 | I | [
"data_preparation",
"initialize_centroids",
"assign_clusters",
"update_centroids",
"kmeans_clustering",
"calculate_silhouette_score"
] | 6 | [
[
"kmeans_clustering",
"assign_clusters"
],
[
"kmeans_clustering",
"initialize_centroids"
],
[
"kmeans_clustering",
"update_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 652085d07f4e4f76e7d674e4422da17b92e83525 | b9044813951bc4397c113bf244b1c14e57c925eb | |||
v1.0 | instruct | Algorithm | Algorithm_42827_I | ### Question: Neural Network Activation Functions
As part of a deep learning module, you are tasked with implementing three commonly used activation functions and their corresponding derivatives. These are crucial for understanding how neural networks learn and are used in the backpropagation algorithm.
### Function ... | import numpy as np
def sigmoid(x):
"""
Applies the sigmoid activation function to the input array.
"""
return 1 / (1 + np.exp(-x))
def relu(x):
"""
Applies the ReLU activation function to the input array.
"""
return np.maximum(0, x)
def tanh(x):
"""
Applies the tanh activation... | import numpy as np
from solution import sigmoid, relu, tanh, sigmoid_derivative, relu_derivative, tanh_derivative
def test_sigmoid():
x = np.array([-1.0, 0.0, 1.0])
expected = np.array([0.26894142, 0.5, 0.73105858])
np.testing.assert_almost_equal(sigmoid(x), expected, decimal=5)
def test_relu():
x = n... | [
{
"docstring": "Applies the sigmoid activation function to the input array.",
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": "Applies the ReLU activation function to the input array.",
"function_declaration": "def relu(x):... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Compute the sigmoid activation function.\n \"\"\"\n return 1 / (1 + np.exp(... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042827",
"row_id": 42827,
"seed_ids": "[743]"
} | 0.453263 | Algorithm_42827 | I | [
"sigmoid",
"relu",
"tanh",
"sigmoid_derivative",
"relu_derivative",
"tanh_derivative"
] | 6 | [
[
"sigmoid_derivative",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 7dab932ac5864cb37b2fa5c70f059e54a3759cc9 | c649ae26eabc66f7d8cedb4522600914fb9ac169 | |||
v1.0 | instruct | Algorithm | Algorithm_42848_I | ### Code Exercise:
Write a function that finds the first `k` numbers in the Fibonacci sequence which are also prime numbers. Return these prime Fibonacci numbers as a list.
### Function Signature
```python
def prime_fibonacci(k: int) -> list:
```
### Input
- An integer `k`, where 1 ≤ `k` ≤ 10,000. This represents the... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def prime_fibonacci(k):
if k <= 0:
... | from solution import prime_fibonacci, is_prime
def test_is_prime():
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(30) == False
def test_prime_fibonacci_length_1():
assert prime_fibon... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_fibonacci(k):",
"function_name": "prime_fibonacci",
"parameter_list": "(k)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def prime_fibonacci(k):\n def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000042848",
"row_id": 42848,
"seed_ids": "[2317]"
} | 0.823396 | Algorithm_42848 | I | [
"is_prime",
"prime_fibonacci"
] | 2 | [
[
"prime_fibonacci",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ace2a8de4330267ed842e4621ec6f0df4b78cb59 | 3d6599982007f550eb822c5917e14abdaba30913 | |||
v1.0 | instruct | Algorithm | Algorithm_42875_I | ### ISBN-10 Verification System
**Scenario**:
You are tasked with developing a verification system for ISBN-10. An ISBN-10 (International Standard Book Number) is a 10-digit code used for book identification. The verifying digit is the last digit of the ISBN, which can be a number or the letter 'X', representing the v... | def calculate_check_digit(isbn: str) -> str:
"""
Calculate the check digit for the given 9-character ISBN-10.
Parameters:
isbn (str): A string of 9 characters representing the first 9 digits of an ISBN-10.
Returns:
str: The check digit, which can be a number (0-9) or 'X'.
"""
i... | from solution import calculate_check_digit, validate_isbn
def test_calculate_check_digit():
assert calculate_check_digit('030640615') == '2'
assert calculate_check_digit('156881111') == 'X'
assert calculate_check_digit('013601267') == '1'
assert calculate_check_digit('123456789') == 'X'
def test_inval... | [
{
"docstring": "Calculate the check digit for the given 9-character ISBN-10.\n\nParameters:\nisbn (str): A string of 9 characters representing the first 9 digits of an ISBN-10.\n\nReturns:\nstr: The check digit, which can be a number (0-9) or 'X'.",
"function_declaration": "def calculate_check_digit(isbn):"... | [
1,
1,
0,
0,
0,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate_check_digit(isbn: str) -> str:\n \"\"\"\n Calculates the check digit for a given 9-character ISBN-10 prefix.\n \"\"\"\n if len(isbn) !=... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000042875",
"row_id": 42875,
"seed_ids": "[1160]"
} | 0.557909 | Algorithm_42875 | I | [
"calculate_check_digit",
"validate_isbn"
] | 2 | [
[
"validate_isbn",
"calculate_check_digit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b8c107c3e13cf66af577110f343fbae82849293d | 4b0363ab26fa44ab32c7024d17bfb4234c28ebf2 | |||
v1.0 | instruct | Algorithm | Algorithm_42877_I | ### Calendar Event Scheduler
You are required to implement a scheduling feature for a simple calendar application. This involves working with date and time manipulations, handling overlapping events, and ensuring all scheduled events are valid within a day.
#### Function 1: Add Event
Write a function `add_event` that... | def time_to_minutes(time):
"""Convert time in HH:MM format to minutes since 00:00."""
hours, minutes = map(int, time.split(":"))
return hours * 60 + minutes
def add_event(events, new_event):
"""
Adds a new event to the calendar if it does not overlap with existing events.
Parameters:
e... | from solution import add_event, list_events
def test_add_event_success():
events = [("09:00", "10:00"), ("11:00", "12:00")]
new_event = ("10:00", "11:00")
result = add_event(events, new_event)
assert result == True
assert events == [("09:00", "10:00"), ("11:00", "12:00"), ("10:00", "11:00")]
def t... | [
{
"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": "Adds a new event to the calendar if it does not overlap with existing events.\n\nPara... | [
0,
1,
0,
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 parse_time(time_str):\n \"\"\"\n Parses a time string in \"HH:MM\" format into minutes since midnight.\n \"\"\"\n hours, minutes = map(int, time_... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042877",
"row_id": 42877,
"seed_ids": "[3476]"
} | 0.611951 | Algorithm_42877 | I | [
"time_to_minutes",
"add_event",
"list_events"
] | 3 | [
[
"add_event",
"time_to_minutes"
],
[
"list_events",
"time_to_minutes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4af11fea01514af6cc47d1d37ed308cb3170b95c | 6e0be76d321dca61e52feca817a710bdf2b31bfd | |||
v1.0 | instruct | Algorithm | Algorithm_42901_I | ### Question: Implement Matrix Rotation and Sum Calculation
As a software engineer, you need to manipulate a list of numbers presented in a square matrix format. Your task is to rotate this matrix by 90 degrees clockwise and then calculate the sum of the elements in the resulting matrix.
#### Your Task
1. Implement a... | def rotate_matrix_90(matrix):
"""
Rotates a square matrix by 90 degrees clockwise.
Parameters:
matrix (list[list[int]]): A square matrix represented as a list of lists.
Returns:
list[list[int]]: A new matrix rotated by 90 degrees clockwise.
"""
n = len(matrix)
rotated_matri... | def test_rotate_matrix_90():
assert rotate_matrix_90([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]
assert rotate_matrix_90([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
assert rotate_matrix_90([[1]]) == [[1]]
assert rotate_matrix_90([[1, 2], [2, 3]]) == [[2, 1], [3, 2]]
def test_sum_r... | [
{
"docstring": "Rotates a square matrix by 90 degrees clockwise.\n\nParameters:\nmatrix (list[list[int]]): A square matrix represented as a list of lists.\n\nReturns:\nlist[list[int]]: A new matrix rotated by 90 degrees clockwise.",
"function_declaration": "def rotate_matrix_90(matrix):",
"function_name... | [
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 rotate_matrix_90(matrix: list[list[int]]) -> list[list[int]]:\n \"\"\"\n Rotates a square matrix by 90 degrees clockwise.\n \"\"\"\n return [list... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042901",
"row_id": 42901,
"seed_ids": "[736]"
} | 0.586401 | Algorithm_42901 | I | [
"rotate_matrix_90",
"sum_rotated_matrix"
] | 2 | [
[
"sum_rotated_matrix",
"rotate_matrix_90"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3a4ce4d61f53d83247da1c46fdfba9e686a66194 | 90488bd234ebb660eee96dc2c39c1e424b26daac | |||
v1.0 | instruct | Algorithm | Algorithm_42905_I | ### String Matching with KMP Algorithm
Write a function that uses the Knuth-Morris-Pratt (KMP) algorithm to find all occurrences of a substring (pattern) within a given string (text). The KMP algorithm should preprocess the pattern to create an LPS (Longest Prefix Suffix) array and use it during the search phase to ac... | def compute_lps(pattern):
"""
Preprocesses the pattern to create the LPS (Longest Prefix Suffix) array.
"""
m = len(pattern)
lps = [0] * m
j = 0 # length of the previous longest prefix suffix
i = 1
while i < m:
if pattern[i] == pattern[j]:
j += 1
lps[i] ... | def test_find_pattern_single_occurrence():
text = "ababcabcabababd"
pattern = "ababd"
assert find_pattern(text, pattern) == [10]
def test_find_pattern_multiple_occurrences():
text = "ababcabcabababcabc"
pattern = "abc"
assert find_pattern(text, pattern) == [2, 5, 12, 15]
def test_find_pattern_... | [
{
"docstring": "Preprocesses the pattern to create the LPS (Longest Prefix Suffix) array.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Uses the KMP algorithm to find all occurrences of the pattern in t... | [
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def compute_lps(pattern):\n \"\"\"\n Preprocesses the pattern to create the LPS (Longest Prefix Suffix) array.\n \"\"\"\n m = len(pattern)\n lps =... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000042905",
"row_id": 42905,
"seed_ids": "[4348]"
} | 0.639698 | Algorithm_42905 | I | [
"compute_lps",
"find_pattern"
] | 2 | [
[
"find_pattern",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a49adc86c8ac347b1b8249a6dfb99188f0ba5178 | 2e494216587092aba773d4a8bbb2684d663befd1 | |||
v1.0 | instruct | Algorithm | Algorithm_42922_I | **Function to Process Real-time Stock Prices and Alert Trigger**
You are developing a stock trading application that needs to monitor real-time stock prices. The application should fetch the latest stock prices at regular intervals and trigger an alert if certain conditions are met.
**Objective**:
Create a function t... | import aiohttp
import asyncio
import time
STOCK_API_URL = "https://api.mockstocktrading.com/price"
class StockFetchError(Exception):
pass
async def fetch_stock_price(session: aiohttp.ClientSession, symbol: str, retries=3, backoff_in_seconds=1) -> float:
for attempt in range(retries):
try:
... | import pytest
import aiohttp
from unittest.mock import AsyncMock, patch, Mock
from solution import fetch_stock_price, StockFetchError
@pytest.mark.asyncio
async def test_fetch_stock_price_success():
mock_session = AsyncMock()
response = AsyncMock()
response.json = AsyncMock(return_value={"price": 300.5})
... | [] | [
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": "import aiohttp\nimport asyncio\nimport time\n\nSTOCK_API_URL = \"https://api.mockstocktrading.com/price\"\n\nasync def fetch_stock_price(session: aiohttp.ClientS... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000042922",
"row_id": 42922,
"seed_ids": "[1921]"
} | 0.522199 | Algorithm_42922 | I | [
"fetch_stock_price",
"check_stock_prices"
] | 2 | [
[
"check_stock_prices",
"fetch_stock_price"
]
] | 1 | [] | false | [
"StockFetchError"
] | true | pytest | true | [
"aiohttp"
] | false | 33fb2ab461cd8e8622b48d12c4b38603501f95bb | 11b2bf07607d0285f8638b7a4d2eef8672a5f44d | |||
v1.0 | instruct | Algorithm | Algorithm_42938_I | ### Matrix Rotation Validator
**Problem Statement:**
You are given a square matrix and an angle of rotation. Your task is to determine whether rotating the matrix by the given angle results in the matrix matching a specified target matrix. You need to write a function that verifies if rotating the given matrix by the... | def rotate_90(original):
"""
Rotates the matrix 90 degrees clockwise.
"""
n = len(original)
return [[original[n - j - 1][i] for j in range(n)] for i in range(n)]
def rotate_180(original):
"""
Rotates the matrix 180 degrees clockwise.
"""
return rotate_90(rotate_90(original))
def ro... | import pytest
from solution import is_matrix_rotation_valid
def test_is_matrix_rotation_valid_90_true():
original = [
[1, 2],
[3, 4]
]
target = [
[3, 1],
[4, 2]
]
assert is_matrix_rotation_valid(original, target, 90) == True
def test_is_matrix_rotation_valid_180_tru... | [
{
"docstring": "Rotates the matrix 90 degrees clockwise.",
"function_declaration": "def rotate_90(original):",
"function_name": "rotate_90",
"parameter_list": "(original)"
},
{
"docstring": "Rotates the matrix 180 degrees clockwise.",
"function_declaration": "def rotate_180(original):",
... | [
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_90(matrix):\n \"\"\"\n Rotates the given matrix by 90 degrees clockwise.\n \"\"\"\n n = len(matrix)\n rotated = [[0] * n for _ in range... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000042938",
"row_id": 42938,
"seed_ids": "[980]"
} | 0.539524 | Algorithm_42938 | I | [
"rotate_90",
"rotate_180",
"rotate_270",
"is_matrix_rotation_valid"
] | 4 | [
[
"is_matrix_rotation_valid",
"rotate_180"
],
[
"is_matrix_rotation_valid",
"rotate_270"
],
[
"is_matrix_rotation_valid",
"rotate_90"
],
[
"rotate_180",
"rotate_90"
],
[
"rotate_270",
"rotate_180"
],
[
"rotate_270",
"rotate_90"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 93b48afd0ddfc762a554899b1035de3fed4ee15a | 4d7e0e0e8464daab38786739eb7e3d6b8000b165 | |||
v1.0 | instruct | Algorithm | Algorithm_42980_I | ### Description:
You are provided with a function, `is_prime`, which checks if a given integer is a prime number. Your task is to implement another function that enumerates all prime numbers between two given integers (inclusive).
### Task:
Implement a function `list_primes(start: int, end: int) -> list[int]` that:
1.... | 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 list_primes(start: int, end: ... | from solution import is_prime, list_primes
def test_is_prime_basic_cases():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
assert is_prime(1... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def list_primes(start, end):",
"function_name": "list_primes",
"parameter_list": "(start, end)"
}
] | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(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 return False\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000042980",
"row_id": 42980,
"seed_ids": "[3164]"
} | 0.729216 | Algorithm_42980 | I | [
"is_prime",
"list_primes"
] | 2 | [
[
"list_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71ce25337318ed9fb181c1b9cca669787aa43500 | d5bf726f4619f6923dd2dc05bda83096138eef0d | |||
v1.0 | instruct | Algorithm | Algorithm_43042_I | ### Tower of Hanoi Recursive Solution and Analysis
**Background**:
The Tower of Hanoi is a classic problem in computer science that involves moving a set of disks from one peg to another, following specific rules. This problem is often used to teach recursion and algorithmic thinking.
**Objective**:
You are asked to ... | def tower_of_hanoi(n, source, target, auxiliary):
if n == 1:
return 1
else:
moves_before = tower_of_hanoi(n - 1, source, auxiliary, target)
move_disk = 1
moves_after = tower_of_hanoi(n - 1, auxiliary, target, source)
return moves_before + move_disk + moves_after
def solv... | from solution import solve_hanoi
def test_solve_hanoi_1_disk():
assert solve_hanoi(1) == 1
def test_solve_hanoi_2_disks():
assert solve_hanoi(2) == 3
def test_solve_hanoi_3_disks():
assert solve_hanoi(3) == 7
def test_solve_hanoi_4_disks():
assert solve_hanoi(4) == 15
def test_solve_hanoi_5_disks()... | [
{
"docstring": null,
"function_declaration": "def tower_of_hanoi(n, source, target, auxiliary):",
"function_name": "tower_of_hanoi",
"parameter_list": "(n, source, target, auxiliary)"
},
{
"docstring": null,
"function_declaration": "def solve_hanoi(num_disks):",
"function_name": "sol... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def solve_hanoi(num_disks: int) -> int:\n \"\"\"\n Calculates and returns the number of moves required to solve the Tower of Hanoi\n problem with the gi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043042",
"row_id": 43042,
"seed_ids": "[579]"
} | 0.540934 | Algorithm_43042 | I | [
"tower_of_hanoi",
"solve_hanoi"
] | 2 | [
[
"solve_hanoi",
"tower_of_hanoi"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd9fa6977197894234d363b2c88bb2249a46f21a | 1f2e8de7d2358df770437f6f085ea8a5d3a10087 | |||
v1.0 | instruct | Algorithm | Algorithm_43049_I | **Context**:
You are to design a function that analyzes a given list of integer numbers and classifies each as "prime", "fibonacci", or "both". A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Fibonacci numbers are a sequence where each number is the sum of the tw... | from typing import List
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def generate_fibonacci_upto(n: int) -> set:
... | from solution import classify_numbers
def test_classify_numbers_example():
numbers = [2, 3, 5, 8, 13, 21, 34, 89]
classify_numbers(numbers)
def test_classify_only_primes():
numbers = [2, 3, 5, 7, 11]
classify_numbers(numbers)
def test_classify_only_fibonacci():
numbers = [0, 1, 1, 2, 3, 5, 8,... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def generate_fibonacci_upto(n):",
"function_name": "generate_fibonacci_upto",
"parameter_list": "(n)"
},
{
... | [
0,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043049",
"row_id": 43049,
"seed_ids": "[3911]"
} | 0.668786 | Algorithm_43049 | I | [
"is_prime",
"generate_fibonacci_upto",
"classify_numbers"
] | 3 | [
[
"classify_numbers",
"generate_fibonacci_upto"
],
[
"classify_numbers",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9a4477411ae6e46d4814115abf6e38be84db59be | 33b109cf036e3183d45d58b42e0bfb86498de6dc | |||
v1.0 | instruct | Algorithm | Algorithm_43051_I | ### Coding Assessment Question
#### Scenario
You are tasked with developing an algorithm for a simulation game that revolves around resource management. One of the key challenges in the game is to determine the order in which players gather resources. The order is determined based on a simple mathematical pattern know... | from typing import List
def is_prime(num: int) -> bool:
"""
Returns True if num is a prime number, otherwise False.
"""
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 =... | from solution import prime_fibonacci, is_prime
def test_prime_fibonacci_1():
assert prime_fibonacci(1) == [2]
def test_prime_fibonacci_3():
assert prime_fibonacci(3) == [2, 3, 5]
def test_prime_fibonacci_5():
assert prime_fibonacci(5) == [2, 3, 5, 13, 89]
def test_prime_fibonacci_10():
assert prime_... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of the first n prime numbers in the Fibonacci sequence.",
"function_declaration... | [
0,
1,
0,
1,
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": "from typing import List\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Helper function to determine if a given number is prime.\n \"\"\"\n if num <= 1... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000043051",
"row_id": 43051,
"seed_ids": "[3210]"
} | 0.757207 | Algorithm_43051 | I | [
"is_prime",
"prime_fibonacci"
] | 2 | [
[
"prime_fibonacci",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d9a25fb79d7af8d4d54db32307cd4394ed73515b | 0e9eb344ed0531e17124e7e34890a6ef995f560a | |||
v1.0 | instruct | Algorithm | Algorithm_43069_I | ### Data Clustering with K-Means Algorithm
#### Context
You are required to implement a K-Means clustering algorithm to group a given set of data points into `k` clusters. This task will help assess your understanding of unsupervised learning, distance metrics, and algorithmic implementation.
#### Task
1. **Implemen... | import numpy as np
def initialize_centroids(data: np.ndarray, k: int) -> np.ndarray:
"""
Randomly selects k data points from the input data as initial centroids.
"""
indices = np.random.choice(data.shape[0], k, replace=False)
return data[indices]
def euclidean_distance(a: np.ndarray, b: np.ndarray... | import numpy as np
from solution import initialize_centroids, euclidean_distance, k_means
def test_initialize_centroids():
data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
k = 2
centroids = initialize_centroids(data, k)
assert centroids.shape == (k, data.shape[1])
for centroid in centroid... | [
{
"docstring": "Randomly selects k data points from the input data as initial centroids.",
"function_declaration": "def initialize_centroids(data, k):",
"function_name": "initialize_centroids",
"parameter_list": "(data, k)"
},
{
"docstring": "Computes the Euclidean distance between two point... | [
0,
1,
1,
0,
1,
0,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport random\n\ndef initialize_centroids(data: np.ndarray, k: int) -> np.ndarray:\n \"\"\"\n Randomly initialize k centroids from the ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043069",
"row_id": 43069,
"seed_ids": "[4704]"
} | 0.793411 | Algorithm_43069 | I | [
"initialize_centroids",
"euclidean_distance",
"k_means"
] | 3 | [
[
"k_means",
"euclidean_distance"
],
[
"k_means",
"initialize_centroids"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 6fc9602e5de31258c0471d8ee15f6d9624d077f6 | 888d494f77770a0a542ed6d71d04955d71ec8eff |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.