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_43121_I | ### Task
In this task, you need to implement a function `k_means_clustering` to perform k-means clustering on a given set of data points. K-means clustering aims to partition the data points into k clusters where each point belongs to the cluster with the nearest mean, serving as the cluster center.
### Requirements:... | import random
import math
def initialize_centroids(data_points, k):
return random.sample(data_points, k)
def assign_clusters(data_points, centroids):
clusters = {i: [] for i in range(len(centroids))}
for point in data_points:
closest_centroid_index = min(
range(len(centroids)), key=lam... | from solution import k_means_clustering, evaluate_clustering
def test_k_means_clustering():
data_points = [(2.3, 4.5), (1.1, 0.2), (4.4, 2.1), (5.1, 1.9), (3.5, 3.5)]
k = 2
clusters = k_means_clustering(data_points, k)
assert len(clusters) == 2
all_points = [point for cluster_points in clusters.val... | [
{
"docstring": null,
"function_declaration": "def initialize_centroids(data_points, k):",
"function_name": "initialize_centroids",
"parameter_list": "(data_points, k)"
},
{
"docstring": null,
"function_declaration": "def assign_clusters(data_points, centroids):",
"function_name": "as... | [
1,
1,
0,
1,
0,
0,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Tuple, Dict\nimport numpy as np\n\ndef k_means_clustering(data_points: List[Tuple[float, ...]], k: int) -> Dict[int, List... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043121",
"row_id": 43121,
"seed_ids": "[492]"
} | 0.804515 | Algorithm_43121 | I | [
"initialize_centroids",
"assign_clusters",
"update_centroids",
"euclidean_distance",
"k_means_clustering",
"evaluate_clustering"
] | 6 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"evaluate_clustering",
"euclidean_distance"
],
[
"evaluate_clustering",
"k_means_clustering"
],
[
"k_means_clustering",
"assign_clusters"
],
[
"k_means_clustering",
"initialize_centroids"
],
[
"k_means_clu... | 6 | [] | false | [] | false | pytest | true | [] | true | 7db859bc1af5260ea5b8f21ff5a49d2447ab259b | f44093c8f26314d2308ad214944e988b01e52522 | |||
v1.0 | instruct | Algorithm | Algorithm_43151_I | ### Coding Assessment Question
#### Context
A Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones, usually starting with 0 and 1. The sequence begins with 0, 1, 1, 2, 3, 5, 8, and so on.
#### Task
Write a function `matrix_fibonacci` that generates an ... | from typing import List
def fibonacci(n: int) -> int:
"""
Helper function to return the nth Fibonacci number.
Uses memoization for efficiency.
"""
memo = [0, 1]
for i in range(2, n + 1):
memo.append(memo[-1] + memo[-2])
return memo[n]
def matrix_fibonacci(n: int) -> List[List[int]]... | def test_matrix_fibonacci_1x1():
assert matrix_fibonacci(1) == [[0]]
def test_matrix_fibonacci_2x2():
assert matrix_fibonacci(2) == [[0, 1], [1, 1]]
def test_matrix_fibonacci_3x3():
assert matrix_fibonacci(3) == [[0, 1, 1], [1, 1, 2], [1, 2, 3]]
def test_matrix_fibonacci_4x4():
assert matrix_fibonacc... | [
{
"docstring": "Helper function to return the nth Fibonacci number.\nUses memoization for efficiency.",
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Returns an n x n matrix where each element (i, j) is the Fibonacci num... | [
1,
1,
0,
1,
0,
1,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_fibonacci(n: int) -> List[List[int]]:\n def fibonacci(num):\n if num <= 1:\n return num\n fib =... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043151",
"row_id": 43151,
"seed_ids": "[4101]"
} | 0.719173 | Algorithm_43151 | I | [
"fibonacci",
"matrix_fibonacci"
] | 2 | [
[
"matrix_fibonacci",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 41997c17615b913efa7799d024196c2e7a629209 | 1834e26715ae5cd4dd70fa88268b1ae44417a0e4 | |||
v1.0 | instruct | Algorithm | Algorithm_43187_I | ### Maximum Subarray Sum using Divide and Conquer
The Maximum Subarray Sum problem involves finding the maximum sum of a contiguous subarray within a given one-dimensional numeric array. Your task is to implement this using the Divide and Conquer approach in Python.
#### Instructions
1. **Define a `max_crossing_sum`... | def max_crossing_sum(arr, low, mid, high):
# Include elements on left of mid
sum_left = float('-inf')
temp_sum = 0
for i in range(mid, low - 1, -1):
temp_sum += arr[i]
if temp_sum > sum_left:
sum_left = temp_sum
# Include elements on right of mid
sum_right = floa... | from solution import maximum_subarray_sum
def test_empty_array():
assert maximum_subarray_sum([]) == 0
def test_single_element():
assert maximum_subarray_sum([1]) == 1
assert maximum_subarray_sum([-1]) == -1
def test_all_negative_nums():
assert maximum_subarray_sum([-1, -2, -3, -4]) == -1
def test_m... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(arr, low, mid, high):",
"function_name": "max_crossing_sum",
"parameter_list": "(arr, low, mid, high)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_sum(arr, low, high):",
"function_name": "max_sub... | [
1,
0,
0,
1,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(arr, low, mid, high):\n \"\"\"\n Helper function to find the maximum subarray sum that crosses the midpoint.\n \"\"\"\n left_sum... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043187",
"row_id": 43187,
"seed_ids": "[1084]"
} | 0.741057 | Algorithm_43187 | I | [
"max_crossing_sum",
"max_subarray_sum",
"maximum_subarray_sum"
] | 3 | [
[
"max_subarray_sum",
"max_crossing_sum"
],
[
"maximum_subarray_sum",
"max_subarray_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 89c844e9cb16f750b7da6fa96f111708d53a8096 | 2b8e2196aeaccf32b35d85335877b1fd534ee88a | |||
v1.0 | instruct | Algorithm | Algorithm_43288_I | ### Problem Statement
You are given two lists of integers representing the coordinates of two points in a 2D plane. Your task is to compute the Euclidean distance between these two points and to determine whether the point represented by the second list is at an integer distance from the point represented by the first... | import math
def euclidean_distance(point1: list, point2: list) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
point1 (list): List containing two integers representing the first point.
point2 (list): List containing two integers representing the s... | from solution import euclidean_distance, is_integer_distance
def test_euclidean_distance():
# Test with standard points
assert math.isclose(euclidean_distance([0, 0], [3, 4]), 5.0, rel_tol=1e-9)
assert math.isclose(euclidean_distance([2, 3], [6, 8]), 6.403124, rel_tol=1e-6)
assert math.isclose(euclidea... | [
{
"docstring": "Calculate the Euclidean distance between two points in a 2D plane.\n\nArgs:\n point1 (list): List containing two integers representing the first point.\n point2 (list): List containing two integers representing the second point.\n\nReturns:\n float: Euclidean distance between the two po... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1: list, point2: list) -> float:\n \"\"\"\n Computes the Euclidean distance between two points in a 2D plane.\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043288",
"row_id": 43288,
"seed_ids": "[3575]"
} | 0.685685 | Algorithm_43288 | I | [
"euclidean_distance",
"is_integer_distance"
] | 2 | [
[
"is_integer_distance",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bac85ac017039dff9f485a993895df979481a5b9 | 851f2cef2d42ee512beceb509c774975f798ee0a | |||
v1.0 | instruct | Algorithm | Algorithm_43336_I | ### Coding Assessment Question
**Context:**
Imagine you are developing software for a logistics company. One of the key features required is to sort the list of delivery packages based on their weights. The company's warehouse management system would benefit from an efficient algorithm which sorts the weights using th... | from typing import List
def merge_sort_packages(packages: List[float]) -> List[float]:
if len(packages) <= 1:
return packages
mid = len(packages) // 2
left_half = merge_sort_packages(packages[:mid])
right_half = merge_sort_packages(packages[mid:])
return merge(left_half, right_hal... | from solution import merge_sort_packages
def test_merge_sort_packages_with_multiple_elements():
assert merge_sort_packages([5.5, 2.1, 9.8, 4.4, 1.0]) == [1.0, 2.1, 4.4, 5.5, 9.8]
assert merge_sort_packages([0.5, 2.1, 2.1, 4.4]) == [0.5, 2.1, 2.1, 4.4]
def test_merge_sort_packages_with_empty_list():
assert... | [
{
"docstring": null,
"function_declaration": "def merge_sort_packages(packages):",
"function_name": "merge_sort_packages",
"parameter_list": "(packages)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left,... | [
1,
1,
1,
0,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort_packages(packages: List[float]) -> List[float]:\n if len(packages) <= 1:\n return packages\n\n mid = len(p... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043336",
"row_id": 43336,
"seed_ids": "[3192]"
} | 0.536064 | Algorithm_43336 | I | [
"merge_sort_packages",
"merge"
] | 2 | [
[
"merge_sort_packages",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 974ae8e908704c267b23c9c66c6859bad2328f80 | 5650ff88c6063798b616c5ba956fcd6fbeee4a09 | |||
v1.0 | instruct | Algorithm | Algorithm_43340_I | ### Scenario:
You are developing a feature for a library management system that helps librarians quickly identify books based on their unique ISBN numbers. Your task is to implement an algorithm that efficiently checks if a given list of ISBN numbers exists within a sorted list of records. Since the ISBN list is sorted... | def binary_search(records, isbn):
left, right = 0, len(records) - 1
while left <= right:
mid = (left + right) // 2
if records[mid] == isbn:
return True
elif records[mid] < isbn:
left = mid + 1
else:
right = mid - 1
return False
def find_is... | from solution import find_isbns
def test_find_isbns_with_existing_isbns():
records = ["0000000000", "1234567890", "2345678901", "3456789012", "4567890123", "5678901234"]
isbns = ["1234567890", "3456789012", "9876543210"]
assert find_isbns(records, isbns) == [True, True, False]
def test_find_isbns_with_all... | [
{
"docstring": null,
"function_declaration": "def binary_search(records, isbn):",
"function_name": "binary_search",
"parameter_list": "(records, isbn)"
},
{
"docstring": "Takes a sorted list of records and a list of ISBNs, and returns a list of boolean values\nindicating if each ISBN in the ... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def binary_search(records, isbn):\n left, right = 0, len(records) - 1\n while left <= right:\n mid = (left + right) // 2\n if records[mid] ==... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043340",
"row_id": 43340,
"seed_ids": "[1198]"
} | 0.583581 | Algorithm_43340 | I | [
"binary_search",
"find_isbns"
] | 2 | [
[
"find_isbns",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 14ccaf12ff0d97ec6a858cbedc47eebf5b55b7b2 | 4bd474d1b65da61297dc36beec3a437e92a3582f | |||
v1.0 | instruct | Algorithm | Algorithm_43358_I | ### Base Conversion and Arithmetic Operations
In this problem, you are expected to implement functionality that allows converting numbers between different bases (2 through 16) and performing arithmetic operations (addition, subtraction, multiplication, and division) on numbers in these bases.
**Task**:
Write the fol... | def validate_base(base):
if base < 2 or base > 16:
raise ValueError("Invalid base. Base must be between 2 and 16 inclusive.")
def validate_number_for_base(number, base):
try:
int(number, base)
except ValueError:
raise ValueError("Invalid number for the specified base.")
def convert... | import pytest
from solution import convert_base, base_addition, base_subtraction, base_multiplication, base_division
def test_convert_base():
assert convert_base('1010', 2, 10) == '10'
assert convert_base('A', 16, 2) == '1010'
assert convert_base('0', 10, 2) == '0'
assert convert_base('10', 10, 2) == '... | [
{
"docstring": null,
"function_declaration": "def validate_base(base):",
"function_name": "validate_base",
"parameter_list": "(base)"
},
{
"docstring": null,
"function_declaration": "def validate_number_for_base(number, base):",
"function_name": "validate_number_for_base",
"param... | [
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": "def convert_base(number: str, from_base: int, to_base: int) -> str:\n if not (2 <= from_base <= 16) or not (2 <= to_base <= 16):\n raise ValueError(\"I... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043358",
"row_id": 43358,
"seed_ids": "[919]"
} | 0.695838 | Algorithm_43358 | I | [
"validate_base",
"validate_number_for_base",
"convert_base",
"base_addition",
"base_subtraction",
"base_multiplication",
"base_division"
] | 7 | [
[
"base_addition",
"convert_base"
],
[
"base_addition",
"validate_base"
],
[
"base_addition",
"validate_number_for_base"
],
[
"base_division",
"convert_base"
],
[
"base_division",
"validate_base"
],
[
"base_division",
"validate_number_for_base"
]... | 14 | [] | false | [] | false | pytest | true | [] | true | e7690605160fe84f2ed50eb123a02bf96ded1972 | 910a58ffb4db06e0a04133323127cc69064a5913 | |||
v1.0 | instruct | Algorithm | Algorithm_43412_I | ## Coding Assessment Question:
#### Context:
Circular primes are prime numbers that remain prime under all rotations of their digits. For instance, the digits of the number 197 can be rotated to form 971, and 719, all of which are prime numbers. Your task is to identify such circular primes up to a given limit.
#### ... | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i... | from solution import find_circular_primes
def test_find_circular_primes_100():
assert find_circular_primes(100) == [2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97]
def test_find_circular_primes_50():
assert find_circular_primes(50) == [2, 3, 5, 7, 11, 13, 17, 31, 37]
def test_find_circular_primes_1():
as... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Helper function to get all rotations of digits of a number.",
"function_declaration": "def get_rotations(n)... | [
1,
0,
0,
1,
0,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n retur... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000043412",
"row_id": 43412,
"seed_ids": "[3538]"
} | 0.617992 | Algorithm_43412 | 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 | 5ccaa886e36de1a50eabe6094b6e24d07ce14221 | 36ca5cf83f298362933f4dc36c2f71fe34da75cc | |||
v1.0 | instruct | Algorithm | Algorithm_43482_I | ### Sum of Primes in a Range
#### Context
In many applications, it's crucial to identify and work with prime numbers efficiently. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. For instance, the primes between 1 and 10 are 2, 3, 5, and 7. Given this context, you... | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
p = 3
while p * p <= n:
if n % p == 0:
return False
p += 2
return True
def sum_of_pr... | from solution import sum_of_primes
def test_sum_of_primes_range_10_20():
assert sum_of_primes(10, 20) == 60
def test_sum_of_primes_range_1_5():
assert sum_of_primes(1, 5) == 10
def test_sum_of_primes_single_prime():
assert sum_of_primes(13, 13) == 13
def test_sum_of_primes_no_primes():
assert sum_of... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers in the range [a, b].",
"function_declaration": "def sum_of_primes(a, b... | [
0,
1,
0,
1,
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 is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043482",
"row_id": 43482,
"seed_ids": "[2579]"
} | 0.628102 | Algorithm_43482 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30a8b4d52acafdbba83ae8c35fb2806935667c75 | b2996ddd2b28be8c1465aeecb2bd517f75c73874 | |||
v1.0 | instruct | Algorithm | Algorithm_43511_I | ### Question: Calculate the Next 10 Leap Years from a Given Year
#### Context:
A leap year in the Gregorian calendar is a year that is divisible by 4, except for years that are divisible by 100 but not by 400. For example, 1996 and 2000 are leap years, but 1900 and 2100 are not.
#### Task:
Implement a Python function... | def is_leap_year(year):
"""Check if a given year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def next_ten_leap_years(start_year):
"""
Returns a list of the next 10 leap years starting from the given year.
Parameters:
start_year (int): A four-digit year ... | from solution import next_ten_leap_years
def test_next_ten_leap_years_from_non_leap_year():
assert next_ten_leap_years(2021) == [2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060]
def test_next_ten_leap_years_from_leap_year():
assert next_ten_leap_years(2020) == [2020, 2024, 2028, 2032, 2036, 2040, 2... | [
{
"docstring": "Check if a given year is a leap year.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"docstring": "Returns a list of the next 10 leap years starting from the given year.\n\nParameters:\nstart_year (int): A... | [
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 next_ten_leap_years(start_year: int) -> list:\n \"\"\"\n Returns a list of the next 10 leap years from the given start year.\n \"\"\"\n def is_le... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043511",
"row_id": 43511,
"seed_ids": "[4398]"
} | 0.690293 | Algorithm_43511 | I | [
"is_leap_year",
"next_ten_leap_years"
] | 2 | [
[
"next_ten_leap_years",
"is_leap_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a67346aa06290fd999c889ba16401b2829efebed | 566ea5aaa3cbef9fee19780e84fff160052a91e4 | |||
v1.0 | instruct | Algorithm | Algorithm_43517_I | **Problem Statement**
Implement a function to determine if a given number is a Lychrel number. A Lychrel number is a natural number that cannot form a palindrome through the iterative process of repeatedly reversing its digits and adding the resulting numbers. For this task, assume that if a palindrome is not found wi... | def is_palindrome(number: int) -> bool:
"""
Checks if a number is a palindrome.
"""
return str(number) == str(number)[::-1]
def is_lychrel(number: int) -> bool:
"""
Determines if a number is a Lychrel number.
"""
for _ in range(50):
number = number + int(str(number)[::-1])
... | def test_is_lychrel_simple_non_lychrel():
assert is_lychrel(56) == False # 56 + 65 = 121 which is a palindrome
def test_is_lychrel_known_lychrel():
assert is_lychrel(196) == True # 196 is a known Lychrel number
def test_is_lychrel_palindrome_check():
assert is_lychrel(121) == False # 121 is already a p... | [
{
"docstring": "Checks if a number is a palindrome.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Determines if a number is a Lychrel number.",
"function_declaration": "def is_lychrel(number):",
... | [
0,
1,
0,
0,
0,
0,
0,
0,
1,
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 is_palindrome(n: int) -> bool:\n return str(n) == str(n)[::-1]\n\ndef reverse_and_add(n: int) -> int:\n return n + int(str(n)[::-1])\n\ndef is_lychrel(... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043517",
"row_id": 43517,
"seed_ids": "[422]"
} | 0.636492 | Algorithm_43517 | I | [
"is_palindrome",
"is_lychrel"
] | 2 | [
[
"is_lychrel",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f5a9ad169adec946a9e48b1766a7079284ba9de4 | 06015e850e7a92f2f246a340dc3ed978fc820627 | |||
v1.0 | instruct | Algorithm | Algorithm_43533_I | ### Problem Statement
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, the proper divisors of 6 are 1, 2, and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number.
Define a function `is_perfect_number(n: int) -> bool` that checks if a given positive integ... | def is_perfect_number(n: int) -> bool:
if n < 2:
return False
divisors_sum = 1
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
divisors_sum += i
if i != n // i:
divisors_sum += n // i
return divisors_sum == n
def count_perfect_number... | import pytest
from solution import is_perfect_number, count_perfect_numbers_in_range
def test_is_perfect_number():
assert is_perfect_number(6) == True
assert is_perfect_number(28) == True
assert is_perfect_number(12) == False
assert is_perfect_number(1) == False
assert is_perfect_number(496) == Tru... | [
{
"docstring": null,
"function_declaration": "def is_perfect_number(n):",
"function_name": "is_perfect_number",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_perfect_numbers_in_range(lower, upper):",
"function_name": "count_perfect_numbers_in_rang... | [
1,
0,
1,
1,
0,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_perfect_number(n: int) -> bool:\n \"\"\"\n Determine if n is a perfect number.\n \"\"\"\n if n <= 1:\n return False\n\n sum_divisors... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043533",
"row_id": 43533,
"seed_ids": "[2422]"
} | 0.649429 | Algorithm_43533 | I | [
"is_perfect_number",
"count_perfect_numbers_in_range"
] | 2 | [
[
"count_perfect_numbers_in_range",
"is_perfect_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71ef4dca80514a04f46ef2a6fc0cf45de7aa8e2f | ffcdce9048f6425d36b751632f4d46037d084dec | |||
v1.0 | instruct | Algorithm | Algorithm_43542_I | ### Maximum Rectangle Sum in a Matrix
**Context**:
Given a 2D matrix of integers, you are required to find the submatrix (contiguous rectangular area) within this 2D matrix which has the largest sum. This problem is critical for applications in image processing and dynamic programming optimization.
**Objective**:
Fin... | from typing import List
def max_rectangle_sum(matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
max_sum = float('-inf')
for left in range(cols):
temp = [0] * rows
for right in range(left, cols):
for r... | from solution import max_rectangle_sum
def test_example_1():
matrix = [
[1, 2, -1, -4, -20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]
]
assert max_rectangle_sum(matrix) == 29
def test_example_2():
matrix = [
[1, 2, 3],
[4, 5, 6],
... | [
{
"docstring": null,
"function_declaration": "def max_rectangle_sum(matrix):",
"function_name": "max_rectangle_sum",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def kadane(arr):",
"function_name": "kadane",
"parameter_list": "(arr)"
}
] | [
1,
1,
1,
0,
1,
0,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_rectangle_sum(matrix: List[List[int]]) -> int:\n if not matrix or not matrix[0]:\n return 0\n \n rows, cols = ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043542",
"row_id": 43542,
"seed_ids": "[3218]"
} | 0.71089 | Algorithm_43542 | I | [
"max_rectangle_sum",
"kadane"
] | 2 | [
[
"max_rectangle_sum",
"kadane"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e23f0eb96f3839029c7eb6315e2e484ea870e5f2 | 65fd124da21e5a3306caaddd348ade2ee8134920 | |||
v1.0 | instruct | Algorithm | Algorithm_43613_I | ### Problem Statement
You are tasked with implementing a basic version of the K-Means clustering algorithm to classify a set of data points into `k` clusters.
### Function to Implement
Implement the function `k_means_clustering(data_points: List[List[float]], k: int, max_epochs: int) -> Tuple[List[List[float]], List... | import random
import math
from typing import List, Tuple
def euclidean_distance(point1: List[float], point2: List[float]) -> float:
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def k_means_clustering(data_points: List[List[float]], k: int, max_epochs: int) -> Tuple[List[List[float]], List[i... | from solution import k_means_clustering
def test_basic_case():
data_points = [[1.0, 2.0], [3.0, 4.0], [1.0, 0.0], [4.0, 2.0], [3.5, 3.5]]
centroids, assignments = k_means_clustering(data_points, 2, 5)
assert len(centroids) == 2
assert len(assignments) == 5
def test_single_point():
data_point ... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def k_means_clustering(data_points, k, max_epochs):",
"function_name": ... | [
1,
1,
1,
1,
0,
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 random\nfrom typing import List, Tuple\nimport math\n\ndef k_means_clustering(data_points: List[List[float]], k: int, max_epochs: int) -> Tuple[List[List[... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043613",
"row_id": 43613,
"seed_ids": "[439]"
} | 0.754348 | Algorithm_43613 | I | [
"euclidean_distance",
"k_means_clustering"
] | 2 | [
[
"k_means_clustering",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0fbc051173045f952ac47ce5bb489df02b14285 | 59eb4a41b32d5f54d8bc83a57318756d5d223bb4 | |||
v1.0 | instruct | Algorithm | Algorithm_43699_I | ### Coding Assessment Question
#### Scenario
You are developing a route calculator for a delivery company that operates in a grid-based city. Your task is to find the shortest path from the starting warehouse to the target delivery destination using the A* (A-star) search algorithm.
#### Function to Implement
Impleme... | import heapq
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star_search(grid, start, goal):
rows, cols = len(grid), len(grid[0])
open_set = []
heapq.heappush(open_set, (0, start))
came_from = {}
g_score = {start: 0}
f_score = {start: heuristic(start, goal)}
... | from solution import a_star_search
def test_a_star_no_obstacles():
grid = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
start = (0, 0)
goal = (2, 2)
assert a_star_search(grid, start, goal) == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
def test_a_star_with_obstacles():
grid = [
... | [
{
"docstring": null,
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def a_star_search(grid, start, goal):",
"function_name": "a_star_search",
"parameter_list": "(grid, start... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef heuristic(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\ndef a_star_search(grid, start, goal):\n rows, cols = len(grid), len(gr... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000043699",
"row_id": 43699,
"seed_ids": "[4452]"
} | 0.665367 | Algorithm_43699 | I | [
"heuristic",
"a_star_search"
] | 2 | [
[
"a_star_search",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a6409df9a51854df4bba269af1ed348fd30af3b9 | a3977b58e59b89d875614782e2ab25f2f3937a72 | |||
v1.0 | instruct | Algorithm | Algorithm_43742_I | ### Context
You are provided with a set of images and a target image. Your task is to implement an image search algorithm that identifies the closest matching image from the set, based on pixel intensity differences. You need to write functions to calculate the difference between two images and find the most similar on... | def calculate_difference(image1, image2):
"""
Calculate the total absolute pixel intensity difference between two images.
Args:
image1 (list of list of int): The first image.
image2 (list of list of int): The second image.
Returns:
int: The total absolute pixel intensity difference... | from solution import calculate_difference, find_closest_image
def test_calculate_difference():
img1 = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
img2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
assert calculate_difference(img1, img2) == 36
img1 = [[100, 200, 150], [100, 50, 75]]
img2 = [[100, 200, 150], [100, 50, ... | [
{
"docstring": "Calculate the total absolute pixel intensity difference between two images.\n\nArgs:\nimage1 (list of list of int): The first image.\nimage2 (list of list of int): The second image.\n\nReturns:\nint: The total absolute pixel intensity difference.",
"function_declaration": "def calculate_diff... | [
0,
0,
1,
1,
1,
0,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate_difference(image1, image2):\n \"\"\"\n Calculate the total absolute pixel intensity difference between two images.\n \n Args:\n imag... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043742",
"row_id": 43742,
"seed_ids": "[467]"
} | 0.588464 | Algorithm_43742 | I | [
"calculate_difference",
"find_closest_image"
] | 2 | [
[
"find_closest_image",
"calculate_difference"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c2364f82129dabb102a877f21063e298789eca00 | 00caa8c43da055630e1217c362f903d1d48725a4 | |||
v1.0 | instruct | Algorithm | Algorithm_43756_I | ### Sorting Algorithms Performance Comparison
#### Scenario:
You are a software engineer at a tech company that needs to analyze and compare the performance of various sorting algorithms. Your team has decided to implement three different sorting algorithms and measure their execution times on a variety of datasets. T... | import time
def bubble_sort(arr):
"""
Returns a sorted list using the Bubble Sort algorithm.
"""
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def merge_sort(arr):
"""
... | from solution import bubble_sort, merge_sort, quick_sort, performance_comparison
def test_bubble_sort():
assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
assert bubble_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2... | [
{
"docstring": "Returns a sorted list using the Bubble Sort algorithm.",
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Returns a sorted list using the Merge Sort algorithm.",
"function_declaration": "def merg... | [
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 time\n\ndef bubble_sort(arr):\n \"\"\"\n Sorts the input list using the Bubble Sort algorithm.\n \n Parameters:\n arr (list of int): An... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043756",
"row_id": 43756,
"seed_ids": "[1849]"
} | 0.499289 | Algorithm_43756 | I | [
"bubble_sort",
"merge_sort",
"quick_sort",
"performance_comparison"
] | 4 | [
[
"performance_comparison",
"bubble_sort"
],
[
"performance_comparison",
"merge_sort"
],
[
"performance_comparison",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4e7823a7a26417728b9ca5cd6103dd644b9ee802 | 9b7e5a4a79d9a4aac253e810511596edddb88ef5 | |||
v1.0 | instruct | Algorithm | Algorithm_43780_I | ### Challenging Coding Assessment Question
#### Context
Sorting algorithms are a fundamental concept in computer science, vital for efficient data manipulation and processing. Understanding and implementing various sorting techniques forms a core part of algorithmic proficiency.
#### Task
Implement a function `merg... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
# Find the middle point to divide the array into two halves
mid = len(arr) // 2
# Call merge_sort recursively on the two halves
left_half = merge_sort(arr[:mid])
right_half = merg... | 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, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5,... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000043780",
"row_id": 43780,
"seed_ids": "[2816]"
} | 0.583638 | Algorithm_43780 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b39f1e5f9a780e52a246660d215c16c444445c8 | 8fc225bc5242e8326362da261d750317b4f21b1e | |||
v1.0 | instruct | Algorithm | Algorithm_43825_I | ### Problem Statement:
You are given a list of words and a pattern. Each word in the list of words must match the specified pattern. A word matches the pattern if there is a bijection between letters in the pattern and letters in the word (i.e., a one-to-one correspondence).
Write a function to find all words in the l... | def matches(word, pattern):
if len(word) != len(pattern):
return False
w_to_p, p_to_w = {}, {}
for w, p in zip(word, pattern):
if w in w_to_p and w_to_p[w] != p:
return False
if p in p_to_w and p_to_w[p] != w:
return False
w_to_p[w] = p
p... | from solution import find_and_replace_pattern
def test_example_case_1():
words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"]
pattern = "abb"
assert find_and_replace_pattern(words, pattern) == ["mee", "aqq"]
def test_example_case_2():
words = ["a", "b", "c"]
pattern = "a"
assert find_and_replace... | [
{
"docstring": null,
"function_declaration": "def matches(word, pattern):",
"function_name": "matches",
"parameter_list": "(word, pattern)"
},
{
"docstring": "Returns a list of words that match the given pattern",
"function_declaration": "def find_and_replace_pattern(words, pattern):",
... | [
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 matches(word, pattern):\n if len(word) != len(pattern):\n return False\n\n w_to_p, p_to_w = {}, {}\n \n for w, p in zip(word, pattern):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000043825",
"row_id": 43825,
"seed_ids": "[1753]"
} | 0.666807 | Algorithm_43825 | I | [
"matches",
"find_and_replace_pattern"
] | 2 | [
[
"find_and_replace_pattern",
"matches"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c4227d7c5f807827e5faab5152f772a4b411c8ae | d33cb767a3a2c3434fc44d74fd5060e8bf37c756 | |||
v1.0 | instruct | Algorithm | Algorithm_43828_I | ### Question: Forest Coverage Calculation
You are working as an environmental data analyst tasked with assessing the changes in forest cover over an array of land parcels. Each parcel may either be forested or non-forested. You need to implement functionality that calculates the percentage change in forested parcels o... | def calculate_forest_coverage(parcels: list[bool]) -> float:
"""
Calculate the percentage of land parcels that are forested.
Args:
parcels: A list of booleans where True represents a forested parcel and False represents a non-forested parcel.
Returns:
A float representing the percentag... | from solution import calculate_forest_coverage, forest_coverage_change
def test_calculate_forest_coverage():
assert calculate_forest_coverage([True, False, True, True, False]) == 60.0
assert calculate_forest_coverage([False, False, False, False]) == 0.0
assert calculate_forest_coverage([True, True, True, T... | [
{
"docstring": "Calculate the percentage of land parcels that are forested.\n\nArgs:\nparcels: A list of booleans where True represents a forested parcel and False represents a non-forested parcel.\n\nReturns:\nA float representing the percentage of forested land parcels.",
"function_declaration": "def calc... | [
0,
1,
0,
0,
1,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate_forest_coverage(parcels):\n \"\"\"\n Returns the percentage of land parcels that are forested.\n \n Parameters:\n parcels (list of b... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000043828",
"row_id": 43828,
"seed_ids": "[736]"
} | 0.510874 | Algorithm_43828 | I | [
"calculate_forest_coverage",
"forest_coverage_change"
] | 2 | [
[
"forest_coverage_change",
"calculate_forest_coverage"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 114a5ac30cb8133b634b5732a4202c4bbe81a857 | 48c8ff43cdaa3119d20cd6ede39c064f3600d937 | |||
v1.0 | instruct | Algorithm | Algorithm_43857_I | ### Problem Statement:
You are required to implement a nearest neighbor search algorithm for finding the closest points to a given query point from a set of points in a 2-D plane. The challenge is to implement the following functionalities:
1. **Distance Calculation**: Write a function to compute the Euclidean distanc... | from typing import List, Tuple
import heapq
import math
def euclidean_distance(a: Tuple[int, int], b: Tuple[int, int]) -> float:
"""
Computes the Euclidean distance between two points a and b.
"""
return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
class Node:
def __init__(self, point: Tuple... | from solution import euclidean_distance, build_kd_tree, find_nearest_neighbor
def test_euclidean_distance():
assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5.0)
assert math.isclose(euclidean_distance((1, 2), (4, 6)), 5.0)
assert math.isclose(euclidean_distance((1, 1), (1, 1)), 0.0)
def test_neare... | [] | [
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": "from typing import List, Tuple, Optional\nimport math\n\ndef euclidean_distance(a: Tuple[int, int], b: Tuple[int, int]) -> float:\n \"\"\"\n Calculate the ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000043857",
"row_id": 43857,
"seed_ids": "[3264]"
} | 0.703167 | Algorithm_43857 | I | [
"euclidean_distance",
"build_kd_tree",
"find_nearest_neighbor"
] | 3 | [
[
"find_nearest_neighbor",
"euclidean_distance"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | ea10dd6b178016b2b014fe24d8c47a1ee9548fc7 | 7ca598bf01464eee858fd160306df96f9426eca6 | |||
v1.0 | instruct | Algorithm | Algorithm_43900_I | ### Programming Assessment Question
#### Context
Working with strings is a fundamental skill in programming. Understanding how to manipulate and analyze strings is crucial. In this task, you will build a function that helps detect palindromes under certain constraints.
#### Task
**Objective:** Write a function that c... | def is_palindrome(substring: str) -> bool:
"""
Checks if the given substring is a palindrome.
"""
return substring == substring[::-1]
def check_substrings_are_palindromes(s: str, substr1_start: int, substr1_end: int, substr2_start: int, substr2_end: int) -> bool:
"""
Checks if the substrings of... | def test_check_substrings_are_palindromes():
assert check_substrings_are_palindromes("madamracecar", 0, 4, 6, 11) == False
assert check_substrings_are_palindromes("aabbaa", 0, 2, 3, 5) == False
assert check_substrings_are_palindromes("abcdedcba", 1, 3, 5, 7) == False
assert check_substrings_are_palindro... | [
{
"docstring": "Checks if the given substring is a palindrome.",
"function_declaration": "def is_palindrome(substring):",
"function_name": "is_palindrome",
"parameter_list": "(substring)"
},
{
"docstring": "Checks if the substrings of s from substr1_start to substr1_end and from substr2_star... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def check_substrings_are_palindromes(s: str, substr1_start: int, substr1_end: int, substr2_start: int, substr2_end: int) -> bool:\n def is_palindrome(substrin... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000043900",
"row_id": 43900,
"seed_ids": "[4838]"
} | 0.776422 | Algorithm_43900 | I | [
"is_palindrome",
"check_substrings_are_palindromes"
] | 2 | [
[
"check_substrings_are_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 58e1c558e3494a533ff1f58c3475959395d8db26 | e8486b4514da12337a1a06f0d10a537c653a0116 | |||
v1.0 | instruct | Algorithm | Algorithm_43975_I | ### Coding Assessment Question
**Problem Statement:**
You are given a library for working with basic polynomial arithmetic. The library includes methods for adding, subtracting, multiplying, and evaluating polynomials. A polynomial is represented as a list of coefficients, starting with the constant term.
**Objective... | from typing import List, Tuple, Union
def add_polynomials(poly1, poly2):
result = [0] * max(len(poly1), len(poly2))
for i in range(len(poly1)):
result[i] += poly1[i]
for i in range(len(poly2)):
result[i] += poly2[i]
return result
def subtract_polynomials(poly1, poly2):
result = [0]... | from solution import perform_polynomial_operations
def test_add_polynomials():
operations = [("add", [[1, 2, 3], [4, 0, 5]])]
result = perform_polynomial_operations(operations)
assert result == [[5, 2, 8]]
def test_subtract_polynomials():
operations = [("subtract", [[7, 2], [5, 1, 1]])]
result = p... | [
{
"docstring": null,
"function_declaration": "def add_polynomials(poly1, poly2):",
"function_name": "add_polynomials",
"parameter_list": "(poly1, poly2)"
},
{
"docstring": null,
"function_declaration": "def subtract_polynomials(poly1, poly2):",
"function_name": "subtract_polynomials"... | [
0,
1,
0,
0,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple, Union\n\ndef add_polynomials(p1: List[int], p2: List[int]) -> List[int]:\n length = max(len(p1), len(p2))\n result = [0] * ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000043975",
"row_id": 43975,
"seed_ids": "[216]"
} | 0.657947 | Algorithm_43975 | I | [
"add_polynomials",
"subtract_polynomials",
"multiply_polynomials",
"evaluate_polynomial",
"perform_polynomial_operations"
] | 5 | [
[
"perform_polynomial_operations",
"add_polynomials"
],
[
"perform_polynomial_operations",
"evaluate_polynomial"
],
[
"perform_polynomial_operations",
"multiply_polynomials"
],
[
"perform_polynomial_operations",
"subtract_polynomials"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | bea34e0e4ae8256af738c901c66aed22d85de05a | 962fe34d5845fb32d8480ddabce8d6a272ea50d8 | |||
v1.0 | instruct | Algorithm | Algorithm_43989_I | Matrix Multiplication and Transposition
You are provided with a function to multiply two matrices and return the result. Your task is to extend the functionality of this function by adding another feature: computing the transpose of the resultant matrix after the multiplication.
### Instructions:
1. Implement a funct... | import numpy as np
def matrix_multiplication(matrix_a, matrix_b):
"""
Multiplies two matrices and returns the result.
"""
if matrix_a.shape[1] != matrix_b.shape[0]:
raise ValueError("Incompatible dimensions for matrix multiplication")
return np.dot(matrix_a, matrix_b)
def transpose_matrix(... | import numpy as np
from solution import matrix_multiplication, transpose_matrix, matrix_multiplication_with_transpose
def test_matrix_multiplication():
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
expected = np.array([[19, 22], [43, 50]])
assert np.array_equal(matrix_mult... | [
{
"docstring": "Multiplies two matrices and returns the result.",
"function_declaration": "def matrix_multiplication(matrix_a, matrix_b):",
"function_name": "matrix_multiplication",
"parameter_list": "(matrix_a, matrix_b)"
},
{
"docstring": "Computes and returns the transpose of a matrix.",
... | [
0,
0,
1,
0,
0,
1,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef matrix_multiplication(matrix_a: np.ndarray, matrix_b: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the product of two matrices.\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000043989",
"row_id": 43989,
"seed_ids": "[601]"
} | 0.625964 | Algorithm_43989 | I | [
"matrix_multiplication",
"transpose_matrix",
"matrix_multiplication_with_transpose"
] | 3 | [
[
"matrix_multiplication_with_transpose",
"matrix_multiplication"
],
[
"matrix_multiplication_with_transpose",
"transpose_matrix"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 0b075b2da024a052964abec4fce4112ac217fb50 | d2d7dbe2ed60a34e4f0a048ece2b8412a7356ae8 | |||
v1.0 | instruct | Algorithm | Algorithm_44070_I | ### Matrix Rotation Check
#### Problem Statement
You are given two n x n matrices. Write a function to determine if one matrix is a rotation of the other. Two matrices are said to be rotations of each other if we can obtain one matrix by rotating the other matrix 90 degrees clockwise any number of times (including zer... | from typing import List
def rotate_matrix_90_clockwise(matrix: List[List[int]]) -> List[List[int]]:
""" Rotates a given NxN matrix 90 degrees clockwise. """
n = len(matrix)
rotated = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
rotated[j][n - 1 - i] = matrix[i][... | from solution import are_rotations
def test_rotation_90_degrees():
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
assert are_rotations(matrix1, matrix2)
def test_rotation_180_degrees():
matrix1 = [
... | [
{
"docstring": "Rotates a given NxN matrix 90 degrees clockwise. ",
"function_declaration": "def rotate_matrix_90_clockwise(matrix):",
"function_name": "rotate_matrix_90_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": "Check if matrix2 is a rotation of matrix1. ",
"function_de... | [
0,
0,
1,
0,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_90(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotate a matrix 90 degrees clockwise.\n \"\"\"\n n =... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000044070",
"row_id": 44070,
"seed_ids": "[4578]"
} | 0.493891 | Algorithm_44070 | I | [
"rotate_matrix_90_clockwise",
"are_rotations"
] | 2 | [
[
"are_rotations",
"rotate_matrix_90_clockwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f9145e81c1805b90c0821840c2adaf92e40dcdb0 | 010139aea48d4552c4202cf3b0915aff1e611e75 | |||
v1.0 | instruct | Algorithm | Algorithm_44121_I | ### Coding Assessment Question
#### Scenario:
Your task is to develop a utility function for monitoring a network by checking the IP addresses that are currently active. For simplicity, we'll use IPv4 addresses, and you need to identify and return the active IP addresses in a sorted order.
#### Task:
Write a Python f... | from typing import List
import re
def validate_ip(ip: str) -> bool:
"""
Validate an IP address to ensure it follows a valid IPv4 format.
"""
pattern = re.compile(
r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}'
r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
)
return pattern.match(... | import pytest
from solution import get_active_ips
def test_single_active_ip():
logs = ["192.168.0.1 - ACTIVE", "192.168.0.2 - INACTIVE", "192.168.0.1 - ACTIVE"]
assert get_active_ips(logs) == ["192.168.0.1"]
def test_multiple_active_ips():
logs = ["10.0.0.1 - ACTIVE", "192.168.1.1 - ACTIVE",
... | [
{
"docstring": "Validate an IP address to ensure it follows a valid IPv4 format.",
"function_declaration": "def validate_ip(ip):",
"function_name": "validate_ip",
"parameter_list": "(ip)"
},
{
"docstring": "Returns a sorted list of unique IP addresses that have a status of \"ACTIVE\".",
... | [
1,
1,
0,
0,
0,
0,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_active_ips(logs: List[str]) -> List[str]:\n \"\"\"\n Extracts unique active IP addresses from the log entries and return... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000044121",
"row_id": 44121,
"seed_ids": "[5249]"
} | 0.651329 | Algorithm_44121 | I | [
"validate_ip",
"get_active_ips"
] | 2 | [
[
"get_active_ips",
"validate_ip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f454faa9a23ee959c55409a12b4e30e8d818d9bc | a77cab97cddf8ec2512162abe10cca696ff41f0c | |||
v1.0 | instruct | Algorithm | Algorithm_44125_I | ### Sum of Unique Primes
#### Problem Statement:
Given an array of integers, determine the sum of all unique prime numbers present in the array. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to implement a function that takes an array of integers... | from math import isqrt
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def sum_of_unique_prim... | from solution import sum_of_unique_primes, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(25) == False
assert is_prime(29) == True
def test_sum_of_unique_primes():
assert sum_of_uniq... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of all unique prime numbers in the given array.\n\n:param arr: list: the list of integers to check\n:return: int: sum of unique prime num... | [
0,
0,
1,
1,
1,
0,
0,
1,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import isqrt\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000044125",
"row_id": 44125,
"seed_ids": "[3456]"
} | 0.640644 | Algorithm_44125 | I | [
"is_prime",
"sum_of_unique_primes"
] | 2 | [
[
"sum_of_unique_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aac678c3a10a2fc51dbfdf35598f87f9469f0ef1 | 34edd5d4b36363ce7132ce86c99cd3ec7b777832 | |||
v1.0 | instruct | Algorithm | Algorithm_44177_I | ### Coding Assessment Question
#### Scenario: Distributed Matrix Multiplication
You are implementing a distributed computing system where large matrix multiplications are offloaded to a cluster of machines. Your task is to design a distributed matrix multiplication algorithm that divides the workload among multiple n... | from typing import List
from multiprocessing import Pool
def single_element_multiplication(args):
A, B, i, j = args
return sum(A[i][k] * B[k][j] for k in range(len(B)))
def distributed_matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
if not A or not B or len(A[0]) != len(B... | from solution import distributed_matrix_multiplication
def test_distributed_matrix_multiplication_basic():
A = [
[1, 2],
[3, 4]
]
B = [
[5, 6],
[7, 8]
]
result = distributed_matrix_multiplication(A, B)
expected = [
[19, 22],
[43, 50]
]
ass... | [
{
"docstring": null,
"function_declaration": "def single_element_multiplication(args):",
"function_name": "single_element_multiplication",
"parameter_list": "(args)"
},
{
"docstring": null,
"function_declaration": "def distributed_matrix_multiplication(A, B):",
"function_name": "dist... | [
1,
1,
0,
1,
0,
0,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom multiprocessing import Pool\n\ndef single_element_multiplication(args):\n A, B, i, j = args\n return sum(A[i][k] * B[k][j] fo... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000044177",
"row_id": 44177,
"seed_ids": "[898]"
} | 0.531907 | Algorithm_44177 | I | [
"single_element_multiplication",
"distributed_matrix_multiplication"
] | 2 | [
[
"distributed_matrix_multiplication",
"single_element_multiplication"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c2c45d2546412e6dbed68f8f6e4512ff7c2fd04f | beba9ab780d8494efad2d119553d9e880f633d45 | |||
v1.0 | instruct | Algorithm | Algorithm_44179_I | ### Coding Assessment: Implementing K-Means Clustering
**Objective**: Implement the K-Means Clustering algorithm to group a set of instances into clusters. You will use the provided utility functions as a reference to create new components to demonstrate your understanding.
### Problem Statement
Given a series of ste... | import random
from typing import List, Dict
def euclidean_distance(point1: List[float], point2: List[float]) -> float:
return sum((x - y) ** 2 for x, y in zip(point1, point2)) ** 0.5
def fit_kmeans_model(data: List[List[float]], k: int) -> Dict[int, List[float]]:
# Randomly initialize the centroids
centro... | from solution import fit_kmeans_model, assign_clusters, calculate_wcss
data = [
[1.0, 2.0],
[1.5, 1.8],
[5.0, 8.0],
[6.0, 9.0],
]
def test_fit_kmeans_model():
centroids = fit_kmeans_model(data, 2)
assert len(centroids) == 2
def test_assign_clusters():
centroids = fit_kmeans_model(data, 2)... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def fit_kmeans_model(data, k):",
"function_name": "fit_kmeans_model",
... | [
1,
0,
0,
1,
0,
1,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\n\ndef fit_kmeans_model(data, k):\n \"\"\"\n Fit the K-Means model to the data and return the centroids.\n \"\"\"\n # Rand... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000044179",
"row_id": 44179,
"seed_ids": "[468]"
} | 0.771258 | Algorithm_44179 | I | [
"euclidean_distance",
"fit_kmeans_model",
"assign_clusters",
"calculate_wcss"
] | 4 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"calculate_wcss",
"euclidean_distance"
],
[
"fit_kmeans_model",
"euclidean_distance"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 18d3cfe9a22ab77d80405426e1d320b0905cec8e | 441245334d1e4a5dcc4d27af8b473a31bfa78fe6 | |||
v1.0 | instruct | Algorithm | Algorithm_44215_I | ### AVL Tree Insertion and Balancing
You are required to implement an AVL Tree from scratch and perform insertion operations that maintain the height-balanced property. An AVL Tree is a self-balancing binary search tree where the difference between the heights of left and right subtrees cannot be more than one for all... | class AVLNode:
def __init__(self, value: int, left: 'AVLNode' = None, right: 'AVLNode' = None, height: int = 1):
self.value = value
self.left = left
self.right = right
self.height = height
def insert(node: AVLNode, key: int) -> AVLNode:
# Base case: If the tree is empty, return... | import pytest
def test_insert():
root = None
values = [10, 20, 30, 40, 50, 25]
for value in values:
root = insert(root, value)
# Check if the root is balanced
assert get_balance(root) in [-1, 0, 1]
# Check specific structure properties of the balanced AVL Tree
# Root should be 30 ... | [] | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class AVLNode:\n def __init__(self, value, left=None, right=None, height=1):\n self.value = value\n self.left = left\n self.right = right... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000044215",
"row_id": 44215,
"seed_ids": "[1741]"
} | 0.528908 | Algorithm_44215 | I | [
"insert",
"get_height",
"get_balance",
"right_rotate",
"left_rotate"
] | 5 | [
[
"get_balance",
"get_height"
],
[
"insert",
"get_balance"
],
[
"insert",
"get_height"
],
[
"insert",
"left_rotate"
],
[
"insert",
"right_rotate"
],
[
"left_rotate",
"get_height"
],
[
"right_rotate",
"get_height"
]
] | 7 | [] | false | [
"AVLNode"
] | true | pytest | false | [] | true | 9826964c94cc67aeab1c31173339d4ae5e9e0bf9 | 9fe2cea5d3a2c8ba3ea6c51e2236bc7c41115a80 | |||
v1.0 | instruct | Algorithm | Algorithm_44261_I | ### Coding Assessment Question
You have been provided with a Python script that processes a large CSV file containing sales data. The script currently reads the entire file into memory, which is inefficient for very large files. Your objective is to refactor the script to handle large files efficiently, incorporating ... | import csv
import logging
def process_large_csv_file(file_path: str, batch_size: int = 1000, stop_on_error: bool = False) -> int:
"""
Processes a large CSV file in a memory-efficient way using streaming and batching.
Args:
file_path (str): Path to the CSV file.
batch_size (int): Number of rows... | import pytest
from solution import process_large_csv_file
def create_test_csv_file(file_path, rows):
with open(file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["id", "name", "price"])
writer.writerows(rows)
def test_process_large_csv_file_correct_rows():... | [
{
"docstring": "Processes a large CSV file in a memory-efficient way using streaming and batching.\n\nArgs:\nfile_path (str): Path to the CSV file.\nbatch_size (int): Number of rows to process in each batch.\nstop_on_error (bool): Whether to stop processing on encountering a critical error.\n\nReturns:\nint: Th... | [
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 csv\nimport logging\n\ndef process_large_csv_file(\n file_path: str,\n batch_size: int = 1000,\n stop_on_error: bool = False\n) -> int:\n \"\"... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000044261",
"row_id": 44261,
"seed_ids": "[2027]"
} | 0.586656 | Algorithm_44261 | I | [
"process_large_csv_file",
"process_batch"
] | 2 | [
[
"process_large_csv_file",
"process_batch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d9621c1b722a38c8b89194207ece4d2ace315aac | 24411ebe9b1f813afbcb56f926668af8c475db88 | |||
v1.0 | instruct | Algorithm | Algorithm_44294_I | ### Neural Network Backpropagation Implementation
You are required to implement a simple feedforward neural network from scratch and perform backpropagation to train the network. Implement the following functions:
1. **initialize_weights** - To initialize the weight matrices for the network.
2. **feedforward** - To c... | import numpy as np
def initialize_weights(input_size: int, hidden_size: int, output_size: int) -> tuple:
"""
Initialize weight matrices for a neural network with one hidden layer.
"""
np.random.seed(42) # For reproducibility
w1 = np.random.randn(input_size, hidden_size) * 0.01
w2 = np.random.r... | from solution import initialize_weights, feedforward, backpropagation, train_network
def test_initialize_weights():
input_size, hidden_size, output_size = 2, 3, 1
w1, w2 = initialize_weights(input_size, hidden_size, output_size)
assert w1.shape == (2, 3)
assert w2.shape == (3, 1)
def test_feedforward(... | [
{
"docstring": "Initialize weight matrices for a neural network with one hidden layer.",
"function_declaration": "def initialize_weights(input_size, hidden_size, output_size):",
"function_name": "initialize_weights",
"parameter_list": "(input_size, hidden_size, output_size)"
},
{
"docstring"... | [
1,
0,
0,
0,
1,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\ndef initialize_weights(input_size... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000044294",
"row_id": 44294,
"seed_ids": "[699]"
} | 0.592299 | Algorithm_44294 | I | [
"initialize_weights",
"sigmoid",
"sigmoid_derivative",
"feedforward",
"backpropagation",
"train_network"
] | 6 | [
[
"backpropagation",
"sigmoid"
],
[
"backpropagation",
"sigmoid_derivative"
],
[
"feedforward",
"sigmoid"
],
[
"sigmoid_derivative",
"sigmoid"
],
[
"train_network",
"backpropagation"
],
[
"train_network",
"initialize_weights"
]
] | 6 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | cf2b69ea2abe4fcb73407f9f7f7ba7d008c23128 | 961f451bd7062efa223ed8b825a11e6e4763ce6f | |||
v1.0 | instruct | Algorithm | Algorithm_44330_I | ### Text File Analysis and Summary
**Context**:
You are provided with a large text file containing an extensive collection of news articles. Your task is to analyze the file to determine several key statistical metrics about the content within the articles.
### Task:
1. **Read and Process**: Write a function to read ... | import os
from collections import Counter
def read_text_file(file_path):
"""Read the content of the text file and return it as a string."""
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
def process_text(content):
"""Process the text content and retur... | import pytest
from solution import read_text_file, process_text, get_text_statistics, print_statistics
def test_read_text_file(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("This is a test file.\nWith some sample text.", encoding='utf-8')
content = read_text_file(test_file)
assert ... | [
{
"docstring": "Read the content of the text file and return it as a string.",
"function_declaration": "def read_text_file(file_path):",
"function_name": "read_text_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Process the text content and return a list of words.",
"function_... | [
1,
0,
1,
1,
1,
1,
0,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nfrom collections import Counter\n\ndef read_text_file(file_path):\n \"\"\"Read the content of the text file and return it as a string.\"\"\"\n w... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000044330",
"row_id": 44330,
"seed_ids": "[786]"
} | 0.710631 | Algorithm_44330 | I | [
"read_text_file",
"process_text",
"get_text_statistics",
"print_statistics",
"analyze_text_file"
] | 5 | [
[
"analyze_text_file",
"get_text_statistics"
],
[
"analyze_text_file",
"print_statistics"
],
[
"analyze_text_file",
"process_text"
],
[
"analyze_text_file",
"read_text_file"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 64f39bc6760fe5df75ca3c6f4d9849e054c016f0 | 4cf27807f234b72080eeb733a6de73e4a689a2da | |||
v1.0 | instruct | Algorithm | Algorithm_44364_I | ### Problem Statement
You are tasked with implementing a system that detects and corrects spelling errors in a given text. The system will use a dictionary of known words to identify misspelled words and suggest possible corrections based on edit distance. The edit distance is defined as the minimum number of operatio... | def edit_distance(word1, word2):
"""
Calculate the edit distance between two words.
"""
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for i in range(len(word1) + 1):
for j in range(len(word2) + 1):
if i == 0:
dp[i][j] = j
elif j == ... | from solution import correct_spelling
def test_correct_spelling_basic():
text = "the quikc bron fox jmps ovr the lazi dog"
dictionary = {"the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog"}
expected = "the quick brown fox jumps over the lazy dog"
assert correct_spelling(text, dictionary) == ... | [
{
"docstring": "Calculate the edit distance between two words.",
"function_declaration": "def edit_distance(word1, word2):",
"function_name": "edit_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Correct the spelling errors in the text using the provided dictionary.",
"f... | [
1,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def edit_distance(word1, word2):\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n \n for i in range(m + 1):\n fo... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000044364",
"row_id": 44364,
"seed_ids": "[610]"
} | 0.584402 | Algorithm_44364 | I | [
"edit_distance",
"correct_spelling"
] | 2 | [
[
"correct_spelling",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e9ff7855eaab7a1b6213bd1f00fc612d37281875 | 7e8c130180120cbcdd2f03476954c0cc3a0e31e3 | |||
v1.0 | instruct | Algorithm | Algorithm_44400_I | ### Context
You are tasked with analyzing sentiment from text data and classifying it as positive or negative. This involves using a Naive Bayes classifier to process a labeled training dataset and then predict sentiments on a test dataset. You need to implement functions to preprocess the text, calculate the necessary... | import re
from collections import defaultdict
from math import log
def preprocess_text(text):
"""
Tokenize and normalize text (convert to lowercase).
"""
tokens = re.findall(r'\b\w+\b', text.lower())
return tokens
def train_naive_bayes(train_data):
"""
Train a Naive Bayes classifier.
"... | from solution import preprocess_text, train_naive_bayes, predict_naive_bayes
def test_preprocess_text():
assert preprocess_text("I love this product!") == ["i", "love", "this", "product"]
assert preprocess_text("This is a TEST.") == ["this", "is", "a", "test"]
assert preprocess_text("") == []
def test_tra... | [
{
"docstring": "Tokenize and normalize text (convert to lowercase).",
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": "Train a Naive Bayes classifier.",
"function_declaration": "def train_naive_bayes(t... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import defaultdict\nimport math\n\ndef preprocess_text(text):\n \"\"\"\n Tokenizes and normalizes text by converting to lowerca... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000044400",
"row_id": 44400,
"seed_ids": "[467]"
} | 0.567224 | Algorithm_44400 | I | [
"preprocess_text",
"train_naive_bayes",
"predict_naive_bayes"
] | 3 | [
[
"predict_naive_bayes",
"preprocess_text"
],
[
"train_naive_bayes",
"preprocess_text"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6bbbd694a6633cd870753d220d8a4b8890a03e88 | 3073e4ae9a7642abb9f6406377352422f5fbd78c | |||
v1.0 | instruct | Algorithm | Algorithm_44411_I | ### Problem Statement:
#### Scenario:
A developer is working with string manipulations and needs to create a function that converts an integer to an English-like string representation. Your task is to help the developer by writing an efficient algorithm that converts any integer within a given range to its correspondin... | NUMS_1_19 = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"
]
TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
THOUSAND... | def test_int_to_english_single_digits():
assert int_to_english(1) == "one"
assert int_to_english(5) == "five"
def test_int_to_english_tens():
assert int_to_english(20) == "twenty"
assert int_to_english(45) == "forty-five"
def test_int_to_english_hundreds():
assert int_to_english(100) == "one hundr... | [
{
"docstring": null,
"function_declaration": "def helper(n):",
"function_name": "helper",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def int_to_english(n):",
"function_name": "int_to_english",
"parameter_list": "(n)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "NUMS_1_19 = [\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n \"ten\", \"eleven\", \"twelve\", \"th... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000044411",
"row_id": 44411,
"seed_ids": "[2690]"
} | 0.567603 | Algorithm_44411 | I | [
"helper",
"int_to_english"
] | 2 | [
[
"int_to_english",
"helper"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 928f0d799ef64abdd4def8c3e1ddcdabe429d7bd | 4e7ce21a39f001dd413c2a7ffce4126ad87b4af7 | |||
v1.0 | instruct | Algorithm | Algorithm_44450_I | ### Question: Implement a Simple Neural Network from Scratch
In this task, you will build a simple feedforward neural network with a single hidden layer from scratch using only numpy. This will help you understand the basics of neural networks, including forward pass, loss calculations, and backward pass for parameter... | import numpy as np
def initialize_parameters(input_dim: int, hidden_dim: int, output_dim: int) -> dict:
"""
Initializes weights and biases of the neural network.
"""
np.random.seed(42)
W1 = np.random.randn(input_dim, hidden_dim) * 0.01
b1 = np.zeros((1, hidden_dim))
W2 = np.random.randn(hid... | import numpy as np
from solution import initialize_parameters, forward_pass, compute_loss, backward_pass, update_parameters
def test_initialize_parameters():
params = initialize_parameters(2, 3, 1)
assert params["W1"].shape == (2, 3)
assert params["b1"].shape == (1, 3)
assert params["W2"].shape == (3, ... | [
{
"docstring": "Initializes weights and biases of the neural network.",
"function_declaration": "def initialize_parameters(input_dim, hidden_dim, output_dim):",
"function_name": "initialize_parameters",
"parameter_list": "(input_dim, hidden_dim, output_dim)"
},
{
"docstring": null,
"func... | [
0,
0,
1,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_parameters(input_dim: int, hidden_dim: int, output_dim: int) -> dict:\n np.random.seed(42) # Ensure reproducibility\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000044450",
"row_id": 44450,
"seed_ids": "[498]"
} | 0.567815 | Algorithm_44450 | I | [
"initialize_parameters",
"sigmoid",
"forward_pass",
"compute_loss",
"backward_pass",
"update_parameters"
] | 6 | [
[
"forward_pass",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 179bc08b3755918b0a5f82888c63380b0ea2cafa | 76c5732c05066465a26e34ae8df80d26ccb7137f | |||
v1.0 | instruct | Algorithm | Algorithm_44498_I | ### Coding Challenge: String Anagram Checks
#### Objective:
Develop a program to check if a list of given pairs of strings are anagrams of each other and summarize the results.
#### Detailed Task Description:
1. **Function Implementations**:
- Implement `are_anagrams(str1: str, str2: str) -> bool`: This function ... | from typing import List, Tuple
def are_anagrams(str1: str, str2: str) -> bool:
"""
Determines if the two provided strings are anagrams of each other.
"""
return sorted(str1) == sorted(str2)
def check_anagrams(pairs: List[Tuple[str, str]]) -> List[bool]:
"""
Checks if each pair of strings in th... | from solution import are_anagrams, check_anagrams
def test_are_anagrams():
assert are_anagrams("listen", "silent") == True
assert are_anagrams("triangle", "integral") == True
assert are_anagrams("apple", "papel") == True
assert are_anagrams("rat", "car") == False
assert are_anagrams("night", "thing... | [
{
"docstring": "Determines if the two provided strings are anagrams of each other.",
"function_declaration": "def are_anagrams(str1, str2):",
"function_name": "are_anagrams",
"parameter_list": "(str1, str2)"
},
{
"docstring": "Checks if each pair of strings in the list are anagrams and retur... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef are_anagrams(str1: str, str2: str) -> bool:\n \"\"\"\n Returns whether str1 and str2 are anagrams of each other.\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000044498",
"row_id": 44498,
"seed_ids": "[3325]"
} | 0.635745 | Algorithm_44498 | I | [
"are_anagrams",
"check_anagrams"
] | 2 | [
[
"check_anagrams",
"are_anagrams"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0334214bbc25325d9eda903760caf7a811544e56 | 5b41cd2b3f76609b5387b6755f269c32e1093329 | |||
v1.0 | instruct | Algorithm | Algorithm_44634_I | ### Genetic Algorithm for Traveling Salesman Problem
**Context**: A logistics company has a fleet of trucks to deliver goods across multiple cities. The company wants to determine the most efficient route for each truck to minimize travel distance. They have formulated this as a Traveling Salesman Problem (TSP) and wa... | import random
import math
from typing import List
class City:
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
def distance_to(self, city) -> float:
return math.sqrt((self.x - city.x) ** 2 + (self.y - city.y) ** 2)
class Route:
def __init__(self, ... | from solution import City, Route, genetic_algorithm_tsp
def test_genetic_algorithm_tsp():
cities = [
City("A", 0, 0),
City("B", 1, 3),
City("C", 4, 3),
City("D", 6, 1),
]
best_route = genetic_algorithm_tsp(cities, population_size=50, mutation_rate=0.02, generations=500)
... | [] | [
1,
1,
0,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\nfrom typing import List\n\nclass City:\n def __init__(self, name, x, y):\n self.name = name\n self.x = x\n se... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000044634",
"row_id": 44634,
"seed_ids": "[5315]"
} | 0.530342 | Algorithm_44634 | I | [
"create_initial_population",
"rank_routes",
"selection",
"breed",
"breed_population",
"mutate",
"mutate_population",
"next_generation",
"genetic_algorithm_tsp"
] | 9 | [
[
"breed_population",
"breed"
],
[
"genetic_algorithm_tsp",
"create_initial_population"
],
[
"genetic_algorithm_tsp",
"next_generation"
],
[
"genetic_algorithm_tsp",
"rank_routes"
],
[
"mutate_population",
"mutate"
],
[
"next_generation",
"breed_po... | 9 | [] | false | [
"City",
"Route"
] | true | pytest | true | [] | true | 8df6df0fc9bc1896c0be0ba6d81bc4d4288c138a | 9dfa0beb1e978e215c0f596974f86b21d7ef16e8 | |||
v1.0 | instruct | Algorithm | Algorithm_44698_I | ### Coding Assessment Question
#### Scenario
You are developing an application for a logistics company to track its fleet of delivery trucks. Trucks move between various locations and record their positions periodically. Each truck's movement is represented as a series of position records, and for early analysis, we'r... | from math import sqrt
from typing import List, Tuple, Dict
def euclidean_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
return sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def longest_distance(truck_positions: Dict[str, List[Tuple[int, int]]]) -> Dict[str, float]:
max_distances = {}
# ... | import pytest
from solution import longest_distance
def test_longest_distance_example():
truck_positions = {
"truck_1": [(0, 0), (3, 4), (6, 8)],
"truck_2": [(1, 1), (4, 5), (7, 9)]
}
assert longest_distance(truck_positions) == {"truck_1": 10.0, "truck_2": 10.0}
def test_longest_distan... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def longest_distance(truck_positions):",
"function_name": "longest_distance",
"para... | [
1,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import sqrt\nfrom typing import List, Tuple, Dict\n\ndef euclidean_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:\n return sqrt((p1[0]... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000044698",
"row_id": 44698,
"seed_ids": "[419]"
} | 0.669957 | Algorithm_44698 | I | [
"euclidean_distance",
"longest_distance"
] | 2 | [
[
"longest_distance",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 69596f571d5b7b62d8983c5d7a0604d08bf9b449 | 56f14c695ab2b26a278586fcc32822424a4f6009 | |||
v1.0 | instruct | Algorithm | Algorithm_44829_I | ### Coding Assessment: Determine if Tree is Symmetric
#### Context
You are working as a software engineer developing a library for manipulating binary trees. One of the features of this library is to determine if a given binary tree is symmetric. A symmetric tree is one that is a mirror reflection of itself about its ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_mirror(left: TreeNode, right: TreeNode) -> bool:
if not left and not right:
return True
if not left or not right:
return False
return (left... | from solution import TreeNode, is_symmetric
def test_symmetric_tree():
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.right = TreeNode(2)
tree.left.left = TreeNode(3)
tree.left.right = TreeNode(4)
tree.right.left = TreeNode(4)
tree.right.right = TreeNode(3)
assert is_symmetric(tree) ==... | [] | [
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": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_sy... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000044829",
"row_id": 44829,
"seed_ids": "[3857]"
} | 0.654684 | Algorithm_44829 | I | [
"is_mirror",
"is_symmetric"
] | 2 | [
[
"is_symmetric",
"is_mirror"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | c02e560bbb1bfa7cd06b810c63ce9c82cea5c5f3 | 96cfc1ebb81fd36cb8db12ba69623373a494fab0 | |||
v1.0 | instruct | Algorithm | Algorithm_44833_I | ### Question: CSV-based Student Grade Management System
#### Context
You are hired by a local school to develop a student grade management system. The school records student grade information in a CSV format. Your task is to implement functions that can read student names and grades from a CSV file, calculate average ... | import csv
from typing import Dict, List
def calculate_averages(file_path: str) -> Dict[str, float]:
"""
Reads the student grades from a CSV file specified by file_path,
calculates the average grade for each student,
and returns a dictionary with student names as keys and their average grades as values... | import pytest
from solution import calculate_averages, identify_low_performers
# Utility function to create a sample CSV file for tests
def create_test_csv(file_path: str, content: str):
with open(file_path, 'w') as file:
file.write(content)
# Test cases for calculate_averages
def test_calculate_averages(... | [
{
"docstring": "Reads the student grades from a CSV file specified by file_path,\ncalculates the average grade for each student,\nand returns a dictionary with student names as keys and their average grades as values.",
"function_declaration": "def calculate_averages(file_path):",
"function_name": "calc... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import csv\nfrom typing import Dict, List\n\ndef calculate_averages(file_path: str) -> Dict[str, float]:\n \"\"\"\n Read the student grades from a CSV file... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000044833",
"row_id": 44833,
"seed_ids": "[440]"
} | 0.659323 | Algorithm_44833 | I | [
"calculate_averages",
"identify_low_performers"
] | 2 | [
[
"identify_low_performers",
"calculate_averages"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea57f6e833cf8f8ee000f107fd34773fb7ab0484 | 4f72852dc4b80cdfa0fa20e301ab7ffd9aaaa90c | |||
v1.0 | instruct | Algorithm | Algorithm_44945_I | ### Matrix Rotation Check: Is It a Rotation?
#### Problem Statement
You are given two `n x n` matrices, `A` and `B`, where `n` is a positive integer. The goal is to determine if matrix `B` can be obtained by rotating matrix `A` (by 90, 180, or 270 degrees).
Write a function `is_rotation(A: List[List[int]], B: List[L... | from typing import List
def rotate_90(matrix: List[List[int]]) -> List[List[int]]:
"""Returns the matrix rotated by 90 degrees clockwise."""
return [list(row) for row in zip(*matrix[::-1])]
def is_rotation(A: List[List[int]], B: List[List[int]]) -> bool:
"""Check if matrix B is a rotation of matrix A by 9... | def test_is_rotation():
A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
B_90 = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
B_180 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
B_270 = [
[3, 6, 9],
[2, 5, 8],
[1, 4, 7]
... | [
{
"docstring": "Returns the matrix rotated by 90 degrees clockwise.",
"function_declaration": "def rotate_90(matrix):",
"function_name": "rotate_90",
"parameter_list": "(matrix)"
},
{
"docstring": "Check if matrix B is a rotation of matrix A by 90, 180, or 270 degrees.",
"function_declar... | [
0,
1,
0,
0,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_90(matrix: List[List[int]]) -> List[List[int]]:\n n = len(matrix)\n rotated = [[0] * n for _ in range(n)]\n for i ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000044945",
"row_id": 44945,
"seed_ids": "[71]"
} | 0.552794 | Algorithm_44945 | I | [
"rotate_90",
"is_rotation"
] | 2 | [
[
"is_rotation",
"rotate_90"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ec004e37eb58b0f25b63b705317facfeec1bbf5a | 882a578ba85203c27a7f269e80b0cfbf9e2b8fa3 | |||
v1.0 | instruct | Algorithm | Algorithm_44967_I | ### Problem Statement
**Implement a Basic Public Key Cryptography System**
In this problem, you are required to implement a simplified version of the RSA algorithm, a widely-used asymmetric cryptographic system. Your function will generate a pair of public and private keys, and then use these keys to encrypt and decr... | import random
def gcd(a, b):
while b:
a, b = b, a % b
return a
def modinv(a, m):
m0, x0, x1 = m, 0, 1
if m == 1:
return 0
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 = x1 - q * x0, x0
if x1 < 0:
x1 += m0
return x1
def is_prime(num):
i... | from solution import generate_keys, encrypt, decrypt
def test_key_generation():
p = 61
q = 53
public_key, private_key = generate_keys(p, q)
assert public_key[0] != private_key[0]
assert public_key[1] == private_key[1]
assert isinstance(public_key, tuple)
assert isinstance(private_key, tuple... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def modinv(a, m):",
"function_name": "modinv",
"parameter_list": "(a, m)"
},
{
"docstring": null,
"functi... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport sympy\n\ndef gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\ndef mod_inverse(e, phi):\n # Use Extended Euclidean... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000044967",
"row_id": 44967,
"seed_ids": "[4176]"
} | 0.702672 | Algorithm_44967 | I | [
"gcd",
"modinv",
"is_prime",
"generate_keys",
"encrypt",
"decrypt"
] | 6 | [
[
"generate_keys",
"gcd"
],
[
"generate_keys",
"is_prime"
],
[
"generate_keys",
"modinv"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 82ea1b51f170246ce1adcb88f8a4c2729c80d968 | 519cf8e94253e03e0b0953d95a2d4241b4719d97 | |||
v1.0 | instruct | Algorithm | Algorithm_45132_I | ### Question: Implement a Sparse Matrix Using Linked Lists
You are tasked with implementing a sparse matrix data structure to efficiently manage matrices with a high proportion of zero values. Your implementation should use linked lists to store non-zero elements and support basic matrix operations.
Your implementati... | def insert(matrix, row, col, value):
"""
Insert an element in the sparse matrix with the given value at the specified row and col.
If the value is zero, remove any existing element at the position.
"""
if value == 0:
if row in matrix and col in matrix[row]:
del matrix[row][col]
... | from solution import insert, get, display
def test_insert_get():
sparse_matrix = {}
insert(sparse_matrix, 0, 1, 5)
assert get(sparse_matrix, 0, 1) == 5
assert get(sparse_matrix, 1, 1) == 0
insert(sparse_matrix, 1, 0, 3)
assert get(sparse_matrix, 1, 0) == 3
insert(sparse_matrix, 0, 1, ... | [
{
"docstring": "Insert an element in the sparse matrix with the given value at the specified row and col.\nIf the value is zero, remove any existing element at the position.",
"function_declaration": "def insert(matrix, row, col, value):",
"function_name": "insert",
"parameter_list": "(matrix, row, ... | [
0,
1,
1,
0,
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 insert(matrix, row, col, value):\n \"\"\"\n Inserts the value at the specified row and column.\n If the value is zero, remove the element from the m... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000045132",
"row_id": 45132,
"seed_ids": "[1857]"
} | 0.463512 | Algorithm_45132 | I | [
"insert",
"get",
"display"
] | 3 | [
[
"display",
"get"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04b3ab8331f90c8832bfd15f5f236192034005ff | 49a8c050802bc7562c50da2d8bcd09402dc769b0 | |||
v1.0 | instruct | Algorithm | Algorithm_45144_I | ### Determine if a Binary Tree is a Subtree of Another Binary Tree
You are given two binary trees, `root` and `subRoot`. Write a function to determine if `subRoot` is a subtree of `root`. A subtree of a binary tree `root` is a tree consisting of a node in `root` and all of its descendants. The `subRoot` tree must have... | from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if not subRoot:
return True
if not root:
r... | from solution import TreeNode, is_subtree
def test_is_subtree_example1():
root = TreeNode(3)
root.left = TreeNode(4)
root.right = TreeNode(5)
root.left.left = TreeNode(1)
root.left.right = TreeNode(2)
subRoot = TreeNode(4)
subRoot.left = TreeNode(1)
subRoot.right = TreeNode(2)
... | [] | [
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": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_su... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045144",
"row_id": 45144,
"seed_ids": "[4238]"
} | 0.62056 | Algorithm_45144 | I | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8336731d26a4345d706d4098ed6c74b75d815aa2 | 99e939082e381b7e7411ae00657aaf2aed11f93b | |||
v1.0 | instruct | Algorithm | Algorithm_45161_I | ## Problem Statement
You are tasked with implementing a feature extraction technique for text data, specifically the term frequency-inverse document frequency (TF-IDF) scheme. This task will involve calculating term frequencies (TF), inverse document frequencies (IDF), and combining these to compute the TF-IDF scores ... | import math
import re
from collections import defaultdict, Counter
from typing import List, Dict
def tokenize(document: str) -> List[str]:
"""
Tokenizes a document into a list of words. Converts to lowercase and removes special characters.
"""
return re.findall(r'\b\w+\b', document.lower())
def comput... | import pytest
from solution import compute_tfidf
def test_compute_tfidf_single_document():
documents = ["The cat sat on the mat."]
result = compute_tfidf(documents)
assert len(result) == 1
assert 'cat' in result[0]
def test_compute_tfidf_multiple_documents():
documents = [
"The cat sat on ... | [
{
"docstring": "Tokenizes a document into a list of words. Converts to lowercase and removes special characters.",
"function_declaration": "def tokenize(document):",
"function_name": "tokenize",
"parameter_list": "(document)"
},
{
"docstring": "Calculates the TF-IDF scores for each term in e... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nimport math\nfrom collections import Counter\nfrom typing import List, Dict\n\ndef compute_tfidf(documents: List[str]) -> List[Dict[str, float]]:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000045161",
"row_id": 45161,
"seed_ids": "[4278]"
} | 0.833033 | Algorithm_45161 | I | [
"tokenize",
"compute_tfidf"
] | 2 | [
[
"compute_tfidf",
"tokenize"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4ec621aba8dc1858960e810f27eeed73fd775a3c | d7abeee88bd078f11be15cd064eb97bf3cfb93da | |||
v1.0 | instruct | Algorithm | Algorithm_45174_I | ### Question
Given a list of integers, write two functions:
1. Determine if the list can be classified as an arithmetic sequence.
2. Calculate the sum of the first `n` terms of the arithmetic sequence if it is valid.
#### Requirements
- Implement the function `is_arithmetic_sequence(sequence: list) -> bool`:
* Thi... | def is_arithmetic_sequence(sequence):
"""
Returns True if the given list forms an arithmetic sequence, else returns False.
"""
if not isinstance(sequence, list):
raise ValueError("Input must be a list.")
if len(sequence) == 0:
return False
if len(sequence) == 1:
... | def test_is_arithmetic_sequence_valid():
assert is_arithmetic_sequence([3, 6, 9, 12]) == True
assert is_arithmetic_sequence([2, 5, 8, 11]) == True
def test_is_arithmetic_sequence_invalid():
assert is_arithmetic_sequence([2, 5, 8, 12]) == False
def test_is_arithmetic_sequence_single_element():
assert i... | [
{
"docstring": "Returns True if the given list forms an arithmetic sequence, else returns False.",
"function_declaration": "def is_arithmetic_sequence(sequence):",
"function_name": "is_arithmetic_sequence",
"parameter_list": "(sequence)"
},
{
"docstring": "Returns the sum of the first n term... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_arithmetic_sequence(sequence: list) -> bool:\n \"\"\"\n Determines if the given list forms an arithmetic sequence.\n \n Args:\n - sequence ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000045174",
"row_id": 45174,
"seed_ids": "[3679]"
} | 0.630869 | Algorithm_45174 | I | [
"is_arithmetic_sequence",
"arithmetic_sequence_sum"
] | 2 | [
[
"arithmetic_sequence_sum",
"is_arithmetic_sequence"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 69800b9713088feba9f8547e612d8a69ae49b12d | 5cd59bd3283db22c327e87ec23ad50d121d709e9 | |||
v1.0 | instruct | Algorithm | Algorithm_45277_I | ### Coding Question: Implement and Analyze the Chinese Remainder Theorem
#### Context
The Chinese Remainder Theorem (CRT) is a powerful tool in number theory and computer science that allows solutions to a system of simultaneous congruences with pairwise coprime moduli. This problem requires understanding modular arit... | from typing import List
from functools import reduce
from math import gcd
def is_coprime_pair(x: int, y: int) -> bool:
return gcd(x, y) == 1
def is_coprime_list(n: List[int]) -> bool:
if not n:
raise ValueError("Input list cannot be empty")
length = len(n)
for i in range(length):
for j... | from solution import is_coprime_list, chinese_remainder_theorem
def test_is_coprime_list_true():
assert is_coprime_list([3, 5, 7]) == True
def test_is_coprime_list_false():
assert is_coprime_list([3, 6, 9]) == False
def test_is_coprime_list_single_element():
assert is_coprime_list([5]) == True
def test_... | [
{
"docstring": null,
"function_declaration": "def is_coprime_pair(x, y):",
"function_name": "is_coprime_pair",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def is_coprime_list(n):",
"function_name": "is_coprime_list",
"parameter_list": "(n)"
},
... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\nfrom math import gcd\n\ndef extended_gcd(a, b):\n \"\"\"\n Return (g, x, y) where g is gcd(a, b) and x, y are integers s... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000045277",
"row_id": 45277,
"seed_ids": "[3459]"
} | 0.599656 | Algorithm_45277 | I | [
"is_coprime_pair",
"is_coprime_list",
"extended_gcd",
"chinese_remainder_theorem"
] | 4 | [
[
"chinese_remainder_theorem",
"extended_gcd"
],
[
"chinese_remainder_theorem",
"is_coprime_list"
],
[
"is_coprime_list",
"is_coprime_pair"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e7156e00f5f031544dd1b52d1f63d918040d998f | 5183e0bf22e9b2311f7af335677cba4257a61077 | |||
v1.0 | instruct | Algorithm | Algorithm_45301_I | ### Problem Statement
You need to implement a function called `min_spanning_tree` that finds the Minimum Spanning Tree (MST) of a given connected, undirected graph using Kruskal's algorithm. Your implementation should efficiently manage the graph's edges and employ the union-find data structure to detect and prevent cy... | 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 min_spanning_tree
def test_example1():
num_nodes = 4
edges = [(0, 1, 1), (1, 2, 4), (0, 2, 3), (2, 3, 2), (1, 3, 5)]
result = min_spanning_tree(num_nodes, edges)
assert result == (6, [(0, 1), (2, 3), (0, 2)])
def test_example2():
num_nodes = 3
edges = [(0, 1, 1), (1, 2, 2)... | [
{
"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,
1,
1,
0,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef min_spanning_tree(\n num_nodes: int, \n edges: List[Tuple[int, int, int]]\n) -> Tuple[int, List[Tuple[int, int]]]:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000045301",
"row_id": 45301,
"seed_ids": "[532]"
} | 0.743953 | Algorithm_45301 | I | [
"find",
"union",
"min_spanning_tree"
] | 3 | [
[
"min_spanning_tree",
"find"
],
[
"min_spanning_tree",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a7277791b6602cb99e979889f479fef0409987e3 | d6c3b9d6cea32482e151b41d9ff48ab183c1d8c6 | |||
v1.0 | instruct | Algorithm | Algorithm_45447_I | ### Question
You need to develop a function that processes an array of integers and sorts all prime numbers in ascending order while leaving the positions of the non-prime numbers unchanged.
**Function Signature:**
```python
def sort_primes(arr: List[int]) -> List[int]:
"""
Sorts the prime numbers in an array ... | from typing import List
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = int(n ** 0.5) + 1
for i in range(3, max_divisor, 2):
... | from solution import sort_primes
def test_sort_primes_with_mixed_numbers():
assert sort_primes([29, 15, -3, 4, 17, 5, 2]) == [2, 15, -3, 4, 5, 17, 29]
def test_sort_primes_with_some_primes():
assert sort_primes([7, 10, 23, 12, 19]) == [7, 10, 19, 12, 23]
def test_sort_primes_with_primes_at_end():
assert ... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Sorts the prime numbers in an array in ascending order while keeping \nthe non-prime numbers in their or... | [
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n for ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045447",
"row_id": 45447,
"seed_ids": "[4077]"
} | 0.664198 | Algorithm_45447 | I | [
"is_prime",
"sort_primes"
] | 2 | [
[
"sort_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9fc884ecdc4fed29069f033c68bb821efcce7acc | 4d22abf42f64c065ba70de171c994aabaff977ae | |||
v1.0 | instruct | Algorithm | Algorithm_45452_I | ### K Nearest Neighbors for Classification
You are required to implement the K Nearest Neighbors (KNN) algorithm from scratch for a classification problem. Your task is to:
1. Download and process a given dataset.
2. Implement the KNN algorithm to classify data points.
3. Evaluate the model using accuracy as the metri... | import numpy as np
import pandas as pd
from collections import Counter
from urllib.error import HTTPError
def collect_dataset(url="https://raw.githubusercontent.com/dataprofessor/data/master/penguins_size.csv"):
try:
df = pd.read_csv(url)
# Selecting only non-null rows for features and label 'speci... | import numpy as np
from solution import collect_dataset, euclidean_distance, knn_predict, evaluate_model
def test_collect_dataset():
data = collect_dataset()
assert data is not None
assert data.shape[1] == 3 # 2 features + 1 label
def test_euclidean_distance():
point1 = np.array([1, 1])
point2 = ... | [
{
"docstring": null,
"function_declaration": "def collect_dataset(url='https://raw.githubusercontent.com/dataprofessor/data/master/penguins_size.csv'):",
"function_name": "collect_dataset",
"parameter_list": "(url='https://raw.githubusercontent.com/dataprofessor/data/master/penguins_size.csv')"
},... | [
0,
0,
1,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport requests\nimport csv\nfrom collections import Counter\nfrom math import sqrt\n\ndef collect_dataset():\n \"\"\"\n Fetches the da... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000045452",
"row_id": 45452,
"seed_ids": "[681]"
} | 0.625169 | Algorithm_45452 | I | [
"collect_dataset",
"euclidean_distance",
"knn_predict",
"evaluate_model",
"main"
] | 5 | [
[
"evaluate_model",
"knn_predict"
],
[
"knn_predict",
"euclidean_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 4741992c7049007afb50f4ec9af15d72b3bd7e0a | d4f10fc30b0270c659599a35aa7600e3a1444db3 | |||
v1.0 | instruct | Algorithm | Algorithm_45480_I | ### Problem Statement
You are tasked with implementing a simplified version of the game "Conway's Game of Life." The game is played on a two-dimensional grid where each cell is either alive or dead. The state of the grid evolves in discrete steps, and the next state of a cell depends on its eight neighbors (horizontal... | def count_live_neighbors(grid, row, col):
"""
Helper function to count live neighbors of a cell (row, col).
"""
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
nrows = len(grid)
ncols = len(grid[0])
live_ne... | from solution import game_of_life
def test_game_of_life_example_case():
grid = [
[0, 1, 0],
[0, 0, 1],
[1, 1, 1],
[0, 0, 0]
]
expected_output = [
[0, 0, 0],
[1, 0, 1],
[0, 1, 1],
[0, 1, 0]
]
assert game_of_life(grid) == expected_output... | [
{
"docstring": "Helper function to count live neighbors of a cell (row, col).",
"function_declaration": "def count_live_neighbors(grid, row, col):",
"function_name": "count_live_neighbors",
"parameter_list": "(grid, row, col)"
},
{
"docstring": "Computes the next state of the grid given its ... | [
0,
0,
1,
0,
1,
1,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def game_of_life(grid: list[list[int]]) -> list[list[int]]:\n def get_live_neighbor_count(x, y):\n live_neighbors = 0\n for dx in [-1, 0, 1]:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000045480",
"row_id": 45480,
"seed_ids": "[2293]"
} | 0.599817 | Algorithm_45480 | I | [
"count_live_neighbors",
"game_of_life"
] | 2 | [
[
"game_of_life",
"count_live_neighbors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2312735702eb43edfe27899e1340732993613798 | a3fbd9d20ec8d16cfc4d69d114f2791fa4721a56 | |||
v1.0 | instruct | Algorithm | Algorithm_45487_I | ### Coding Assessment Question
### Implementing a Merge Sort Algorithm
You are required to implement the merge sort algorithm, a classic divide-and-conquer sorting technique. Merge sort is known for its efficiency and consistency in performance.
### Objective
Implement a function `merge_sort(arr: list) -> list` that ... | def merge_sort(arr: list) -> list:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: list, right: list) -> list:
sorted_arr = []
left_idx, right_idx = 0,... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([3]) == [3]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3]) == [1, 2, 3]
def test_merge_sort_unsorted():
assert merge_sort([3, 1, 2]) == [1... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr: list) -> list:\n \"\"\"\n Sorts the given list of integers using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045487",
"row_id": 45487,
"seed_ids": "[108]"
} | 0.626301 | Algorithm_45487 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 13ad49c112e4f3fd8180fa7086a81afb000e72d1 | 81d2c876c5e7cd5a3cf954d742fa7a18f5d27c05 | |||
v1.0 | instruct | Algorithm | Algorithm_45537_I | ### K-Means Clustering for Customer Segmentation
You are tasked with implementing the K-Means clustering algorithm from scratch to perform customer segmentation based on purchasing behaviors. Your task involves:
1. Downloading and processing a given dataset.
2. Implementing the K-Means algorithm.
3. Visualizing the cl... | import numpy as np
import matplotlib.pyplot as plt
import requests
import csv
from typing import Tuple
def collect_dataset() -> np.matrix:
"""
Downloads and processes the customer behavior dataset.
"""
url = 'https://example.com/customer_behavior.csv' # Example URL; replace with actual URL
respons... | import numpy as np
import pytest
from solution import collect_dataset, initialize_centroids, assign_clusters, update_centroids, run_kmeans, visualize_clusters
def test_collect_dataset(monkeypatch):
def mock_get(url):
from io import StringIO
class MockResponse:
def __init__(self... | [
{
"docstring": "Downloads and processes the customer behavior dataset.",
"function_declaration": "def collect_dataset():",
"function_name": "collect_dataset",
"parameter_list": "()"
},
{
"docstring": "Randomly initializes k centroids from the dataset.",
"function_declaration": "def initi... | [
0,
1,
1,
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 numpy as np\nimport matplotlib.pyplot as plt\nimport requests\nimport csv\n\ndef collect_dataset() -> np.matrix:\n url = 'https://example.com/customer_... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000045537",
"row_id": 45537,
"seed_ids": "[681]"
} | 0.701942 | Algorithm_45537 | I | [
"collect_dataset",
"initialize_centroids",
"assign_clusters",
"update_centroids",
"run_kmeans",
"visualize_clusters",
"main"
] | 7 | [
[
"run_kmeans",
"assign_clusters"
],
[
"run_kmeans",
"initialize_centroids"
],
[
"run_kmeans",
"update_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"requests"
] | false | c7dcba3fdf9515691dd1f8ac84c9d1795c03355f | a526e75b36a4b82ac623ab3d46db56d9b3bb6c46 | |||
v1.0 | instruct | Algorithm | Algorithm_45571_I | ### Scenario
You are tasked with developing a function to aid in data analysis for a telecommunications company. They need a utility that can identify valid IP addresses within a given string. An IP address consists of four octets, each ranging from 0 to 255, separated by dots. Your function should extract and return a... | import re
def extract_valid_ip_addresses(s: str) -> list:
"""
Extracts and returns all valid IP addresses found in the input string.
"""
# Regular expression to match potential IP addresses (not yet validated)
potential_ips = re.findall(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', s)
valid_ips = []
... | from solution import extract_valid_ip_addresses
def test_valid_ip_addresses():
assert extract_valid_ip_addresses("The IPs are 192.168.1.1 and 10.0.0.1.") == ['192.168.1.1', '10.0.0.1']
def test_no_valid_ip_addresses():
assert extract_valid_ip_addresses("Invalid IPs: 256.100.50.25, 192.168.1.999") == []
def t... | [
{
"docstring": "Extracts and returns all valid IP addresses found in the input string.",
"function_declaration": "def extract_valid_ip_addresses(s):",
"function_name": "extract_valid_ip_addresses",
"parameter_list": "(s)"
},
{
"docstring": "Helper function to check if an octet is valid:\n- S... | [
1,
1,
0,
1,
0,
0,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef extract_valid_ip_addresses(s: str) -> list:\n \"\"\"\n Extracts and returns all valid IP addresses from the input string.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000045571",
"row_id": 45571,
"seed_ids": "[2088]"
} | 0.701026 | Algorithm_45571 | I | [
"extract_valid_ip_addresses",
"is_valid_octet"
] | 2 | [
[
"extract_valid_ip_addresses",
"is_valid_octet"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e83816201313aa23491b17763b38add367b3c29c | 471bf6b5549853ce354cd35d683df2338af69677 | |||
v1.0 | instruct | Algorithm | Algorithm_45612_I | **Problem Statement:**
You are provided with a list of strings where each string consists of a mix of letters and digits. Your goal is to rearrange the characters in each string such that:
1. All letters appear before any digits.
2. Both letters and digits within their own groups should maintain their original order.
... | def rearrange_string(s):
"""
Rearranges the input string such that all letters appear before any digits while maintaining their original order.
:param s: Input string containing a mix of alphanumeric characters
:return: Rearranged string with letters first followed by digits
"""
letters = '... | from solution import rearrange_string, combine_rearranged_strings
def test_rearrange_string():
assert rearrange_string("a1b2c3") == "abc123"
assert rearrange_string("x9y8") == "xy98"
assert rearrange_string("1a2b3") == "ab123"
assert rearrange_string("abcd1234") == "abcd1234"
assert rearrange_strin... | [
{
"docstring": "Rearranges the input string such that all letters appear before any digits while maintaining their original order.\n\n:param s: Input string containing a mix of alphanumeric characters\n:return: Rearranged string with letters first followed by digits",
"function_declaration": "def rearrange_... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rearrange_string(s):\n \"\"\"\n Rearranges the characters in the given string such that all letters appear before any digits,\n maintaining their or... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000045612",
"row_id": 45612,
"seed_ids": "[2811]"
} | 0.610348 | Algorithm_45612 | I | [
"rearrange_string",
"combine_rearranged_strings"
] | 2 | [
[
"combine_rearranged_strings",
"rearrange_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 52c311bcb51d2079d016b02cdae147089f9d47e7 | 1ae53b4e4f2ff9d18f76598db810b190056c2f40 | |||
v1.0 | instruct | Algorithm | Algorithm_45652_I | ### Question: User Authentication System
You are required to implement a simple user authentication system. The system will manage user registrations and logins. All user data, including usernames and passwords, should be stored in a dictionary-like structure.
#### Function Signatures:
```python
def register_user(use... | users_db = {}
def encrypt_password(password: str) -> str:
return password[::-1] # For simplicity, reversing the string as encryption.
def register_user(username: str, password: str) -> None:
"""
Registers a new user with a username and password.
Args:
username (str): The username for the new use... | import pytest
from solution import users_db, register_user, login_user, encrypt_password
def setup_module(module):
"""
Setup test users and clear the database before running tests.
"""
users_db.clear()
def test_encrypt_password():
assert encrypt_password("password") == "drowssap"
assert encryp... | [
{
"docstring": null,
"function_declaration": "def encrypt_password(password):",
"function_name": "encrypt_password",
"parameter_list": "(password)"
},
{
"docstring": "Registers a new user with a username and password.\n\nArgs:\nusername (str): The username for the new user.\npassword (str): ... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "# In-memory storage of users for the authentication system\nusers_db = {}\n\ndef encrypt_password(password: str) -> str:\n \"\"\"\n A simple reversible enc... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000045652",
"row_id": 45652,
"seed_ids": "[1996]"
} | 0.618291 | Algorithm_45652 | I | [
"encrypt_password",
"register_user",
"login_user"
] | 3 | [
[
"login_user",
"encrypt_password"
],
[
"register_user",
"encrypt_password"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f4aa65b8f1a64c0b26f229cb4f528c92cdd7f069 | db2c5ebcad067f0384b836e5ab767118df0fdd42 | |||
v1.0 | instruct | Algorithm | Algorithm_45654_I | ### Problem Statement
You are developing a system for managing network devices, each of which has a unique IP address. To ensure efficient monitoring, you need to determine the longest sequence of consecutive active IP addresses given a list of active IPs.
Write a function named `longest_consecutive_active_ips` that t... | def ip_to_int(ip):
"""
Converts an IPv4 address from its string representation to an integer.
"""
parts = ip.split('.')
return int(parts[0]) * (256**3) + int(parts[1]) * (256**2) + int(parts[2]) * 256 + int(parts[3])
def longest_consecutive_active_ips(active_ips):
"""
Returns the length of ... | def test_longest_consecutive_active_ips_example_1():
assert longest_consecutive_active_ips(["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.2.1"]) == 3
def test_longest_consecutive_active_ips_example_2():
assert longest_consecutive_active_ips(["10.0.0.1", "10.0.0.3", "10.0.0.2", "10.0.0.4", "10.0.0.5"]) ... | [
{
"docstring": "Converts an IPv4 address from its string representation to an integer.",
"function_declaration": "def ip_to_int(ip):",
"function_name": "ip_to_int",
"parameter_list": "(ip)"
},
{
"docstring": "Returns the length of the longest sequence of consecutive active IP addresses.",
... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def ip_to_int(ip):\n \"\"\"\n Convert an IPv4 string address to an integer representation.\n \"\"\"\n parts = ip.split('.')\n return (int(parts[0]... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000045654",
"row_id": 45654,
"seed_ids": "[1557]"
} | 0.542805 | Algorithm_45654 | I | [
"ip_to_int",
"longest_consecutive_active_ips"
] | 2 | [
[
"longest_consecutive_active_ips",
"ip_to_int"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | b4f20b28678a34b5b83a4c10deb6cc1a64f56660 | 6573ef1d926ae4763bd3ade4c486afacd370867e | |||
v1.0 | instruct | Algorithm | Algorithm_45662_I | ### Coding Assessment Question
You are tasked with implementing a function that analyzes traffic data collected from a city's main intersections to determine peak traffic hours. The data is obtained from an API that provides traffic counts at each intersection for every hour of the day.
#### Function Specification
*... | import requests
from datetime import datetime
def get_peak_traffic_hours(intersections, date, threshold=1000):
"""
Returns a dictionary where keys are intersection names and values are lists of
hours during which the traffic count exceeded the specified threshold.
"""
# Check if the input date is ... | # solution.py should contain the solution code written above
from solution import get_peak_traffic_hours, validate_date
import pytest
import requests
from unittest.mock import patch
def test_validate_date():
assert validate_date('2021-09-01') == True
assert validate_date('2021-09-31') == False
assert valid... | [
{
"docstring": "Returns a dictionary where keys are intersection names and values are lists of \nhours during which the traffic count exceeded the specified threshold.",
"function_declaration": "def get_peak_traffic_hours(intersections, date, threshold=1000):",
"function_name": "get_peak_traffic_hours",... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom datetime import datetime\n\ndef get_peak_traffic_hours(intersections: list, date: str, threshold=1000):\n \"\"\"\n Analyzes traffic d... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000045662",
"row_id": 45662,
"seed_ids": "[1886]"
} | 0.561585 | Algorithm_45662 | I | [
"get_peak_traffic_hours",
"validate_date"
] | 2 | [
[
"get_peak_traffic_hours",
"validate_date"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | e78830e73506adb9eef22a234de74586b1838849 | fd48f0461fee363a991c50fa6ecbe546866f6985 | |||
v1.0 | instruct | Algorithm | Algorithm_45701_I | Implement a Python function `next_happy_number` that takes an integer `n` as an argument. The function should return the smallest happy number that is greater than `n`.
### Requirements:
1. A happy number is defined as a number which eventually reaches 1 when replaced by the sum of the square of each digit.
2. The fun... | def sum_of_squares_of_digits(num):
"""
Returns the sum of the squares of the digits of the given number.
"""
return sum(int(digit) ** 2 for digit in str(num))
def is_happy_number(num):
"""
Determines if a number is a happy number.
"""
seen = set()
while num != 1 and num not in seen:... | from solution import next_happy_number, is_happy_number, sum_of_squares_of_digits
def test_sum_of_squares_of_digits():
assert sum_of_squares_of_digits(19) == 82
assert sum_of_squares_of_digits(7) == 49
assert sum_of_squares_of_digits(100) == 1
def test_is_happy_number():
assert is_happy_number(19) == ... | [
{
"docstring": "Returns the sum of the squares of the digits of the given number.",
"function_declaration": "def sum_of_squares_of_digits(num):",
"function_name": "sum_of_squares_of_digits",
"parameter_list": "(num)"
},
{
"docstring": "Determines if a number is a happy number.",
"functio... | [
0,
1,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def sum_of_squares_of_digits(number):\n \"\"\"\n Helper function to return the sum of the squares of the digits of a number.\n \"\"\"\n return sum(in... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000045701",
"row_id": 45701,
"seed_ids": "[3492]"
} | 0.627006 | Algorithm_45701 | I | [
"sum_of_squares_of_digits",
"is_happy_number",
"next_happy_number"
] | 3 | [
[
"is_happy_number",
"sum_of_squares_of_digits"
],
[
"next_happy_number",
"is_happy_number"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a0263865ea1369f72c24e2eae064b4a9cf43eded | 02dd0573bf39834e0fd86d910c743ae4d504b94a | |||
v1.0 | instruct | Algorithm | Algorithm_45722_I | ### Coding Question: Implement a Merge Sort Algorithm for Linked List
#### Context
Merge Sort is an efficient, stable, and comparison-based sorting algorithm. It works by dividing the unsorted list into smaller sublists and then merges them back in a sorted manner. Sorting a linked list using Merge Sort involves diffe... | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def split_list(head):
"""
Split the linked list into two halves.
"""
fast = head
slow = head
prev = None
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.n... | def linked_list_from_array(arr):
"""
Helper function to create a linked list from an array of values.
"""
if not arr:
return None
head = ListNode(arr[0])
current = head
for value in arr[1:]:
current.next = ListNode(value)
current = current.next
return head
def ar... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef split_list(head):\n \"\"\"\n Split the linked list into ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045722",
"row_id": 45722,
"seed_ids": "[4087]"
} | 0.531123 | Algorithm_45722 | I | [
"split_list",
"merge_lists",
"merge_sort"
] | 3 | [
[
"merge_sort",
"merge_lists"
],
[
"merge_sort",
"split_list"
]
] | 2 | [] | false | [
"ListNode"
] | true | pytest | false | [] | true | d53de1e71aab017f007278a3948ae0f5699fd059 | be07fe529e377ddcbc646fd0fe8118734223b85e | |||
v1.0 | instruct | Algorithm | Algorithm_45754_I | ### Question: Matrix Determinant Calculator Enhancement
You are provided with a function that calculates the determinant of a square matrix. The existing implementation can handle 2x2 and 3x3 matrices but needs enhancement for robustness and error handling.
#### Your Task
Enhance the given function to:
1. Support mat... | def matrix_determinant(matrix: list[list[float]]) -> float:
"""
Calculate the determinant of a square matrix.
Args:
matrix (list of list of float): A square matrix represented as a list of lists.
Returns:
float: Determinant of the matrix.
Raises:
ValueError: If the input i... | from solution import matrix_determinant, minor
import pytest
def test_determinant_2x2_matrix():
assert matrix_determinant([[1, 2], [3, 4]]) == -2.0
def test_determinant_3x3_matrix():
assert matrix_determinant([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) == -306.0
def test_determinant_4x4_matrix():
assert matrix_d... | [
{
"docstring": "Calculate the determinant of a square matrix.\n\nArgs:\nmatrix (list of list of float): A square matrix represented as a list of lists.\n\nReturns:\nfloat: Determinant of the matrix.\n\nRaises:\nValueError: If the input is not a matrix or the matrix is not square.",
"function_declaration": "... | [
1,
1,
0,
1,
0,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def matrix_determinant(matrix: list[list[float]]) -> float:\n \"\"\"\n Calculates the determinant of a square matrix.\n \n Args:\n matrix (list of... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045754",
"row_id": 45754,
"seed_ids": "[729]"
} | 0.4564 | Algorithm_45754 | I | [
"matrix_determinant",
"minor"
] | 2 | [
[
"matrix_determinant",
"minor"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 585f5bf04f93d8111181dac2966cfba1f8f0ec41 | 1bfcd959affb80a091c862f5d513c67f2c38252f | |||
v1.0 | instruct | Algorithm | Algorithm_45771_I | ### In-Place Merge Sort Task
**Objective:**
Implement the Merge Sort algorithm to sort an array of integers using in-place techniques to minimize space complexity. The function should ensure that the list `arr` is sorted in ascending order, directly modifying the list in place.
**Function Signature:**
```python
def m... | from typing import List
def merge_sort_in_place(arr: List[int], l: int, r: int) -> None:
if l < r:
mid = (l + r) // 2
# Recursively sort first and second halves
merge_sort_in_place(arr, l, mid)
merge_sort_in_place(arr, mid + 1, r)
# Merge the sorted halves
merge(ar... | from solution import merge_sort_in_place
def test_merge_sort_in_place_basic():
arr = [8, 3, -2, 7, 4, -6, 8]
merge_sort_in_place(arr, 0, len(arr) - 1)
assert arr == [-6, -2, 3, 4, 7, 8, 8]
def test_merge_sort_in_place_single_element():
arr = [1]
merge_sort_in_place(arr, 0, len(arr) - 1)
assert... | [
{
"docstring": null,
"function_declaration": "def merge_sort_in_place(arr, l, r):",
"function_name": "merge_sort_in_place",
"parameter_list": "(arr, l, r)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, l, mid, r):",
"function_name": "merge",
"parameter_list": "(... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort_in_place(arr, l, r):\n \"\"\"\n In-place merge sort function to sort the array `arr` from indices `l` to `r`.\n \"\"\"\n def merge(arr... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045771",
"row_id": 45771,
"seed_ids": "[1191]"
} | 0.635681 | Algorithm_45771 | I | [
"merge_sort_in_place",
"merge"
] | 2 | [
[
"merge_sort_in_place",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf64a722fa63677a4735f10a58e2b6c287a26a27 | 759719cb1dafac777263a771f19e0fc045f1ab2d | |||
v1.0 | instruct | Algorithm | Algorithm_45922_I | ### Coding Assessment Question: Magic Square Permutations
#### Background:
A magic square is a 3x3 grid of distinct numbers from 1 to 9 such that the sums of numbers in each row, each column, and both main diagonals are equal.
Consider a function `isMagicSquare(grid)` that returns `True` if the given 3x3 grid forms ... | from itertools import permutations
def isMagicSquare(grid):
"""
Checks if a 3x3 grid forms a magic square.
"""
# Check sums of rows, columns, and diagonals
sums = [sum(row) for row in grid] + \
[sum(grid[i][j] for i in range(3)) for j in range(3)] + \
[sum(grid[i][i] for i in ... | import pytest
from solution import isMagicSquare, countMagicSquares
def test_isMagicSquare_true():
assert isMagicSquare([[2, 7, 6], [9, 5, 1], [4, 3, 8]]) == True
def test_isMagicSquare_false():
assert isMagicSquare([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == False
def test_countMagicSquares():
assert countMag... | [
{
"docstring": "Checks if a 3x3 grid forms a magic square.",
"function_declaration": "def isMagicSquare(grid):",
"function_name": "isMagicSquare",
"parameter_list": "(grid)"
},
{
"docstring": "Returns the count of all possible 3x3 magic squares using numbers 1 to 9.",
"function_declarati... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef isMagicSquare(grid):\n \"\"\"\n Check if a 3x3 grid forms a magic square.\n \"\"\"\n target_sum = 15 # Bec... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000045922",
"row_id": 45922,
"seed_ids": "[2241]"
} | 0.69761 | Algorithm_45922 | I | [
"isMagicSquare",
"countMagicSquares"
] | 2 | [
[
"countMagicSquares",
"isMagicSquare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 753fe2b734a05580ccae5ef2d2928808fe75dde8 | 6c2e979cd1f9a198e5362a4e826af3b4645de076 | |||
v1.0 | instruct | Algorithm | Algorithm_45976_I | ### Problem Statement
You are tasked with helping a logistics company optimize their delivery system. They need to be able to determine the earliest time by which all of their delivery vehicles can meet at a particular stop, given their respective schedules.
Write a function `find_earliest_meeting_time(schedules)` th... | from math import gcd
from functools import reduce
from typing import List
def lcm(a, b):
return a * b // gcd(a, b)
def find_earliest_meeting_time(schedules: List[int]) -> int:
def lcm_multiple(numbers):
return reduce(lcm, numbers, 1)
lcm_time = lcm_multiple(schedules)
return lcm_time... | def test_find_earliest_meeting_time():
assert find_earliest_meeting_time([3, 7, 11]) == 231
assert find_earliest_meeting_time([5, 10, 15]) == 30
assert find_earliest_meeting_time([2, 3, 5, 7]) == 210
assert find_earliest_meeting_time([1, 1, 1]) == 1
assert find_earliest_meeting_time([1, 2, 3]) == 6
... | [
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_earliest_meeting_time(schedules):",
"function_name": "find_earliest_meeting_time",
"parameter_list": "(sched... | [
1,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef find_earliest_meeting_time(schedules):\n \"\"\"\n Return the earliest meeting time (in minutes) for all sc... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000045976",
"row_id": 45976,
"seed_ids": "[283]"
} | 0.666221 | Algorithm_45976 | I | [
"lcm",
"find_earliest_meeting_time"
] | 2 | [
[
"find_earliest_meeting_time",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 548a67e8e8d74f2227fdabb8d94339e90242e1cb | a08e4e84890891cda09f707591f32b1c0a02b736 | |||
v1.0 | instruct | Algorithm | Algorithm_46064_I | ### Coding Assessment Question:
#### Scenario:
As part of your role in teaching data structures and algorithms, you have designed a task to assess the students' understanding of binary search trees (BST). The task involves implementing functions to insert elements into the BST and finding the lowest common ancestor (L... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_node(root, value):
if root is None:
return TreeNode(value)
if value < root.val:
root.left = insert_node(root.left, value)
elif value > ... | from solution import TreeNode, insert_node, find_lca, create_bst
def test_insert_node():
root = None
values = [20, 10, 30, 5, 15]
for value in values:
root = insert_node(root, value)
assert root.val == 20
assert root.left.val == 10
assert root.right.val == 30
assert root.left.left.v... | [] | [
0,
0,
1,
1,
1,
0,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n \"\"\"\n Definition for a binary tree node.\n \"\"\"\n def __init__(self, x):\n self.value = x\n self.left = None\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046064",
"row_id": 46064,
"seed_ids": "[386]"
} | 0.583983 | Algorithm_46064 | I | [
"insert_node",
"find_lca",
"create_bst"
] | 3 | [
[
"create_bst",
"insert_node"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 69ef180347099b01ca67544736eb833b848626d0 | da85812e5b92f04afbf3aba320e9889f639276b1 | |||
v1.0 | instruct | Algorithm | Algorithm_46120_I | ### Problem Statement:
You are required to implement a function that takes an integer `n` and returns the `n`th number in the sequence of Fibonacci numbers. However, to optimize the computation for large values of `n`, you need to use matrix exponentiation method. Fibonacci sequence is defined as:
- `F(0) = 0`
- `F(1)... | def matrix_multiply(A, B):
"""Multiplies two 2x2 matrices A and B"""
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
]
def matrix_power(matrix, n):
"""Performs matrix ... | from solution import fibonacci
def test_fibonacci_0():
assert fibonacci(0) == 0
def test_fibonacci_1():
assert fibonacci(1) == 1
def test_fibonacci_5():
assert fibonacci(5) == 5
def test_fibonacci_10():
assert fibonacci(10) == 55
def test_fibonacci_20():
assert fibonacci(20) == 6765
def test_f... | [
{
"docstring": "Multiplies two 2x2 matrices A and B",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Performs matrix exponentiation",
"function_declaration": "def matrix_power(matrix, n):",
"func... | [
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": "def matrix_mult(A, B):\n \"\"\"Multiplies two 2x2 matrices A and B.\"\"\"\n return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000046120",
"row_id": 46120,
"seed_ids": "[4746]"
} | 0.778501 | Algorithm_46120 | I | [
"matrix_multiply",
"matrix_power",
"fibonacci"
] | 3 | [
[
"fibonacci",
"matrix_power"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 26408c87782bd18c7128012f88d67ffd0a20d547 | bdba03fab72c24feb7d11f3c7d6972e19bbb9ad7 | |||
v1.0 | instruct | Algorithm | Algorithm_46126_I | ### Coding Assessment Question
#### Context:
Fibonacci sequences are a classic example in many algorithmic challenges. The recursive approach for generating the Fibonacci sequence is straightforward but inefficient. In this task, you will implement an efficient iterative solution and compare its performance with the r... | from typing import List
def fibonacci_iterative(n: int) -> List[int]:
if n == 0:
return []
elif n == 1:
return [0]
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2])
return fib_sequence
def fibonacci_recursive(n: int, memo... | from solution import fibonacci_iterative, generate_fibonacci_recursive
import time
def test_fibonacci_iterative():
assert fibonacci_iterative(0) == []
assert fibonacci_iterative(1) == [0]
assert fibonacci_iterative(5) == [0, 1, 1, 2, 3]
assert fibonacci_iterative(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34... | [
{
"docstring": null,
"function_declaration": "def fibonacci_iterative(n):",
"function_name": "fibonacci_iterative",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def fibonacci_recursive(n, memo={}):",
"function_name": "fibonacci_recursive",
"parameter_l... | [
1,
0,
1,
0,
1,
1,
1,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef fibonacci_iterative(n: int) -> List[int]:\n \"\"\"\n Returns the first n numbers in the Fibonacci sequence using an iterativ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000046126",
"row_id": 46126,
"seed_ids": "[952]"
} | 0.752336 | Algorithm_46126 | I | [
"fibonacci_iterative",
"fibonacci_recursive",
"generate_fibonacci_recursive"
] | 3 | [
[
"generate_fibonacci_recursive",
"fibonacci_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 482ef2e4d578171184d79bc7fe00581ebcdde5d4 | 41fe114ba563745653711193cd9bfcc0ebc380b5 | |||
v1.0 | instruct | Algorithm | Algorithm_46168_I | ### Question
**Prime Factorization and Pie Chart Visualization**
In this challenge, you will implement a function that performs prime factorization of a given integer and then plots the result as a pie chart. This problem tests your ability to implement basic number theory algorithms and visualize the results using p... | import matplotlib.pyplot as plt
from collections import Counter
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def prime_factor_pie_ch... | import pytest
from solution import prime_factors, prime_factor_pie_chart
def test_prime_factors_360():
assert prime_factors(360) == [2, 2, 2, 3, 3, 5]
def test_prime_factors_128():
assert prime_factors(128) == [2]*7
def test_prime_factors_10007():
assert prime_factors(10007) == [10007] # 10007 is a prim... | [
{
"docstring": null,
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_factor_pie_chart(number):",
"function_name": "prime_factor_pie_chart",
"parameter_list": "(nu... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\nfrom collections import Counter\n\ndef prime_factors(n):\n \"\"\"\n Returns the list of prime factors of a given integer n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000046168",
"row_id": 46168,
"seed_ids": "[4855]"
} | 0.591799 | Algorithm_46168 | I | [
"prime_factors",
"prime_factor_pie_chart"
] | 2 | [
[
"prime_factor_pie_chart",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | d75991587266f2f572e100173800c4f7d71d8858 | 8c36645a338c79ded1b7f2538db93132d478bb0a | |||
v1.0 | instruct | Algorithm | Algorithm_46245_I | ### Question Title: Weather Data Analyzer with Safe Dictionary Access
### Scenario
You have been tasked with developing a script that processes weather data from a JSON API response. This data includes details such as temperature, humidity, and weather conditions. Your script needs to handle missing keys gracefully a... | import requests
from typing import Any, Dict
from collections import namedtuple
# Define the WeatherData named tuple
WeatherData = namedtuple('WeatherData', ['temperature', 'humidity', 'condition'])
def safe_get(d: Dict[str, Any], key: str, default: Any) -> Any:
"""
Safely returns the value for the given key ... | import pytest
from unittest.mock import patch
from solution import fetch_weather_data, safe_get, WeatherData
def test_safe_get_existing_key():
data = {'key1': 'value1'}
assert safe_get(data, 'key1', 'default') == 'value1'
def test_safe_get_missing_key():
data = {'key1': 'value1'}
assert safe_get(data,... | [
{
"docstring": "Safely returns the value for the given key from the dictionary.\nIf the key does not exist, returns the provided default value.",
"function_declaration": "def safe_get(d, key, default):",
"function_name": "safe_get",
"parameter_list": "(d, key, default)"
},
{
"docstring": "Fe... | [
1,
1,
1,
0,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom typing import Any, Dict\nfrom collections import namedtuple\n\nWeatherData = namedtuple('WeatherData', ['temperature', 'humidity', 'conditi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046245",
"row_id": 46245,
"seed_ids": "[2295]"
} | 0.61894 | Algorithm_46245 | I | [
"safe_get",
"fetch_weather_data"
] | 2 | [
[
"fetch_weather_data",
"safe_get"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | d035fd7b6dd66b32b2bf7bea6883377b0eeed1b1 | 35d1cffb9fb59ac0c81ab69329ec095c1e88d37a | |||
v1.0 | instruct | Algorithm | Algorithm_46279_I | ### Graph Algorithm: Minimum Spanning Tree with Kruskal's Algorithm
Given an undirected graph with `N` nodes and `M` edges, where each edge has a specific weight associated with it, your task is to find the Minimum Spanning Tree (MST) of this graph using Kruskal’s algorithm. The graph is represented as a list of edges... | from typing import List, Tuple
def find(parent, i):
"""
Function to find the set of an element i (uses path compression)
"""
if parent[i] == i:
return i
else:
parent[i] = find(parent, parent[i])
return parent[i]
def union(parent, rank, x, y):
"""
Function to do unio... | from solution import kruskal
def test_kruskal_basic():
edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4)]
N = 4
expected = [(1, 2, 1), (1, 3, 2), (0, 2, 3)]
result = kruskal(edges, N)
assert sorted(result) == sorted(expected)
def test_kruskal_disconnected_graph():
edges = [(0, 1, ... | [
{
"docstring": "Function to find the set of an element i (uses path compression)",
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": "Function to do union of two sets of x and y (uses union by rank)",
"function_decl... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\nclass DisjointSetUnion:\n def __init__(self, size):\n self.parent = list(range(size))\n self.rank = [0] * size... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000046279",
"row_id": 46279,
"seed_ids": "[1900]"
} | 0.766827 | Algorithm_46279 | I | [
"find",
"union",
"kruskal"
] | 3 | [
[
"kruskal",
"find"
],
[
"kruskal",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b9f528e3a81197a16bbf35c36d9391ec0fcb5232 | 0db548a955c8fbb0f01567d85e8d6b1b476ef078 | |||
v1.0 | instruct | Algorithm | Algorithm_46282_I | ### Problem Statement: File Deduplicator
You work for a data storage company that frequently deals with large amounts of data. A significant challenge is ensuring that redundant files are not stored multiple times, saving both space and costs. You've been tasked with creating a solution that can identify and remove du... | import os
import hashlib
def hash_file(filepath):
"""Generate MD5 hash for the content of the file."""
hash_md5 = hashlib.md5()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def find_duplicates(direc... | import os
import tempfile
import pytest
from solution import find_duplicates, remove_duplicates
def create_test_file(path, content):
with open(path, 'w') as f:
f.write(content)
@pytest.fixture
def setup_filesystem():
with tempfile.TemporaryDirectory() as tmpdir:
# Create files
create_t... | [
{
"docstring": "Generate MD5 hash for the content of the file.",
"function_declaration": "def hash_file(filepath):",
"function_name": "hash_file",
"parameter_list": "(filepath)"
},
{
"docstring": "Find duplicates in a specified directory.",
"function_declaration": "def find_duplicates(di... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\n\ndef hash_file(filepath):\n \"\"\"Generate a hash for the given file.\"\"\"\n hasher = hashlib.sha256()\n with open(filepath... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000046282",
"row_id": 46282,
"seed_ids": "[296]"
} | 0.580322 | Algorithm_46282 | I | [
"hash_file",
"find_duplicates",
"remove_duplicates"
] | 3 | [
[
"find_duplicates",
"hash_file"
],
[
"remove_duplicates",
"find_duplicates"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6a84a25f2471abca61b096f1da0b6bdb2f34621b | bb17292f698e4178d28e7b1e8709b8dbe5e66d9c | |||
v1.0 | instruct | Algorithm | Algorithm_46324_I | ### Pathfinding in a Grid with Obstacles
An essential problem in robotics and game development is finding a path between two points in a grid while avoiding obstacles. One common method for solving this problem is using the A* search algorithm, which is an informed search algorithm that uses a heuristic to improve per... | from heapq import heappop, heappush
from typing import List, Tuple
def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:
"""
Calculate the Manhattan distance heuristic.
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star_search(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[i... | from solution import a_star_search
def test_a_star_search_example():
grid = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]
start = (0, 0)
goal = (4, 4)
result = a_star_search(grid, start, goal)
# Choose any of the ... | [
{
"docstring": "Calculate the Manhattan distance heuristic.",
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": "Perform A* search to find the shortest path from start to goal in a grid with obstacles.",
"function_d... | [
0,
1,
0,
0,
1,
0,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef a_star_search(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]:... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046324",
"row_id": 46324,
"seed_ids": "[3614]"
} | 0.638187 | Algorithm_46324 | I | [
"heuristic",
"a_star_search"
] | 2 | [
[
"a_star_search",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3f29aecc70492acd50312a8354ebe75edfea8a7b | c196d9787a8b1e766e1e9459bc96ef9506c03f94 | |||
v1.0 | instruct | Algorithm | Algorithm_46407_I | ### Prime Palindrome Challenge
#### Overview:
You are given a positive integer `N`. Your task is to find the smallest prime number greater than or equal to `N` that is also a palindrome. A palindrome is a number that reads the same forward and backward, such as 121 or 797.
#### Function Signature:
```python
def small... | def is_palindrome(num: int) -> bool:
"""
Checks if a number is a palindrome.
"""
return str(num) == str(num)[::-1]
def is_prime(num: int) -> bool:
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 =... | from solution import is_palindrome, is_prime, smallest_prime_palindrome
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(1) == True
assert is_palindrome(22) == True
def test_is_prime():
assert is_prime(2) == True
assert is_prim... | [
{
"docstring": "Checks if a number is a palindrome.",
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_pr... | [
0,
0,
1,
1,
0,
1,
0,
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": "def is_palindrome(num):\n \"\"\"\n Checks whether a given number is a palindrome.\n \"\"\"\n return str(num) == str(num)[::-1]\n\ndef is_prime(num):\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046407",
"row_id": 46407,
"seed_ids": "[1324]"
} | 0.736619 | Algorithm_46407 | I | [
"is_palindrome",
"is_prime",
"smallest_prime_palindrome"
] | 3 | [
[
"smallest_prime_palindrome",
"is_palindrome"
],
[
"smallest_prime_palindrome",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0ba73832a30cdd35a9d60fee59c28f6b21172e80 | 281c52c9f76b81ec31827926fc1f0f94846aa3a1 | |||
v1.0 | instruct | Algorithm | Algorithm_46413_I | ### Problem Statement
You are tasked with implementing a function to find the "longest" word that can be formed by deleting some characters of a given string `s`, and where the word formed must be a subsequence of a list of words `d`. If there are multiple possible results, return the longest word with the smallest le... | from typing import List
def is_subsequence(x: str, y: str) -> bool:
"""
Helper function to check if x is a subsequence of y
"""
it = iter(y)
return all(c in it for c in x)
def find_longest_word_in_string(s: str, d: List[str]) -> str:
"""
Returns the longest word in dictionary d that can be... | def test_find_longest_word_in_string():
assert find_longest_word_in_string("abpcplea", ["ale", "apple", "monkey", "plea"]) == "apple"
assert find_longest_word_in_string("abpcplea", ["a", "b", "c"]) == "a"
assert find_longest_word_in_string("", ["a", "b", "c"]) == ""
assert find_longest_word_in_string("a... | [
{
"docstring": "Helper function to check if x is a subsequence of y",
"function_declaration": "def is_subsequence(x, y):",
"function_name": "is_subsequence",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the longest word in dictionary d that can be formed by deleting \nsome character... | [
0,
1,
0,
0,
1,
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": "from typing import List\n\ndef find_longest_word_in_string(s: str, d: List[str]) -> str:\n def is_subsequence(x):\n it = iter(s)\n return all(c ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046413",
"row_id": 46413,
"seed_ids": "[127]"
} | 0.745988 | Algorithm_46413 | I | [
"is_subsequence",
"find_longest_word_in_string"
] | 2 | [
[
"find_longest_word_in_string",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 69e31f9828981bca402ae721ecd928a2fda50a59 | 8422304f94c743adc50151e579058186f02c175c | |||
v1.0 | instruct | Algorithm | Algorithm_46474_I | ### Decision Tree Classifier Implementation Challenge
#### Context
You are presented with a dataset of medical records where each record contains information about patient symptoms and a binary diagnosis: healthy (0) or diseased (1). Your task is to implement a decision tree classifier from scratch in Python to predic... | import numpy as np
def entropy(y):
unique, counts = np.unique(y, return_counts=True)
probabilities = counts / len(y)
return -np.sum(probabilities * np.log2(probabilities))
def information_gain(y, y_left, y_right):
weight_left = len(y_left) / len(y)
weight_right = len(y_right) / len(y)
return e... | import pytest
import numpy as np
from solution import decision_tree_classifier
def test_single_node_tree():
X = np.array([[0], [0], [0], [0]])
y = np.array([1, 1, 1, 1])
tree = decision_tree_classifier(X, y, max_depth=1)
assert tree == {'class': 1}
def test_two_node_tree():
X = np.array([[0], [1],... | [
{
"docstring": null,
"function_declaration": "def entropy(y):",
"function_name": "entropy",
"parameter_list": "(y)"
},
{
"docstring": null,
"function_declaration": "def information_gain(y, y_left, y_right):",
"function_name": "information_gain",
"parameter_list": "(y, y_left, y_r... | [
0,
1,
1,
0,
0,
0,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import Counter\n\ndef entropy(y):\n counter = Counter(y)\n probabilities = [count / len(y) for count in counter.values... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000046474",
"row_id": 46474,
"seed_ids": "[524]"
} | 0.560723 | Algorithm_46474 | I | [
"entropy",
"information_gain",
"split_dataset",
"best_split",
"build_tree",
"decision_tree_classifier"
] | 6 | [
[
"best_split",
"information_gain"
],
[
"best_split",
"split_dataset"
],
[
"build_tree",
"best_split"
],
[
"build_tree",
"split_dataset"
],
[
"decision_tree_classifier",
"build_tree"
],
[
"information_gain",
"entropy"
]
] | 6 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a5250faaa17293b62e839c94f2ed48c8ee0527e3 | 3bf613590f1999332f230180051dccd661d0cdff | |||
v1.0 | instruct | Algorithm | Algorithm_46537_I | ### K-Nearest Neighbors (KNN) Classifier Implementation
You are tasked with implementing a simple K-Nearest Neighbors (KNN) classifier from scratch to classify a given dataset into two classes.
**Objective**:
Write a Python function named `knn_classifier` that classifies data points based on the KNN algorithm and eva... | import math
from collections import Counter
from typing import List
def euclidean_distance(point1: List[float], point2: List[float]) -> float:
"""
Calculates the Euclidean distance between two points.
"""
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def knn_classifier(train_data... | from solution import knn_classifier
def test_knn_simple_case():
train_data = [[1, 2], [2, 3], [3, 4], [6, 7], [7, 8], [8, 9]]
train_labels = [0, 0, 0, 1, 1, 1]
test_data = [[2, 3, 0], [7, 8, 1]]
k = 3
accuracy = knn_classifier(train_data, train_labels, test_data, k)
assert accuracy == 1.0
def ... | [
{
"docstring": "Calculates the Euclidean distance between two points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def knn_classifier(train... | [
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 math\nfrom collections import Counter\nfrom typing import List\n\ndef euclidean_distance(point1: List[float], point2: List[float]) -> float:\n \"\"\"\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000046537",
"row_id": 46537,
"seed_ids": "[4266]"
} | 0.623921 | Algorithm_46537 | I | [
"euclidean_distance",
"knn_classifier"
] | 2 | [
[
"knn_classifier",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 459d8c97be02bb13c7490ab48178434d0e4a47fb | cb04a36d7cd3ad7536a518a3f1a55b703313df95 | |||
v1.0 | instruct | Algorithm | Algorithm_46541_I | ### Sudoku Solver
You are required to implement a Sudoku solver that fills in the missing numbers in a given 9x9 Sudoku grid. Your implementation will help assess your abilities to handle backtracking and constraint satisfaction problems in algorithm design.
#### Problem Statement
Create a function `solve_sudoku(gri... | def is_valid_move(grid, row, col, num):
"""
Check if placing num at grid[row][col] is valid according to Sudoku rules.
"""
for i in range(9):
# Check the row
if grid[row][i] == num:
return False
# Check the column
if grid[i][col] == num:
return Fal... | from solution import solve_sudoku
def test_sudoku_solver():
grid = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, ... | [
{
"docstring": "Check if placing num at grid[row][col] is valid according to Sudoku rules.",
"function_declaration": "def is_valid_move(grid, row, col, num):",
"function_name": "is_valid_move",
"parameter_list": "(grid, row, col, num)"
},
{
"docstring": "Solves the given Sudoku puzzle in-pla... | [
1,
0,
0,
0,
1,
1,
1,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_valid(grid, r, c, num):\n # Check if 'num' is not in the current row, column and 3x3 sub-grid\n for i in range(9):\n if grid[r][i] == num or ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046541",
"row_id": 46541,
"seed_ids": "[1704]"
} | 0.656423 | Algorithm_46541 | I | [
"is_valid_move",
"solve_sudoku"
] | 2 | [
[
"solve_sudoku",
"is_valid_move"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 11c9b9fb9945278fca7a0b7aa52ba89a2feef364 | 251a0b0165d277f098951d77dbd6e296b2c17729 | |||
v1.0 | instruct | Algorithm | Algorithm_46621_I | ### Coding Assessment Question
**Scenario**:
You are tasked with developing a financial software that assists bankers in determining the loan eligibility of clients based on their credit scores. The software should use a logistic regression model to make predictions about whether a client is likely to default on a loa... | from typing import List
import numpy as np
def sigmoid(z):
"""Compute the sigmoid of z"""
return 1 / (1 + np.exp(-z))
def logistic_regression_predict(train_scores: List[int], train_defaults: List[int], query_score: int) -> float:
"""
Predict the probability of default for a given credit score using lo... | import pytest
from solution import logistic_regression_predict
def test_logistic_regression_predict_basic():
train_scores = [600, 650, 700, 750, 800]
train_defaults = [1, 0, 0, 0, 0]
query_score = 675
result = logistic_regression_predict(train_scores, train_defaults, query_score)
assert 0 <= result... | [
{
"docstring": "Compute the sigmoid of z",
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},
{
"docstring": "Predict the probability of default for a given credit score using logistic regression.",
"function_declaration": "def logistic_regr... | [
1,
1,
1,
0,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.optimize import minimize\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef compute_cost(theta, X, y):\n m = y.size\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046621",
"row_id": 46621,
"seed_ids": "[4131]"
} | 0.731345 | Algorithm_46621 | I | [
"sigmoid",
"logistic_regression_predict"
] | 2 | [
[
"logistic_regression_predict",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 502be18b710475f4b825edd20f4d4d25fa931431 | b517e191f80db04b0d2ab2a1f82c24a67dd4b0cd | |||
v1.0 | instruct | Algorithm | Algorithm_46748_I | ### Coding Question: Optimizing Merge Sort for Linked List
You are given an implementation of merge sort for sorting an array of integers. Your task is to modify and extend the existing algorithm to sort a singly linked list instead of an array. The given linked list is defined using the `ListNode` class.
### Task
1.... | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def merge_sort_linked_list(head: ListNode) -> ListNode:
"""
Sorts a linked list using merge sort.
:param head: ListNode, the head of the linked list to be sorted.
:return: ListNode, the head ... | import pytest
from solution import merge_sort_linked_list, linked_list_to_list, list_to_linked_list
def test_merge_sort_empty_list():
head = list_to_linked_list([])
sorted_head = merge_sort_linked_list(head)
assert linked_list_to_list(sorted_head) == []
def test_merge_sort_single_element():
head = lis... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\ndef find_middle(head: ListNode) -> ListNode... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000046748",
"row_id": 46748,
"seed_ids": "[383]"
} | 0.518559 | Algorithm_46748 | I | [
"merge_sort_linked_list",
"find_middle",
"merge_two_lists",
"linked_list_to_list",
"list_to_linked_list"
] | 5 | [
[
"merge_sort_linked_list",
"find_middle"
],
[
"merge_sort_linked_list",
"merge_two_lists"
]
] | 2 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | de394de5ef77531a843372146c963985c0eb49b8 | c5ec0d79064bedb92a9ca3dfedf6314c53b013a4 | |||
v1.0 | instruct | Algorithm | Algorithm_46752_I | ### Coding Assessment Question: Matrix Operation and Statistics
#### Context:
In mathematical computations, operations with matrices are essential, and it's vital to perform them efficiently. Given a matrix representing data points, different computational statistics are required to analyze this data.
#### Problem St... | def transpose_matrix(matrix):
"""
Returns the transpose of the given matrix.
"""
if not matrix:
return []
return [list(row) for row in zip(*matrix)]
def matrix_mean(matrix):
"""
Returns a list of mean values of each column in the matrix.
"""
if not matrix or not matrix[0]:
... | from solution import (
transpose_matrix,
matrix_mean,
matrix_variance,
correlation_coefficient,
normalize_matrix
)
def test_transpose_matrix():
assert transpose_matrix([[1, 2, 3]]) == [[1], [2], [3]]
assert transpose_matrix([[1], [2], [3]]) == [[1, 2, 3]]
assert transpose_matrix([]) == ... | [
{
"docstring": "Returns the transpose of the given matrix.",
"function_declaration": "def transpose_matrix(matrix):",
"function_name": "transpose_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Returns a list of mean values of each column in the matrix.",
"function_declaration":... | [
1,
0,
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": "import numpy as np\n\ndef transpose_matrix(matrix):\n \"\"\"\n Returns the transpose of the given matrix.\n \n matrix: list of lists\n \"\"\"\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000046752",
"row_id": 46752,
"seed_ids": "[4028]"
} | 0.615887 | Algorithm_46752 | I | [
"transpose_matrix",
"matrix_mean",
"matrix_variance",
"correlation_coefficient",
"normalize_matrix"
] | 5 | [
[
"matrix_variance",
"matrix_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 984668554c21a86b0f8e91501ec7834e985a5ff5 | 59bd035f9f555e104f14854e3ff8f8d6deedb162 | |||
v1.0 | instruct | Algorithm | Algorithm_46806_I | ### Challenging Coding Assessment Question
#### Context
Sorting algorithms are fundamental in computer science and have various levels of complexity and efficiency. Today’s challenge focuses on implementing a sophisticated sorting algorithm that handles large datasets efficiently while providing stable output.
#### ... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: List[int], right: List[int]) -> List[int]:
so... | def test_merge_sort():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert merge_sort([5, 3, 8, 6, 2, 7, 4, 1]) == [1, 2, 3, 4, 5, 6, 7, 8]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
assert merge_... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046806",
"row_id": 46806,
"seed_ids": "[2816]"
} | 0.590232 | Algorithm_46806 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 0818ee8f846fd81dd0b881137895faae97f28b41 | dfd9942089e33a0dbd334299b8521f6963f4b7fe | |||
v1.0 | instruct | Algorithm | Algorithm_46925_I | **Question:**
You are asked to write a function that finds the smallest positive integer `n` such that the value of `n^3` contains all the digits from 0 to 9 at least once.
Instead of brute-forcing through every integer, consider an optimized strategy to narrow down potential candidates and quickly check if their cu... | def contains_all_digits(number):
"""
Helper function to check if the number contains all digits from 0 to 9 at least once.
"""
digits = set(str(number))
return len(digits) == 10 and all(str(d) in digits for d in range(10))
def find_smallest_cube():
"""
Find the smallest positive integer n s... | from solution import find_smallest_cube
def test_find_smallest_cube():
result = find_smallest_cube()
assert isinstance(result, int), "Result should be an integer"
assert result > 0, "Result should be positive"
assert contains_all_digits(result ** 3), "The cube of the result should contain all digits fr... | [
{
"docstring": "Helper function to check if the number contains all digits from 0 to 9 at least once.",
"function_declaration": "def contains_all_digits(number):",
"function_name": "contains_all_digits",
"parameter_list": "(number)"
},
{
"docstring": "Find the smallest positive integer n suc... | [
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 contains_all_digits(n):\n \"\"\"\n Check if the number n contains all digits from 0 to 9 at least once.\n \"\"\"\n digits = set(str(n))\n retu... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000046925",
"row_id": 46925,
"seed_ids": "[2933]"
} | 0.682 | Algorithm_46925 | I | [
"contains_all_digits",
"find_smallest_cube"
] | 2 | [
[
"find_smallest_cube",
"contains_all_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 51d43bed8ebb18768412497b16d63394b5396d65 | bb9df625c9db22dadf462ce9a48e44dd4fe75f33 | |||
v1.0 | instruct | Algorithm | Algorithm_46946_I | ### Question: Aggregating and Analyzing Server Logs
You are required to write a Python script to process and analyze server log files. The log files are in a standardized format, and include log entries that consist of the timestamp, HTTP method, URI, status code, and response time. Your task is to analyze these logs ... | import re
import sys
import logging
from collections import defaultdict
def parse_log_entry(line: str):
"""
Parses a single log entry and returns a tuple with the extracted data.
:param line: A single line from the log file.
:return: A tuple with (timestamp, http_method, uri, status_code, response_tim... | import os
import tempfile
from solution import analyze_server_logs, parse_log_entry
def test_parse_log_entry():
entry = '[2023-04-12T12:34:56Z] "GET /index.html" 200 0.123'
parsed = parse_log_entry(entry)
assert parsed == ('2023-04-12T12:34:56Z', 'GET', '/index.html', 200, 0.123)
entry = '[2023-04-12T... | [
{
"docstring": "Parses a single log entry and returns a tuple with the extracted data.\n\n:param line: A single line from the log file.\n:return: A tuple with (timestamp, http_method, uri, status_code, response_time).",
"function_declaration": "def parse_log_entry(line):",
"function_name": "parse_log_en... | [
0,
0,
0,
1,
1,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nimport sys\nfrom collections import defaultdict\nfrom statistics import mean\n\ndef parse_log_line(line):\n pattern = r'\\[(.*?)\\] \"(\\w+) (.*?)\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000046946",
"row_id": 46946,
"seed_ids": "[2353]"
} | 0.647908 | Algorithm_46946 | I | [
"parse_log_entry",
"analyze_server_logs"
] | 2 | [
[
"analyze_server_logs",
"parse_log_entry"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15d9921e54cfcf439d56b59c5c6e3d9fb182d68d | 20fb06c010099bcb6b717d061d36ba65202ef09e | |||
v1.0 | instruct | Algorithm | Algorithm_46949_I | ### Problem Statement
You are tasked with developing a feature for a fitness tracking application that analyzes a user's running performance over a specified number of days. The application should calculate the user's total distance ran, average distance per day, and identify the longest run in the given timeframe.
#... | from typing import List
def total_distance(distances: List[float]) -> float:
if not all(d >= 0 for d in distances):
raise ValueError("All distances must be non-negative")
return round(sum(distances), 2)
def average_distance(distances: List[float]) -> float:
if not distances:
return 0.0
... | import pytest
from solution import total_distance, average_distance, longest_run, running_summary
def test_total_distance():
assert total_distance([5.0, 7.2, 3.3, 4.7, 6.6]) == 26.8
assert total_distance([10.5, 8.6, 12.3, 7.4]) == 38.8
with pytest.raises(ValueError):
total_distance([-1.0, 5.0])
de... | [
{
"docstring": null,
"function_declaration": "def total_distance(distances):",
"function_name": "total_distance",
"parameter_list": "(distances)"
},
{
"docstring": null,
"function_declaration": "def average_distance(distances):",
"function_name": "average_distance",
"parameter_li... | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef total_distance(distances: List[float]) -> float:\n \"\"\"\n Returns the total distance run over the specified days.\n \"\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000046949",
"row_id": 46949,
"seed_ids": "[640]"
} | 0.692547 | Algorithm_46949 | I | [
"total_distance",
"average_distance",
"longest_run",
"running_summary"
] | 4 | [
[
"running_summary",
"average_distance"
],
[
"running_summary",
"longest_run"
],
[
"running_summary",
"total_distance"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9c97d68c10351b1e0f285cbea4d380d1e20381df | 52c332a1c898b34d0688e0139fe869055972836c | |||
v1.0 | instruct | Algorithm | Algorithm_46969_I | ### Question: Efficiently Find Closest Points
#### Scenario
You are given a list of points in a 2D plane, each represented by their `(x, y)` coordinates. Your task is to find the `k` closest points to the origin `(0, 0)` using the Euclidean distance. This is a common problem in various fields like computer graphics, g... | import heapq
def euclidean_distance(point):
"""
Helper function to calculate the squared Euclidean distance from origin (0, 0).
Squared distance is used to avoid floating-point operations and preserve performance.
"""
x, y = point
return x * x + y * y
def find_closest_points(points, k):
""... | from solution import find_closest_points
def test_find_closest_points_example():
points = [(1, 3), (3, 4), (2, -1)]
k = 2
expected = {(1, 3), (2, -1)} # sets are used because the order does not matter
assert set(find_closest_points(points, k)) == expected
def test_find_closest_points_basic():
poi... | [
{
"docstring": "Helper function to calculate the squared Euclidean distance from origin (0, 0).\nSquared distance is used to avoid floating-point operations and preserve performance.",
"function_declaration": "def euclidean_distance(point):",
"function_name": "euclidean_distance",
"parameter_list": ... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nimport math\n\ndef find_closest_points(points, k):\n \"\"\"\n Finds and returns the k closest points to the origin (0, 0).\n \n Args:\n... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000046969",
"row_id": 46969,
"seed_ids": "[4277]"
} | 0.705817 | Algorithm_46969 | I | [
"euclidean_distance",
"find_closest_points"
] | 2 | [
[
"find_closest_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 22b70fcaed0ec18c4ef4d18fc716f78470a55da7 | 8cadccd287b14544157d4a56e7adecb98bc8a398 | |||
v1.0 | instruct | Algorithm | Algorithm_46996_I | Implement a function `prime_indices` that takes a list of integers and returns a list of indices where the elements are prime numbers.
A prime number is a natural number greater than 1 that is not divisible by any positive integers other than 1 and itself.
#### Function Signature
```python
def prime_indices(numbers: ... | 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 prime_indices(numbers: List[int]) -> List[... | from solution import prime_indices
def test_prime_indices_with_primes():
assert prime_indices([0, 1, 2, 3, 4, 5, 6, 7]) == [2, 3, 5, 7]
def test_prime_indices_with_mixed_numbers():
assert prime_indices([10, 14, 17, 19, 21, 23]) == [2, 3, 5]
def test_prime_indices_with_no_primes():
assert prime_indices([4... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_indices(numbers):",
"function_name": "prime_indices",
"parameter_list": "(numbers)"
}
] | [
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 is_prime(num: int) -> bool:\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000046996",
"row_id": 46996,
"seed_ids": "[4138]"
} | 0.722014 | Algorithm_46996 | I | [
"is_prime",
"prime_indices"
] | 2 | [
[
"prime_indices",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56ca7c912c3ab4e13578c3221b359bfef3be9df1 | cc5d256f9d3222ae667423c874eed658f9345abd | |||
v1.0 | instruct | Algorithm | Algorithm_47053_I | ### Palindromic Sum
**Overview**:
A number is said to be a palindromic number if it reads the same backward as forward. Sometimes, a non-palindromic number can be converted to a palindromic number by repeatedly reversing its digits and adding the result to the original number. This process is repeated until a palindro... | def is_palindrome(num: int) -> bool:
return str(num) == str(num)[::-1]
def palindromic_sum(num: int) -> int:
if not isinstance(num, int) or num <= 0:
raise ValueError("Input must be a positive integer")
while not is_palindrome(num):
num += int(str(num)[::-1])
return num | from solution import palindromic_sum
def test_palindromic_sum_small_number():
assert palindromic_sum(56) == 121
def test_palindromic_sum_large_operation():
assert palindromic_sum(87) == 4884
def test_palindromic_sum_already_palindrome():
assert palindromic_sum(121) == 121
assert palindromic_sum(9) ==... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def palindromic_sum(num):",
"function_name": "palindromic_sum",
"parameter_list": "(num)"
}
] | [
1,
0,
0,
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": "def is_palindrome(n):\n return str(n) == str(n)[::-1]\n\ndef palindromic_sum(num: int) -> int:\n if not isinstance(num, int) or num <= 0:\n raise Va... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047053",
"row_id": 47053,
"seed_ids": "[3472]"
} | 0.677671 | Algorithm_47053 | I | [
"is_palindrome",
"palindromic_sum"
] | 2 | [
[
"palindromic_sum",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c1e76bd87b3e060714d6a1471c2a5a4c461c90d | f58e83c44d5e9d54b74b31a7fccf5580cb03bcc8 | |||
v1.0 | instruct | Algorithm | Algorithm_47092_I | ### Matrix Rotation Checker
Given two square matrices `matrix1` and `matrix2` of size `n x n`, determine if `matrix2` can be obtained by rotating `matrix1` by 90, 180, or 270 degrees. If `matrix2` can be obtained by any such rotation, return the rotation degree. Otherwise, return -1.
### Function Signature
```python
... | def rotate_90(matrix):
"""Rotate the given n x n matrix by 90 degrees."""
n = len(matrix)
return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)]
def check_rotation(matrix1, matrix2):
"""
Returns the degree of rotation needed to obtain matrix2 from matrix1,
or -1 if such rotation is... | def test_rotation_90():
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[3, 1], [4, 2]]
assert check_rotation(matrix1, matrix2) == 90
def test_rotation_180():
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[4, 3], [2, 1]]
assert check_rotation(matrix1, matrix2) == 180
def test_rotation_270():
matrix1 = [[1, ... | [
{
"docstring": "Rotate the given n x n matrix by 90 degrees.",
"function_declaration": "def rotate_90(matrix):",
"function_name": "rotate_90",
"parameter_list": "(matrix)"
},
{
"docstring": "Returns the degree of rotation needed to obtain matrix2 from matrix1,\nor -1 if such rotation is not ... | [
1,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def check_rotation(matrix1, matrix2):\n def rotate_90(matrix):\n return [list(reversed(col)) for col in zip(*matrix)]\n\n if matrix1 == matrix2:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000047092",
"row_id": 47092,
"seed_ids": "[2239]"
} | 0.544791 | Algorithm_47092 | I | [
"rotate_90",
"check_rotation"
] | 2 | [
[
"check_rotation",
"rotate_90"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 0620c90d77989c842309cc275551a251ca40ac00 | 966f70018e013712640e27bc5514305b0ef99456 | |||
v1.0 | instruct | Algorithm | Algorithm_47093_I | ### Coding Assessment Question
#### Problem Statement
**Context**:
Jack is a computer scientist focusing on data structures and algorithms. He's currently working on optimizing a search algorithm using balanced trees. One of his tasks is to validate if a given binary search tree remains balanced after a series of ins... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_bst(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_bst(root.left, val)
else:
root.right = ... | import pytest
from solution import TreeNode, validate_balanced_bst
def test_validate_balanced_bst_example1():
root = TreeNode(10)
operations = [5, 15, 3, 7, 18]
expected = [True, True, True, True, True]
assert validate_balanced_bst(root, operations) == expected
def test_validate_balanced_bst_example2(... | [] | [
0,
1,
0,
1,
0,
1,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "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 inser... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000047093",
"row_id": 47093,
"seed_ids": "[2018]"
} | 0.702688 | Algorithm_47093 | I | [
"insert_bst",
"height",
"is_balanced",
"validate_balanced_bst"
] | 4 | [
[
"is_balanced",
"height"
],
[
"validate_balanced_bst",
"insert_bst"
],
[
"validate_balanced_bst",
"is_balanced"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 23f9832c5d234c0e2b0248a76cb3b827e2559e25 | d9a749ca3e870429447be54ab7a160bb8a4d3055 | |||
v1.0 | instruct | Algorithm | Algorithm_47115_I | **Context:** Radix Sort is a non-comparative integer sorting algorithm that sorts numbers by processing individual digits. It works well with data that has a fixed length of integer representations and is often implemented for sorting large numbers efficiently. Your task will be to sort an array of integers using Radix... | from typing import List
from math import log10
def counting_sort_for_radix(arr, exp, base):
n = len(arr)
output = [0] * n
count = [0] * base
for i in range(n):
index = abs(arr[i]) // exp
count[index % base] += 1
for i in range(1, base):
count[i] += count[i - 1]
for i ... | from solution import custom_radix_sort
def test_single_negative_element():
assert custom_radix_sort([-1]) == [-1]
def test_single_non_negative_element():
assert custom_radix_sort([0]) == [0]
assert custom_radix_sort([1]) == [1]
def test_mixed_elements_simple():
assert custom_radix_sort([-15, 3, 0, -2... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp, base):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp, base)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, base=10):",
"function_name": "radix_sort"... | [
0,
0,
0,
0,
0,
1,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef custom_radix_sort(arr: List[int]) -> List[int]:\n def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000047115",
"row_id": 47115,
"seed_ids": "[950]"
} | 0.644609 | Algorithm_47115 | I | [
"counting_sort_for_radix",
"radix_sort",
"custom_radix_sort"
] | 3 | [
[
"custom_radix_sort",
"radix_sort"
],
[
"radix_sort",
"counting_sort_for_radix"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1a48fd431aac930e3d9b02c82eea57990ae25d56 | 62a5d1a68c2eb01b0b07a45a401ff5cd75aebe84 | |||
v1.0 | instruct | Algorithm | Algorithm_47182_I | ## Question
Sorting algorithms are fundamental in computer science due to their wide application in various domains. Implement the Merge Sort algorithm to sort a list of integers in non-decreasing order.
### Function Signature
```python
def merge_sort(arr: List[int]) -> List[int]:
pass
```
### Input
* A list of i... | def merge_sort(arr):
"""
Performs the merge sort algorithm on a list of integers.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A new list containing the elements of the input list in non-decreasing order.
"""
if len(arr) <= 1:
return a... | def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_multiple_elements():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_negatives():
assert merge_sor... | [
{
"docstring": "Performs the merge sort algorithm on a list of integers.\n\nParameters:\n arr (list): A list of integers to be sorted.\n\nReturns:\n list: A new list containing the elements of the input list in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"function_name"... | [
1,
1,
0,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047182",
"row_id": 47182,
"seed_ids": "[2073]"
} | 0.617074 | Algorithm_47182 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3419ed0cfda998ed04e4e986de231bd2217ba5c0 | 4494b3df5002622f58b3fac6419adb3beb2ed751 | |||
v1.0 | instruct | Algorithm | Algorithm_47210_I | ### Problem Statement:
You are working on a file processing system that reads large files line-by-line and performs a transformation on each line before saving the results to a new file. Extend the provided `process_files` function to handle multiple files simultaneously, implement logging for success and failure mess... | import concurrent.futures
import logging
from typing import List, Callable
import os
# Set up logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def process_file(input_file: str, output_file: str, transform: Callable[[str], str]) -> None:
try:
... | import pytest
import os
from solution import process_files, upper_case_transform
def write_test_file(filename, lines):
with open(filename, 'w') as f:
for line in lines:
f.write(line)
def read_file_lines(filename):
with open(filename, 'r') as f:
return f.readlines()
def test_proce... | [
{
"docstring": null,
"function_declaration": "def process_file(input_file, output_file, transform):",
"function_name": "process_file",
"parameter_list": "(input_file, output_file, transform)"
},
{
"docstring": null,
"function_declaration": "def process_files(input_files, output_files, tr... | [
1,
1,
1,
0,
0,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import logging\nfrom typing import List, Callable\nimport concurrent.futures\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000047210",
"row_id": 47210,
"seed_ids": "[2259]"
} | 0.541086 | Algorithm_47210 | I | [
"process_file",
"process_files",
"upper_case_transform"
] | 3 | [
[
"process_files",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38b09e2999f18cbcb88046ab42da8ea17880e409 | 3a90a3e09c2f37c56c7c510b08909a056c5fbf81 | |||
v1.0 | instruct | Algorithm | Algorithm_47385_I | ### Array Rotation Challenges
**Context**: Array rotations are common operations in many programming problems, where elements of the array are shifted either to the left or right. Your task is to implement functions that handle left and right rotations on arrays efficiently.
**Tasks**:
1. `left_rotate(arr: list, k: i... | def reverse_array_partition(arr, start, end):
"""
Helper function to reverse a portion of the array from start index to end index.
"""
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def left_rotate(arr, k):
"""
Rotates elements of the ... | from solution import left_rotate, right_rotate
def test_left_rotate():
assert left_rotate([1, 2, 3, 4, 5], 2) == [3, 4, 5, 1, 2]
assert left_rotate([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
assert left_rotate([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]
assert left_rotate([1, 2, 3, 4, 5], 7) == [3, 4, 5, 1, 2]
... | [
{
"docstring": "Helper function to reverse a portion of the array from start index to end index.",
"function_declaration": "def reverse_array_partition(arr, start, end):",
"function_name": "reverse_array_partition",
"parameter_list": "(arr, start, end)"
},
{
"docstring": "Rotates elements of... | [
0,
0,
0,
0,
0,
1,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def left_rotate(arr, k):\n \"\"\"\n Rotates elements of the array to the left by k positions.\n \"\"\"\n n = len(arr)\n k = k % n # To handle the... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000047385",
"row_id": 47385,
"seed_ids": "[4851]"
} | 0.622943 | Algorithm_47385 | I | [
"reverse_array_partition",
"left_rotate",
"right_rotate"
] | 3 | [
[
"left_rotate",
"reverse_array_partition"
],
[
"right_rotate",
"reverse_array_partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ca82b93d0360be7712d2fea8e326d84b9b89e2a0 | 6bb601d5c3b260e7dbfc661b6bc0e9f97f40746f | |||
v1.0 | instruct | Algorithm | Algorithm_47396_I | ### Question
Write a function that sorts a list of integers using the Merge Sort algorithm. Ensure the implementation handles both even and odd length lists, including an empty list and a single-element list.
#### Function Signature
```python
def merge_sort(arr: list[int]) -> list[int]:
```
#### Input
* `arr` (list[i... | def merge_sort(arr: list[int]) -> list[int]:
"""
Sorts a list of integers using the Merge Sort algorithm.
"""
if len(arr) <= 1: # Base case for recursion: an empty list or a single-element list
return arr
# Split the list into two halves
mid = len(arr) // 2
left_half = merge_so... | from solution import merge_sort
def test_merge_sort_general_case():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elemen... | [
{
"docstring": "Sorts a list of integers using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"function_declaration": "def merge(l... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr: list[int]) -> list[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half = merge_sort(arr[:mid])\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047396",
"row_id": 47396,
"seed_ids": "[1560]"
} | 0.621259 | Algorithm_47396 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ff7fa2418f88c9ff736df83bb2649d332954d0db | 611659681e55ebe6da3a0e90c7318cc5733e8f29 | |||
v1.0 | instruct | Algorithm | Algorithm_47414_I | ### Task
Create a simple text-based tic-tac-toe game where two players can play against each other by taking turns.
### Objectives:
1. Write a function `initialize_board() -> List[List[str]]` to create a 3x3 game board initialized with empty spaces.
2. Implement the `print_board(board: List[List[str]]) -> None` functi... | from typing import List
def initialize_board() -> List[List[str]]:
"""
Initialize the tic-tac-toe board as a 3x3 list filled with empty spaces.
"""
return [[' ' for _ in range(3)] for _ in range(3)]
def print_board(board: List[List[str]]) -> None:
"""
Print the current state of the board.
... | from solution import initialize_board, print_board, make_move, check_winner
def test_initialize_board():
board = initialize_board()
assert board == [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
def test_make_move():
board = initialize_board()
assert make_move(board, 1, 1, 'X') == True
assert... | [
{
"docstring": "Initialize the tic-tac-toe board as a 3x3 list filled with empty spaces.",
"function_declaration": "def initialize_board():",
"function_name": "initialize_board",
"parameter_list": "()"
},
{
"docstring": "Print the current state of the board.",
"function_declaration": "de... | [
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 initialize_board():\n \"\"\"\n Creates and returns a 3x3 game board initialized with empty spaces (' ').\n \"\"\"\n return [[' ' for _ in range(3... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000047414",
"row_id": 47414,
"seed_ids": "[1830]"
} | 0.607844 | Algorithm_47414 | I | [
"initialize_board",
"print_board",
"make_move",
"check_winner",
"play_game"
] | 5 | [
[
"play_game",
"check_winner"
],
[
"play_game",
"initialize_board"
],
[
"play_game",
"make_move"
],
[
"play_game",
"print_board"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 65c2f204fbedd5e6066420b7376d71df2d09b1d2 | 1ef84c2ad964e482cc1b697d9f38ce6249cc876c | |||
v1.0 | instruct | Algorithm | Algorithm_47489_I | Circular Prime Number Detection
#### Description
A circular prime is a prime number that remains prime when its digits are cyclically permuted in any order. For example, 197 is a circular prime because all rotations of its digits (197, 971, and 719) are prime. You need to determine whether a given integer is a circula... | def sieve_of_eratosthenes(limit):
"""
Generate a list of booleans where the index is marked True if it's a prime number.
Uses Sieve of Eratosthenes method.
"""
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False # 0 and 1 are not primes
p = 2
while (p * p <= limit):
... | from solution import is_circular_prime
def test_is_circular_prime():
# Circular primes
assert is_circular_prime(197) == True
assert is_circular_prime(2) == True
assert is_circular_prime(11) == True
# Not circular primes
assert is_circular_prime(23) == False
assert is_circular_prime(10) == ... | [
{
"docstring": "Generate a list of booleans where the index is marked True if it's a prime number.\nUses Sieve of Eratosthenes method.",
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Check... | [
1,
0,
0,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_circular_prime(n: int) -> bool:\n def is_prime(num: int) -> bool:\n if num <= 1:\n return False\n if num == 2:\n re... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047489",
"row_id": 47489,
"seed_ids": "[4820]"
} | 0.626848 | Algorithm_47489 | I | [
"sieve_of_eratosthenes",
"is_prime",
"rotate_number",
"is_circular_prime"
] | 4 | [
[
"is_circular_prime",
"is_prime"
],
[
"is_circular_prime",
"rotate_number"
],
[
"is_circular_prime",
"sieve_of_eratosthenes"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 65368c96956269e3bcdb1fe3dfa7a726350286c2 | 76722f77b989b88d230a7095a102690f8d3d006d | |||
v1.0 | instruct | Algorithm | Algorithm_47511_I | ### Question
#### Scenario:
You are developing an application that requires handling and processing a sequence of mathematical expressions involving common arithmetic operations. To ensure the expressions are evaluated correctly and efficiently, you decide to implement a stack-based approach to evaluate postfix (Rever... | def evaluate_postfix(expression: str) -> int:
stack = []
tokens = expression.split()
for token in tokens:
if is_operator(token):
op2 = stack.pop()
op1 = stack.pop()
result = perform_operation(op1, op2, token)
stack.append(result)
else:
... | from solution import evaluate_postfix, is_operator, perform_operation
def test_evaluate_postfix():
assert evaluate_postfix("2 3 + 5 *") == 25
assert evaluate_postfix("10 2 / 5 +") == 10
assert evaluate_postfix("7 8 + 3 2 + /") == 3
assert evaluate_postfix("3 4 + 2 * 7 /") == 2
assert evaluate_postf... | [
{
"docstring": null,
"function_declaration": "def evaluate_postfix(expression):",
"function_name": "evaluate_postfix",
"parameter_list": "(expression)"
},
{
"docstring": null,
"function_declaration": "def is_operator(char):",
"function_name": "is_operator",
"parameter_list": "(ch... | [
0,
1,
0,
0,
1,
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 evaluate_postfix(expression: str) -> int:\n stack = []\n tokens = expression.split()\n \n for token in tokens:\n if is_operator(token):\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000047511",
"row_id": 47511,
"seed_ids": "[1495]"
} | 0.590894 | Algorithm_47511 | I | [
"evaluate_postfix",
"is_operator",
"perform_operation"
] | 3 | [
[
"evaluate_postfix",
"is_operator"
],
[
"evaluate_postfix",
"perform_operation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 87b67b3cb2f5af6814cd75f09ab455b869ad4a7c | d11222dced5f0c1f9196f0c8e093cea590b9bc12 | |||
v1.0 | instruct | Algorithm | Algorithm_47534_I | ### Scenario
You are developing a feature for a text editor that automatically corrects basic spelling mistakes using a predefined dictionary. The feature should replace each misspelled word with the closest matching word from the dictionary in terms of Levenshtein distance.
### Task
Implement the function `auto_corre... | from typing import List
from functools import lru_cache
def levenshtein_distance(word1: str, word2: str) -> int:
"""
Calculate the Levenshtein distance between two words.
"""
@lru_cache(None)
def distance(i, j):
if i == 0:
return j
if j == 0:
return i
... | from solution import auto_correct
def test_auto_correct_example_case():
sentences = [['speling', 'mistake', 'in', 'thes', 'sentense'], ['orrect', 'this', 'plea']]
dictionary = ['spelling', 'mistake', 'in', 'the', 'sentence', 'correct', 'this', 'please']
expected_output = [['spelling', 'mistake', 'in', 'the... | [
{
"docstring": "Calculate the Levenshtein distance between two words.",
"function_declaration": "def levenshtein_distance(word1, word2):",
"function_name": "levenshtein_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Replace misspelled words in sentences with the closest mat... | [
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 heapq\nfrom typing import List\n\ndef levenshtein_distance(a: str, b: str) -> int:\n if a == b:\n return 0\n if not a:\n return len(b)... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000047534",
"row_id": 47534,
"seed_ids": "[4283]"
} | 0.601663 | Algorithm_47534 | I | [
"levenshtein_distance",
"auto_correct"
] | 2 | [
[
"auto_correct",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3b4ec6e517ec221da20eacd29435cc02073af729 | ad471ad0fe69b62e72a2396bb86a8b2804c16b23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.