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_24460_I | ## Problem Statement
You are given a list of dates representing the start and end dates of various tasks in a project. Your task is to write a function to determine the maximum number of overlapping tasks at any given point in time.
### Input
- A list of tuples, where each tuple contains two dates (strings) in the fo... | from datetime import datetime
def convert_to_date(date_str):
"""
Convert a date string in format 'YYYY-MM-DD' to a datetime.date object.
"""
return datetime.strptime(date_str, '%Y-%m-%d').date()
def max_overlapping_tasks(tasks):
"""
Calculate the maximum number of overlapping tasks at any give... | from solution import convert_to_date, max_overlapping_tasks
def test_convert_to_date():
assert convert_to_date('2023-03-01') == datetime.strptime('2023-03-01', '%Y-%m-%d').date()
assert convert_to_date('2000-01-01') == datetime.strptime('2000-01-01', '%Y-%m-%d').date()
def test_max_overlapping_tasks():
ta... | [
{
"docstring": "Convert a date string in format 'YYYY-MM-DD' to a datetime.date object.",
"function_declaration": "def convert_to_date(date_str):",
"function_name": "convert_to_date",
"parameter_list": "(date_str)"
},
{
"docstring": "Calculate the maximum number of overlapping tasks at any g... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef convert_to_date(date_str):\n \"\"\"\n Converts a string date to a datetime.date object.\n \"\"\"\n return dateti... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000024460",
"row_id": 24460,
"seed_ids": "[2026]"
} | 0.624554 | Algorithm_24460 | I | [
"convert_to_date",
"max_overlapping_tasks"
] | 2 | [
[
"max_overlapping_tasks",
"convert_to_date"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc38de3ba8eb49eb775b5b86f9aa86128d83d859 | 910b3c1632fcb27684cffd87379eee9383a10cf3 | |||
v1.0 | instruct | Algorithm | Algorithm_24500_I | ### Question:
**[Graph Theory] Maximum Network Flow**
You are tasked with implementing a function to determine the maximum flow possible in a flow network. The network consists of nodes and directed edges where each edge has a certain capacity. The primary operations to support are:
1. **Maximum Flow Computation**: ... | from collections import deque, defaultdict
def bfs(capacity, s, t, parent):
visited = set()
queue = deque([s])
visited.add(s)
while queue:
u = queue.popleft()
for v in capacity[u]:
if v not in visited and capacity[u][v] > 0: # Check if not visited and there's ... | def test_max_flow_example():
assert max_flow(4, [(0, 1, 1000), (1, 2, 1), (0, 2, 1000), (2, 3, 1000), (1, 3, 1000)], 0, 3) == 2000
def test_max_flow_no_capacity():
assert max_flow(3, [(0, 1, 0), (1, 2, 0)], 0, 2) == 0
def test_max_flow_direct_path():
assert max_flow(2, [(0, 1, 100)], 0, 1) == 100
def tes... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, s, t, parent)"
},
{
"docstring": "Implementation of the Edmonds-Karp algorithm for finding the maximum flow in a flow network.",
"function_declaration": ... | [
1,
0,
0,
0,
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": "from collections import deque, defaultdict\n\ndef bfs(capacity, source, sink, parent):\n visited = set()\n queue = deque([source])\n visited.add(source)... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000024500",
"row_id": 24500,
"seed_ids": "[1566]"
} | 0.601259 | Algorithm_24500 | I | [
"bfs",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 69beff9ee12c657883509fab65bc1c86a3fc6936 | d31abe5510d449e2f5832e1c0785866c553b68a3 | |||
v1.0 | instruct | Algorithm | Algorithm_24501_I | ### Question: Custom Recursive Quick Sort
Implement a custom variation of the recursive quick sort algorithm for a list of integers, which includes a condition to move certain values to the beginning of the list at the end of the sorting process.
### Instructions:
1. **Function Signature**: Implement a function `cus... | def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
def quick_sort_rec(arr, low, high):
if low < high:
... | def test_custom_rec_quick_sort():
col = [3, 2, 1, 4, 3, 0, 2]
target_val = 3
custom_rec_quick_sort(col, 0, len(col) - 1, target_val)
assert col == [3, 3, 0, 1, 2, 2, 4]
def test_empty_array():
col = []
target_val = 1
custom_rec_quick_sort(col, 0, len(col) - 1, target_val)
assert col == ... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quick_sort_rec(arr, low, high):",
"function_name": "quick_sort_rec",
"parameter_l... | [
1,
1,
1,
1,
0,
1,
0,
1,
0
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def partition(arr, low, high):\n pivot = arr[high]\n i = low - 1\n for j in range(low, high):\n if arr[j] < pivot:\n i += 1\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000024501",
"row_id": 24501,
"seed_ids": "[1022]"
} | 0.582054 | Algorithm_24501 | I | [
"partition",
"quick_sort_rec",
"custom_rec_quick_sort"
] | 3 | [
[
"custom_rec_quick_sort",
"quick_sort_rec"
],
[
"quick_sort_rec",
"partition"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | ac26d1d19d975482e3555a169690cbfa6e86e101 | 98452d0e3b9da8d6545036c924be06c53f711db3 | |||
v1.0 | instruct | Algorithm | Algorithm_24507_I | ### Coding Assessment Question: Polynomial Root Finder Using Newton's Method
#### Background
Newton's Method (also known as the Newton-Raphson method) is an iterative root-finding algorithm that produces successively better approximations to the root (or zero) of a real-valued function. Given a differentiable function... | def polynomial_function(coefficients, x):
return sum(c * x**i for i, c in enumerate(reversed(coefficients)))
def polynomial_derivative(coefficients, x):
return sum(i * c * x**(i-1) for i, c in enumerate(reversed(coefficients)) if i != 0)
def newtons_method(coefficients, initial_guess, tolerance, max_iteration... | from solution import newtons_method
def test_newtons_method_simple():
# Polynomial: x^2 - 2
coefficients = [1, 0, -2]
assert abs(newtons_method(coefficients, 1, 0.0001, 1000) - 1.4142135623730951) < 0.0001
def test_newtons_method_cubic():
# Polynomial: x^3 - x - 2
coefficients = [1, 0, -1, -2]
... | [
{
"docstring": null,
"function_declaration": "def polynomial_function(coefficients, x):",
"function_name": "polynomial_function",
"parameter_list": "(coefficients, x)"
},
{
"docstring": null,
"function_declaration": "def polynomial_derivative(coefficients, x):",
"function_name": "pol... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def polynomial_function(coefficients, x):\n \"\"\"\n Calculate the polynomial value for the given x.\n\n :param coefficients: List of coefficients for t... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000024507",
"row_id": 24507,
"seed_ids": "[3307]"
} | 0.6555 | Algorithm_24507 | I | [
"polynomial_function",
"polynomial_derivative",
"newtons_method"
] | 3 | [
[
"newtons_method",
"polynomial_derivative"
],
[
"newtons_method",
"polynomial_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f339585f3d5375bb80b2a286b8a8654a7b188ef2 | 393d4c990ed2ea9d5c795f4c741c4f78efb369cb | |||
v1.0 | instruct | Algorithm | Algorithm_24544_I | ### Cryptocurrency Portfolio Tracker
You are working on a cryptocurrency portfolio tracker that collects data about various cryptocurrencies and calculates the current value of a user's portfolio. Your task is to extend the existing code to fetch the price of a specific cryptocurrency from a given API and then compute... | import requests
def fetch_crypto_price(api_url: str, currency: str) -> float:
"""
Return the current price of `currency` in USD.
The function makes an HTTP GET request to fetch the cryptocurrency price.
Handles non-200 responses and other potential issues gracefully.
"""
try:
response =... | import pytest
import requests
from unittest.mock import patch
from solution import fetch_crypto_price, portfolio_value
API_URL = "https://api.coingecko.com/api/v3/simple/price"
def mock_fetch_response(*args, **kwargs):
# Mock response data mimicking the API response structure
class MockResponse:
def ... | [
{
"docstring": "Return the current price of `currency` in USD.\nThe function makes an HTTP GET request to fetch the cryptocurrency price.\nHandles non-200 responses and other potential issues gracefully.",
"function_declaration": "def fetch_crypto_price(api_url, currency):",
"function_name": "fetch_cryp... | [
0,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom requests.exceptions import RequestException\n\ndef fetch_crypto_price(api_url: str, currency: str) -> float:\n \"\"\"\n Return the cu... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000024544",
"row_id": 24544,
"seed_ids": "[2420]"
} | 0.45397 | Algorithm_24544 | I | [
"fetch_crypto_price",
"portfolio_value"
] | 2 | [
[
"portfolio_value",
"fetch_crypto_price"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 3ef69f8fa9891fe884bbfc2b54284a61d8ef8452 | 51e4529870dd00be664b4dbe8ece006c72098c22 | |||
v1.0 | instruct | Algorithm | Algorithm_24554_I | ### Coding Question: Implement a Simple JSON Configuration Merger
Configuring complex systems often involves managing multiple configuration files across various environments. These configuration files are typically in JSON format and might have overlapping settings that need merging.
#### Objective
Write a Python fu... | import json
import os
from typing import List, Dict
def deep_merge(dict1: Dict, dict2: Dict) -> Dict:
for key, value in dict2.items():
if key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict):
dict1[key] = deep_merge(dict1[key], value)
else:
dict1[key] = ... | import json
import pytest
from solution import merge_json_configs
def test_merge_single_file(tmpdir):
config1 = tmpdir.join("config1.json")
config1.write(json.dumps({
"settingA": "value1",
"nestedSetting": {
"subSetting1": "subValue1"
}
}))
result = merge_json_c... | [
{
"docstring": null,
"function_declaration": "def deep_merge(dict1, dict2):",
"function_name": "deep_merge",
"parameter_list": "(dict1, dict2)"
},
{
"docstring": null,
"function_declaration": "def merge_json_configs(file_paths):",
"function_name": "merge_json_configs",
"parameter... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import json\nimport os\nfrom typing import List, Dict\n\ndef deep_merge(dict1: Dict, dict2: Dict) -> Dict:\n \"\"\"\n Recursively merges dict2 into dict1.\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000024554",
"row_id": 24554,
"seed_ids": "[3967]"
} | 0.657705 | Algorithm_24554 | I | [
"deep_merge",
"merge_json_configs"
] | 2 | [
[
"merge_json_configs",
"deep_merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2aeb28f70aca0be558bea916e3b4ea8f20b97ab3 | 305b72c3418ba33393988db5f90ea1e1c752dc69 | |||
v1.0 | instruct | Algorithm | Algorithm_24592_I | ### K-Nearest Neighbors (KNN) from Scratch
You are required to implement the K-Nearest Neighbors algorithm from scratch and optimize it for classification tasks. Implement the following functions:
1. **compute_distance** - To compute the distance between two samples.
2. **get_neighbors** - To find the k-nearest neigh... | import math
from collections import Counter
def compute_distance(sample1: list[float], sample2: list[float]) -> float:
"""
Compute the Euclidean distance between two samples.
Args:
- sample1 (list[float]): First sample vector.
- sample2 (list[float]): Second sample vector.
Returns:
- f... | import pytest
from solution import compute_distance, get_neighbors, predict_class, evaluate_accuracy
def test_compute_distance():
sample1 = [1.0, 2.0]
sample2 = [4.0, 6.0]
assert compute_distance(sample1, sample2) == 5.0
def test_get_neighbors():
training_samples = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0],... | [] | [
0,
0,
1,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef compute_distance(sample1, sample2):\n \"\"\"\n Compute the Euclidean distance between two samples.\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000024592",
"row_id": 24592,
"seed_ids": "[699]"
} | 0.657914 | Algorithm_24592 | I | [
"compute_distance",
"get_neighbors",
"predict_class",
"evaluate_accuracy"
] | 4 | [
[
"evaluate_accuracy",
"predict_class"
],
[
"get_neighbors",
"compute_distance"
],
[
"predict_class",
"get_neighbors"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 76010a04ff5c32ae533d3c084dcfaebe0c0f8264 | c4b07873e04034b69c6f72745e71fc99dddb16d5 | |||
v1.0 | instruct | Algorithm | Algorithm_24602_I | ### Coding Assessment Question
#### Task
Write a function that finds all "self-dividing numbers" within a given range. A self-dividing number is defined as a number that is divisible by each of its digits without any remainder. The function should return a list of all self-dividing numbers within the specified range, ... | from typing import List
def is_self_dividing(n: int) -> bool:
"""
Check if a number is self-dividing.
"""
original = n
while n > 0:
digit = n % 10
if digit == 0 or original % digit != 0:
return False
n //= 10
return True
def self_dividing_numbers(left: int, ... | from solution import self_dividing_numbers, is_self_dividing
def test_is_self_dividing():
assert is_self_dividing(1) == True
assert is_self_dividing(128) == True
assert is_self_dividing(12) == True
assert is_self_dividing(102) == False
assert is_self_dividing(120) == False
def test_self_dividing_n... | [
{
"docstring": "Check if a number is self-dividing.",
"function_declaration": "def is_self_dividing(n):",
"function_name": "is_self_dividing",
"parameter_list": "(n)"
},
{
"docstring": "Find all self-dividing numbers within the given range [left, right].",
"function_declaration": "def se... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef self_dividing_numbers(left: int, right: int) -> List[int]:\n def is_self_dividing(num: int) -> bool:\n original_num = nu... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000024602",
"row_id": 24602,
"seed_ids": "[2390]"
} | 0.614235 | Algorithm_24602 | I | [
"is_self_dividing",
"self_dividing_numbers"
] | 2 | [
[
"self_dividing_numbers",
"is_self_dividing"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c66230a0b03aa56d43383549e7b43a3e3322c015 | 650acb2b281f477cec24034762a298f5fca7ac29 | |||
v1.0 | instruct | Algorithm | Algorithm_24619_I | ### Coding Question
#### Context
You are working for a logistics company to optimize the route planning of their delivery trucks. The current implementation uses a brute force method to determine the optimal route and takes too long for large sets of delivery locations. They need a more efficient solution.
#### Probl... | from itertools import permutations
import math
def calculate_distance(p1, p2):
"""
Calculate the Euclidean distance between two points p1 and p2.
"""
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def total_distance(route):
"""
Calculate the total distance of the given route inc... | from solution import min_distance_route
def test_empty_list():
assert min_distance_route([]) == 0.0
def test_single_location():
assert min_distance_route([(0, 0)]) == 0.0
def test_identical_points():
assert min_distance_route([(0, 0), (0, 0), (0, 0)]) == 0.0
def test_four_points_square():
assert min... | [
{
"docstring": "Calculate the Euclidean distance between two points p1 and p2.",
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Calculate the total distance of the given route including returni... | [
1,
1,
1,
0,
0,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import itertools\nimport math\n\ndef min_distance_route(locations):\n \"\"\"\n Given a list of (x, y) coordinates, returns the minimum distance required to... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000024619",
"row_id": 24619,
"seed_ids": "[3840]"
} | 0.671138 | Algorithm_24619 | I | [
"calculate_distance",
"total_distance",
"min_distance_route"
] | 3 | [
[
"min_distance_route",
"total_distance"
],
[
"total_distance",
"calculate_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 84f12a32deb297a7b1567ee46ac656887ca4c76e | c3ea182476760235aa3bd9ec577e4bf483193684 | |||
v1.0 | instruct | Algorithm | Algorithm_24644_I | ### Problem Statement
You are given a list of integers. Your task is to implement a function that sorts the list using the merge sort algorithm.
### Function Signature
```python
def merge_sort(arr: List[int]) -> List[int]:
"""
This function should sort the list `arr` using merge sort algorithm and return the ... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: List[int], right: List[int]) -> List[int]:
... | from solution import merge_sort
def test_merge_sort_unsorted():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_mixed_numbers():
assert merge_sort([10, -1, 2, 5, 0, 6, 4, -5]) == [-5, -1, 0, 2, 4, 5, 6, 10]
def test_merge_sort_random_order():
assert merge_s... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n This function sorts the list `arr` using merge sort algorithm and return... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000024644",
"row_id": 24644,
"seed_ids": "[3923]"
} | 0.648047 | Algorithm_24644 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31bc6ebc1ab1d709b8e3b0a46b98f274ca7cacfc | dfd9942089e33a0dbd334299b8521f6963f4b7fe | |||
v1.0 | instruct | Algorithm | Algorithm_24708_I | ### Question: Implement an Optimized Matrix Multiplication Algorithm
#### Context
You are developing a mathematical library that requires efficient matrix operations. Matrix multiplication is a fundamental operation frequently used in various applications, from graphics transformations to scientific computing.
#### T... | def add_matrix(A, B):
"""
Add two matrices element-wise.
"""
n = len(A)
return [[A[i][j] + B[i][j] for j in range(n)] for i in range(n)]
def sub_matrix(A, B):
"""
Subtract matrix B from matrix A element-wise.
"""
n = len(A)
return [[A[i][j] - B[i][j] for j in range(n)] for i in ... | from solution import optimized_matrix_multiplication
def test_optimized_matrix_multiplication_small_matrices():
A = [[1.0, 2.0], [3.0, 4.0]]
B = [[5.0, 6.0], [7.0, 8.0]]
expected_result = [[19.0, 22.0], [43.0, 50.0]]
result = optimized_matrix_multiplication(A, B)
assert result == expected_result
d... | [
{
"docstring": "Add two matrices element-wise.",
"function_declaration": "def add_matrix(A, B):",
"function_name": "add_matrix",
"parameter_list": "(A, B)"
},
{
"docstring": "Subtract matrix B from matrix A element-wise.",
"function_declaration": "def sub_matrix(A, B):",
"function_na... | [
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": "def optimized_matrix_multiplication(A, B):\n def classical_multiplication(A, B):\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i i... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000024708",
"row_id": 24708,
"seed_ids": "[3687]"
} | 0.504677 | Algorithm_24708 | I | [
"add_matrix",
"sub_matrix",
"matrix_mult",
"optimized_matrix_multiplication"
] | 4 | [
[
"matrix_mult",
"add_matrix"
],
[
"matrix_mult",
"sub_matrix"
],
[
"optimized_matrix_multiplication",
"matrix_mult"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 67c974b6591369510e46d338cff577d9ef46d602 | ce02d1fb1c1b202388135829a42ab00202969913 | |||
v1.0 | instruct | Algorithm | Algorithm_24719_I | ### Sorting Algorithms Analysis Assessment
#### Context
You are expected to implement and compare the performance of classic sorting algorithms: Quick Sort, Merge Sort, and Heap Sort. This task tests your understanding of sorting mechanisms and efficiency analysis, as well as your ability to implement and optimize the... | from typing import List, Callable
def quick_sort(arr: List[int]) -> List[int]:
"""
Sorts an array using the Quick Sort algorithm.
"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x f... | import random
from solution import quick_sort, merge_sort, heap_sort, measure_performance
def generate_dataset(size: int, min_value: int = 0, max_value: int = 10000) -> List[int]:
"""
Generates a random dataset of integers within specified range.
"""
return [random.randint(min_value, max_value) for _ i... | [
{
"docstring": "Sorts an array using the Quick Sort algorithm.",
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts an array using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
... | [
1,
1,
1,
0,
1,
0,
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": "from typing import List, Callable\nimport random\nimport time\n\ndef quick_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Quick sort implementation.\n \"... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000024719",
"row_id": 24719,
"seed_ids": "[4704]"
} | 0.556987 | Algorithm_24719 | I | [
"quick_sort",
"merge_sort",
"merge",
"heap_sort",
"measure_performance"
] | 5 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6741f7c9e3be6871d4cc7721c10ef1df5c48e4f1 | 8f7534e97b98d726437555a7247145ec047d4bc2 | |||
v1.0 | instruct | Algorithm | Algorithm_24725_I | ### Scenario
You are working with a system that processes large datasets containing geographical coordinates. Your task is to identify clusters of points that are geographically close to one another. The clustering algorithm you need to implement uses a form of Density-Based Spatial Clustering of Applications with Nois... | from typing import List, Tuple
from math import sqrt
def euclidean_distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float:
return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def dbscan(points: List[Tuple[float, float]], eps: float, min_points: int) -> List[int]:
labels = [-1] * len(points)
... | def test_single_point():
points = [(0, 0)]
eps = 0.1
min_points = 1
assert dbscan(points, eps, min_points) == [0]
def test_no_neighbors():
points = [(0, 0), (10, 10)]
eps = 1
min_points = 2
assert dbscan(points, eps, min_points) == [-1, -1]
def test_all_points_in_one_cluster():
poi... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def dbscan(points, eps, min_points):",
"function_name": "dbscan",
"parameter_list":... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport math\n\ndef haversine_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:\n R = 6371.0 # Radi... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000024725",
"row_id": 24725,
"seed_ids": "[4622]"
} | 0.653074 | Algorithm_24725 | I | [
"euclidean_distance",
"dbscan",
"get_neighbors",
"expand_cluster"
] | 4 | [
[
"dbscan",
"expand_cluster"
],
[
"dbscan",
"get_neighbors"
],
[
"expand_cluster",
"get_neighbors"
],
[
"get_neighbors",
"euclidean_distance"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 3ff11c81427cb7bae6e5687bb426d298fc429562 | 278bde1daf2f07a57a4ac49e865a72f8360574ff | |||
v1.0 | instruct | Algorithm | Algorithm_24821_I | ### Coding Assessment Question
#### Requirements
You are tasked with implementing an algorithm to find the median of a given list of integers using the Quickselect algorithm. Your task is to write a Python function `find_median(arr: list[int]) -> float` that computes the median value.
#### Input
* `arr`: A list of i... | def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quickselect(arr, low, high, k):
if low == high:
... | from solution import find_median
def test_find_median_odd_length():
assert find_median([3, 2, 1, 5, 4]) == 3.0
def test_find_median_even_length():
assert find_median([3, 2, 1, 4]) == 2.5
def test_find_median_single_element():
assert find_median([42]) == 42.0
def test_find_median_identical_elements():
... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quickselect(arr, low, high, k):",
"function_name": "quickselect",
"parameter_list... | [
1,
0,
1,
1,
0,
0,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def quickselect(arr, left, right, k):\n if left == right: # If the list contains only one element, return that element\n return arr[left]\n \n p... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000024821",
"row_id": 24821,
"seed_ids": "[4602]"
} | 0.730256 | Algorithm_24821 | I | [
"partition",
"quickselect",
"find_median"
] | 3 | [
[
"find_median",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0500043d09be47f2eafa0009a9a57e0d5ed5a4c3 | e24f3c93479a0ca891cd91bb5037dbf4a0e31ed6 | |||
v1.0 | instruct | Algorithm | Algorithm_24858_I | **[Question 2]: Balanced Binary Search Tree Validation**
You are given a binary tree, and you need to determine if it is a balanced binary search tree (BST). A balanced BST is defined as a BST where the height of the two subtrees of every node never differs by more than one and all the nodes follow the BST property.
... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_bst(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
if node.val <= lower or node.val >= upper:
return False
return... | from solution import TreeNode, is_bst, check_height_balance, is_balanced_bst
def test_is_bst():
# Example tree
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
root.right.right = TreeNode(18)
assert is_... | [] | [
1,
0,
1,
1,
0,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "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_bs... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000024858",
"row_id": 24858,
"seed_ids": "[2017]"
} | 0.741459 | Algorithm_24858 | I | [
"is_bst",
"check_height_balance",
"is_balanced_bst"
] | 3 | [
[
"is_balanced_bst",
"check_height_balance"
],
[
"is_balanced_bst",
"is_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 6108556037a05353629b6e8e8994663cbaf58333 | 315ac9175a652dff648ffcff6c359e382242aa1f | |||
v1.0 | instruct | Algorithm | Algorithm_24897_I | ### Sparse Matrix Multiplication Implementation
**Context**:
You are given two sparse matrices. A sparse matrix is a matrix in which most of the elements are zero. As such, using conventional matrix multiplication methods would be inefficient both in terms of time and space complexity. You aim to implement an efficien... | def parse_input(matrix):
"""Convert the list of tuples representation to a sparse matrix dictionary."""
sparse_matrix = {}
for i, j, val in matrix:
if i not in sparse_matrix:
sparse_matrix[i] = {}
sparse_matrix[i][j] = val
return sparse_matrix
def multiply_sparse_matrices(ma... | def test_parse_input():
assert parse_input([(0, 1, 5), (1, 2, 7)]) == {0: {1: 5}, 1: {2: 7}}
assert parse_input([(0, 0, 1), (0, 4, 2), (1, 1, 3)]) == {0: {0: 1, 4: 2}, 1: {1: 3}}
assert parse_input([(1, 2, 4)]) == {1: {2: 4}}
def test_multiply_sparse_matrices():
matrix1 = [
(0, 0, 1),
... | [
{
"docstring": "Convert the list of tuples representation to a sparse matrix dictionary.",
"function_declaration": "def parse_input(matrix):",
"function_name": "parse_input",
"parameter_list": "(matrix)"
},
{
"docstring": "Multiply two sparse matrices and return the result as a list of tuple... | [
1,
0,
1,
0,
0,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def parse_input(matrix):\n \"\"\"Convert the list of tuples representation to a sparse matrix dictionary.\"\"\"\n sparse_matrix = {}\n for i, j, val in ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000024897",
"row_id": 24897,
"seed_ids": "[786]"
} | 0.491759 | Algorithm_24897 | I | [
"parse_input",
"multiply_sparse_matrices"
] | 2 | [
[
"multiply_sparse_matrices",
"parse_input"
]
] | 1 | [
"parse_input"
] | false | [] | false | pytest | false | [] | true | 038cb3d5f6ccea96903ef9bd57b8fbf917682d57 | ff6dd6536dca187aba0dfb5ef5bd07d32242d7a4 | |||
v1.0 | instruct | Algorithm | Algorithm_24904_I | ### AVL Tree - Insertion and Height Calculation
#### Background:
An AVL Tree is a self-balancing binary search tree where the difference in heights of the left and right subtrees of any node is no more than one. The tree rotates to maintain balance during insertions, ensuring O(log n) time complexity for insertion and... | class AVLNode:
def __init__(self, key: int):
self.key = key
self.left = None
self.right = None
self.height = 1 # Initial height of the node
def get_height(node):
if not node:
return 0
return node.height
def update_height(node):
if node:
node.height = 1 ... | from solution import AVLNode, insert_avl, calculate_height
def test_insert_single_node():
root = None
root = insert_avl(root, 10)
assert root.key == 10
assert calculate_height(root) == 1
def test_insert_left_rotation():
root = None
root = insert_avl(root, 10)
root = insert_avl(root, 20)
... | [] | [
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": "class AVLNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n\ndef insert_... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000024904",
"row_id": 24904,
"seed_ids": "[1333]"
} | 0.51606 | Algorithm_24904 | I | [
"get_height",
"update_height",
"get_balance",
"rotate_right",
"rotate_left",
"insert_avl",
"calculate_height"
] | 7 | [
[
"calculate_height",
"get_height"
],
[
"get_balance",
"get_height"
],
[
"insert_avl",
"get_balance"
],
[
"insert_avl",
"rotate_left"
],
[
"insert_avl",
"rotate_right"
],
[
"insert_avl",
"update_height"
],
[
"rotate_left",
"update_heigh... | 9 | [] | false | [
"AVLNode"
] | true | pytest | true | [] | true | 1c7fe659614b2384c19099c709209e28a42f5066 | 46c4dd7da447c171440da7247726e7f8da200141 | |||
v1.0 | instruct | Algorithm | Algorithm_24934_I | ### Prime Pair Sequence
#### Scenario
You are working on a cryptographic algorithm that makes use of prime numbers. A specific sequence of prime number pairs is required, where every pair consists of two consecutive prime numbers.
#### Task
Write a function `prime_pairs_sequence` that takes an integer `n` and returns... | def is_prime(num):
"""Helper function to check if a given number is a prime."""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return Fal... | from solution import is_prime, prime_pairs_sequence
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert not is_prime(0)
assert is_prime(13)
assert not is_prime(14)
def test_prime_pairs_sequence():
assert... | [
{
"docstring": "Helper function to check if a given number is a prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of n pairs of consecutive prime numbers.",
"function_declaration": "def prime_pa... | [
0,
0,
1,
1,
0,
1,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a given number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000024934",
"row_id": 24934,
"seed_ids": "[3947]"
} | 0.72835 | Algorithm_24934 | I | [
"is_prime",
"prime_pairs_sequence"
] | 2 | [
[
"prime_pairs_sequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e78dcc8a4bc24fb185f1e504f88974d928de170b | 3a5031a1a766b625f7884b37f726f92adadc4fe5 | |||
v1.0 | instruct | Algorithm | Algorithm_24966_I | ### Matrix Multiplication Optimization with Strassen's Algorithm
#### Background
Matrix multiplication is a fundamental operation in many scientific computing and machine learning applications. Traditional matrix multiplication has a time complexity of \(O(n^3)\), which can be inefficient for large matrices. Strassen'... | import numpy as np
import time
def strassen_matrix_multiplication(A: np.ndarray, B: np.ndarray) -> np.ndarray:
assert A.shape == B.shape, 'Matrices must be the same size'
assert A.shape[0] == A.shape[1], 'Matrices must be square'
n = A.shape[0]
if n == 1:
return A * B
mid = n // 2
... | import numpy as np
from solution import strassen_matrix_multiplication, compare_matrix_multiplication
def test_strassen_small_matrices():
A = np.array([
[1, 2],
[3, 4]
])
B = np.array([
[5, 6],
[7, 8]
])
expected_C = np.array([
[19, 22],
[43, 50]
... | [
{
"docstring": null,
"function_declaration": "def strassen_matrix_multiplication(A, B):",
"function_name": "strassen_matrix_multiplication",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def pad_matrix_to_power_of_two(A):",
"function_name": "pad_matrix_t... | [
1,
0,
1,
1,
0,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport time\n\ndef naive_matrix_multiplication(A, B):\n \"\"\"\n Naive matrix multiplication.\n \"\"\"\n return np.dot(A, B)\n\nd... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000024966",
"row_id": 24966,
"seed_ids": "[3835]"
} | 0.552241 | Algorithm_24966 | I | [
"strassen_matrix_multiplication",
"pad_matrix_to_power_of_two",
"unpad_matrix",
"compare_matrix_multiplication"
] | 4 | [
[
"compare_matrix_multiplication",
"pad_matrix_to_power_of_two"
],
[
"compare_matrix_multiplication",
"strassen_matrix_multiplication"
],
[
"compare_matrix_multiplication",
"unpad_matrix"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 0c08d75cfdd12eb873b4762a69d6df0ad3001161 | 90fc510f3b9fb0114f12048e6a272bd84e7a0dd0 | |||
v1.0 | instruct | Algorithm | Algorithm_24987_I | ### Coding Assessment Question
As part of your assessments on graph theory and pathfinding algorithms, you are tasked with implementing a more efficient version of a classic pathfinding algorithm. This problem requires enhancing the Dijkstra's algorithm to efficiently handle graphs containing negative edge weights by l... | import heapq
def bellman_ford(graph, start, end):
# Initialization
distance = {node: float('inf') for node in graph}
predecessor = {node: None for node in graph}
distance[start] = 0
# Relax edges |V|-1 times
for _ in range(len(graph) - 1):
for u in graph:
for v in graph... | from solution import efficient_pathfinder
def test_no_negative_edges():
graph = {
'A': {'B': 1, 'C': 4},
'B': {'C': 2, 'D': 5},
'C': {'D': 1},
'D': {}
}
assert efficient_pathfinder(graph, 'A', 'D') == (['A', 'B', 'C', 'D'], 4)
def test_with_negative_edges():
graph = {
... | [
{
"docstring": null,
"function_declaration": "def bellman_ford(graph, start, end):",
"function_name": "bellman_ford",
"parameter_list": "(graph, start, end)"
},
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start, end):",
"function_name": "dijkstra",
"paramete... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def efficient_pathfinder(graph, start, end):\n import heapq\n\n def dijkstra(graph, start):\n pq = [(0, start)]\n dist = {node: float('inf') ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000024987",
"row_id": 24987,
"seed_ids": "[3197]"
} | 0.683308 | Algorithm_24987 | I | [
"bellman_ford",
"dijkstra",
"has_negative_edge",
"efficient_pathfinder"
] | 4 | [
[
"efficient_pathfinder",
"bellman_ford"
],
[
"efficient_pathfinder",
"dijkstra"
],
[
"efficient_pathfinder",
"has_negative_edge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4560b1491f9ceb93eab1d0e23e9defb38a634bff | 8e36da991498e0a0d195f5f343488b3c47a701d0 | |||
v1.0 | instruct | Algorithm | Algorithm_24990_I | ### Coding Assessment Question
**Objective:**
Write a function to determine if a number is a highly composite number. Highly composite numbers are defined as a positive integer that has more divisors than any smaller positive integer.
**Function Signature:**
```python
def is_highly_composite_number(n: int) -> bool:
... | import math
def count_divisors(n):
count = 0
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
count += 1
if i != n // i:
count += 1
return count
def is_highly_composite_number(n):
max_divisors = 0
for i in range(1, n):
current_divisor... | from solution import is_highly_composite_number
def test_highly_composite_numbers():
assert is_highly_composite_number(1) == True
assert is_highly_composite_number(2) == True
assert is_highly_composite_number(4) == True
assert is_highly_composite_number(6) == True
assert is_highly_composite_number(... | [
{
"docstring": null,
"function_declaration": "def count_divisors(n):",
"function_name": "count_divisors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_highly_composite_number(n):",
"function_name": "is_highly_composite_number",
"parameter_list":... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def count_divisors(x: int) -> int:\n \"\"\"\n Helper function to count the number of divisors of a given number x.\n \"\"\"\n count = 0\n for i in... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000024990",
"row_id": 24990,
"seed_ids": "[3936]"
} | 0.628969 | Algorithm_24990 | I | [
"count_divisors",
"is_highly_composite_number"
] | 2 | [
[
"is_highly_composite_number",
"count_divisors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1828f7ed18e2ccc2b16cb4155fac6e99b04712a2 | 30ba5e6a83b7fd9be88fe08397ae3a17e7210354 | |||
v1.0 | instruct | Algorithm | Algorithm_25022_I | ### Question: Integer to Roman Numerals
#### Scenario:
Converting between different numeral systems is a common problem in computer science and programming. One interesting variation of this problem is converting integers to their Roman numeral representations. Roman numerals are a numeral system originating from anci... | def int_to_roman(num: int) -> str:
"""
Converts a given integer to its Roman numeral representation.
"""
value_to_roman = [
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")
]
... | def test_int_to_roman():
assert int_to_roman(1) == "I"
assert int_to_roman(4) == "IV"
assert int_to_roman(9) == "IX"
assert int_to_roman(58) == "LVIII"
assert int_to_roman(1994) == "MCMXCIV"
assert int_to_roman(2023) == "MMXXIII"
assert int_to_roman(3999) == "MMMCMXCIX"
def test_verify_conv... | [
{
"docstring": "Converts a given integer to its Roman numeral representation.",
"function_declaration": "def int_to_roman(num):",
"function_name": "int_to_roman",
"parameter_list": "(num)"
},
{
"docstring": "Shows the integer and its corresponding Roman numeral form.",
"function_declarat... | [
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 int_to_roman(num: int) -> str:\n \"\"\"\n Converts an integer to its Roman numeral representation.\n \"\"\"\n val = [\n 1000, 900, 500, 40... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025022",
"row_id": 25022,
"seed_ids": "[5232]"
} | 0.703678 | Algorithm_25022 | I | [
"int_to_roman",
"verify_conversion"
] | 2 | [
[
"verify_conversion",
"int_to_roman"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 731075b5ccb79a14c6f8100bdba724c3fb86bd76 | ed05154d9cee23a2a93fd408135c8202e4a1c4da | |||
v1.0 | instruct | Algorithm | Algorithm_25051_I | ### Question: Implement a Text-based Tic-Tac-Toe Game
Create a basic text-based Tic-Tac-Toe game where two players can play against each other. Implement a function `play_tic_tac_toe` which initializes a 3x3 board and allows the players to make moves alternately. Each move involves placing either 'X' or 'O' on the boa... | def initialize_board():
return [[' ' for _ in range(3)] for _ in range(3)]
def print_board(board):
for row in board:
print(' | '.join(row))
print('-' * 5)
def check_winner(board, marker):
# Check rows, columns, and diagonals
for row in board:
if all(spot == marker for spot in r... | from solution import initialize_board, print_board, check_winner, is_board_full, get_player_move, play_tic_tac_toe
def test_initialize_board():
board = initialize_board()
assert board == [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
def test_check_winner():
board = [
['X', 'X', 'X'],
... | [
{
"docstring": null,
"function_declaration": "def initialize_board():",
"function_name": "initialize_board",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
... | [
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": "def check_winner(board):\n # Check rows and columns\n for i in range(3):\n if board[i][0] == board[i][1] == board[i][2] != ' ':\n return ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000025051",
"row_id": 25051,
"seed_ids": "[1037]"
} | 0.567446 | Algorithm_25051 | I | [
"initialize_board",
"print_board",
"check_winner",
"is_board_full",
"get_player_move",
"play_tic_tac_toe"
] | 6 | [
[
"play_tic_tac_toe",
"check_winner"
],
[
"play_tic_tac_toe",
"get_player_move"
],
[
"play_tic_tac_toe",
"initialize_board"
],
[
"play_tic_tac_toe",
"is_board_full"
],
[
"play_tic_tac_toe",
"print_board"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 51a6595e4dd45d3cb6bc700359f3f548a7e94318 | 140fc589e0cfa75657df84bf140f7c69c9bbbe7f | |||
v1.0 | instruct | Algorithm | Algorithm_25103_I | ### Neural Network from Scratch
Your task is to implement a simple feedforward neural network from scratch, using only Python's standard libraries. This network will perform binary classification on a provided dataset. The neural network will have one input layer, one hidden layer, and one output layer with the follow... | import numpy as np
def sigmoid(x: float) -> float:
"""
Sigmoid activation function.
"""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x: float) -> float:
"""
Derivative of the sigmoid function.
"""
return x * (1 - x)
def initialize_weights(input_size: int, hidden_size: int) -> tu... | import numpy as np
from solution import sigmoid, sigmoid_derivative, initialize_weights, forward_propagation, back_propagation, train_neural_network, predict
def test_sigmoid():
assert np.isclose(sigmoid(0), 0.5)
assert np.isclose(sigmoid(2), 0.880797)
assert np.isclose(sigmoid(-2), 0.119203)
def test_sig... | [
{
"docstring": "Sigmoid activation function.",
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": "Derivative of the sigmoid function.",
"function_declaration": "def sigmoid_derivative(x):",
"function_name": "sigmoid_deriv... | [
1,
0,
1,
0,
0,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x: float) -> float:\n \"\"\"\n Returns the sigmoid of x.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_deri... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025103",
"row_id": 25103,
"seed_ids": "[4722]"
} | 0.552986 | Algorithm_25103 | I | [
"sigmoid",
"sigmoid_derivative",
"initialize_weights",
"forward_propagation",
"back_propagation",
"train_neural_network",
"predict"
] | 7 | [
[
"back_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"predict",
"forward_propagation"
],
[
"train_neural_network",
"back_propagation"
],
[
"train_neural_network",
"forward_propagation"
],
[
"train_neural_network",
"... | 6 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | e5f94ed7c6c051ed0b3f38e34c4d18a5a1b58e0d | 1774ab53cd7ab7c20dfe86012101ebd022e2a99a | |||
v1.0 | instruct | Algorithm | Algorithm_25141_I | ### Scenario and Task
You are working on a robotic warehouse management system, and part of your task is to ensure that the robots do not collide while moving items around the warehouse. To achieve this, you need to implement a collision detection system for the robots.
### Problem Statement
Implement a function `co... | from typing import List, Tuple
import math
def distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Helper function to calculate the Euclidean distance between two points.
"""
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def collision_detect(rob... | from solution import collision_detect
def test_no_collisions():
robots = [
("R1", (0.0, 0.0), (1.0, 1.0)),
("R2", (5.0, 5.0), (6.0, 6.0)),
("R3", (10.0, 10.0), (11.0, 11.0))
]
threshold = 0.5
assert collision_detect(robots, threshold) == []
def test_one_collision_at_current_pos... | [
{
"docstring": "Helper function to calculate the Euclidean distance between two points.",
"function_declaration": "def distance(point1, point2):",
"function_name": "distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Detect collisions between robots in a 2D space.\n\nParameter... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport math\n\ndef distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:\n return math.sqrt((point1[0] ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025141",
"row_id": 25141,
"seed_ids": "[4486]"
} | 0.563739 | Algorithm_25141 | I | [
"distance",
"collision_detect"
] | 2 | [
[
"collision_detect",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d45df45a51495e86ea8ac0963c001695330c4804 | 70809ad0d480a680d4b14cefc6faaf9156e25496 | |||
v1.0 | instruct | Algorithm | Algorithm_25153_I | ### Coding Assessment Question
**Objective:**
Write a function that identifies amicable numbers. Two numbers are amicable if the sum of the proper divisors (excluding itself) of each is equal to the other number. Your implementation should be efficient and handle large numbers gracefully.
**Function Signature:**
```p... | def sum_of_proper_divisors(n: int) -> int:
"""
Calculate the sum of proper divisors of n (excluding the number itself)
"""
if n <= 1:
return 0
result = 1 # 1 is a proper divisor of any number > 1
sqrt_n = int(n ** 0.5)
for i in range(2, sqrt_n + 1):
if n % i == 0:
... | from solution import are_amicable_numbers
def test_amicable_numbers():
assert are_amicable_numbers(220, 284) == True
assert are_amicable_numbers(1184, 1210) == True
assert are_amicable_numbers(2620, 2924) == True
assert are_amicable_numbers(6232, 6368) == True
def test_non_amicable_numbers():
asse... | [
{
"docstring": "Calculate the sum of proper divisors of n (excluding the number itself)",
"function_declaration": "def sum_of_proper_divisors(n):",
"function_name": "sum_of_proper_divisors",
"parameter_list": "(n)"
},
{
"docstring": "Return True if a and b are amicable numbers, otherwise Fal... | [
0,
1,
0,
0,
0,
0,
1,
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 sum_of_proper_divisors(n: int) -> int:\n \"\"\"\n Returns the sum of proper divisors of n (excluding n itself).\n \"\"\"\n if n < 2:\n ret... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025153",
"row_id": 25153,
"seed_ids": "[3936]"
} | 0.657121 | Algorithm_25153 | I | [
"sum_of_proper_divisors",
"are_amicable_numbers"
] | 2 | [
[
"are_amicable_numbers",
"sum_of_proper_divisors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3bec25bdbfb21d48e0af76d5149ae4cdcbe3327e | ebde8cb59b3a9375453f50b53cda21b3fb094fe2 | |||
v1.0 | instruct | Algorithm | Algorithm_25227_I | ### Question: Fibonacci Sequence Checker and Sum
You are tasked with implementing a function that checks if a list of numbers represents a portion of the Fibonacci sequence and another function that calculates the sum of that sequence. The Fibonacci sequence is defined as:
- F(0) = 0
- F(1) = 1
- F(n) = F(n-1) +... | def is_fibonacci_sequence(series):
"""
Checks if the provided series is a portion of the Fibonacci sequence.
:param series: list of integers
:return: bool indicating whether the series is part of the Fibonacci sequence
"""
if not isinstance(series, list) or not series:
raise ValueError(... | from solution import is_fibonacci_sequence, fibonacci_sum
import pytest
def test_is_fibonacci_sequence_valid():
assert is_fibonacci_sequence([0, 1, 1, 2, 3, 5, 8]) == True
assert is_fibonacci_sequence([1, 1, 2, 3, 5]) == True
assert is_fibonacci_sequence([0]) == True
assert is_fibonacci_sequence([1]) =... | [
{
"docstring": "Checks if the provided series is a portion of the Fibonacci sequence.\n\n:param series: list of integers\n:return: bool indicating whether the series is part of the Fibonacci sequence",
"function_declaration": "def is_fibonacci_sequence(series):",
"function_name": "is_fibonacci_sequence"... | [
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": "def is_fibonacci_sequence(series: list) -> bool:\n \"\"\"\n Returns True if the series follows the Fibonacci sequence, otherwise False.\n \"\"\"\n if... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000025227",
"row_id": 25227,
"seed_ids": "[4188]"
} | 0.635456 | Algorithm_25227 | I | [
"is_fibonacci_sequence",
"fibonacci_sum"
] | 2 | [
[
"fibonacci_sum",
"is_fibonacci_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a53051f83ddaccd6f67f7c112c1972dc4723159 | f2b9d5285509abe5855a0eac267887edb4b649ec | |||
v1.0 | instruct | Algorithm | Algorithm_25243_I | ### Question: Rotational Cipher
A rotational cipher, also known as a Caesar Cipher, is a simple encryption technique where each letter in a given text is shifted a certain number of places down or up the alphabet.
For this problem, you'll write two functions:
1. `rotational_cipher_encrypt` that encrypts a given strin... | def rotational_cipher_encrypt(text: str, shift: int) -> str:
"""
Encrypts the given text using a rotational cipher with the specified shift.
"""
result = []
for char in text:
if 'a' <= char <= 'z':
result.append(chr((ord(char) - ord('a') + shift) % 26 + ord('a')))
elif '... | from solution import rotational_cipher_encrypt, rotational_cipher_decrypt
def test_rotational_cipher_encrypt():
assert rotational_cipher_encrypt('Hello, World!', 3) == 'Khoor, Zruog!'
assert rotational_cipher_encrypt('HELLO, WORLD!', 5) == 'MJQQT, BTWQI!'
assert rotational_cipher_encrypt('abcXYZ', 2) == 'c... | [
{
"docstring": "Encrypts the given text using a rotational cipher with the specified shift.",
"function_declaration": "def rotational_cipher_encrypt(text, shift):",
"function_name": "rotational_cipher_encrypt",
"parameter_list": "(text, shift)"
},
{
"docstring": "Decrypts the given text encr... | [
0,
1,
1,
0,
1,
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 rotational_cipher_encrypt(text: str, shift: int) -> str:\n \"\"\"\n Encrypts the given text using a rotational cipher with the specified shift.\n\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025243",
"row_id": 25243,
"seed_ids": "[349]"
} | 0.820702 | Algorithm_25243 | I | [
"rotational_cipher_encrypt",
"rotational_cipher_decrypt"
] | 2 | [
[
"rotational_cipher_decrypt",
"rotational_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5d907b38185c747dd5e429a757bd829b6516bc8e | 4a22c72ee8951bdc893aae9b88ef44151f720084 | |||
v1.0 | instruct | Algorithm | Algorithm_25262_I | ### Prime Number Path
Given a grid of numbers, your task is to determine if there exists a path from the top-left corner to the bottom-right corner, where every number in the path is a prime number. You can only move right or down at any point in time.
### Problem Statement
Create a function `prime_path_exists` that ... | from typing import List
from collections import deque
def is_prime(n: int) -> bool:
"""Check if a number is a prime number."""
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... | def test_prime_path_exists():
grid1 = [
[2, 3, 5],
[4, 2, 3],
[7, 11, 13]
]
assert prime_path_exists(grid1) == True
grid2 = [
[4, 6, 8],
[2, 2, 3],
[5, 5, 6]
]
assert prime_path_exists(grid2) == False
grid3 = [
[2, 2, 2],
[4, ... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Check if there exists a path from top-left to bottom-right composed of prime numbers.",
"function_declaration": "def ... | [
1,
0,
1,
0,
0,
1,
1,
0,
0
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number n is prime.\"\"\"\n if n <= 1:\n r... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000025262",
"row_id": 25262,
"seed_ids": "[207]"
} | 0.596553 | Algorithm_25262 | I | [
"is_prime",
"prime_path_exists"
] | 2 | [
[
"prime_path_exists",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f73bee34f68afa8e9ac0ef035e90200dccfae4f6 | d1d3e09f0709439ad30e450c7cf1df7d123f5424 | |||
v1.0 | instruct | Algorithm | Algorithm_25275_I | ### Coding Assessment Question: Implement K-Means Clustering Algorithm
You are required to implement a K-Means Clustering algorithm. The algorithm must be capable of partitioning a given dataset into K clusters. Your implementation should utilize the basic concepts of K-Means clustering.
#### Task Requirements:
1. **... | import random
import math
def initialize_centroids(data_points, number_of_clusters):
"""
Initialize centroids by selecting K random data points as initial centroids.
"""
return random.sample(data_points, number_of_clusters)
def euclidean_distance(data_point, centroid):
"""
Calculate the Euclid... | import pytest
from solution import initialize_centroids, euclidean_distance, assign_clusters, compute_centroids, k_means_clustering, evaluate_clustering
def test_initialize_centroids():
data = [[1, 2], [3, 4], [5, 6], [7, 8]]
centroids = initialize_centroids(data, 2)
assert len(centroids) == 2
assert a... | [
{
"docstring": "Initialize centroids by selecting K random data points as initial centroids.",
"function_declaration": "def initialize_centroids(data_points, number_of_clusters):",
"function_name": "initialize_centroids",
"parameter_list": "(data_points, number_of_clusters)"
},
{
"docstring"... | [
0,
0,
1,
1,
0,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom math import sqrt\n\ndef initialize_centroids(data_points, number_of_clusters):\n \"\"\"\n Initializes centroids by randomly selecting '... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025275",
"row_id": 25275,
"seed_ids": "[479]"
} | 0.715883 | Algorithm_25275 | I | [
"initialize_centroids",
"euclidean_distance",
"assign_clusters",
"compute_centroids",
"k_means_clustering",
"evaluate_clustering"
] | 6 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"evaluate_clustering",
"euclidean_distance"
],
[
"k_means_clustering",
"assign_clusters"
],
[
"k_means_clustering",
"compute_centroids"
],
[
"k_means_clustering",
"initialize_centroids"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | f0a186956ea2571592e0552dbae573eb48d3e436 | fb5906f98bdcdf3ac224ef44da3ce3e584c38db3 | |||
v1.0 | instruct | Algorithm | Algorithm_25276_I | ### Question
You are given a task to implement a function that segments a list of strings into groups where each group contains strings with the same number of vowels. The provided Python function `group_by_vowel_count` should return a dictionary where the keys are the counts of vowels and the values are lists of stri... | def count_vowels(s: str) -> int:
"""
Counts the number of vowels in a given string.
"""
vowels = {'a', 'e', 'i', 'o', 'u'}
return sum(1 for char in s if char in vowels)
def group_by_vowel_count(strings: list[str]) -> dict[int, list[str]]:
"""
Segments a list of strings into groups where eac... | def test_count_vowels():
assert count_vowels("apple") == 2
assert count_vowels("banana") == 3
assert count_vowels("pear") == 2
assert count_vowels("grape") == 2
assert count_vowels("kiwi") == 2
assert count_vowels("plum") == 1
assert count_vowels("blueberry") == 3
assert count_vowels("ma... | [
{
"docstring": "Counts the number of vowels in a given string.",
"function_declaration": "def count_vowels(s):",
"function_name": "count_vowels",
"parameter_list": "(s)"
},
{
"docstring": "Segments a list of strings into groups where each group contains\nstrings with the same number of vowel... | [
0,
0,
0,
0,
1,
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": "def count_vowels(s: str) -> int:\n \"\"\"\n Counts the number of vowels in the input string.\n \n Args:\n s (str): The input string.\n \n Re... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000025276",
"row_id": 25276,
"seed_ids": "[488]"
} | 0.800483 | Algorithm_25276 | I | [
"count_vowels",
"group_by_vowel_count"
] | 2 | [
[
"group_by_vowel_count",
"count_vowels"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8353b02ca9dcc58840e10db3a2e5999ff5cde413 | afbacd4adf14bd67cbb850fd25dc0662d94ca87e | |||
v1.0 | instruct | Algorithm | Algorithm_25300_I | ### Coding Assessment Question
You are given an array `nums` consisting of positive integers and an integer `k`. Write a function `find_kth_smallest(nums: List[int], k: int) -> int` that returns the kth smallest element in the array. Your implementation should be highly efficient and utilize an appropriate algorithm t... | from typing import List
import random
def partition(nums, left, right):
pivot = nums[right]
i = left
for j in range(left, right):
if nums[j] <= pivot:
nums[i], nums[j] = nums[j], nums[i]
i += 1
nums[i], nums[right] = nums[right], nums[i]
return i
def quickselect(num... | def test_find_kth_smallest():
nums1 = [7, 10, 4, 3, 20, 15]
k1 = 3
assert find_kth_smallest(nums1, k1) == 7
nums2 = [2, 1, 6, 8, 5, 3]
k2 = 5
assert find_kth_smallest(nums2, k2) == 6
nums3 = [50, 40, 30, 20, 10]
k3 = 4
assert find_kth_smallest(nums3, k3) == 40
# Additional... | [
{
"docstring": null,
"function_declaration": "def partition(nums, left, right):",
"function_name": "partition",
"parameter_list": "(nums, left, right)"
},
{
"docstring": null,
"function_declaration": "def quickselect(nums, left, right, k):",
"function_name": "quickselect",
"param... | [
1,
1,
0,
1,
1,
0,
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": "from typing import List\nimport random\n\ndef partition(arr, l, r):\n pivot = arr[r]\n i = l\n for j in range(l, r):\n if arr[j] <= pivot:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025300",
"row_id": 25300,
"seed_ids": "[5021]"
} | 0.730208 | Algorithm_25300 | I | [
"partition",
"quickselect",
"find_kth_smallest"
] | 3 | [
[
"find_kth_smallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 126a73cbc531ba8c3545ea558e968827ed61413e | eec073da896d5fe37cd85607c413d6b6ac69c502 | |||
v1.0 | instruct | Algorithm | Algorithm_25326_I | ### Coding Assessment: Implementing K-Means Clustering
**Objective**: Implement the K-Means Clustering algorithm to group a set of instances into `k` clusters. You will use provided functions and general algorithmic steps as a reference to create new functions that complete the clustering process.
### Problem Stateme... | import random
import math
def assign_clusters(features, centroids):
"""
Assigns data points to the nearest centroid.
Parameters:
features (list[list[float]]): 2D list of feature values.
centroids (list[list[float]]): 2D list of centroid values.
Returns:
list[int]: ... | from solution import assign_clusters, update_centroids, k_means
def test_assign_clusters():
features = [[1.0, 2.0], [5.0, 8.0], [1.5, 1.8]]
centroids = [[1.0, 2.0], [5.0, 8.0]]
expected = [0, 1, 0]
assert assign_clusters(features, centroids) == expected
def test_update_centroids():
features = [[1.... | [
{
"docstring": "Assigns data points to the nearest centroid.\n\nParameters:\n features (list[list[float]]): 2D list of feature values.\n centroids (list[list[float]]): 2D list of centroid values.\n \nReturns:\n list[int]: List of cluster assignments for each instance.",
"function_declaration": "... | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\n\ndef assign_clusters(features, centroids):\n \"\"\"\n Assign each instance to the nearest centroid.\n Args:\n - features... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000025326",
"row_id": 25326,
"seed_ids": "[468]"
} | 0.761027 | Algorithm_25326 | I | [
"assign_clusters",
"update_centroids",
"euclidean_distance",
"k_means"
] | 4 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"k_means",
"assign_clusters"
],
[
"k_means",
"update_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2c5dc3a7b229963c350dcc5dc2c3b11dbdef9e75 | db04abe81b4bad9828f5c11f703620001018fd7d | |||
v1.0 | instruct | Algorithm | Algorithm_25336_I | ### Coding Assessment Question
In this assessment, you need to extend a URL shortening service by implementing a custom algorithm to generate unique short URLs and ensure the service can handle high volumes of URL shortening requests while preventing collisions. This exercise is designed to test your understanding of ... | import string
import random
import threading
# Base62 characters
BASE62 = string.digits + string.ascii_letters
# In-memory store for URL mappings, for demonstration purposes
url_mapping = {}
lock = threading.Lock()
def base62_encode(num):
"""Encodes a number in base62."""
if num == 0:
return BASE62[0... | import pytest
from solution import generate_short_url, is_unique, store_url_mapping, url_mapping
def test_base62_encode():
from solution import base62_encode
assert base62_encode(0) == '0'
assert base62_encode(1) == '1'
assert base62_encode(61) == 'Z'
assert base62_encode(62) == '10'
assert bas... | [
{
"docstring": "Encodes a number in base62.",
"function_declaration": "def base62_encode(num):",
"function_name": "base62_encode",
"parameter_list": "(num)"
},
{
"docstring": "Checks if the generated short URL is unique in the database.",
"function_declaration": "def is_unique(short_url)... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\nclass URLShortener:\n def __init__(self):\n self.url_map = {}\n self.short_url_set = set()\n self.base62_... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000025336",
"row_id": 25336,
"seed_ids": "[427]"
} | 0.509614 | Algorithm_25336 | I | [
"base62_encode",
"is_unique",
"store_url_mapping",
"generate_short_url"
] | 4 | [
[
"generate_short_url",
"base62_encode"
],
[
"generate_short_url",
"is_unique"
],
[
"generate_short_url",
"store_url_mapping"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0ec53c9054570e72f6d8cfb7a896c140dbd10d92 | 6d74cb2b1fb62e6d2434a9121963d796e975a711 | |||
v1.0 | instruct | Algorithm | Algorithm_25422_I | ### Coding Question: Efficient Graph Traversal and Modification
#### Context
In graph theory, certain tasks involve both traversal and dynamic modification of graph structures. Imagine we have a directed graph where each node represents a task and each edge represents a dependency. The graph can be modified by adding... | from collections import deque, defaultdict
def bfs_shortest_path(graph, start, end, n):
"""
Perform BFS to determine the shortest path from start to end node.
If there is no path, return -1.
"""
if start == end:
return 0
visited = [False] * n
queue = deque([(start, 0)])
visited[... | from solution import manage_graph
def test_example_case():
result = manage_graph(4, [
("add_edge", 0, 1),
("add_edge", 1, 2),
("shortest_path", 0, 2),
("add_edge", 2, 3),
("shortest_path", 0, 3),
("remove_edge", 1, 2),
("shortest_path", 0, 2)
])
asser... | [
{
"docstring": "Perform BFS to determine the shortest path from start to end node.\nIf there is no path, return -1.",
"function_declaration": "def bfs_shortest_path(graph, start, end, n):",
"function_name": "bfs_shortest_path",
"parameter_list": "(graph, start, end, n)"
},
{
"docstring": "Ma... | [
0,
0,
1,
0,
1,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef manage_graph(n: int, operations: list[tuple[str, int, int]]) -> list[int]:\n \"\"\"\n Manages a directed ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000025422",
"row_id": 25422,
"seed_ids": "[2045]"
} | 0.607536 | Algorithm_25422 | I | [
"bfs_shortest_path",
"manage_graph"
] | 2 | [
[
"manage_graph",
"bfs_shortest_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cc181aca523fcab484bf30c1833651f5b699a42b | 089b92d068843df6c91a1634c1fcc2009b910837 | |||
v1.0 | instruct | Algorithm | Algorithm_25470_I | ### Problem Description
You are tasked with implementing a function that checks whether a given integer is a Carmichael number. Carmichael numbers are composite numbers (non-prime) that satisfy specific properties in modular arithmetic, making them pseudo-primes for one or more bases. Implement a function `is_carmicha... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def is_composite(n):
if n < 4:
return False
if n % 2 == 0 or n % 3 == 0:
return True
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return True
i += 6
return False
def is_carmic... | def test_is_carmichael_number_561():
assert is_carmichael_number(561) == True
def test_is_carmichael_number_1105():
assert is_carmichael_number(1105) == True
def test_is_carmichael_number_1729():
assert is_carmichael_number(1729) == True
def test_is_carmichael_number_15():
assert is_carmichael_number... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def is_composite(n):",
"function_name": "is_composite",
"parameter_list": "(n)"
},
{
"docstring": null,
"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef is_composite(n):\n if n < 4:\n return False\n if n % 2 == 0 or n % 3 == 0... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000025470",
"row_id": 25470,
"seed_ids": "[3786]"
} | 0.567074 | Algorithm_25470 | I | [
"gcd",
"is_composite",
"is_carmichael_number"
] | 3 | [
[
"is_carmichael_number",
"gcd"
],
[
"is_carmichael_number",
"is_composite"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c836b237f16d44cc66bf848c3b83b79a4b54cac7 | 29d9816db1a1cba231bdb8d282c2337bd736f355 | |||
v1.0 | instruct | Algorithm | Algorithm_25535_I | ### Problem Statement
You need to implement a calculator for fraction arithmetic. The calculator should be able to perform addition, subtraction, multiplication, and division of fractions and output the result in simplest form.
### Function Signatures
```python
def add_fractions(frac1: tuple[int, int], frac2: tuple[in... | from math import gcd
def simplify_fraction(numerator: int, denominator: int) -> tuple[int, int]:
common_divisor = gcd(numerator, denominator)
return numerator // common_divisor, denominator // common_divisor
def add_fractions(frac1: tuple[int, int], frac2: tuple[int, int]) -> tuple[int, int]:
num1, den1 =... | from solution import add_fractions, subtract_fractions, multiply_fractions, divide_fractions
def test_add_fractions():
assert add_fractions((1, 3), (1, 6)) == (1, 2)
assert add_fractions((1, 4), (1, 4)) == (1, 2)
assert add_fractions((2, 5), (3, 7)) == (29, 35)
def test_subtract_fractions():
assert su... | [
{
"docstring": null,
"function_declaration": "def simplify_fraction(numerator, denominator):",
"function_name": "simplify_fraction",
"parameter_list": "(numerator, denominator)"
},
{
"docstring": null,
"function_declaration": "def add_fractions(frac1, frac2):",
"function_name": "add_... | [
1,
0,
1,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Helper function to compute the greatest common divisor using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000025535",
"row_id": 25535,
"seed_ids": "[4310]"
} | 0.698835 | Algorithm_25535 | I | [
"simplify_fraction",
"add_fractions",
"subtract_fractions",
"multiply_fractions",
"divide_fractions"
] | 5 | [
[
"add_fractions",
"simplify_fraction"
],
[
"divide_fractions",
"simplify_fraction"
],
[
"multiply_fractions",
"simplify_fraction"
],
[
"subtract_fractions",
"simplify_fraction"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 0cb26a6ab3eb20fde7e15fb1c1afc7be2662927f | 104eacf0555f1aa7a04153dc8aa1c03c86b3db5d | |||
v1.0 | instruct | Algorithm | Algorithm_25567_I | Multi-Class Logistic Regression Implementation
You are required to implement a multi-class logistic regression classifier from scratch and optimize its performance for training and prediction tasks. Implement the following functions:
1. **softmax** - To compute the softmax activation for a given input vector.
2. **cr... | import numpy as np
def softmax(logits: list[float]) -> list[float]:
"""
Compute the softmax activation for the given input vector.
Args:
- logits (list[float]): Input vector of logits.
Returns:
- list[float]: Softmax probabilities.
"""
exp_logits = np.exp(logits - np.max(logits)) ... | import pytest
from solution import softmax, cross_entropy_loss, train, predict
def test_softmax():
input_vector = [2.0, 1.0, 0.1]
expected_output = [0.65900114, 0.24243297, 0.09856589]
output = softmax(input_vector)
assert np.allclose(output, expected_output, atol=1e-6), f"Expected: {expected_output}, ... | [] | [
1,
0,
1,
1,
1,
1,
0,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef softmax(logits):\n \"\"\"\n Compute the softmax activation for the given input vector.\n Args:\n - logits (list[float]): In... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000025567",
"row_id": 25567,
"seed_ids": "[699]"
} | 0.583055 | Algorithm_25567 | I | [
"softmax",
"cross_entropy_loss",
"train",
"predict"
] | 4 | [
[
"predict",
"softmax"
],
[
"train",
"cross_entropy_loss"
],
[
"train",
"softmax"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 9b12f4f67fe29dab6cbaa8459c2f1de6aa420451 | 6cb52a7283a491f5400efe0a377ac675a0690443 | |||
v1.0 | instruct | Algorithm | Algorithm_25588_I | ### Coding Challenge
**Scenario**: You are provided with a list of words. Your task is to find the longest word in the list that can be constructed by concatenating other words from the list (including the word itself multiple times).
**Function Signature**:
```python
def longest_concatenated_word(words: list[str]) -... | def can_form(word, word_set, memo):
if word in memo:
return memo[word]
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
if prefix in word_set and (suffix in word_set or can_form(suffix, word_set, memo)):
memo[word] = True
return True
... | def test_example1():
words = ["cat", "dog", "catdog"]
assert longest_concatenated_word(words) == "catdog"
def test_example2():
words = ["apple", "banana", "app", "le", "appapple"]
assert longest_concatenated_word(words) == "appapple"
def test_example3():
words = ["hello", "world"]
assert longe... | [
{
"docstring": null,
"function_declaration": "def can_form(word, word_set, memo):",
"function_name": "can_form",
"parameter_list": "(word, word_set, memo)"
},
{
"docstring": null,
"function_declaration": "def longest_concatenated_word(words):",
"function_name": "longest_concatenated_... | [
0,
1,
1,
0,
0,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_concatenated_word(words: list[str]) -> str:\n def can_form(word, word_set):\n if word in memo:\n return memo[word]\n for ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000025588",
"row_id": 25588,
"seed_ids": "[4938]"
} | 0.712745 | Algorithm_25588 | I | [
"can_form",
"longest_concatenated_word"
] | 2 | [
[
"longest_concatenated_word",
"can_form"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f9559d50b697612dc269cfe8a83513baf93c8876 | 5c5fdf79521f6309f4753664171653c1b58ece55 | |||
v1.0 | instruct | Algorithm | Algorithm_25613_I | ### Sorting a List Using Merge Sort
You are required to implement the merge sort algorithm to sort a list of integers in non-decreasing order. Your function will recursively divide the list into two halves, sort each half, and then merge the sorted halves into a single sorted list.
#### Function Signature
```python
d... | def merge_sort(array):
# Base case: arrays with fewer than 2 elements are already sorted
if len(array) < 2:
return array
# Split array into two halves
mid = len(array) // 2
left_half = merge_sort(array[:mid])
right_half = merge_sort(array[mid:])
# Merge sorted halves
re... | from solution import merge_sort
def test_merge_sort_random():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_duplicates():
assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
... | [
{
"docstring": null,
"function_declaration": "def merge_sort(array):",
"function_name": "merge_sort",
"parameter_list": "(array)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(array: list[int]) -> list[int]:\n \"\"\"\n Perform merge sort on a list of integers and return the sorted list.\n \"\"\"\n if len(arra... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025613",
"row_id": 25613,
"seed_ids": "[5001]"
} | 0.636752 | Algorithm_25613 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a9becf65ba1e82d64d0b8525edb30f288decc1d | ccbf098c079ecbde11b5bec358f2940ecbf55b4d | |||
v1.0 | instruct | Algorithm | Algorithm_25620_I | ### N-th Fibonacci Number - Using Matrix Exponentiation
#### Scenario:
You are tasked with implementing a high-performance function to calculate the N-th Fibonacci number for a large-scale simulation. The traditional recursive and iterative approaches become inefficient for very large values of N, so you should use ma... | 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_exponentiate(matrix, power):
... | from solution import nth_fibonacci
def test_fibonacci_base_cases():
assert nth_fibonacci(0) == 0
assert nth_fibonacci(1) == 1
def test_fibonacci_small_numbers():
assert nth_fibonacci(2) == 1
assert nth_fibonacci(3) == 2
assert nth_fibonacci(4) == 3
assert nth_fibonacci(5) == 5
def test_fibona... | [
{
"docstring": "Multiplies two 2x2 matrices A and B.",
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Exponentiates matrix to the given power using binary exponentiation.",
"function_declaration": "d... | [
0,
1,
1,
1,
1,
0,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def nth_fibonacci(n: int) -> int:\n \"\"\"\n Returns the N-th Fibonacci number using matrix exponentiation.\n \"\"\"\n if n == 0:\n return 0\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025620",
"row_id": 25620,
"seed_ids": "[3013]"
} | 0.675408 | Algorithm_25620 | I | [
"matrix_multiply",
"matrix_exponentiate",
"nth_fibonacci"
] | 3 | [
[
"matrix_exponentiate",
"matrix_multiply"
],
[
"nth_fibonacci",
"matrix_exponentiate"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5f20a94055095f4103600faeef56a56b8f2e89ad | b67be6d89d24e0941ad7d645fd36691a91f8f410 | |||
v1.0 | instruct | Algorithm | Algorithm_25653_I | ### Matrix Multiplication with Strassen's Algorithm
You are provided with a basic implementation of matrix multiplication. Your task is to enhance the existing functionality by adding an efficient multiplication method using Strassen's algorithm. Additionally, implement a method to compare the performance of Strassen'... | import numpy as np
import time
def traditional_matrix_multiply(A, B):
"""
Multiplies two matrices using the traditional matrix multiplication method.
"""
return np.dot(A, B)
def strassen_matrix_multiply(A, B):
"""
Multiplies two matrices using Strassen's algorithm.
"""
n = A.shape[0]
... | import numpy as np
from solution import traditional_matrix_multiply, strassen_matrix_multiply, compare_methods
def test_traditional_matrix_multiply():
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = traditional_matrix_multiply(A, B)
expected_result = np.array([[19, 22], [43, 50]]... | [
{
"docstring": "Multiplies two matrices using the traditional matrix multiplication method.",
"function_declaration": "def traditional_matrix_multiply(A, B):",
"function_name": "traditional_matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": "Multiplies two matrices using Strassen... | [
1,
1,
1,
0,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport time\n\ndef traditional_matrix_multiply(A: np.ndarray, B: np.ndarray) -> np.ndarray:\n return np.dot(A, B)\n\ndef strassen_matrix_m... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000025653",
"row_id": 25653,
"seed_ids": "[601]"
} | 0.51539 | Algorithm_25653 | I | [
"traditional_matrix_multiply",
"strassen_matrix_multiply",
"compare_methods"
] | 3 | [
[
"compare_methods",
"strassen_matrix_multiply"
],
[
"compare_methods",
"traditional_matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 6e24235127e4b841dc7fdea7d6812f6ffc96f43a | 16d352ca270366c5ab6c0ebb8068ac909a113801 | |||
v1.0 | instruct | Algorithm | Algorithm_25764_I | ### Task
You are tasked with designing a function that normalizes a given dictionary based on the descriptions provided below.
### Function Signature
```python
def normalize_dict(data: dict) -> dict:
```
### Input
* **data** (dict): A dictionary where the keys are strings and the values are either integers, floats, s... | def normalize_value(value):
"""
Normalizes a single value. Converts numeric strings to int or float.
"""
if isinstance(value, str):
try:
if '.' in value:
return float(value)
else:
return int(value)
except ValueError:
ret... | from solution import normalize_dict
def test_normalize_basic():
assert normalize_dict({"a": 1, "b": "2", "c": {"d": "3.5", "e": "4"}}) == {"a": 1, "b": 2, "c": {"d": 3.5, "e": 4}}
def test_normalize_nested():
assert normalize_dict({"key1": "7", "key2": {"nestedKey1": "8.0", "nestedKey2": -5}}) == {"key1": 7, ... | [
{
"docstring": "Normalizes a single value. Converts numeric strings to int or float.",
"function_declaration": "def normalize_value(value):",
"function_name": "normalize_value",
"parameter_list": "(value)"
},
{
"docstring": "Recursively normalizes a dictionary, converting numeric strings to ... | [
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 normalize_dict(data: dict) -> dict:\n def normalize_value(value):\n if isinstance(value, dict):\n return normalize_dict(value)\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000025764",
"row_id": 25764,
"seed_ids": "[5129]"
} | 0.661352 | Algorithm_25764 | I | [
"normalize_value",
"normalize_dict"
] | 2 | [
[
"normalize_dict",
"normalize_value"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6eaaee3158c374d4464b4b97974e32e831611589 | 56616c37f8b90d4079f7ad92f2a1c99da8fd6e21 | |||
v1.0 | instruct | Algorithm | Algorithm_25871_I | ### Coding Assessment Question
Create a function `merge_sort` that implements the Merge Sort algorithm to sort a list of integers. This exercise will test your capability to implement a classic divide-and-conquer sorting technique. The function should handle the entire list as well as subranges of the list defined by ... | def merge_sort(sequence, start=None, end=None):
"""
Implements the Merge Sort algorithm to sort a list of integers in place.
Parameters:
- sequence (list): The list to be sorted.
- start (int, optional): The starting index of the list portion to sort. Defaults to 0.
- end (int, optional): T... | def test_merge_sort():
# Test case 1: Sorting an empty list
seq = []
merge_sort(seq)
assert seq == [], "Test case failed: Sorting an empty list"
# Test case 2: Sorting a single-element list
seq = [5]
merge_sort(seq)
assert seq == [5], "Test case failed: Sorting a single-element list"
... | [
{
"docstring": "Implements the Merge Sort algorithm to sort a list of integers in place.\n\nParameters:\n- sequence (list): The list to be sorted.\n- start (int, optional): The starting index of the list portion to sort. Defaults to 0.\n- end (int, optional): The ending index of the list portion to sort. Defaul... | [
0,
1,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(sequence: list, start: int | None = None, end: int | None = None) -> None:\n if start is None:\n start = 0\n if end is None:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000025871",
"row_id": 25871,
"seed_ids": "[1354]"
} | 0.590969 | Algorithm_25871 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 79b3420f8a98c1bc60037855b0f0888a7b40ad43 | e6cb425280371455078478fc1538b0e13099afa6 | |||
v1.0 | instruct | Algorithm | Algorithm_25895_I | ### Order Statistics Implementation Challenge
#### Problem Statement
You are tasked with implementing an algorithm to find the k-th smallest element in an unsorted array using the median of medians method to achieve linear time complexity. Your implementation should handle various edge cases and ensure robust perform... | def partition(arr, low, high, pivot_index):
pivot = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
store_index = low
for i in range(low, high):
if arr[i] < pivot:
arr[store_index], arr[i] = arr[i], arr[store_index]
store_index += 1
arr[stor... | def test_kth_smallest_examples():
assert kth_smallest([3, 6, 2, 7, 5, 1, 4], 4) == 4
def test_kth_smallest_single_element():
assert kth_smallest([10], 1) == 10
def test_kth_smallest_first_element():
assert kth_smallest([7, 10, 4, 3, 20, 15], 1) == 3
def test_kth_smallest_last_element():
assert kth_sm... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high, pivot_index):",
"function_name": "partition",
"parameter_list": "(arr, low, high, pivot_index)"
},
{
"docstring": null,
"function_declaration": "def median_of_medians(arr, low, high):",
"function_name": "medi... | [
0,
0,
1,
0,
0,
0,
0,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def kth_smallest(arr: list, k: int) -> int:\n \"\"\"\n Implements the median of medians method to find the k-th smallest element in the array.\n :param ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000025895",
"row_id": 25895,
"seed_ids": "[3747]"
} | 0.723614 | Algorithm_25895 | I | [
"partition",
"median_of_medians",
"select",
"kth_smallest"
] | 4 | [
[
"kth_smallest",
"select"
],
[
"select",
"median_of_medians"
],
[
"select",
"partition"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | e101f7019bf220439f7cfe5b09197daa7a16af60 | e721f605375e654131240ad0f48926d8261b8077 | |||
v1.0 | instruct | Algorithm | Algorithm_25902_I | ### Coding Challenge: Book Recommendations and Reviews Aggregator
Your task is to develop a Python script that aggregates book information and user reviews from two APIs: Google Books API and Goodreads API. You are to implement error handling and data aggregation, ensuring a robust response even in cases of partial AP... | import requests
import concurrent.futures
# Put your API key(s) here
GOOGLE_BOOKS_API_KEY = "your_google_books_api_key"
GOODREADS_API_KEY = "your_goodreads_api_key"
GOOGLE_BOOKS_URL_BASE = "https://www.googleapis.com/books/v1/volumes"
GOODREADS_URL_BASE = "https://www.goodreads.com/book/isbn"
def fetch_google_books_... | from solution import get_book_info
def test_get_book_info_valid_isbn():
results = get_book_info("9780143127741")
assert "GoogleBooks" in results
assert "Goodreads" in results
def test_get_book_info_invalid_isbn():
results = get_book_info("invalid_isbn")
assert "GoogleBooks" in results
assert "... | [
{
"docstring": null,
"function_declaration": "def fetch_google_books_data(isbn):",
"function_name": "fetch_google_books_data",
"parameter_list": "(isbn)"
},
{
"docstring": null,
"function_declaration": "def fetch_goodreads_data(isbn):",
"function_name": "fetch_goodreads_data",
"p... | [
0,
1,
0,
1,
0,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nimport concurrent.futures\n\n# Mock API key(s) here\nGOOGLE_BOOKS_API_KEY = \"mock_google_books_api_key\"\nGOODREADS_API_KEY = \"mock_goodreads_... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000025902",
"row_id": 25902,
"seed_ids": "[2556]"
} | 0.51158 | Algorithm_25902 | I | [
"fetch_google_books_data",
"fetch_goodreads_data",
"get_book_info"
] | 3 | [
[
"get_book_info",
"fetch_goodreads_data"
],
[
"get_book_info",
"fetch_google_books_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | d5c2aece1c8cf4390bfcd7c7b423aa101f8c2661 | 57624daae1fec5e981f3775b4182818f215dbdc2 | |||
v1.0 | instruct | Algorithm | Algorithm_25946_I | ### Problem Statement: Fraction Simplifier
You are required to design a function that simplifies a given fraction to its lowest terms. This involves reducing the numerator and the denominator by their greatest common divisor (GCD).
**Context and Functions:**
A fraction is composed of two integers, a numerator `n` an... | from typing import Tuple
def gcd(a: int, b: int) -> int:
"""
Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
"""
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a
def simplify_fraction(numerator: int, denominator: int) -> Tuple[int, int]... | def test_gcd():
assert gcd(48, 18) == 6
assert gcd(-48, 18) == 6
assert gcd(48, -18) == 6
assert gcd(-48, -18) == 6
assert gcd(0, 18) == 18
assert gcd(48, 0) == 48
def test_simplify_fraction():
assert simplify_fraction(42, 56) == (3, 4)
assert simplify_fraction(-42, 56) == (-3, 4)
a... | [
{
"docstring": "Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Simplify a fraction given by its numerator and denominator.\nReturn a t... | [
1,
1,
1,
0,
0,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Tuple\n\ndef gcd(a: int, b: int) -> int:\n \"\"\"\n Calculates the greatest common divisor (GCD) of two numbers.\n Uses the Euclidean... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000025946",
"row_id": 25946,
"seed_ids": "[824]"
} | 0.696107 | Algorithm_25946 | I | [
"gcd",
"simplify_fraction"
] | 2 | [
[
"simplify_fraction",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5487b8df804b05066472a9b4a88a4b1f318adf7c | 1df2908125ca3ca3b10eb252a1bda48e74ba1db7 | |||
v1.0 | instruct | Algorithm | Algorithm_25987_I | ### Decision Tree Classifier from Scratch
**Problem Statement**: Implement a Decision Tree Classifier from scratch in Python. Your task is to understand and implement the key components and functionalities of the Decision Tree algorithm. Demonstrate your coding proficiency by writing correct, optimized, and tested cod... | import numpy as np
def gini_impurity(y):
"""
Calculate the Gini impurity for a list of labels y.
"""
_, counts = np.unique(y, return_counts=True)
prob = counts / len(y)
return 1 - np.sum(prob**2)
def best_split(X, y):
"""
Find the best feature and threshold to split on to minimize Gini... | import pytest
from solution import gini_impurity, best_split, decision_tree
import numpy as np
def test_gini_impurity_single_class():
y = np.array([1, 1, 1, 1])
assert gini_impurity(y) == 0.0
def test_gini_impurity_two_classes():
y = np.array([1, 0, 1, 0])
assert gini_impurity(y) == 0.5
def test_best... | [] | [
0,
1,
0,
0,
1,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\n\ndef gini_impurity(y):\n \"\"\"\n Calculate the Gini impurity for an array of labels.\n\n Parameters:\n y (np.ndarray): Array ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000025987",
"row_id": 25987,
"seed_ids": "[385]"
} | 0.575924 | Algorithm_25987 | I | [
"gini_impurity",
"best_split",
"decision_tree"
] | 3 | [
[
"decision_tree",
"best_split"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | f3d7f6a67fdd9e52a06716424f4df82d18f21e0f | 9f0569c53a43315fa76d86222ac7289a5773bd4b | |||
v1.0 | instruct | Algorithm | Algorithm_26027_I | ### Coding Assessment Question
#### Context:
You are tasked with developing a function that identifies the first occurrence of a specific substring pattern within a given text. This problem is based on the idea of string matching algorithms and is similar to the well-known Knuth-Morris-Pratt (KMP) algorithm.
#### Tas... | def build_lps(pattern):
"""
Builds the Longest Prefix Suffix (LPS) array used in the KMP algorithm.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
... | from solution import find_substring_pattern
def test_find_substring_pattern_example1():
assert find_substring_pattern("abdabcababc", "abc") == 3
def test_find_substring_pattern_example2():
assert find_substring_pattern("abcdefg", "hij") == -1
def test_find_substring_pattern_example3():
assert find_substr... | [
{
"docstring": "Builds the Longest Prefix Suffix (LPS) array used in the KMP algorithm.",
"function_declaration": "def build_lps(pattern):",
"function_name": "build_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Finds the starting index of the first occurrence of the pattern in the t... | [
0,
1,
0,
1,
1,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def build_lps(pattern):\n \"\"\"\n Helper function to build the Longest Prefix Suffix (LPS) array.\n This array is used to skip characters while matchin... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000026027",
"row_id": 26027,
"seed_ids": "[2694]"
} | 0.647949 | Algorithm_26027 | I | [
"build_lps",
"find_substring_pattern"
] | 2 | [
[
"find_substring_pattern",
"build_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c4c00c6525b000b1ce4e676f70e7dd31b50dfe6 | da4d5cbbc858cbb557cf4912c210c89fe4ac2c9d | |||
v1.0 | instruct | Algorithm | Algorithm_26095_I | ### Skill Level Evaluation: Sorting Algorithm Efficiency
**Scenario**: As part of a project, a software development company is required to analyze large datasets efficiently. They need an algorithm that can analyze the performance of different sorting techniques (such as bubble sort, merge sort, and quick sort) based ... | import time
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
r... | from solution import bubble_sort, merge_sort, quick_sort, compare_sorts
def test_bubble_sort_correctness():
assert bubble_sort([3, 2, 1]) == [1, 2, 3]
assert bubble_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_merge_sort_correctness():
assert merge_sort([3, 2, 1]) == [1, 2, 3]
assert merge_... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring... | [
1,
1,
1,
0,
0,
0,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000026095",
"row_id": 26095,
"seed_ids": "[3301]"
} | 0.586247 | Algorithm_26095 | I | [
"bubble_sort",
"merge_sort",
"quick_sort",
"compare_sorts"
] | 4 | [
[
"compare_sorts",
"bubble_sort"
],
[
"compare_sorts",
"merge_sort"
],
[
"compare_sorts",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1771a4fbc52d59e6e7cbe747db9e5d1dea1cf511 | aab92d187eeee79088562e86a17c84c1417f7e76 | |||
v1.0 | instruct | Algorithm | Algorithm_26103_I | ## Problem Statement:
You are given a string representing a mathematical expression containing non-negative integers and the operators: `+`, `-`, `*`, and `/`. The task is to evaluate this expression and return the result as an integer. Note that the expressions are valid and properly formatted without any spaces.
**F... | def evaluate_expression(expression: str) -> int:
def apply_operator(operands, operator):
b = operands.pop()
a = operands.pop()
if operator == '+':
operands.append(a + b)
elif operator == '-':
operands.append(a - b)
elif operator == '*':
ope... | from solution import evaluate_expression
def test_simple_addition():
assert evaluate_expression("3+2") == 5
def test_simple_multiplication():
assert evaluate_expression("3*2") == 6
def test_combination_operations():
assert evaluate_expression("3+2*2") == 7
def test_division_truncation():
assert eval... | [
{
"docstring": null,
"function_declaration": "def evaluate_expression(expression):",
"function_name": "evaluate_expression",
"parameter_list": "(expression)"
},
{
"docstring": null,
"function_declaration": "def precedence(op):",
"function_name": "precedence",
"parameter_list": "(... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def evaluate_expression(expression: str) -> int:\n \"\"\"\n Evaluate a mathematical expression with +, -, *, / operators and no spaces.\n \n Paramete... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000026103",
"row_id": 26103,
"seed_ids": "[66]"
} | 0.63507 | Algorithm_26103 | I | [
"evaluate_expression",
"precedence"
] | 2 | [
[
"evaluate_expression",
"precedence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0ba0e54539c1ade7392342d8a68596f87a10091f | 4c4b7fefbe696376c72a7cfdfecc24890f87c8a6 | |||
v1.0 | instruct | Algorithm | Algorithm_26115_I | ### Coding Question
#### Context:
You are building a text analysis tool that needs to process sentences by identifying and extracting unique acronyms along with their frequency of occurrence. This is critical for understanding the usage of abbreviations in various documents.
#### Requirements:
1. **Function Implement... | import re
from collections import defaultdict
def extract_acronyms(text: str) -> dict:
"""
Extracts all unique acronyms and their frequencies from the given text.
Args:
text (str): The text to extract acronyms from.
Returns:
dict: A dictionary where keys are acronyms and values are their freq... | from solution import extract_acronyms, find_most_common_acronym
def test_extract_acronyms():
text = "The NASA rover landed on Mars. NASA's mission was a success. The CEO of a company praised NASA."
assert extract_acronyms(text) == {'NASA': 3, 'CEO': 1}
text = "The FBI and CIA are well-known acronyms."
... | [
{
"docstring": "Extracts all unique acronyms and their frequencies from the given text.\n\nArgs:\ntext (str): The text to extract acronyms from.\n\nReturns:\ndict: A dictionary where keys are acronyms and values are their frequencies.",
"function_declaration": "def extract_acronyms(text):",
"function_na... | [
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 re\nfrom collections import Counter\n\ndef extract_acronyms(text: str) -> dict:\n \"\"\"\n Extracts all unique acronyms and their frequencies from t... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026115",
"row_id": 26115,
"seed_ids": "[3641]"
} | 0.667301 | Algorithm_26115 | I | [
"extract_acronyms",
"find_most_common_acronym"
] | 2 | [
[
"find_most_common_acronym",
"extract_acronyms"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f74634c456e181be0b3ab0747766fdea7ec6567 | dc27c50254e3bee8b89e8f58f7327c4db6502096 | |||
v1.0 | instruct | Algorithm | Algorithm_26142_I | ### Coding Assessment Question: Implement a Simple Linear Regression Model
You are required to implement a Simple Linear Regression model. This model should be capable of training on a given dataset (with a single feature) and predicting the continuous output for new input instances. Your implementation should follow ... | import random
import numpy as np
def generate_linear_dataset(slope, intercept, noise_level, instance_count):
"""
Generate a simple dataset based on a given linear relationship with some noise.
"""
dataset = []
for _ in range(instance_count):
x = random.random() * 100
noise = random.... | from solution import generate_linear_dataset, calculate_mean, calculate_covariance, calculate_variance, calculate_coefficients, predict_y_values, calculate_rmse
def test_generate_linear_dataset():
data = generate_linear_dataset(2.0, 5.0, 1.0, 50)
assert len(data) == 50
assert all(isinstance(point, tuple) a... | [
{
"docstring": "Generate a simple dataset based on a given linear relationship with some noise.",
"function_declaration": "def generate_linear_dataset(slope, intercept, noise_level, instance_count):",
"function_name": "generate_linear_dataset",
"parameter_list": "(slope, intercept, noise_level, inst... | [
0,
0,
1,
0,
0,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\n\ndef generate_linear_dataset(slope, intercept, noise_level, instance_count):\n \"\"\"\n Generate a dataset based on a linear r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026142",
"row_id": 26142,
"seed_ids": "[479]"
} | 0.655769 | Algorithm_26142 | I | [
"generate_linear_dataset",
"calculate_mean",
"calculate_covariance",
"calculate_variance",
"calculate_coefficients",
"predict_y_values",
"calculate_rmse"
] | 7 | [
[
"calculate_covariance",
"calculate_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b0e721a4bf94c8e6e5bba7db7e523f0ee6238ecb | d92ada7c74d7983141b89df0950c63194c29fa39 | |||
v1.0 | instruct | Algorithm | Algorithm_26160_I | ### Problem Statement
You are given a string \( p \) consisting of lowercase and uppercase letters. Your task is to find and return all unique ways to split the string \( p \) into valid IP addresses. A string is a valid IP address if:
1. It consists of exactly four integers (called octets) separated by a single dot (... | from typing import List
def is_valid_octet(s: str) -> bool:
# check if the string is a valid octet
return len(s) > 0 and 0 <= int(s) <= 255 and (s[0] != '0' or s == "0")
def restore_ip_addresses(p: str) -> List[str]:
n = len(p)
if n > 12 or n < 4:
return []
result = []
for i in r... | from solution import restore_ip_addresses
def test_example_cases():
assert restore_ip_addresses("25525511135") == ["255.255.11.135", "255.255.111.35"]
assert restore_ip_addresses("0000") == ["0.0.0.0"]
assert restore_ip_addresses("1111") == ["1.1.1.1"]
assert restore_ip_addresses("010010") == ["0.10.0.... | [
{
"docstring": null,
"function_declaration": "def is_valid_octet(s):",
"function_name": "is_valid_octet",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def restore_ip_addresses(p):",
"function_name": "restore_ip_addresses",
"parameter_list": "(p)"
}
] | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_valid_octet(octet: str) -> bool:\n \"\"\"\n Check if a given string is a valid octet for an IP address.\n \n Parame... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000026160",
"row_id": 26160,
"seed_ids": "[2666]"
} | 0.627092 | Algorithm_26160 | I | [
"is_valid_octet",
"restore_ip_addresses"
] | 2 | [
[
"restore_ip_addresses",
"is_valid_octet"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8bff1ea6023c7489c5bcd157a0a7efd5a8b6dfc0 | e23777163f922f4ea990480a1d5fcd59c9494ca4 | |||
v1.0 | instruct | Algorithm | Algorithm_26173_I | ### Triangulating a Simple Polygon
#### Background:
A simple polygon is a polygon that does not intersect itself and has only one boundary. Triangulation of a simple polygon is the process of dividing the polygon into non-overlapping triangles. Triangulating a polygon is an important operation in computational geometr... | def is_convex(a, b, c):
""" Returns True if the triangle (a, b, c) is convex, otherwise False. """
# Calculate cross product to determine the orientation
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) > 0
def is_point_in_triangle(pt, v1, v2, v3):
""" Returns True if pt is inside t... | from solution import triangulate_polygon
def test_triangulate_square():
vertices = [
[0.0, 0.0],
[2.0, 0.0],
[2.0, 2.0],
[0.0, 2.0]
]
expected = [
[[0.0, 0.0], [2.0, 0.0], [2.0, 2.0]],
[[0.0, 0.0], [2.0, 2.0], [0.0, 2.0]],
]
result = triangulate_polyg... | [
{
"docstring": "Returns True if the triangle (a, b, c) is convex, otherwise False. ",
"function_declaration": "def is_convex(a, b, c):",
"function_name": "is_convex",
"parameter_list": "(a, b, c)"
},
{
"docstring": "Returns True if pt is inside the triangle (v1, v2, v3), otherwise False. ",
... | [
0,
0,
0,
1,
0,
1,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_counter_clockwise(p0, p1, p2):\n \"\"\"\n Check if the turn formed by the points p0, p1, p2 is counter-clockwise.\n \"\"\"\n return (p1[0] - p... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000026173",
"row_id": 26173,
"seed_ids": "[1333]"
} | 0.524884 | Algorithm_26173 | I | [
"is_convex",
"is_point_in_triangle",
"is_ear",
"triangulate_polygon"
] | 4 | [
[
"is_ear",
"is_convex"
],
[
"is_ear",
"is_point_in_triangle"
],
[
"triangulate_polygon",
"is_ear"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7f860b25508c1a665dfd54937f75e9c1991f5f4f | eeb632a5d5e69e3b9bafe5c38d9bd4e7fc3009c6 | |||
v1.0 | instruct | Algorithm | Algorithm_26181_I | ### Problem Statement:
You are to implement a simplified version of the RC4 stream cipher algorithm.
### Input:
1. **Key**: A string of arbitrary length (but less than 256 characters).
2. **Message**: A string representing the plaintext to be encrypted.
### Output:
1. **Cipher Text**: A hexadecimal string resulting f... | def ksa(key):
key_length = len(key)
S = list(range(256))
j = 0
for i in range(256):
j = (j + S[i] + ord(key[i % key_length])) % 256
S[i], S[j] = S[j], S[i]
return S
def prga(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], ... | from solution import encrypt, decrypt
def test_encryption_decryption():
key = "Key"
message = "Plaintext"
cipher_text = encrypt(key, message)
plain_text = decrypt(key, cipher_text)
assert plain_text == message
def test_empty_message():
key = "Key"
message = ""
cipher_text = encrypt(key... | [
{
"docstring": null,
"function_declaration": "def ksa(key):",
"function_name": "ksa",
"parameter_list": "(key)"
},
{
"docstring": null,
"function_declaration": "def prga(S):",
"function_name": "prga",
"parameter_list": "(S)"
},
{
"docstring": null,
"function_declarati... | [
0,
0,
0,
0,
0,
1,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def ksa(key):\n key_length = len(key)\n S = list(range(256))\n j = 0\n for i in range(256):\n j = (j + S[i] + ord(key[i % key_length])) % 256\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000026181",
"row_id": 26181,
"seed_ids": "[5358]"
} | 0.564139 | Algorithm_26181 | I | [
"ksa",
"prga",
"convert_to_hex",
"convert_from_hex",
"xor_bytes",
"encrypt",
"decrypt"
] | 7 | [
[
"decrypt",
"convert_from_hex"
],
[
"decrypt",
"ksa"
],
[
"decrypt",
"prga"
],
[
"decrypt",
"xor_bytes"
],
[
"encrypt",
"convert_to_hex"
],
[
"encrypt",
"ksa"
],
[
"encrypt",
"prga"
],
[
"encrypt",
"xor_bytes"
]
] | 8 | [] | false | [] | false | pytest | true | [] | true | 014eea941a02f41c942e78aff73c9014b57c0eac | 3315824c0b84d7f777d1849c597c570830b54946 | |||
v1.0 | instruct | Algorithm | Algorithm_26189_I | ### Prime Sequence Identification
You are tasked with creating a function that can identify prime number sequences within a list of integers. A prime number sequence is defined as a continuous sublist within the list where all the elements are prime numbers.
#### Task
Create a function named `find_prime_sequences` th... | 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 find_prime_sequences(numbers: List[int]) -... | from solution import find_prime_sequences, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(20) == False
def test_find_prime_sequences_case1():
numbers = [2, 3, 4, 5, 7, 8, 13, 17, 19, 23... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_prime_sequences(numbers):",
"function_name": "find_prime_sequences",
"parameter_list": "(numbers)"
}
] | [
1,
1,
0,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000026189",
"row_id": 26189,
"seed_ids": "[4787]"
} | 0.69405 | Algorithm_26189 | I | [
"is_prime",
"find_prime_sequences"
] | 2 | [
[
"find_prime_sequences",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4621d70966f69a2188ddc132eb684470c5562f10 | 7ecd48e35c9674ce027e123fa2158b6381f12685 | |||
v1.0 | instruct | Algorithm | Algorithm_26198_I | **Scenario**:
You are tasked with developing a spell checker for a text editor. The requirement is to check if each word in a given text exists in a provided dictionary of words. If a word is not found in the dictionary, you need to suggest corrections based on the Levenshtein distance, which measures the number of sin... | def levenshtein_distance(word1, word2):
"""
Calculate the Levenshtein distance between two words.
"""
if len(word1) < len(word2):
return levenshtein_distance(word2, word1)
# Initialization of the distance matrix
previous_row = range(len(word2) + 1)
for i, c1 in enumerate(word1):
... | from solution import spell_check
def test_spell_check_simple():
text = "speling correctin"
dictionary = ["spelling", "correction", "checking", "words"]
expected_output = {'speling': ['spelling'], 'correctin': ['correction']}
assert spell_check(text, dictionary) == expected_output
def test_spell_check_... | [
{
"docstring": "Calculate the Levenshtein distance between two words.",
"function_declaration": "def levenshtein_distance(word1, word2):",
"function_name": "levenshtein_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Check the spelling of each word in the text against the pr... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def levenshtein_distance(a, b):\n \"\"\"\n Calculate the Levenshtein distance between two strings a and b.\n \"\"\"\n if len(a) < len(b):\n re... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000026198",
"row_id": 26198,
"seed_ids": "[121]"
} | 0.590048 | Algorithm_26198 | I | [
"levenshtein_distance",
"spell_check"
] | 2 | [
[
"spell_check",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 78130f739999ea40a42b1903ba0421264018285e | 5921d4f740adc8d9f3e2605cf5ce45b6d9f67bb2 | |||
v1.0 | instruct | Algorithm | Algorithm_26228_I | ### Coding Question
#### Context
You are familiar with the concept of palindrome strings, which are strings that read the same forward and backward. Checking if a string is a palindrome is a common programming exercise. However, let's take it a step further and explore the concept of "rotated palindromes."
A string ... | def is_palindrome(s):
"""
Helper function to check if a given string is a palindrome.
"""
return s == s[::-1]
def is_rotated_palindrome(s: str) -> bool:
"""
Determine whether the given string can be rotated to form a palindrome.
"""
if len(s) <= 1:
return True
# Constru... | def test_is_rotated_palindrome_positive():
assert is_rotated_palindrome("aab") == True
assert is_rotated_palindrome("baab") == True
assert is_rotated_palindrome("aba") == True
assert is_rotated_palindrome("aaaa") == True
assert is_rotated_palindrome("a") == True
def test_is_rotated_palindrome_n... | [
{
"docstring": "Helper function to check if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Determine whether the given string can be rotated to form a palindrome.",
"function_... | [
0,
1,
0,
1,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_rotated_palindrome(s):\n \"\"\"\n Returns True if the string s can be rotated to form a palindrome.\n \"\"\"\n def is_palindrome(t):\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000026228",
"row_id": 26228,
"seed_ids": "[376]"
} | 0.744978 | Algorithm_26228 | I | [
"is_palindrome",
"is_rotated_palindrome"
] | 2 | [
[
"is_rotated_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 4421c073ac8bbdd01e00bfef4ecee558c4f90ce0 | 4c12ed43adcff0a4e651282d38f2d3a25157995e | |||
v1.0 | instruct | Algorithm | Algorithm_26364_I | ### Problem Statement:
Implement a function that simulates a basic inventory management system for a small retail shop. The shop keeps track of its stock in an inventory dictionary, where the keys are item names and the values are the quantities in stock. Your task is to create functions to add items, remove items, re... | from typing import Dict
def add_item(inventory: Dict[str, int], item: str, quantity: int) -> None:
"""
Adds a specified quantity of an item to the inventory.
If the item already exists, increases the quantity.
Parameters:
- inventory (dict): The current inventory of the shop.
- item (str):... | def test_add_item():
inventory = {}
add_item(inventory, "apples", 10)
assert inventory == {"apples": 10}
add_item(inventory, "apples", 5)
assert inventory == {"apples": 15}
add_item(inventory, "oranges", 7)
assert inventory == {"apples": 15, "oranges": 7}
def test_remove_item():
... | [
{
"docstring": "Adds a specified quantity of an item to the inventory.\nIf the item already exists, increases the quantity.\n\nParameters:\n- inventory (dict): The current inventory of the shop.\n- item (str): The name of the item to add to the inventory.\n- quantity (int): The quantity of the item to add.",
... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Dict\n\ndef add_item(inventory: Dict[str, int], item: str, quantity: int) -> None:\n \"\"\"\n Adds a specified quantity of an item to th... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026364",
"row_id": 26364,
"seed_ids": "[359]"
} | 0.504574 | Algorithm_26364 | I | [
"add_item",
"remove_item",
"restock_item",
"check_stock"
] | 4 | [
[
"restock_item",
"add_item"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d820b1014d9660aadb2b8c4ba3f6e6570065498f | 2c33aca4ac88f624c4e67eb439402012c9c2d4d0 | |||
v1.0 | instruct | Algorithm | Algorithm_26492_I | ### Coding Assessment Question
#### Context
You are contributing to a software library aimed at simulating and visualizing planetary orbits for educational purposes. The library includes various utilities for working with different types of orbits, including elliptical and circular orbits. An orbit can be described b... | def semi_major_axis(periapsis: float, apoapsis: float) -> float:
"""
Calculate the semi-major axis of an elliptical orbit.
Parameters:
periapsis (float): Distance of the periapsis point.
apoapsis (float): Distance of the apoapsis point.
Returns:
float: Semi-major axis of the orbit.... | from solution import semi_major_axis, eccentricity, describe_orbit
def test_semi_major_axis():
assert semi_major_axis(5, 15) == 10.0
assert semi_major_axis(2, 4) == 3.0
assert semi_major_axis(1.5, 3.5) == 2.5
def test_eccentricity():
assert eccentricity(5, 15) == 0.5
assert eccentricity(2, 4) == 0... | [
{
"docstring": "Calculate the semi-major axis of an elliptical orbit.\n\nParameters:\nperiapsis (float): Distance of the periapsis point.\napoapsis (float): Distance of the apoapsis point.\n\nReturns:\nfloat: Semi-major axis of the orbit.\n\nRaises:\nValueError: If periapsis or apoapsis are not positive or peri... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def semi_major_axis(periapsis: float, apoapsis: float) -> float:\n \"\"\"\n Calculate the semi-major axis of an elliptical orbit.\n \n :param periaps... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026492",
"row_id": 26492,
"seed_ids": "[3595]"
} | 0.523169 | Algorithm_26492 | I | [
"semi_major_axis",
"eccentricity",
"describe_orbit"
] | 3 | [
[
"describe_orbit",
"eccentricity"
],
[
"describe_orbit",
"semi_major_axis"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 680f1b741cc9fcdfe7de04d0ee88c746419c8ed7 | 963aab19468890bd579448a41c2fbc6f274386ef | |||
v1.0 | instruct | Algorithm | Algorithm_26503_I | ### Logistic Regression with Regularization
You are given a dataset and asked to implement logistic regression with L2 regularization. Write a function `logistic_regression` that fits the logistic regression model to the provided dataset and includes options for penalty and tolerance.
#### Function Signature
```pytho... | import numpy as np
from typing import Tuple
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def compute_cost(X, y, theta, penalty):
m = len(y)
h = sigmoid(np.dot(X, theta))
cost = (-1/m) * np.sum(y * np.log(h) + (1 - y) * np.log(1 - h))
reg_cost = cost + (penalty/(2*m)) * np.sum(np.square(theta[1:]))
... | import numpy as np
from solution import logistic_regression
def test_logistic_regression():
X = np.array([
[1.0, 2.0],
[1.5, 1.8],
[5.0, 8.0],
[8.0, 8.0],
[1.0, 0.6],
[9.0, 11.0]
])
y = np.array([0, 0, 1, 1, 0, 1])
learning_rate = 0.01
max_iter = 10... | [
{
"docstring": null,
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},
{
"docstring": null,
"function_declaration": "def compute_cost(X, y, theta, penalty):",
"function_name": "compute_cost",
"parameter_list": "(X, y, theta, penalty... | [
1,
0,
1,
1,
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 typing import Tuple, List\n\ndef sigmoid(z: np.ndarray) -> np.ndarray:\n return 1 / (1 + np.exp(-z))\n\ndef compute_cost(X: np.ndarra... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026503",
"row_id": 26503,
"seed_ids": "[382]"
} | 0.69324 | Algorithm_26503 | I | [
"sigmoid",
"compute_cost",
"compute_gradient",
"logistic_regression"
] | 4 | [
[
"compute_cost",
"sigmoid"
],
[
"compute_gradient",
"sigmoid"
],
[
"logistic_regression",
"compute_cost"
],
[
"logistic_regression",
"compute_gradient"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 0777a6a05ea703ad66c7a3735b31208da6e40c93 | a0a6132d1b02708ab951fdae58a49c6403627a13 | |||
v1.0 | instruct | Algorithm | Algorithm_26615_I | ### Image Denoising Using Non-Local Means Algorithm
#### Context
Image denoising is a critical preprocessing step in various image processing and computer vision tasks. The Non-Local Means (NLM) algorithm is a powerful method for denoising, which computes the denoised pixel value by taking a weighted average of simil... | import numpy as np
from scipy.ndimage import convolve
def get_patch(image, i, j, patch_size):
"""
Extracts a patch of size patch_size x patch_size centered at (i, j) from the image.
"""
half_patch = patch_size // 2
patch = image[max(0, i - half_patch):i + half_patch + 1, max(0, j - half_patch):j + ... | import numpy as np
from solution import denoise_image
def test_denoise_image_tiny_image():
noisy_image = np.array([[0.5, 0.6], [0.7, 0.8]], dtype=np.float32)
patch_size = 3
search_window_size = 5
h = 0.1
denoised_image = denoise_image(noisy_image, patch_size, search_window_size, h)
assert denoi... | [
{
"docstring": "Extracts a patch of size patch_size x patch_size centered at (i, j) from the image.",
"function_declaration": "def get_patch(image, i, j, patch_size):",
"function_name": "get_patch",
"parameter_list": "(image, i, j, patch_size)"
},
{
"docstring": "Computes the Non-Local Means... | [
0,
0,
1,
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": "import numpy as np\nfrom scipy.ndimage import generic_filter\n\ndef denoise_patches(image, patch_size):\n # Function to extract all patches of the given size ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000026615",
"row_id": 26615,
"seed_ids": "[4868]"
} | 0.505627 | Algorithm_26615 | I | [
"get_patch",
"compute_nlm_weights",
"denoise_image"
] | 3 | [
[
"compute_nlm_weights",
"get_patch"
],
[
"denoise_image",
"compute_nlm_weights"
],
[
"denoise_image",
"get_patch"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 1b3cd9ef111fc43e807536b230ff55876d6dede6 | 1ee8ee9374a1000a69a063e08f54aa2d8a26d968 | |||
v1.0 | instruct | Algorithm | Algorithm_26880_I | ### Coding Assessment Question: LCM of Multiple Numbers
#### Objective
Implement a function `lcm_multiple(nums: List[int]) -> int` that calculates the Least Common Multiple (LCM) of a list of integers. This function should handle various scenarios including lists with multiple elements, edge cases, and large integers... | from functools import reduce
from math import gcd
from typing import List
def lcm(a, b):
"""
Returns the least common multiple of a and b
"""
return abs(a * b) // gcd(a, b)
def lcm_multiple(nums: List[int]) -> int:
"""
Returns the least common multiple of a list of integers
"""
if not ... | import pytest
from solution import lcm_multiple
def test_lcm_multiple_positive_numbers():
assert lcm_multiple([1, 2, 3, 4, 5]) == 60
def test_lcm_multiple_with_negative_numbers():
assert lcm_multiple([-5, 10, -20]) == 20
def test_lcm_multiple_one_element():
assert lcm_multiple([7]) == 7
def test_lcm_mul... | [
{
"docstring": "Returns the least common multiple of a and b",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple of a list of integers",
"function_declaration": "def lcm_multiple(nums):",
... | [
0,
1,
1,
0,
1,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom functools import reduce\nfrom math import gcd\n\ndef lcm(a: int, b: int) -> int:\n \"\"\"\n Calculates the least common multi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026880",
"row_id": 26880,
"seed_ids": "[3637]"
} | 0.698218 | Algorithm_26880 | I | [
"lcm",
"lcm_multiple"
] | 2 | [
[
"lcm_multiple",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f4c27df138a154dcb289ff31dc526df2c101501 | a4db172974841c5928e84f26ead8caa19b853bc6 | |||
v1.0 | instruct | Algorithm | Algorithm_26901_I | ### Coding Challenge: Validate and Classify IP Addresses
#### Objective:
Implement functions to validate and classify IP addresses (IPv4 or IPv6) from a given file containing a list of addresses. Your task is to read these addresses, determine their type, and count the number of valid IPv4, IPv6, and invalid addresses... | import re
from typing import Tuple
def is_valid_ipv4(ip: str) -> bool:
"""
Checks if a given string is a valid IPv4 address.
"""
pattern = re.compile(r'^(\d{1,3}\.){3}\d{1,3}$')
if pattern.match(ip):
parts = ip.split(".")
for part in parts:
if not 0 <= int(part) <= 255:
... | import pytest
from solution import is_valid_ipv4, is_valid_ipv6, classify_ip_addresses
def test_is_valid_ipv4():
assert is_valid_ipv4("192.168.0.1") == True
assert is_valid_ipv4("255.255.255.255") == True
assert is_valid_ipv4("192.168.0.256") == False
assert is_valid_ipv4("123.456.789.0") == False
... | [
{
"docstring": "Checks if a given string is a valid IPv4 address.",
"function_declaration": "def is_valid_ipv4(ip):",
"function_name": "is_valid_ipv4",
"parameter_list": "(ip)"
},
{
"docstring": "Checks if a given string is a valid IPv6 address.",
"function_declaration": "def is_valid_ip... | [
0,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nfrom typing import Tuple\n\ndef is_valid_ipv4(ip: str) -> bool:\n pattern = re.compile(r\"^(\\d{1,3}\\.){3}\\d{1,3}$\")\n if not pattern.match(i... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000026901",
"row_id": 26901,
"seed_ids": "[3325]"
} | 0.615279 | Algorithm_26901 | I | [
"is_valid_ipv4",
"is_valid_ipv6",
"classify_ip_addresses"
] | 3 | [
[
"classify_ip_addresses",
"is_valid_ipv4"
],
[
"classify_ip_addresses",
"is_valid_ipv6"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c28d1035247c8109198ee2932b5ef78523a73c13 | a322252c2e8777f045c37920c5586de1e1d1d75c | |||
v1.0 | instruct | Algorithm | Algorithm_26939_I | ### Coding Challenge: Real-Time Flight Status Tracker
Your task is to develop a real-time flight status tracking program that pulls information from two different APIs: AviationStack and FlightAware. The goal is to implement a Python function that retrieves data from both APIs, handles possible errors, and aggregates ... | import requests
import concurrent.futures
import datetime
# Define your API keys here
AVIATIONSTACK_API_KEY = "your_aviationstack_api_key"
FLIGHTAWARE_API_KEY = "your_flightaware_api_key"
AVIATIONSTACK_URL_BASE = "http://api.aviationstack.com/v1/flights"
FLIGHTAWARE_URL_BASE = "http://api.flightaware.com/json/FlightX... | import pytest
from solution import get_flight_status
def mock_aviationstack_success(flight_number, date):
return {
'data': [{
'flight': {
'status': 'departed',
'departure_time': '2023-10-10T10:00:00Z',
'arrival_time': '2023-10-10T12:00:00Z'
... | [
{
"docstring": null,
"function_declaration": "def fetch_aviationstack(flight_number, date):",
"function_name": "fetch_aviationstack",
"parameter_list": "(flight_number, date)"
},
{
"docstring": null,
"function_declaration": "def fetch_flightaware(flight_number, date):",
"function_nam... | [
0,
0,
0,
0,
0,
0,
1,
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\nimport concurrent.futures\n\n# Define your API keys here\nAVIATIONSTACK_API_KEY = \"your_aviationstack_api_key\"\nFLIGHTAWARE_API_KEY = \"your_f... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000026939",
"row_id": 26939,
"seed_ids": "[2556]"
} | 0.538411 | Algorithm_26939 | I | [
"fetch_aviationstack",
"fetch_flightaware",
"get_flight_status"
] | 3 | [
[
"get_flight_status",
"fetch_aviationstack"
],
[
"get_flight_status",
"fetch_flightaware"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | e4f587f791f987ed6360fe7df106e1fd86baedb6 | 89ec04c22f59ab70a903f7c0d07ccf921fcc9ef2 | |||
v1.0 | instruct | Algorithm | Algorithm_27044_I | ### Coding Assessment Question
You are assigned the task of identifying palindromic numbers and their positions within a specified sequence. A palindromic number reads the same backward as forward, such as 121 or 1331. In this task, you'll write a function that takes an integer `n` and returns a list of the first `n` ... | from typing import List
def is_palindromic(number: int) -> bool:
"""
Helper function to check if a number is palindromic.
"""
return str(number) == str(number)[::-1]
def generate_palindromic_numbers(n: int) -> List[int]:
"""
Returns a list of the first n palindromic numbers.
"""
palind... | from solution import generate_palindromic_numbers
def test_generate_palindromic_numbers_edge_cases():
assert generate_palindromic_numbers(1) == [1]
assert generate_palindromic_numbers(2) == [1, 2]
assert generate_palindromic_numbers(3) == [1, 2, 3]
def test_generate_palindromic_numbers_small_n():
asse... | [
{
"docstring": "Helper function to check if a number is palindromic.",
"function_declaration": "def is_palindromic(number):",
"function_name": "is_palindromic",
"parameter_list": "(number)"
},
{
"docstring": "Returns a list of the first n palindromic numbers.",
"function_declaration": "d... | [
0,
0,
1,
0,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def generate_palindromic_numbers(n):\n \"\"\"\n Generates the first n palindromic numbers.\n \n :param n: integer specifying the number of palindromi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027044",
"row_id": 27044,
"seed_ids": "[2401]"
} | 0.730461 | Algorithm_27044 | I | [
"is_palindromic",
"generate_palindromic_numbers"
] | 2 | [
[
"generate_palindromic_numbers",
"is_palindromic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3dfb1ef4f9c8727939ca63a730db7d3a5d5b0704 | e18648b7297dd54f82d1b7e38363439300b13779 | |||
v1.0 | instruct | Algorithm | Algorithm_27118_I | ### Implement a Simple File Compression Algorithm
You are required to implement a simple text-based file compression and decompression algorithm using the Huffman coding technique. Your task is to write Python functions that compress a given input text file and then decompress it back to its original content.
#### Fu... | import heapq
import os
from collections import defaultdict, Counter
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(tex... | import os
from solution import compress_file, decompress_file
def setup_module(module):
""" setup any state specific to the execution of the given module."""
with open('input.txt', 'w') as file:
file.write("this is an example for huffman encoding and decoding")
def teardown_module(module):
""" tea... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nimport os\n\nclass HuffmanNode:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n self.left = None\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000027118",
"row_id": 27118,
"seed_ids": "[431]"
} | 0.617722 | Algorithm_27118 | I | [
"build_huffman_tree",
"build_codes",
"huffman_encoding",
"huffman_decoding",
"compress_file",
"decompress_file",
"encode_object",
"decode_object"
] | 8 | [
[
"compress_file",
"encode_object"
],
[
"compress_file",
"huffman_encoding"
],
[
"decompress_file",
"decode_object"
],
[
"decompress_file",
"huffman_decoding"
],
[
"huffman_encoding",
"build_codes"
],
[
"huffman_encoding",
"build_huffman_tree"
]
... | 6 | [] | false | [
"HuffmanNode"
] | true | pytest | true | [] | true | 80bd673a22562c1bfb1e192402ad718e030db4ca | c698a97a4b4ede808b4848214c21589313b9d76e | |||
v1.0 | instruct | Algorithm | Algorithm_27146_I | ### Coding Assessment Question
#### Context:
You are developing a feature for a messaging application that involves encoding and decoding text messages. Given the requirement to use a simple Caesar cipher for encoding and decoding, your task is to create functions to handle these operations efficiently.
#### Task:
... | def encode_caesar_cipher(text: str, shift: int) -> str:
def shift_char(c, shift):
if c.isalpha():
start = ord('A') if c.isupper() else ord('a')
return chr((ord(c) - start + shift) % 26 + start)
return c
return ''.join(shift_char(c, shift) for c in text)
def decode_c... | def test_encode_simple_shift():
assert encode_caesar_cipher("abcXYZ", 2) == "cdeZAB"
def test_decode_simple_shift():
assert decode_caesar_cipher("cdeZAB", 2) == "abcXYZ"
def test_encode_with_wrap_around():
assert encode_caesar_cipher("zZaA", 1) == "aAbB"
assert encode_caesar_cipher("zZaA", 26) == "zZa... | [
{
"docstring": null,
"function_declaration": "def encode_caesar_cipher(text, shift):",
"function_name": "encode_caesar_cipher",
"parameter_list": "(text, shift)"
},
{
"docstring": null,
"function_declaration": "def decode_caesar_cipher(encoded_text, shift):",
"function_name": "decode... | [
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 encode_caesar_cipher(text: str, shift: int) -> str:\n def shift_char(c, shift):\n if 'a' <= c <= 'z':\n return chr((ord(c) - ord('a') + ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027146",
"row_id": 27146,
"seed_ids": "[2629]"
} | 0.662666 | Algorithm_27146 | I | [
"encode_caesar_cipher",
"decode_caesar_cipher"
] | 2 | [
[
"decode_caesar_cipher",
"encode_caesar_cipher"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 99dce744bdb07fe223148efe43149875c439a7e1 | 509f9097cd26e9ed849381f7efb5f2eb4952ccd0 | |||
v1.0 | instruct | Algorithm | Algorithm_27159_I | ### Scenario:
You are developing a software tool to manage the inventory of books in a library. One of the features required is a utility that can categorize books based on their International Standard Book Number (ISBN). The ISBN can be either 10 or 13 digits, and validation rules differ for each format.
### Task:
I... | def validate_isbn(isbn: str) -> bool:
"""
Validates the given ISBN (either ISBN-10 or ISBN-13).
Parameters:
isbn (str): The ISBN to validate.
Returns:
bool: True if the ISBN is valid, False otherwise.
"""
isbn = isbn.replace("-", "").upper()
if len(isbn) ==... | def test_validate_isbn_valid_isbn10():
assert validate_isbn("0471958697") == True
assert validate_isbn("0306406152") == True
def test_validate_isbn_invalid_isbn10():
assert validate_isbn("047195869X") == False
assert validate_isbn("0306406151") == False
def test_validate_isbn_valid_isbn13():
asser... | [
{
"docstring": "Validates the given ISBN (either ISBN-10 or ISBN-13).\n\nParameters:\n isbn (str): The ISBN to validate.\n \nReturns:\n bool: True if the ISBN is valid, False otherwise.",
"function_declaration": "def validate_isbn(isbn):",
"function_name": "validate_isbn",
"parameter_list":... | [
0,
0,
1,
1,
1,
1,
1,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def validate_isbn(isbn: str) -> bool:\n \"\"\"\n Validates an ISBN-10 or ISBN-13 string.\n \"\"\"\n # Removing hyphens from the ISBN string\n isbn... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000027159",
"row_id": 27159,
"seed_ids": "[3483]"
} | 0.559989 | Algorithm_27159 | I | [
"validate_isbn",
"validate_isbn10",
"validate_isbn13"
] | 3 | [
[
"validate_isbn",
"validate_isbn10"
],
[
"validate_isbn",
"validate_isbn13"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 2884907ecd28354d4845e0967f64e8de086f1c88 | 6af0659cbae41c12c94f967b054a58a9af2fc0c9 | |||
v1.0 | instruct | Algorithm | Algorithm_27224_I | ### Coding Assessment: Implementing K-Nearest Neighbors (KNN)
**Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. You will use the provided KNN model and utility functions as a reference to create new components to demonstrate your understanding.
### Problem Statement
Give... | import math
from collections import Counter
def fit_knn_model(features, labels, k):
"""
Fits the KNN model with the provided training features and labels.
Parameters:
features (list[list[float]]): 2D list of feature values for training instances.
labels (list[int]): List of labels correspondin... | import pytest
from solution import fit_knn_model, predict_instances, calculate_accuracy
def test_fit_knn_model():
features = [[1, 2], [2, 3], [3, 4]]
labels = [0, 1, 0]
k = 2
model = fit_knn_model(features, labels, k)
assert model['features'] == features
assert model['labels'] == labels
ass... | [] | [
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 math\nfrom collections import Counter\n\ndef fit_knn_model(features, labels, k):\n \"\"\"\n Fits the KNN model using given training data.\n \n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027224",
"row_id": 27224,
"seed_ids": "[468]"
} | 0.549728 | Algorithm_27224 | I | [
"fit_knn_model",
"euclidean_distance",
"predict_instances",
"calculate_accuracy"
] | 4 | [
[
"predict_instances",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d828969c9524544b54a795009908648e1a1fd42 | 08bae9c566cca865ac93c1c54fb57cb3d18d331e | |||
v1.0 | instruct | Algorithm | Algorithm_27244_I | ### Coding Assessment Question
#### Context
Sorting algorithms are fundamental in computer science, and understanding them is crucial for efficiency in data handling. We're going to explore one of the classic sorting algorithms, Merge Sort, and see how it performs on different data sets.
#### The Task
Using your know... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
# Splitting the array into two halves
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[in... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([5]) == [5]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_merge_sort_reverse_sorted_list():
assert merge_sort... | [
{
"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": "0000027244",
"row_id": 27244,
"seed_ids": "[3225]"
} | 0.658178 | Algorithm_27244 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 648b14ae3847d9f06e430ef9c5cdc9c3afbc174b | 989b2eb4f503deafdd0790d44bab7d38f8dd59ab | |||
v1.0 | instruct | Algorithm | Algorithm_27247_I | ### Problem Statement
You need to implement a function to find the determinant of a matrix and use this determinant function to check if a system of linear equations has a unique solution or not. These operations are essential in solving and understanding linear systems widely used in engineering, physics, and compute... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
"""
Calculate the determinant of a square matrix using recursion (Laplace expansion).
"""
if len(matrix) != len(matrix[0]):
raise ValueError("Matrix must be square")
if len(matrix) == 1:
return matrix[... | from solution import determinant, has_unique_solution
def test_determinant_1x1_matrix():
matrix = [[4]]
assert determinant(matrix) == 4
def test_determinant_2x2_matrix():
matrix = [
[1, 2],
[3, 4]
]
assert determinant(matrix) == -2
def test_determinant_3x3_matrix():
matrix = [... | [
{
"docstring": "Calculate the determinant of a square matrix using recursion (Laplace expansion).",
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Check if the system of linear equations represented by coeff... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef determinant(matrix: List[List[float]]) -> float:\n if len(matrix) == 1:\n return matrix[0][0]\n\n if len(matrix) == 2... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027247",
"row_id": 27247,
"seed_ids": "[4326]"
} | 0.47114 | Algorithm_27247 | I | [
"determinant",
"has_unique_solution"
] | 2 | [
[
"has_unique_solution",
"determinant"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0992923c454eabfc8111d4497380e876016ef3d9 | 3e440f76beae59f473bd10084f7de20e8506c662 | |||
v1.0 | instruct | Algorithm | Algorithm_27274_I | ### Coding Question: Calculate i-Modulus of an Array
Given an array of integers, your task is to implement two functions that perform operations based on the modulus of each element with its index (1-based indexing).
1. **Function 1: `modulus_lst(lst: list[int]) -> list[int]`**:
* **Input**: A list of integers `... | def modulus_lst(lst):
"""
Returns a list of the modulus of each element with its 1-based index.
"""
return [elem % (i + 1) for i, elem in enumerate(lst)]
def modulus_summary(lst):
"""
Returns a tuple containing the count of zeros, sum of all elements,
and average of all elements in the resu... | from solution import modulus_lst, modulus_summary
def test_modulus_lst():
assert modulus_lst([6, 7, 8, 9]) == [0, 1, 2, 1]
assert modulus_lst([3, 4, 5, 6, 7]) == [0, 0, 2, 2, 2]
assert modulus_lst([10, 20, 30]) == [0, 0, 0]
def test_modulus_summary():
assert modulus_summary([6, 7, 8, 9]) == (1, 4, 1.0... | [
{
"docstring": "Returns a list of the modulus of each element with its 1-based index.",
"function_declaration": "def modulus_lst(lst):",
"function_name": "modulus_lst",
"parameter_list": "(lst)"
},
{
"docstring": "Returns a tuple containing the count of zeros, sum of all elements,\nand avera... | [
1,
1,
1,
1,
1,
1,
0,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def modulus_lst(lst):\n \"\"\"\n Returns a list where each element is the modulus of the original element by its 1-based index.\n \"\"\"\n return [el... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027274",
"row_id": 27274,
"seed_ids": "[3746]"
} | 0.590169 | Algorithm_27274 | I | [
"modulus_lst",
"modulus_summary"
] | 2 | [
[
"modulus_summary",
"modulus_lst"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10b9ba00805fab1e52b275d18e6fc47b66810c9c | f2dbac4b7da69b79e640e2f09c62e0f62df4ed05 | |||
v1.0 | instruct | Algorithm | Algorithm_27354_I | ### Prime Anagram
**Problem Description**:
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Two numbers are considered anagrams of each other if they contain the exact same digits in a different order.
For example, `213` and `231` are anagrams of `123`.
Your t... | from itertools import permutations
def sieve_of_eratosthenes(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
primes = []
for num in range(2, limit + 1):
if sieve[num]:
primes.append(num)
for multiple in range(num*num, limit + 1, num):
sie... | def test_find_smallest_prime_anagram():
assert find_smallest_prime_anagram() == 13
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(31) == True
assert is_prime(0) == False
assert is_prime(1... | [
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from itertools import permutations\nfrom sympy import primerange\n\ndef generate_primes(limit):\n \"\"\"\n Generates prime numbers up to a given limit.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000027354",
"row_id": 27354,
"seed_ids": "[2684]"
} | 0.567645 | Algorithm_27354 | I | [
"sieve_of_eratosthenes",
"is_prime",
"find_smallest_prime_anagram"
] | 3 | [
[
"find_smallest_prime_anagram",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bcd5bcf404c076b2155a21d8b2842247c5c4bca5 | 735b6c8a78a1d36250ec282474abd71903aad747 | |||
v1.0 | instruct | Algorithm | Algorithm_27364_I | ### Programming Question: Implement Median of Medians for Linear Time Selection
You are tasked with implementing the Median of Medians algorithm to find the k-th smallest element in an unsorted array. The Median of Medians algorithm is a deterministic algorithm that provides an efficient approach to selection in linea... | def partition(arr, low, high, pivot_index):
pivot_value = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
store_index = low
for i in range(low, high):
if arr[i] < pivot_value:
arr[store_index], arr[i] = arr[i], arr[store_index]
store_index += 1
... | def test_median_of_medians_single_element():
assert median_of_medians_main([5], 1) == 5
def test_median_of_medians_basic():
assert median_of_medians_main([7, 10, 4, 3, 20, 15], 3) == 7
assert median_of_medians_main([1, 3, 5, 7, 9], 1) == 1
assert median_of_medians_main([100, 5, 2, 6, 14, 99, -50, 72], ... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high, pivot_index):",
"function_name": "partition",
"parameter_list": "(arr, low, high, pivot_index)"
},
{
"docstring": null,
"function_declaration": "def select(arr, low, high, k):",
"function_name": "select",
... | [
1,
1,
0,
1,
0,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def partition(arr, pivot):\n less = []\n greater = []\n equal = 0\n for num in arr:\n if num < pivot:\n less.append(num)\n e... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027364",
"row_id": 27364,
"seed_ids": "[905]"
} | 0.731544 | Algorithm_27364 | I | [
"partition",
"select",
"median_of_medians",
"median_of_medians_main"
] | 4 | [
[
"median_of_medians_main",
"select"
],
[
"select",
"median_of_medians"
],
[
"select",
"partition"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 37e732dcdcfe3c9ab83818497fc287e68a901023 | e3f2f5f1afc78e53d931ea4ab121db47d8654040 | |||
v1.0 | instruct | Algorithm | Algorithm_27379_I | ### Question: Generate and Validate Sudoku Puzzles
#### Context:
You need to develop a solution that can create a valid Sudoku puzzle of various difficulties and also validate a given Sudoku board to ensure it meets the puzzle requirements. The Sudoku puzzle must follow the standard rules, where each row, column, and ... | import random
from typing import List
def generate_empty_sudoku() -> List[List[int]]:
return [[0]*9 for _ in range(9)]
def is_valid(board: List[List[int]], row: int, col: int, num: int) -> bool:
"""Check if it's valid to place num at board[row][col]."""
for i in range(9):
if board[row][i] == num... | from solution import generate_sudoku, validate_sudoku
def test_generate_sudoku_puzzle():
for pre_filled in range(17, 50, 3):
board = generate_sudoku(pre_filled)
assert len(board) == 9
assert all(len(row) == 9 for row in board)
filled_cells = sum(sum(1 for cell in row if cell != 0) f... | [
{
"docstring": null,
"function_declaration": "def generate_empty_sudoku():",
"function_name": "generate_empty_sudoku",
"parameter_list": "()"
},
{
"docstring": "Check if it's valid to place num at board[row][col].",
"function_declaration": "def is_valid(board, row, col, num):",
"func... | [
1,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\n\ndef generate_empty_sudoku() -> List[List[int]]:\n return [[0]*9 for _ in range(9)]\n\n\ndef is_valid(board: List[L... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000027379",
"row_id": 27379,
"seed_ids": "[2356]"
} | 0.612652 | Algorithm_27379 | I | [
"generate_empty_sudoku",
"is_valid",
"solve_sudoku",
"generate_sudoku",
"validate_sudoku"
] | 5 | [
[
"generate_sudoku",
"generate_empty_sudoku"
],
[
"generate_sudoku",
"solve_sudoku"
],
[
"solve_sudoku",
"is_valid"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 796b75ab38084432c98fbe96c0bdf996660530ba | 41742da2e40b55fe18bc4b0054f8e0e1e20d8e75 | |||
v1.0 | instruct | Algorithm | Algorithm_27392_I | ### Radix Sort Implementation
Radix Sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.
Your task is to implement the `radix_sort` function, which sorts a list of non-negative integers usin... | def counting_sort(arr, exp):
"""
A function to perform counting sort based on the exponent value (digits place).
"""
n = len(arr)
# Output array
output = [0] * n
# Initialize count array
count = [0] * 10
# Store the count of occurrences in count[]
for i in range(n)... | from solution import radix_sort
def test_radix_sort_simple_case():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_with_duplicates():
assert radix_sort([1, 4, 1, 2, 7, 5, 2]) == [1, 1, 2, 2, 4, 5, 7]
def test_radix_sort_with_zeros():
assert ra... | [
{
"docstring": "A function to perform counting sort based on the exponent value (digits place).",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "Function to perform radix sort on the given list of no... | [
1,
0,
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 counting_sort_for_radix(arr, exp):\n \"\"\"\n A helper function to perform counting sort on the array based on the digit\n represented by exp (10^i)... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027392",
"row_id": 27392,
"seed_ids": "[720]"
} | 0.677272 | Algorithm_27392 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7788d2dfa9be4f35ca922b4f1b390e3df31833c8 | 5a608aac1df41a13aa18bcc3055a4fa6836134ba | |||
v1.0 | instruct | Algorithm | Algorithm_27410_I | ### Fibonacci Sequence and Modular Arithmetic
#### Context:
The Fibonacci sequence is often encountered in programming challenges. For this task, you are required to efficiently calculate the Fibonacci numbers and apply modular arithmetic to keep the values manageable.
#### Requirements:
1. **Function 1**: Implement ... | def fibonacci(n):
"""
Returns the n-th Fibonacci number.
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Input must be a non-negative integer.")
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a... | from solution import fibonacci, fibonacci_mod_m
def test_fibonacci():
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(5) == 5
assert fibonacci(10) == 55
def test_fibonacci_invalid_input():
import pytest
with pytest.raises(ValueError):
fibonacci(-1)
with pytest.ra... | [
{
"docstring": "Returns the n-th Fibonacci number.",
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Returns the n-th Fibonacci number modulo m.",
"function_declaration": "def fibonacci_mod_m(n, m):",
"function_nam... | [
0,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def fibonacci(n: int) -> int:\n \"\"\"\n Returns the n-th Fibonacci number.\n \"\"\"\n if n < 0:\n raise ValueError(\"Input must be a non-nega... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027410",
"row_id": 27410,
"seed_ids": "[2433]"
} | 0.657258 | Algorithm_27410 | I | [
"fibonacci",
"fibonacci_mod_m"
] | 2 | [
[
"fibonacci_mod_m",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6bc7d9e32dcf764f3529f915fb1b4dc5cda050e1 | 27db3b665c13fd6f162bd08724ff4dea1627a28b | |||
v1.0 | instruct | Algorithm | Algorithm_27431_I | ### Problem Statement
You are required to write a function that takes a list of integers and returns a new list containing only the prime numbers from the original list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This function will be useful in applications... | def is_prime(n):
"""
Returns True if n is a prime number, otherwise returns False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return Fa... | from solution import extract_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(11) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(15) == False
def test_extract_primes_exam... | [
{
"docstring": "Returns True if n is a prime number, otherwise returns False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers from the input list 'numbers'.",
"function_declaration": "de... | [
1,
1,
1,
1,
1,
1,
0,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import isqrt\n\ndef is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027431",
"row_id": 27431,
"seed_ids": "[841]"
} | 0.669927 | Algorithm_27431 | I | [
"is_prime",
"extract_primes"
] | 2 | [
[
"extract_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39c8e87bef95786502e9b8103fa83f313456fe42 | 7f16595d00f98536eb707a1b3ea8e83b847b7cc0 | |||
v1.0 | instruct | Algorithm | Algorithm_27445_I | ### Coding Assessment Question
**Scenario**: In computer science, sorting algorithms are essential for efficiently organizing data. Sorting large datasets can significantly improve performance in data retrieval and manipulation tasks. While there are various common sorting algorithms like quicksort and mergesort, it i... | from typing import List
def custom_sort(arr: List[int]) -> List[int]:
if not arr:
return arr
min_val, max_val = min(arr), max(arr)
bucket_range = (max_val - min_val) // len(arr) + 1
buckets = [[] for _ in range((max_val - min_val) // bucket_range + 1)]
for num in arr:
bucket_index... | from solution import custom_sort
def test_empty_list():
assert custom_sort([]) == []
def test_single_element_list():
assert custom_sort([1]) == [1]
assert custom_sort([-1]) == [-1]
def test_multiple_elements():
assert custom_sort([4, 2, 2, 8, 3, 3, 1]) == [1, 2, 2, 3, 3, 4, 8]
assert custom_sort(... | [
{
"docstring": null,
"function_declaration": "def custom_sort(arr):",
"function_name": "custom_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
}
] | [
1,
0,
0,
1,
1,
0,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef custom_sort(arr: List[int]) -> List[int]:\n def insertion_sort(bucket: List[int]) -> List[int]:\n for i in range(1, len(... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027445",
"row_id": 27445,
"seed_ids": "[5319]"
} | 0.617188 | Algorithm_27445 | I | [
"custom_sort",
"insertion_sort"
] | 2 | [
[
"custom_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4772a0c243bb66c77d0982ca4b84cac4bfbc7b1a | e4137405f6fd84953d647cf39ea5c9f2708a3d31 | |||
v1.0 | instruct | Algorithm | Algorithm_27527_I | ### Question: Implement a Custom KMeans Clustering with KMeans++
You are tasked with implementing KMeans clustering algorithm with the KMeans++ initialization to enhance the performance and accuracy of clustering.
#### Step 1: Implement KMeans++ Initialization
1. **Function Signature**:
```python
def kmeans_p... | import numpy as np
from typing import Tuple
def kmeans_plus_plus_initialization(data: np.ndarray, k: int) -> np.ndarray:
"""
Perform KMeans++ initialization to select initial centroids.
Parameters:
data (np.ndarray): The data array of shape (m, n).
k (int): The number of clusters.
... | import numpy as np
from solution import kmeans_plus_plus_initialization, kmeans_clustering
def generate_synthetic_data():
from sklearn.datasets import make_blobs
data, _ = make_blobs(n_samples=300, centers=4, n_features=2, random_state=42)
return data
def test_kmeans_plus_plus_initialization_shape():
... | [
{
"docstring": "Perform KMeans++ initialization to select initial centroids.\n\nParameters:\n data (np.ndarray): The data array of shape (m, n).\n k (int): The number of clusters.\n\nReturns:\n np.ndarray: An array of shape (k, n) with the initialized centroids.",
"function_declaration": "def kmean... | [
0,
1,
0,
1,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef kmeans_plus_plus_initialization(data: np.ndarray, k: int) -> np.ndarray:\n np.random.seed(42) # for reproducibility\n \n n_sa... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027527",
"row_id": 27527,
"seed_ids": "[514]"
} | 0.80107 | Algorithm_27527 | I | [
"kmeans_plus_plus_initialization",
"kmeans_clustering"
] | 2 | [
[
"kmeans_clustering",
"kmeans_plus_plus_initialization"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | feab2aaa3a1b06ea4ea535676edd6ae1ae9f6063 | 76afd3da05a57e607bff0f78cc9a4875166ddfa5 | |||
v1.0 | instruct | Algorithm | Algorithm_27539_I | ### Problem Statement:
You are given two functions that convert between Roman numerals and integers:
1. `int_to_roman` - Converts an integer to its Roman numeral representation.
2. `roman_to_int` - Converts a Roman numeral to its integer representation.
Your task is to write a new function `roman_numeral_conversion` ... | def roman_numeral_conversion(num: int) -> bool:
"""
Converts an integer to a Roman numeral and then back to an integer.
Verifies if the final result matches the original input integer.
Returns True if they are equal, otherwise False.
"""
roman_numeral = int_to_roman(num)
converted_back_... | def test_roman_numeral_conversion():
assert roman_numeral_conversion(1) == True
assert roman_numeral_conversion(4) == True
assert roman_numeral_conversion(9) == True
assert roman_numeral_conversion(58) == True
assert roman_numeral_conversion(1990) == True
assert roman_numeral_conversion(3999) ==... | [
{
"docstring": "Converts an integer to a Roman numeral and then back to an integer.\nVerifies if the final result matches the original input integer.\n\nReturns True if they are equal, otherwise False.",
"function_declaration": "def roman_numeral_conversion(num):",
"function_name": "roman_numeral_conver... | [
0,
0,
1,
0,
0,
0,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def roman_numeral_conversion(num: int) -> bool:\n \"\"\"\n Converts the integer to its Roman numeral representation and back,\n and checks if it matches... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027539",
"row_id": 27539,
"seed_ids": "[3316]"
} | 0.622463 | Algorithm_27539 | I | [
"roman_numeral_conversion",
"int_to_roman",
"roman_to_int"
] | 3 | [
[
"roman_numeral_conversion",
"int_to_roman"
],
[
"roman_numeral_conversion",
"roman_to_int"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 4288a07061483afd94693728b566567ff754daec | d0be43ecbb7fa60b952e3fa0d895dda04789e389 | |||
v1.0 | instruct | Algorithm | Algorithm_27560_I | #### Question:
In this task, you are required to implement a function that evaluates a string containing valid mathematical expressions and computes their results. This exercise is intended to assess your comprehension and ability to handle basic arithmetic operations and expression parsing.
### Requirements:
1. **F... | def evaluate_expression(expression: str) -> float:
"""
Evaluates a string containing a mathematical expression and returns its result as a float.
"""
def apply_operator(operands, operator):
b = operands.pop()
a = operands.pop()
if operator == '+':
operands.append(a + ... | from solution import evaluate_expression
def test_evaluate_simple_addition():
assert evaluate_expression("3 + 2") == 5.0
def test_evaluate_with_mult_operations():
assert evaluate_expression("3 + 2 * 2") == 7.0
def test_evaluate_with_spaces():
assert evaluate_expression(" 3 + 2 ") == 5.0
def test_evaluat... | [
{
"docstring": "Evaluates a string containing a mathematical expression and returns its result as a float.",
"function_declaration": "def evaluate_expression(expression):",
"function_name": "evaluate_expression",
"parameter_list": "(expression)"
},
{
"docstring": null,
"function_declarat... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def evaluate_expression(expression: str) -> float:\n \"\"\"\n Evaluates a mathematical expression provided as a string and returns the result as a float.\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000027560",
"row_id": 27560,
"seed_ids": "[1116]"
} | 0.626902 | Algorithm_27560 | I | [
"evaluate_expression",
"precedence"
] | 2 | [
[
"evaluate_expression",
"precedence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d6918c81c0622cd0d809c1e3e92a29c47e2eb370 | bf9b86b288d6cae2a1f96b9c4fa21bb1546246f2 | |||
v1.0 | instruct | Algorithm | Algorithm_27569_I | ### Fibonacci Sequence Generator and Validator
You are required to implement functions to generate the first `n` numbers in the Fibonacci sequence and to validate if a given number is part of the Fibonacci sequence. Your task is to write a Python function that generates the Fibonacci sequence and another function to v... | import math
def generate_fibonacci(n):
"""
Generates the first n numbers in the Fibonacci sequence.
:param n: Number of Fibonacci numbers to generate
:return: List containing the first n numbers of the Fibonacci sequence
"""
if n <= 0:
return []
elif n == 1:
return [0]
... | from solution import generate_fibonacci, validate_fibonacci
def test_generate_fibonacci():
assert generate_fibonacci(0) == []
assert generate_fibonacci(1) == [0]
assert generate_fibonacci(2) == [0, 1]
assert generate_fibonacci(3) == [0, 1, 1]
assert generate_fibonacci(5) == [0, 1, 1, 2, 3]
asse... | [
{
"docstring": "Generates the first n numbers in the Fibonacci sequence.\n\n:param n: Number of Fibonacci numbers to generate\n:return: List containing the first n numbers of the Fibonacci sequence",
"function_declaration": "def generate_fibonacci(n):",
"function_name": "generate_fibonacci",
"parame... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def generate_fibonacci(n):\n \"\"\"\n Generates the first n numbers in the Fibonacci sequence.\n \n Parameters:\n n (int): The number of Fibonacci... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027569",
"row_id": 27569,
"seed_ids": "[431]"
} | 0.793832 | Algorithm_27569 | I | [
"generate_fibonacci",
"validate_fibonacci",
"is_perfect_square"
] | 3 | [
[
"validate_fibonacci",
"is_perfect_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c14cd67f8d9b2023064651771ccbef57dd327dba | 8584e26b7fd1c6526d9ec90939d713a4b23c05ee | |||
v1.0 | instruct | Algorithm | Algorithm_27590_I | ### Challenge:
You are given a binary tree represented as a list in level order traversal. Your task is to write a function that converts this list representation into a proper binary tree structure, and then perform an inorder traversal of the binary tree.
**Function Signature**:
```python
def list_to_inorder_tree(ar... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def list_to_tree(arr):
if not arr:
return None
root = TreeNode(arr[0])
queue = [root]
i = 1
while queue and i < len(arr):
node = queue.pop... | from solution import list_to_inorder_tree
def test_inorder_traversal_example_1():
assert list_to_inorder_tree([1, 2, 3, None, 4, 5]) == [2, 4, 1, 5, 3]
def test_inorder_traversal_example_2():
assert list_to_inorder_tree([3, 9, 20, None, None, 15, 7]) == [9, 3, 15, 20, 7]
def test_empty_tree():
assert lis... | [] | [
0,
0,
0,
0,
1,
0,
1,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027590",
"row_id": 27590,
"seed_ids": "[5158]"
} | 0.5646 | Algorithm_27590 | I | [
"list_to_tree",
"inorder_traversal",
"list_to_inorder_tree"
] | 3 | [
[
"list_to_inorder_tree",
"inorder_traversal"
],
[
"list_to_inorder_tree",
"list_to_tree"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 6e0d866a331cd6efbf283f987e71f42a109bdac7 | 40924c43dfe25f0fb31562519da4e7fc0e7d9c20 | |||
v1.0 | instruct | Algorithm | Algorithm_27608_I | ### Coding Assessment Question
### Scenario
Sorting algorithms are fundamental in computer science, used to organize data for efficient retrieval and processing. One common variant is sorting a list of dictionaries based on specific key values.
### Task
Implement a sorting function in Python that sorts a list of dict... | from typing import List, Dict, Any
def get_nested_value(d: Dict[str, Any], key: str) -> Any:
keys = key.split('.')
for k in keys:
d = d.get(k, None)
return d
def sort_dicts(dict_list: List[Dict[str, Any]], key: str) -> List[Dict[str, Any]]:
return sorted(dict_list, key=lambda d: get_nested_val... | from solution import sort_dicts
def test_sort_by_primary_key():
people = [
{"name": "Alice", "age": 25, "address": {"city": "New York", "zip": "10001"}},
{"name": "Bob", "age": 22, "address": {"city": "San Francisco", "zip": "94105"}},
{"name": "Charlie", "age": 30, "address": {"city": "Bos... | [
{
"docstring": null,
"function_declaration": "def get_nested_value(d, key):",
"function_name": "get_nested_value",
"parameter_list": "(d, key)"
},
{
"docstring": null,
"function_declaration": "def sort_dicts(dict_list, key):",
"function_name": "sort_dicts",
"parameter_list": "(di... | [
0,
1,
1,
1,
1,
1,
1,
0,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Any\n\ndef sort_dicts(dict_list: List[Dict[str, Any]], key: str) -> List[Dict[str, Any]]:\n def get_nested_value(d: Dict[str, A... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027608",
"row_id": 27608,
"seed_ids": "[1816]"
} | 0.647185 | Algorithm_27608 | I | [
"get_nested_value",
"sort_dicts"
] | 2 | [
[
"sort_dicts",
"get_nested_value"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 415d898cd1a71712e32e3b864dfa95fcb3ad2e29 | 79d4d86d851c9fce2769148d59dd17570b1efa63 | |||
v1.0 | instruct | Algorithm | Algorithm_27618_I | ### In-Order Successor in BST
#### Objective:
Implement a function to find the in-order successor of a given node in a Binary Search Tree (BST).
#### Context:
In-order traversal of a BST yields nodes in ascending order. The in-order successor of a node is the next node in this sequence. This concept is crucial in sce... | class TreeNode:
def __init__(self, val=0, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def in_order_successor(node: TreeNode | None) -> TreeNode | None:
"""
Finds the in-order successor of the given node in a BS... | from solution import TreeNode, in_order_successor
def test_in_order_successor():
# Construct the BST as described in the problem statement
root = TreeNode(20)
root.left = TreeNode(8, parent=root)
root.right = TreeNode(22, parent=root)
root.left.left = TreeNode(4, parent=root.left)
root.left.rig... | [] | [
1,
0,
1,
1,
1,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None, parent=None):\n self.val = val\n self.left = left\n self.right = right... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000027618",
"row_id": 27618,
"seed_ids": "[1616]"
} | 0.534069 | Algorithm_27618 | I | [
"in_order_successor",
"find_min"
] | 2 | [
[
"in_order_successor",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8cfce2b54bf38959fc2e731a2401f90b66d5904d | a4854ff1542ed4fcc30a819b453c778c9a6be5c0 | |||
v1.0 | instruct | Algorithm | Algorithm_27620_I | ### Coding Assessment Question
You are provided with two implementations of an algorithm that computes the factorial of a non-negative integer. One implementation is iterative, and the other uses recursion.
### Task
Write a Python function that performs the following steps:
1. Reads in a non-negative integer.
2. Comp... | def factorial_iterative(n):
"""
Computes the factorial of n using an iterative approach.
"""
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_recursive(n):
"""
Computes the factorial of n using a recursive approach.
"""
if n == 0 or n == 1:
... | from solution import factorial_comparison
def test_factorial_comparison_positive():
assert factorial_comparison(5) == "Matching Factorials: 120"
assert factorial_comparison(10) == "Matching Factorials: 3628800"
assert factorial_comparison(0) == "Matching Factorials: 1"
assert factorial_comparison(1) ==... | [
{
"docstring": "Computes the factorial of n using an iterative approach.",
"function_declaration": "def factorial_iterative(n):",
"function_name": "factorial_iterative",
"parameter_list": "(n)"
},
{
"docstring": "Computes the factorial of n using a recursive approach.",
"function_declara... | [
1,
1,
1,
1,
1,
0,
0,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def factorial_iterative(n):\n \"\"\"\n Computes the factorial of a non-negative integer iteratively.\n \"\"\"\n result = 1\n for i in range(2, n +... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000027620",
"row_id": 27620,
"seed_ids": "[3959]"
} | 0.570865 | Algorithm_27620 | I | [
"factorial_iterative",
"factorial_recursive",
"factorial_comparison"
] | 3 | [
[
"factorial_comparison",
"factorial_iterative"
],
[
"factorial_comparison",
"factorial_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b9ff6060b8ec55bd285f45454464f67cbf2b81f9 | e95d96001afdb181a939ef071cd8ea85db3c154a | |||
v1.0 | instruct | Algorithm | Algorithm_27624_I | ### Coding Assessment Question
#### Context
You are continuing your work on a geometric calculator application, enhancing its ability to handle three-dimensional shapes. You have integrated support for regular dodecahedra and icosahedra. Now, you want to expand your library to include another polyhedron - a regular o... | import math
def octahedron_surface_area(edge: float) -> float:
"""
Returns the surface area of a regular octahedron.
Parameters:
edge (float): The length of the edge of the octahedron.
Returns:
float: The surface area.
Raises:
ValueError: If the edge length is not a posit... | import pytest
from solution import octahedron_surface_area, octahedron_volume, describe_octahedron
def test_octahedron_surface_area():
assert octahedron_surface_area(3) == pytest.approx(2 * math.sqrt(3) * 9, rel=1e-9)
assert octahedron_surface_area(4.5) == pytest.approx(2 * math.sqrt(3) * 20.25, rel=1e-9)
def... | [
{
"docstring": "Returns the surface area of a regular octahedron.\n\nParameters:\n edge (float): The length of the edge of the octahedron.\n\nReturns:\n float: The surface area.\n\nRaises:\n ValueError: If the edge length is not a positive number.",
"function_declaration": "def octahedron_surface_a... | [
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 math\n\ndef octahedron_surface_area(edge: float) -> float:\n \"\"\"\n Returns the surface area of a regular octahedron given the edge length.\n \... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000027624",
"row_id": 27624,
"seed_ids": "[3595]"
} | 0.558639 | Algorithm_27624 | I | [
"octahedron_surface_area",
"octahedron_volume",
"describe_octahedron"
] | 3 | [
[
"describe_octahedron",
"octahedron_surface_area"
],
[
"describe_octahedron",
"octahedron_volume"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 70c325817afada86f8f2ff9d7e50c0c3ce880e53 | 9f4d2b2ab7f28169301319df7174ad0415c2a61f | |||
v1.0 | instruct | Algorithm | Algorithm_27630_I | ### Question: Fibonacci Path Sum
Given an integer matrix `grid` of size `m x n` and `m * n <= 10^5`, where each cell represents the cost of stepping on it, write a function `fibonacci_path_sum(grid: List[List[int]]) -> int` that calculates the minimum cost to reach the bottom-right corner from the top-left corner. The... | def is_fibonacci(n):
"""
Check if a number is a Fibonacci number.
"""
if n < 0:
return False
a, b = 0, 1
while b < n:
a, b = b, a + b
return b == n
from typing import List
from collections import deque
def fibonacci_path_sum(grid: List[List[int]]) -> int:
"""
Calcul... | import pytest
from solution import fibonacci_path_sum
def test_example_1():
grid = [
[1, 2, 3],
[5, 2, 3],
[3, 2, 2]
]
assert fibonacci_path_sum(grid) == 11
def test_example_2():
grid = [
[10, 5, 8],
[7, 5, 18],
[13, 1, 5]
]
assert fibonacci_path... | [
{
"docstring": "Check if a number is a Fibonacci number.",
"function_declaration": "def is_fibonacci(n):",
"function_name": "is_fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the minimal cost of a valid path moving on Fibonacci cells only from top-left to bottom-right.",
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque\n\n# Function to check if a number is Fibonacci\ndef is_fibonacci(n):\n if n <= 0:\n return False\n x, y = 0, 1\n w... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000027630",
"row_id": 27630,
"seed_ids": "[3014]"
} | 0.627868 | Algorithm_27630 | I | [
"is_fibonacci",
"fibonacci_path_sum"
] | 2 | [
[
"fibonacci_path_sum",
"is_fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7177dfb6499505a55487bd868dff14aa3b8389cf | 17cce9eac24a24d16bc67a4293ebac22c01419f5 | |||
v1.0 | instruct | Algorithm | Algorithm_27637_I | ### Question: Implement Kruskal’s Algorithm with Union-Find Optimization
You are tasked with implementing Kruskal's algorithm to find the Minimum Spanning Tree (MST) of a connected, undirected graph. To optimize the algorithm, use a union-find data structure (disjoint-set) with path compression and union by rank.
###... | def find(parent, i):
if parent[i] != i:
parent[i] = find(parent, parent[i])
return parent[i]
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if root_x != root_y:
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif ran... | from solution import kruskal_mst
def test_kruskal_basic():
edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4)]
n = 4
assert kruskal_mst(edges, n) == [(1, 2, 1), (1, 3, 2), (0, 2, 3)]
def test_kruskal_disjoint_sets():
edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
n =... | [
{
"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)"
},
... | [
0,
0,
0,
1,
0,
1,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] != i:\n # Path compression\n parent[i] = find(parent, parent[i])\n return parent[i]\n\ndef union(parent, ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027637",
"row_id": 27637,
"seed_ids": "[416]"
} | 0.673317 | Algorithm_27637 | I | [
"find",
"union",
"kruskal_mst"
] | 3 | [
[
"kruskal_mst",
"find"
],
[
"kruskal_mst",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 85c5dae79f52a6cc9d2183b53e6b4a4fef2c5c19 | cfc1de2f273fecb3b50f8c073d7272a2f950420b | |||
v1.0 | instruct | Algorithm | Algorithm_27711_I | ### AVL Tree Insertion and Balance
You are required to implement an AVL Tree, a self-balancing binary search tree, to test your understanding of advanced data structures and tree balancing algorithms in Python.
#### Problem Statement
Design and implement the following methods for an AVL Tree:
1. `insert(root, key)`:... | class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def insert(root, key):
# Perform the normal BST insertion
if not root:
return AVLNode(key)
if key < root.key:
root.left = insert(root.left, key)
... | from solution import AVLNode, insert, preorder_traversal
def test_avl_insert_single():
root = None
root = insert(root, 10)
assert preorder_traversal(root) == [10]
def test_avl_insert_multiple():
root = None
keys = [10, 20, 30, 40, 50, 25]
for key in keys:
root = insert(root, key)
p... | [] | [
1,
1,
1,
0,
0,
1,
0,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class AVLNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n\ndef insert(... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000027711",
"row_id": 27711,
"seed_ids": "[1704]"
} | 0.534452 | Algorithm_27711 | I | [
"insert",
"left_rotate",
"right_rotate",
"get_height",
"get_balance",
"preorder_traversal"
] | 6 | [
[
"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 | true | [] | true | 60a00f6c1ec33e7f5997fa335c24077da7e69943 | 9b03f5b346033a27a813aff4202173b3d7fbfa40 | |||
v1.0 | instruct | Algorithm | Algorithm_27808_I | ### Problem Statement
You are tasked with implementing two functions to find the greatest common divisor (GCD) and least common multiple (LCM) of a list of integers.
#### Function Definitions
1. **GCD Function (`gcd_list`)**:
- **Input**: A list of non-negative integers `nums`.
- **Output**: An integer represe... | from math import gcd
from functools import reduce
def gcd_list(nums):
if not nums or any(not isinstance(n, int) or n < 0 for n in nums):
raise ValueError("List must contain only non-negative integers.")
def gcd_multiple(numbers):
return reduce(gcd, numbers)
return gcd_multiple(num... | import pytest
from solution import gcd_list, lcm_list
def test_gcd_list():
assert gcd_list([24, 36, 48]) == 12
assert gcd_list([5, 10, 15]) == 5
assert gcd_list([1, 1, 1]) == 1
assert gcd_list([17, 19, 23]) == 1
with pytest.raises(ValueError):
gcd_list([-24, 36, 48])
with pytest.raises(... | [
{
"docstring": null,
"function_declaration": "def gcd_list(nums):",
"function_name": "gcd_list",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef gcd_list(nums: list) -> int:\n def gcd(a, b):\n while b:\n a, b = b, a % b\n return ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000027808",
"row_id": 27808,
"seed_ids": "[3594]"
} | 0.670651 | Algorithm_27808 | I | [
"gcd_list",
"lcm",
"lcm_list"
] | 3 | [
[
"lcm_list",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9b886fab21153578a4f1e280fe009292456d5eba | 9d43b3940ae126c626174aff9aa31cd1e304fe23 | |||
v1.0 | instruct | Algorithm | Algorithm_27822_I | ### Question: Reverse a Linked List in K-Group Intervals
**Context**:
You need to develop a function that reverses a linked list in groups of `k` nodes. This means that if the linked list has nodes 1 -> 2 -> 3 -> 4 -> 5 and `k` is 2, the linked list should be modified to 2 -> 1 -> 4 -> 3 -> 5. However, if `k` is 3, th... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_k_group(head, k):
"""
Reverses the nodes of a linked list in k-group intervals.
Parameters:
head : ListNode
The head node of the linked list.
k : int
The size o... | from solution import ListNode, reverse_k_group
def list_to_linked(lst):
if not lst:
return None
head = ListNode(lst[0])
current = head
for value in lst[1:]:
current.next = ListNode(value)
current = current.next
return head
def linked_to_list(node):
lst = []
while no... | [] | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef reverse_k_group(head, k):\n \"\"\"\n Re... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000027822",
"row_id": 27822,
"seed_ids": "[401]"
} | 0.611936 | Algorithm_27822 | I | [
"reverse_k_group",
"reverse"
] | 2 | [
[
"reverse_k_group",
"reverse"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 595d6b60dc26569893ea5978e7777f6adee3df94 | 36d8a3957a3d27396e954fa5ce91a59cf3e5ffd4 | |||
v1.0 | instruct | Algorithm | Algorithm_27833_I | ### Problem Statement
In this task, you will write a function that checks if a number is a circular prime. A circular prime is a prime number that remains prime when its digits are cyclically rotated in any order.
### Guidelines
- Implement a function `is_circular_prime(n: int) -> bool` that returns `True` if the in... | def is_prime(num):
"""Helper function to check if a number is prime."""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def rotations(n):
"""Generate all cyclic rotations of an integer n."""
s = str(n)
retu... | from solution import is_circular_prime
def test_single_digit_primes():
assert is_circular_prime(2) == True
assert is_circular_prime(3) == True
assert is_circular_prime(5) == True
assert is_circular_prime(7) == True
def test_non_circular_primes():
assert is_circular_prime(23) == False # 23 -> 32
... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generate all cyclic rotations of an integer n.",
"function_declaration": "def rotations(n):",
"func... | [
1,
0,
1,
0,
0,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000027833",
"row_id": 27833,
"seed_ids": "[2791]"
} | 0.671341 | Algorithm_27833 | I | [
"is_prime",
"rotations",
"is_circular_prime"
] | 3 | [
[
"is_circular_prime",
"is_prime"
],
[
"is_circular_prime",
"rotations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 400bcd1b7060ff57fbec6d210b00a4cd221e9a32 | 0e0401485e67c044a911f2bf761b9c26cea4bb07 | |||
v1.0 | instruct | Algorithm | Algorithm_27838_I | ### Implementation of Simple K-Means Clustering
You are required to implement the K-Means clustering algorithm from scratch. Your task is to:
1. Download and process a given dataset.
2. Implement the K-Means algorithm to cluster the data points.
3. Evaluate the clustering performance using within-cluster sum of square... | import numpy as np
import pandas as pd
from urllib.request import urlopen
def collect_dataset():
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
df = pd.read_csv(url)
data = df.drop(columns=['species']).values
return data
def euclidean_distance(point1, point2):
retur... | import pytest
import numpy as np
from solution import collect_dataset, euclidean_distance, assign_clusters, update_centroids, compute_wcss, run_k_means
def test_collect_dataset():
data = collect_dataset()
assert data.shape == (150, 4) # Iris dataset should have 150 rows and 4 features
def test_euclidean_dist... | [
{
"docstring": null,
"function_declaration": "def collect_dataset():",
"function_name": "collect_dataset",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(... | [
0,
0,
1,
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": "import numpy as np\nimport pandas as pd\nfrom urllib import request\n\ndef collect_dataset():\n url = \"https://raw.githubusercontent.com/mwaskom/seaborn-data... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000027838",
"row_id": 27838,
"seed_ids": "[681]"
} | 0.720724 | Algorithm_27838 | I | [
"collect_dataset",
"euclidean_distance",
"assign_clusters",
"update_centroids",
"compute_wcss",
"run_k_means"
] | 6 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"compute_wcss",
"euclidean_distance"
],
[
"run_k_means",
"assign_clusters"
],
[
"run_k_means",
"compute_wcss"
],
[
"run_k_means",
"update_centroids"
]
] | 5 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | c884b6ec7478f29f6b1b8b0f10a6605415f854da | a3546bd982b665fe4ce31b1d6bcfb3a8cc0dd1ba | |||
v1.0 | instruct | Algorithm | Algorithm_27850_I | ### Coding Assessment Question:
#### String Manipulation: Word Reversal
You are tasked with implementing a function that performs a specific string manipulation: reversing the order of words in a given sentence while maintaining the words' original order of characters, and a function that checks if the reversal proce... | def reverse_words(sentence: str) -> str:
"""
Reverse the order of words in a sentence.
:param sentence: A string containing words separated by spaces.
:return: A string with the words in reversed order.
"""
# Removing leading and trailing spaces and then split by spaces
words = sentence... | from solution import reverse_words, validate_reversal
def test_reverse_words_simple():
assert reverse_words("hello world") == "world hello"
def test_reverse_words_with_extra_spaces():
assert reverse_words(" hello world ") == "world hello"
assert reverse_words(" ") == ""
def test_reverse_words_singl... | [
{
"docstring": "Reverse the order of words in a sentence.\n\n:param sentence: A string containing words separated by spaces.\n:return: A string with the words in reversed order.",
"function_declaration": "def reverse_words(sentence):",
"function_name": "reverse_words",
"parameter_list": "(sentence)"... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def reverse_words(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a given sentence.\n\n Args:\n sentence (str): A string containing ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027850",
"row_id": 27850,
"seed_ids": "[4148]"
} | 0.695964 | Algorithm_27850 | I | [
"reverse_words",
"validate_reversal"
] | 2 | [
[
"validate_reversal",
"reverse_words"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f5fa3807b03aa5a94734e35e7b1730d07297745 | 1411e625f905b75467313706913dc9d9a99005b2 | |||
v1.0 | instruct | Algorithm | Algorithm_27878_I | **Least Common Multiple Array Query**
**Objective**:
Implement a function to precompute the Least Common Multiple (LCM) values for all pairs of integers from 1 to `n`. The function should also efficiently handle queries to return the LCM for given pairs.
**Problem Statement**:
Write a function `precompute_lcm_and_que... | from math import gcd
def lcm(x, y):
return x * y // gcd(x, y)
def precompute_lcm_and_query(n: int, queries: list) -> list:
lcm_table = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(i, n + 1):
lcm_table[i][j] = lcm(i, j)
results = []
fo... | def test_precompute_lcm_and_query():
n = 10
queries = [(1, 2), (3, 4), (5, 10), (6, 6)]
result = precompute_lcm_and_query(n, queries)
assert result == [2, 12, 10, 6]
def test_single_query():
n = 15
queries = [(4, 6)]
result = precompute_lcm_and_query(n, queries)
assert result == [12]
d... | [
{
"docstring": null,
"function_declaration": "def lcm(x, y):",
"function_name": "lcm",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def precompute_lcm_and_query(n, queries):",
"function_name": "precompute_lcm_and_query",
"parameter_list": "(n, queri... | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def gcd(x, y):\n while y:\n x, y = y, x % y\n return x\n\ndef lcm(x, y):\n return x * y // gcd(x, y)\n\ndef precompute_lcm_and_query(n, queries):... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000027878",
"row_id": 27878,
"seed_ids": "[3134]"
} | 0.709826 | Algorithm_27878 | I | [
"lcm",
"precompute_lcm_and_query"
] | 2 | [
[
"precompute_lcm_and_query",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 86a10f2f756c230c735d9c88bc68170f87e04980 | 762b80183a7e7581f9c74e972b67cd09e2971018 | |||
v1.0 | instruct | Algorithm | Algorithm_28035_I | ### Matrix Multiplication and Reduction
#### Your Task:
Implement a function that multiplies two matrices, A and B, and then reduces the resulting matrix to a single value using a specified reduction operation.
#### Function Description
1. **matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]*... | from typing import List
def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
num_rows_A, num_cols_A = len(A), len(A[0])
num_rows_B, num_cols_B = len(B), len(B[0])
assert num_cols_A == num_rows_B, "Number of columns in A must be equal to number of rows in B"
C = [[0]... | from solution import matrix_multiply, matrix_reduce, matrix_mult_and_reduce
def test_matrix_multiply():
A = [[1, 2, 3],
[4, 5, 6]]
B = [[7, 8],
[9, 10],
[11, 12]]
expected = [[58, 64],
[139, 154]]
assert matrix_multiply(A, B) == expected
def test_matrix_reduc... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def matrix_reduce(matrix, operation):",
"function_name": "matrix_reduce",
"parameter_list": "... | [
1,
0,
1,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n num_rows_A, num_cols_A = len(A), len(A[0])\n n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000028035",
"row_id": 28035,
"seed_ids": "[770]"
} | 0.575857 | Algorithm_28035 | I | [
"matrix_multiply",
"matrix_reduce",
"matrix_mult_and_reduce"
] | 3 | [
[
"matrix_mult_and_reduce",
"matrix_multiply"
],
[
"matrix_mult_and_reduce",
"matrix_reduce"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d42738f1eb029fe867d7168bdb176b12da48f1f9 | 2d86798c029ca1ef104862ff25c2782c7c523dc7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.