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_8902_I | ### Problem Statement
You are provided with a task to implement a sorting algorithm that sorts a given list of integers in non-decreasing order. However, instead of implementing a standard known sorting algorithm like quicksort or mergesort, you will be implementing a **Pancake Sorting** algorithm.
### Detailed Requi... | def flip(sublist, k):
"""
Flip the first k elements of the sublist.
:param sublist: List of integers.
:param k: Number of elements from the start to flip.
:return: Modified sublist after flipping.
"""
sublist[:k] = sublist[:k][::-1]
return sublist
def pancake_sort(arr):
"""
... | from solution import flip, pancake_sort
def test_flip():
assert flip([1, 2, 3, 4, 5], 3) == [3, 2, 1, 4, 5]
assert flip([1, 2, 3, 4], 4) == [4, 3, 2, 1]
assert flip([4, 3, 2, 1], 2) == [3, 4, 2, 1]
def test_pancake_sort():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
assert pancake_sort([1, 2... | [
{
"docstring": "Flip the first k elements of the sublist.\n\n:param sublist: List of integers.\n:param k: Number of elements from the start to flip.\n:return: Modified sublist after flipping.",
"function_declaration": "def flip(sublist, k):",
"function_name": "flip",
"parameter_list": "(sublist, k)"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def flip(sublist, k):\n \"\"\"\n Flip the first k elements of the sublist.\n \n :param sublist: List of integers.\n :param k: Number of elements f... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000008902",
"row_id": 8902,
"seed_ids": "[3979]"
} | 0.736209 | Algorithm_8902 | I | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e167639461a2b7df9f983d1ec864e7617a6b9f7c | ab6686e1ad47a5f36a3cd5cbb0377be5799f0784 | |||
v1.0 | instruct | Algorithm | Algorithm_8924_I | **Consecutive Primes Sum**
**Problem Statement**:
You are tasked with finding the longest sequence of consecutive prime numbers that adds up to a prime less than a given number `n`. Write a function to identify the length of this sequence and the corresponding sum.
**Function Signature**:
```python
def consecutive_pr... | from typing import List, Tuple
def sieve_of_eratosthenes(limit: int) -> List[int]:
is_prime = [True] * limit
is_prime[0] = is_prime[1] = False
for start in range(2, int(limit**0.5) + 1):
if is_prime[start]:
for multiple in range(start*start, limit, start):
is_prime[... | from solution import sieve_of_eratosthenes, consecutive_primes_sum
def test_sieve_of_eratosthenes():
assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]
assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]
def test_consecutive_primes_sum():
assert consecutive_primes_sum(100) == (6, 41)
assert... | [
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": null,
"function_declaration": "def consecutive_primes_sum(n):",
"function_name": "consecutive_primes_sum",
"pa... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef sieve_of_eratosthenes(limit: int) -> List[int]:\n is_prime = [True] * limit\n is_prime[0] = is_prime[1] = False\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000008924",
"row_id": 8924,
"seed_ids": "[2180]"
} | 0.595683 | Algorithm_8924 | I | [
"sieve_of_eratosthenes",
"consecutive_primes_sum"
] | 2 | [
[
"consecutive_primes_sum",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3c06f98696c897cd1f263c7e829d546c63926879 | 3ab114aa619f3abc29ab33720c30437ead726eca | |||
v1.0 | instruct | Algorithm | Algorithm_8933_I | **Question**: Distance Between Nodes in a Binary Tree
**Context**:
Given a binary tree, determine the distance between two nodes in the tree. The distance between two nodes is defined as the number of edges in the shortest path between them.
**Details**:
1. Implement a function `find_distance(root: TreeNode, node1: ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_lca(root: TreeNode, node1: int, node2: int) -> TreeNode:
if not root or root.val == node1 or root.val == node2:
return root
left_lca = find_lca(... | from solution import TreeNode, find_distance
def test_find_distance_between_siblings():
node1 = TreeNode(4)
node2 = TreeNode(5)
node3 = TreeNode(2, node1, node2)
node4 = TreeNode(3)
root = TreeNode(1, node3, node4)
assert find_distance(root, 4, 5) == 2
def test_find_distance_across_levels... | [] | [
0,
1,
1,
1,
0,
1,
1,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "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 find_... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000008933",
"row_id": 8933,
"seed_ids": "[5137]"
} | 0.613239 | Algorithm_8933 | I | [
"find_lca",
"find_distance"
] | 2 | [
[
"find_distance",
"find_lca"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 16b791fe557b657f0cb3c6d03f75c61944e1e98f | 47c363e115893d8ee0d4d566b3ee27490ece0b8d | |||
v1.0 | instruct | Algorithm | Algorithm_8948_I | ### Huffman Coding Tree Construction and Encoding
**Scenario**:
Given a set of characters and their corresponding frequencies, you need to construct a Huffman coding tree. Your task is to implement a function that generates the Huffman codes for each character and returns a dictionary with characters as keys and their... | import heapq
from collections import defaultdict
from typing import Dict
class HeapNode:
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 merge_nodes(left: He... | import pytest
from solution import build_huffman_tree
def test_single_element():
frequencies = {'a': 1, 'b': 1}
result = build_huffman_tree(frequencies)
expected_keys = set(frequencies.keys())
assert set(result.keys()) == expected_keys
def test_example_case_1():
frequencies = {
'a': 5,
... | [] | [
1,
1,
1,
0,
1,
0,
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 heapq\nfrom collections import defaultdict\nfrom typing import Dict\n\nclass HeapNode:\n def __init__(self, char, freq):\n self.char = char\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000008948",
"row_id": 8948,
"seed_ids": "[3938]"
} | 0.549901 | Algorithm_8948 | I | [
"merge_nodes",
"build_codes",
"build_huffman_tree"
] | 3 | [
[
"build_huffman_tree",
"build_codes"
],
[
"build_huffman_tree",
"merge_nodes"
]
] | 2 | [] | false | [
"HeapNode"
] | true | pytest | true | [] | true | 96fe4bcd28c9e9ba56739b3ea3d214ebef04b0ca | d9e1166c83ddb0bc1fe98171d55bcb6ba23a17e2 | |||
v1.0 | instruct | Algorithm | Algorithm_9081_I | ### Question: Implement and Evaluate Decision Tree Algorithms
In this task, you will implement the Decision Tree algorithm from scratch for both classification and regression tasks. Decision Trees are non-parametric supervised learning methods used for classification and regression.
#### Objectives:
1. Implement the... | import numpy as np
def entropy(y):
"""
Calculate the entropy of a label array y.
"""
hist = np.bincount(y)
ps = hist / len(y)
return -np.sum([p * np.log2(p) for p in ps if p > 0])
def information_gain(parent, left, right):
"""
Calculate the information gain of a split.
"""
num_... | from solution import decision_tree_classifier, decision_tree_regressor
import numpy as np
def test_decision_tree_classifier():
X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
y = np.array([0, 1, 0, 1, 0])
tree = decision_tree_classifier(X, y, max_depth=3, min_samples_split=2)
assert isinstance(t... | [
{
"docstring": "Calculate the entropy of a label array y.",
"function_declaration": "def entropy(y):",
"function_name": "entropy",
"parameter_list": "(y)"
},
{
"docstring": "Calculate the information gain of a split.",
"function_declaration": "def information_gain(parent, left, right):",... | [
0,
1,
0,
1,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import Counter\n\ndef entropy(y):\n hist = np.bincount(y)\n ps = hist / len(y)\n return -np.sum([p * np.log2(p) for... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000009081",
"row_id": 9081,
"seed_ids": "[498]"
} | 0.597951 | Algorithm_9081 | I | [
"entropy",
"information_gain",
"mse",
"split",
"best_split",
"build_tree",
"decision_tree_classifier",
"decision_tree_regressor"
] | 8 | [
[
"best_split",
"information_gain"
],
[
"best_split",
"mse"
],
[
"best_split",
"split"
],
[
"build_tree",
"best_split"
],
[
"build_tree",
"split"
],
[
"decision_tree_classifier",
"build_tree"
],
[
"decision_tree_regressor",
"build_tree"... | 8 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 706f653949996da7e1e53d486e6dc961391afb05 | 6cc7c9804240b643b4549d31d40b860a357d8495 | |||
v1.0 | instruct | Algorithm | Algorithm_9106_I | ### Question: URL Shortener Service
You are tasked with creating a simplified URL shortener service using Python. This service will take long URLs and convert them into shorter versions. The structure should support maintaining a record of the shortened URLs and their corresponding original URLs, as well as retrieving... | import random
import string
import re
url_mapping = {}
short_code_length = 6
def shorten_url(long_url: str) -> str:
"""
Takes a long URL and returns a shortened version.
"""
if not validate_url(long_url):
raise ValueError("Invalid URL")
short_code = generate_unique_short_code()
url_map... | import pytest
from solution import shorten_url, retrieve_original_url, validate_url
def test_shorten_url():
original_url = "https://www.openai.com/research/gpt-3/"
short_url = shorten_url(original_url)
short_code = short_url.split('/')[-1]
assert len(short_code) == 6
assert original_url == retrieve... | [
{
"docstring": "Takes a long URL and returns a shortened version.",
"function_declaration": "def shorten_url(long_url):",
"function_name": "shorten_url",
"parameter_list": "(long_url)"
},
{
"docstring": "Takes a short code and returns the original URL.",
"function_declaration": "def retr... | [
1,
1,
0,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import string\nimport random\n\n# In-memory storage for URL mappings\nurl_map = {}\n\ndef generate_short_code() -> str:\n \"\"\"\n Generates a unique short... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009106",
"row_id": 9106,
"seed_ids": "[2353]"
} | 0.570226 | Algorithm_9106 | I | [
"shorten_url",
"retrieve_original_url",
"generate_unique_short_code",
"validate_url"
] | 4 | [
[
"shorten_url",
"generate_unique_short_code"
],
[
"shorten_url",
"validate_url"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 87fcc9953cc3226f14cd688a67136306f3ea4372 | 4f462276a97a3f237d84930dec453198d791c158 | |||
v1.0 | instruct | Algorithm | Algorithm_9123_I | ```markdown
### Coding Assessment Question
You are given two different implementations to find the number of occurrences of a target value within a list. One implementation uses a simple iterative method, and the other uses a recursive method.
### Task
Write a Python function that performs the following steps:
1. Rea... | def iterative_count(input_list, target):
"""
Counts the occurrences of the target value using an iterative method.
"""
count = 0
for num in input_list:
if num == target:
count += 1
return count
def recursive_count(input_list, target, index=0):
"""
Counts the occurren... | from solution import find_target_count
def test_find_target_count_matching():
assert find_target_count([1, 3, 1, 7, 1, 2, 1, 6, 1, 10], 1) == "Matching Counts: 5"
assert find_target_count([4, -2, 19, -30, 0, 18, 19], 19) == "Matching Counts: 2"
assert find_target_count([1, 2, 3, 4, 5], 6) == "Matching Coun... | [
{
"docstring": "Counts the occurrences of the target value using an iterative method.",
"function_declaration": "def iterative_count(input_list, target):",
"function_name": "iterative_count",
"parameter_list": "(input_list, target)"
},
{
"docstring": "Counts the occurrences of the target val... | [
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 find_target_count(input_list, target):\n if not input_list:\n return \"Empty list provided\"\n \n def iterative_count(lst, tgt):\n ret... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000009123",
"row_id": 9123,
"seed_ids": "[3959]"
} | 0.587294 | Algorithm_9123 | I | [
"iterative_count",
"recursive_count",
"find_target_count"
] | 3 | [
[
"find_target_count",
"iterative_count"
],
[
"find_target_count",
"recursive_count"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3cbd44630ee3e11c5e35057c85c46d278b7b8e16 | 4e4bb10423871809cf6caeb7eeb3143ef068954c | |||
v1.0 | instruct | Algorithm | Algorithm_9294_I | Binary Search and Sorting Algorithms
You are required to implement two functions from scratch: one for performing insertions using binary search and another for sorting a list using an insertion sort algorithm enhanced with binary search for finding the correct position. Implement the following functions:
1. **binary... | def binary_search_insert_position(arr: list[int], val: int, start: int, end: int) -> int:
"""
Find the index to insert val in arr[start:end] using binary search.
Args:
- arr (list[int]): The list in which to search for the insertion position.
- val (int): The value to be inserted.
- start (... | from solution import binary_search_insert_position, binary_insertion_sort
def test_binary_search_insert_position():
assert binary_search_insert_position([1, 3, 5, 7], 4, 0, 3) == 2
assert binary_search_insert_position([1, 3, 5, 7], 0, 0, 3) == 0
assert binary_search_insert_position([1, 3, 5, 7], 8, 0, 3) =... | [
{
"docstring": "Find the index to insert val in arr[start:end] using binary search.\n\nArgs:\n- arr (list[int]): The list in which to search for the insertion position.\n- val (int): The value to be inserted.\n- start (int): The starting index of the search range (inclusive).\n- end (int): The ending index of t... | [
0,
0,
1,
1,
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 binary_search_insert_position(arr: list[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Find the index to insert val in arr[start:end] using b... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009294",
"row_id": 9294,
"seed_ids": "[699]"
} | 0.59092 | Algorithm_9294 | I | [
"binary_search_insert_position",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"binary_search_insert_position"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a70bf95a2a01b6e156ee9fcb8ce185bca598f532 | 702aab032727b09e940ba8c02d10462c0a8db7c1 | |||
v1.0 | instruct | Algorithm | Algorithm_9296_I | #### Coding Assessment Question
You are given a problem where you need to analyze a grid of characters and identify the length of the longest word that can be constructed by moving to adjacent (horizontally or vertically) characters. Words are formed in a "snake-like" manner, where you can revisit characters but canno... | from typing import List, Tuple, Set
def get_neighbors(x: int, y: int, grid: List[List[str]]) -> List[Tuple[int, int]]:
neighbors = []
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
rows, cols = len(grid), len(grid[0])
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < ... | from solution import get_neighbors, longest_word_from, longest_snake_word
def test_get_neighbors():
assert get_neighbors(1, 1, [['a', 'b'], ['c', 'd']]) == [(0, 1), (1, 0)]
def test_longest_word_from():
assert longest_word_from(0, 0, [['a', 'b'], ['c', 'd']], set()) == 4
assert longest_word_from(1, 1, [['... | [
{
"docstring": null,
"function_declaration": "def get_neighbors(x, y, grid):",
"function_name": "get_neighbors",
"parameter_list": "(x, y, grid)"
},
{
"docstring": null,
"function_declaration": "def longest_word_from(x, y, grid, visited):",
"function_name": "longest_word_from",
"... | [
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": "from typing import List, Tuple, Set\n\ndef get_neighbors(x: int, y: int, grid: List[List[str]]) -> List[Tuple[int, int]]:\n neighbors = []\n rows, cols = l... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000009296",
"row_id": 9296,
"seed_ids": "[2699]"
} | 0.709822 | Algorithm_9296 | I | [
"get_neighbors",
"longest_word_from",
"longest_snake_word"
] | 3 | [
[
"longest_snake_word",
"longest_word_from"
],
[
"longest_word_from",
"get_neighbors"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d1ec0118e53234668dfea36154c1ab51cb5cfa56 | 54721e7e8fd7c188a1619d30fe804440ce55e25a | |||
v1.0 | instruct | Algorithm | Algorithm_9327_I | ### Problem: Optimizing Image Processing Pipeline
#### Scenario
You have been tasked with optimizing an existing image processing pipeline. The current implementation suffers from inefficiencies due to sequential processing and redundant I/O operations. Your goal is to enhance the pipeline using batch processing and p... | import os
from PIL import Image
from concurrent.futures import ThreadPoolExecutor
def process_image(image_path):
"""
Dummy image processing function. Replace with actual processing code.
"""
# Open an image file
with Image.open(image_path) as img:
# Perform some operations (example: convert... | import os
import shutil
from PIL import Image
import pytest
from solution import optimize_image_pipeline
@pytest.fixture(scope="module")
def setup_test_images(tmpdir_factory):
"""
Setup test images and return their paths and output directory.
"""
image_dir = tmpdir_factory.mktemp("images")
output_d... | [
{
"docstring": "Dummy image processing function. Replace with actual processing code.",
"function_declaration": "def process_image(image_path):",
"function_name": "process_image",
"parameter_list": "(image_path)"
},
{
"docstring": "Save the processed image to the specified output path.",
... | [
0,
1,
0,
1,
1,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport concurrent.futures\nfrom PIL import Image\n\ndef process_image(image_path):\n \"\"\"\n Dummy image processing function that just opens an... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000009327",
"row_id": 9327,
"seed_ids": "[900]"
} | 0.518846 | Algorithm_9327 | I | [
"process_image",
"save_image",
"process_batch",
"optimize_image_pipeline"
] | 4 | [
[
"optimize_image_pipeline",
"process_batch"
],
[
"process_batch",
"process_image"
],
[
"process_batch",
"save_image"
]
] | 3 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 099ff46d10cda374275576f325cb1ff9fd2be0be | ff50ecb3a9455021409e7152edbeea47981f8d5c | |||
v1.0 | instruct | Algorithm | Algorithm_9365_I | ### Matrix Rotation Checker
#### Scenario:
You are working on a data visualization project that involves displaying a series of image transformations. One common transformation is rotation. Your task is to determine if a given matrix `B` can be obtained by rotating another matrix `A` by 90, 180, or 270 degrees.
#### ... | from typing import List
def rotate_90(A: List[List[int]]) -> List[List[int]]:
"""
Rotates the matrix A by 90 degrees clockwise.
"""
n = len(A)
return [[A[n - j - 1][i] for j in range(n)] for i in range(n)]
def is_rotation_matrix(A: List[List[int]], B: List[List[int]]) -> bool:
"""
Returns ... | from solution import is_rotation_matrix
def test_rotation_90():
A = [
[1, 2],
[3, 4]
]
B = [
[3, 1],
[4, 2]
]
assert is_rotation_matrix(A, B) == True
def test_rotation_180():
A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
B = [
[... | [
{
"docstring": "Rotates the matrix A by 90 degrees clockwise.",
"function_declaration": "def rotate_90(A):",
"function_name": "rotate_90",
"parameter_list": "(A)"
},
{
"docstring": "Returns True if matrix B is a rotation of matrix A by 90, 180, or 270 degrees.",
"function_declaration": "... | [
0,
1,
0,
0,
1,
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": "from typing import List\n\ndef rotate_90_clockwise(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates the given n x n matrix by 90 degrees clo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009365",
"row_id": 9365,
"seed_ids": "[3013]"
} | 0.549688 | Algorithm_9365 | I | [
"rotate_90",
"is_rotation_matrix"
] | 2 | [
[
"is_rotation_matrix",
"rotate_90"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 594236e1088d7a15da61e91c145e997adce4c6de | 121672c34c25a3f2494fef4dcdfe1888ed9de1ac | |||
v1.0 | instruct | Algorithm | Algorithm_9410_I | ### Problem: Matrix Operation Implementation
Your task is to implement a matrix operation system that integrates various matrix manipulation functions into a unified module. The goal is to develop functions for common matrix operations, ensuring proper input validation, and efficient computation.
#### Task Requiremen... | def mat_addition(mat1, mat2):
"""
Returns the addition of two matrices mat1 and mat2.
"""
if not mat1 or not mat2:
raise ValueError("Matrices cannot be empty")
if len(mat1) != len(mat2) or len(mat1[0]) != len(mat2[0]):
raise ValueError("Matrices must have the same dimensions")
re... | import pytest
from solution import (
mat_addition,
mat_subtraction,
mat_multiplication,
mat_transposition,
mat_determinant_2x2,
mat_determinant_3x3,
mat_inversion_2x2
)
def test_mat_addition():
assert mat_addition([[1, 2], [3, 4]], [[4, 3], [2, 1]]) == [[5, 5], [5, 5]]
def test_mat_add... | [
{
"docstring": "Returns the addition of two matrices mat1 and mat2.",
"function_declaration": "def mat_addition(mat1, mat2):",
"function_name": "mat_addition",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Returns the subtraction of two matrices mat1 and mat2.",
"function_declarati... | [
1,
0,
0,
0,
0,
1,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def mat_addition(mat1, mat2):\n if not mat1 or not mat2:\n raise ValueError(\"Matrices cannot be empty\")\n if len(mat1) != len(mat2) or len(mat1[0]... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009410",
"row_id": 9410,
"seed_ids": "[3259]"
} | 0.550138 | Algorithm_9410 | I | [
"mat_addition",
"mat_subtraction",
"mat_multiplication",
"mat_transposition",
"mat_determinant_2x2",
"mat_determinant_3x3",
"mat_inversion_2x2"
] | 7 | [
[
"mat_inversion_2x2",
"mat_determinant_2x2"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c75cdc2338ce9553ee77764a75a4ea60ca45e9f0 | 8e099f59b08ec7aec3a587d355bb44a0554585f2 | |||
v1.0 | instruct | Algorithm | Algorithm_9427_I | ### Scenario
You are working on a text analysis tool that processes a large number of text files and generates a summary report. One critical feature of the tool is to count the frequency of each word in the text files, ignoring punctuation and variations in capitalization. The text files are read from a directory, and... | import os
import string
def clean_text(text: str) -> str:
"""
Remove punctuation from the given text and convert it to lowercase.
"""
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator).lower()
def count_word_frequencies(directory: str) -> dict:
"""
Cou... | import tempfile
import os
from solution import clean_text, count_word_frequencies
def test_clean_text():
assert clean_text("Hello, World!") == "hello world"
assert clean_text("Testing, one, two, three...") == "testing one two three"
assert clean_text("No punctuation") == "no punctuation"
def test_count_wo... | [
{
"docstring": "Remove punctuation from the given text and convert it to lowercase.",
"function_declaration": "def clean_text(text):",
"function_name": "clean_text",
"parameter_list": "(text)"
},
{
"docstring": "Count the frequency of each word in all .txt files within the specified director... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport string\n\ndef clean_text(text: str) -> str:\n \"\"\"\n Removes punctuation from the text and converts it to lowercase.\n \"\"\"\n t... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009427",
"row_id": 9427,
"seed_ids": "[4281]"
} | 0.754553 | Algorithm_9427 | I | [
"clean_text",
"count_word_frequencies"
] | 2 | [
[
"count_word_frequencies",
"clean_text"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f204705976525158d6d8d1306bf1e5d3d5ebbf5 | f210c42992f4d2b468ffd810df56685128774b10 | |||
v1.0 | instruct | Algorithm | Algorithm_9615_I | ### Dijkstra's Shortest Path Algorithm Implementation
#### Objective
Implement Dijkstra's algorithm to find the shortest paths from a given source vertex to all other vertices in a weighted, directed graph.
#### Scenario
In network routing, it is crucial to determine the most efficient paths to ensure data packets ar... | import heapq
def initialize_single_source(graph, source):
"""
Initializes the distance and previous vertices for the graph.
"""
distances = {vertex: float('inf') for vertex in graph}
previous = {vertex: None for vertex in graph}
distances[source] = 0
return distances, previous
def relax(u,... | from solution import dijkstra
def test_dijkstra_with_example_graph():
graph = {
0: [(1, 4), (2, 1)],
1: [(3, 1)],
2: [(1, 2), (3, 5)],
3: []
}
source = 0
distances, paths = dijkstra(graph, source)
assert distances == {0: 0, 1: 3, 2: 1, 3: 4}
assert paths == {0: [... | [
{
"docstring": "Initializes the distance and previous vertices for the graph.",
"function_declaration": "def initialize_single_source(graph, source):",
"function_name": "initialize_single_source",
"parameter_list": "(graph, source)"
},
{
"docstring": "Relaxes the edge and updates the distanc... | [
0,
1,
1,
0,
0,
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 heapq\n\ndef initialize_single_source(graph, source):\n distances = {vertex: float('inf') for vertex in graph}\n previous = {vertex: None for vertex... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009615",
"row_id": 9615,
"seed_ids": "[3881]"
} | 0.690108 | Algorithm_9615 | I | [
"initialize_single_source",
"relax",
"extract_min",
"dijkstra"
] | 4 | [
[
"dijkstra",
"extract_min"
],
[
"dijkstra",
"initialize_single_source"
],
[
"dijkstra",
"relax"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e200f9aec8676aa1f8d755035b45d86cfdbd5db9 | ced59ecafcd0a171235b7a2af96bcd6465c904e3 | |||
v1.0 | instruct | Algorithm | Algorithm_9616_I | Given the following snippet of a program that is supposed to implement the A* search algorithm for finding the shortest path in a graph:
```python
class Node:
def __init__(self, name: str, neighbors: dict[str, int]) -> None:
self.name = name
self.neighbors = neighbors
self.g = float('inf')
... | class Node:
def __init__(self, name: str, neighbors: dict[str, int]) -> None:
self.name = name
self.neighbors = neighbors
self.g = float('inf')
self.f = float('inf')
self.came_from = None
def heuristic(node1: Node, node2: Node) -> int:
coordinates = {
"A": (0, 0)... | from solution import Node, a_star, heuristic, reconstruct_path
def test_heuristic():
nodes = {
"A": Node("A", {}),
"B": Node("B", {})
}
assert heuristic(nodes["A"], nodes["B"]) == 1 # Coordinates (0, 0) and (1, 0)
def test_a_star_simple():
nodes = {
"A": Node("A", {"B": 1}),
... | [] | [
1,
0,
1,
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": "class Node:\n def __init__(self, name: str, neighbors: dict[str, int]) -> None:\n self.name = name\n self.neighbors = neighbors\n self.g ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009616",
"row_id": 9616,
"seed_ids": "[4589]"
} | 0.453764 | Algorithm_9616 | I | [
"heuristic",
"a_star",
"reconstruct_path"
] | 3 | [
[
"a_star",
"heuristic"
],
[
"a_star",
"reconstruct_path"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 9f7a127c0936b32aec6be9884d3007d2e0d8394c | d1a854bd341fa87783b3be650c6a388392df393e | |||
v1.0 | instruct | Algorithm | Algorithm_9633_I | ### Coding Assessment Question: Implement a Decision Tree Classifier
You are required to implement a simple Decision Tree Classifier from scratch. The model should be able to train on a given dataset and predict the class of new instances. Your implementation should follow the basic principles of Decision Trees, inclu... | import math
from collections import Counter
def calculate_entropy(labels):
"""
Calculate the entropy of a dataset.
:param labels: List of labels (int)
:return: Entropy value (float)
"""
total_count = len(labels)
label_counts = Counter(labels)
entropy = 0.0
for count in lab... | from solution import calculate_entropy, calculate_information_gain, split_dataset, build_tree, predict, accuracy
def test_calculate_entropy():
assert math.isclose(calculate_entropy([1, 0, 1, 1, 0, 0]), 1.0)
assert math.isclose(calculate_entropy([1, 1, 1, 1]), 0.0)
assert math.isclose(calculate_entropy([0, ... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef calculate_entropy(labels):\n \"\"\"\n Calculate the entropy of a list of labels.\n \n Args:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009633",
"row_id": 9633,
"seed_ids": "[479]"
} | 0.541716 | Algorithm_9633 | I | [
"calculate_entropy",
"calculate_information_gain",
"split_dataset",
"build_tree",
"predict",
"accuracy"
] | 6 | [
[
"build_tree",
"calculate_entropy"
],
[
"build_tree",
"calculate_information_gain"
],
[
"build_tree",
"split_dataset"
],
[
"calculate_information_gain",
"calculate_entropy"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 6a5b476aa595ff5937f9cdba12a93fbf235122d4 | 96d027b00509366248666455887df6f10336715f | |||
v1.0 | instruct | Algorithm | Algorithm_9740_I | ### Coding Assessment Question
#### AVL Tree Insertion and Deletion
Given the code snippet for constructing an AVL Tree (a self-balancing binary search tree), your task is to implement functions to insert a new value and delete an existing value while maintaining the tree's balanced properties.
#### Function Signatu... | class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def get_height(node):
if not node:
return 0
return node.height
def update_height(node):
if node:
node.height = 1 + max(get_height(node.left), get_he... | from solution import AVLNode, insert, delete
def test_insert_simple():
root = None
values = [10, 20, 30]
for val in values:
root = insert(root, val)
assert root.key == 20
assert root.left.key == 10
assert root.right.key == 30
def test_insert_complex():
root = None
values = [10,... | [] | [
1,
1,
0,
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": "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 get_hei... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000009740",
"row_id": 9740,
"seed_ids": "[1663]"
} | 0.553958 | Algorithm_9740 | I | [
"get_height",
"update_height",
"get_balance",
"left_rotate",
"right_rotate",
"insert",
"min_value_node",
"delete"
] | 8 | [
[
"delete",
"get_balance"
],
[
"delete",
"left_rotate"
],
[
"delete",
"min_value_node"
],
[
"delete",
"right_rotate"
],
[
"delete",
"update_height"
],
[
"get_balance",
"get_height"
],
[
"insert",
"get_balance"
],
[
"insert",
... | 13 | [] | false | [
"AVLNode"
] | true | pytest | true | [] | true | c94348812dbd095a320aefe7692d80ba33cd5c40 | 76fac98adb86b93f0fe6e2ce8ca24cd554c0eae3 | |||
v1.0 | instruct | Algorithm | Algorithm_9874_I | ### Neural Network from Scratch
**Objective**: Implement a simple feedforward neural network from scratch to solve a binary classification problem.
### Background
Neural networks are a set of algorithms, modeled loosely after the human brain, that are designed to recognize patterns. They interpret sensory data throu... | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def simple_neural_network(train_data: np.ndarray, test_data: np.ndarray, hidden_units: int, learning_rate: float, epochs: int) -> np.ndarray:
np.random.seed(42) # For reproducibility
# S... | import numpy as np
from solution import simple_neural_network
def test_simple_neural_network():
train_data = np.array([
[1, 2.0, 3.0],
[0, 1.0, 1.0],
[1, 2.5, 3.5],
[0, 1.5, 1.5]
])
test_data = np.array([
[2.0, 2.5],
[1.2, 1.3]
])
hidden_units = 5
... | [
{
"docstring": null,
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def sigmoid_derivative(x):",
"function_name": "sigmoid_derivative",
"parameter_list": "(x)"
},
{
"docstring... | [
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 numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\ndef simple_neural_network(train_d... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000009874",
"row_id": 9874,
"seed_ids": "[389]"
} | 0.603234 | Algorithm_9874 | I | [
"sigmoid",
"sigmoid_derivative",
"simple_neural_network"
] | 3 | [
[
"simple_neural_network",
"sigmoid"
],
[
"simple_neural_network",
"sigmoid_derivative"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 2e8f03025ce794fd60888ddedf64c8d83921270e | e834bff49a4849baee979b614f249ebb10584ce1 | |||
v1.0 | instruct | Algorithm | Algorithm_9940_I | ### Background
The Knuth-Morris-Pratt (KMP) algorithm is an efficient string matching algorithm that finds occurrences of a pattern within a text. It preprocesses the pattern by creating a longest prefix suffix (LPS) array that helps in avoiding unnecessary comparisons during the search phase.
### Problem Statement
Wr... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Computes the Longest Prefix Suffix (LPS) array used in the KMP algorithm.
LPS array is the longest proper prefix which is also a suffix.
"""
lps = [0] * len(pattern)
length = 0 # Length of the previous longest prefix suffi... | def test_kmp_search():
from solution import kmp_search
def test_single_occurrence():
assert kmp_search("abc", "ababcabc") == [2, 5]
def test_multiple_occurrences():
assert kmp_search("a", "aaaaa") == [0, 1, 2, 3, 4]
assert kmp_search("aa", "aaaaa") == [0, 1, 2, 3]
def test_pat... | [
{
"docstring": "Computes the Longest Prefix Suffix (LPS) array used in the KMP algorithm.\nLPS array is the longest proper prefix which is also a suffix.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Im... | [
1,
1,
1,
0,
0,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Computes the Longest Prefix Suffix (LPS) array used in the KMP algorithm.... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000009940",
"row_id": 9940,
"seed_ids": "[3894]"
} | 0.601009 | Algorithm_9940 | I | [
"compute_lps",
"kmp_search"
] | 2 | [
[
"kmp_search",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3fd757d6f38f50dae34487c5e6c7825e0c428c35 | 934113ddde8b337ecd9019334f8f4ee8e4462b61 | |||
v1.0 | instruct | Algorithm | Algorithm_9945_I | ### Binary Search Tree (BST): Operations Analysis
**Scenario**: You are given a binary search tree (BST) containing integer values. Your task is to implement a set of functions to perform various operations on the BST, including insertion, deletion, search, and finding the minimum and maximum values.
**Function Speci... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:... | import pytest
from solution import TreeNode, insert_into_bst, delete_from_bst, search_bst, find_min, find_max
def create_test_bst():
root = TreeNode(10)
root = insert_into_bst(root, 5)
root = insert_into_bst(root, 15)
root = insert_into_bst(root, 3)
root = insert_into_bst(root, 7)
root = insert... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \nd... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000009945",
"row_id": 9945,
"seed_ids": "[82]"
} | 0.592389 | Algorithm_9945 | I | [
"insert_into_bst",
"delete_from_bst",
"search_bst",
"find_min",
"find_max",
"get_min"
] | 6 | [
[
"delete_from_bst",
"get_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | a5d313e134c678937afdfda51dcf100d63b3df8d | 24be929b5fc3da16c07842b079d40d846d83b243 | |||
v1.0 | instruct | Algorithm | Algorithm_9991_I | ### Sudoku Solver
#### Problem Description
You are tasked with implementing a function to solve a classic 9x9 Sudoku puzzle. The input will be a partially filled 9x9 grid, and the function should fill in the empty cells such that each row, column, and 3x3 subgrid contains all digits from 1 to 9 exactly once.
#### Imp... | def is_valid(grid, row, col, num):
"""
Check whether it's valid to place num at position (row, col) in the Sudoku grid.
"""
for i in range(9):
if grid[row][i] == num or grid[i][col] == num:
return False
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
for i in range... | from solution import is_valid, solve_sudoku, print_grid
def test_is_valid():
grid = [
[5, 3, 0, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
... | [
{
"docstring": "Check whether it's valid to place num at position (row, col) in the Sudoku grid.",
"function_declaration": "def is_valid(grid, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(grid, row, col, num)"
},
{
"docstring": "Solve the given Sudoku puzzle using backt... | [
0,
1,
0,
1,
1,
1,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_valid(grid, row, col, num):\n \"\"\"\n Check if placing the number `num` at position (row, col) is valid\n in the context of the given `grid`.\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000009991",
"row_id": 9991,
"seed_ids": "[1809]"
} | 0.682083 | Algorithm_9991 | I | [
"is_valid",
"solve_sudoku",
"print_grid"
] | 3 | [
[
"solve_sudoku",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 94f88db87c440f46b69338e27cb5754c5813bcd9 | 9ba74773c774c665f0bca50742264875e79ce378 | |||
v1.0 | instruct | Algorithm | Algorithm_10110_I | ### Robotic Navigation in a Grid
#### Problem Description
You are tasked with implementing a navigation system for a robot in a two-dimensional grid. The grid is represented by a matrix of integers where `0` represents an empty cell, and `1` represents an obstacle. The robot can start at any cell containing a `0` and ... | from typing import List, Tuple
from collections import deque
def shortest_path(grid: List[List[int]], start: Tuple[int, int], end: Tuple[int, int]) -> List[Tuple[int, int]]:
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
queue = deque([(start, [start])])
visited = ... | from solution import shortest_path, visualize_path, navigate_robot
def test_shortest_path_found():
grid = [
[0, 0, 1, 0],
[1, 0, 1, 0],
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
]
start = (0, 0)
end = (4, 3)
expected_path = [(0, 0), (0, 1), (1, 1), (2, 1), (2,... | [
{
"docstring": null,
"function_declaration": "def shortest_path(grid, start, end):",
"function_name": "shortest_path",
"parameter_list": "(grid, start, end)"
},
{
"docstring": null,
"function_declaration": "def visualize_path(grid, path):",
"function_name": "visualize_path",
"par... | [
0,
0,
1,
0,
1,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nfrom collections import deque\n\ndef shortest_path(grid: List[List[int]], start: Tuple[int, int], end: Tuple[int, int]) -> List[T... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000010110",
"row_id": 10110,
"seed_ids": "[4673]"
} | 0.687854 | Algorithm_10110 | I | [
"shortest_path",
"visualize_path",
"navigate_robot"
] | 3 | [
[
"navigate_robot",
"shortest_path"
],
[
"navigate_robot",
"visualize_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 862caf486d5ef411bde9e3bd39bbf6106af289bf | 79676e473c00746b5b542c897f74fc261fc87387 | |||
v1.0 | instruct | Algorithm | Algorithm_10113_I | ### Traveling Salesperson Problem with Genetic Algorithm
**Context**: A logistics company is trying to optimize its delivery routes to minimize travel distance and time. They have formulated this as a Traveling Salesperson Problem (TSP) and want you to use a genetic algorithm to find an optimal route visiting each del... | import random
import math
import numpy as np
class City:
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
def distance_to(self, other_city) -> float:
"""
Returns the Euclidean distance to another city.
"""
return math.sqrt((self.x -... | def test_city_distance():
city1 = City('A', 0, 0)
city2 = City('B', 3, 4)
assert city1.distance_to(city2) == 5.0
def test_create_route():
cities = [City(f'City{i}', i, i) for i in range(5)]
route = create_route(cities)
assert len(route) == 5
assert len(set(route)) == 5
def test_route_dista... | [] | [
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 random\nimport numpy as np\n\nclass City:\n def __init__(self, name, x, y):\n self.name = name\n self.x = x\n self.y = y\n\n de... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000010113",
"row_id": 10113,
"seed_ids": "[5315]"
} | 0.566049 | Algorithm_10113 | I | [
"create_route",
"initial_population",
"route_distance",
"rank_routes",
"selection",
"crossover",
"mutate",
"next_generation",
"genetic_algorithm"
] | 9 | [
[
"genetic_algorithm",
"initial_population"
],
[
"genetic_algorithm",
"next_generation"
],
[
"genetic_algorithm",
"rank_routes"
],
[
"genetic_algorithm",
"route_distance"
],
[
"initial_population",
"create_route"
],
[
"next_generation",
"crossover"... | 10 | [] | false | [
"City"
] | true | pytest | false | [
"numpy"
] | false | 1a5b69027bc1545a3fc5aeec7c52411235e676fa | 5edf82dc84609bb58d341405f9ad8c45e2bf4907 | |||
v1.0 | instruct | Algorithm | Algorithm_10117_I | ### Scramble and Sort Strings
Write a function that takes a list of words and returns a list where each word is scrambled (except for the first and last letters) and then sorted by the lengths of the original words in descending order. If two words have the same length, maintain their original order.
#### Task
Implem... | import random
from typing import List
def scramble_word(word: str) -> str:
if len(word) <= 3:
return word
middle = list(word[1:-1])
random.shuffle(middle)
return word[0] + ''.join(middle) + word[-1]
def scramble_and_sort(words: List[str]) -> List[str]:
scrambled_words = [scramble_word(word... | from solution import scramble_and_sort
import pytest
def test_scramble_and_sort_example1():
result = scramble_and_sort(["apple", "hello", "world", "a", "I", "am", "coding"])
expected_lengths = [6, 5, 5, 5, 2, 1, 1]
assert [len(word) for word in result] == expected_lengths
def test_scramble_and_sort_exampl... | [
{
"docstring": null,
"function_declaration": "def scramble_word(word):",
"function_name": "scramble_word",
"parameter_list": "(word)"
},
{
"docstring": null,
"function_declaration": "def scramble_and_sort(words):",
"function_name": "scramble_and_sort",
"parameter_list": "(words)"... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef scramble_word(word: str) -> str:\n if len(word) <= 3:\n return word\n middle = list(word[1:-1])\n r... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000010117",
"row_id": 10117,
"seed_ids": "[2089]"
} | 0.750305 | Algorithm_10117 | I | [
"scramble_word",
"scramble_and_sort"
] | 2 | [
[
"scramble_and_sort",
"scramble_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 191b5d9a8bc7e4bce8997daed9144522841ea3b3 | 14055fd5e27febf8cfb1d6be17c6f921478bf421 | |||
v1.0 | instruct | Algorithm | Algorithm_10121_I | ### Context
Sorting algorithms are fundamental in computer science and are used to arrange elements in a particular order. One of the more advanced and efficient sorting algorithms is Merge Sort, which uses a divide-and-conquer approach to recursively divide the array into two halves, sort each half, and then merge 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_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert merg... | [
{
"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,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Perform merge sort on the given list and return the sorted list.\n \"... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010121",
"row_id": 10121,
"seed_ids": "[4255]"
} | 0.680425 | Algorithm_10121 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 138fc099419d463411e69fb155cefc88d48803d7 | 5ab903200915641e0de6f6f632d6c25dd523ab36 | |||
v1.0 | instruct | Algorithm | Algorithm_10203_I | ### Task
Implement an algorithm to check if a given binary tree is symmetric. A binary tree is symmetric if it is a mirror of itself.
### Objective
Given a binary tree, write a function `is_symmetric` that returns `True` if the tree is symmetric, and `False` otherwise.
### Input
- A binary tree represented by its ro... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_mirror(t1, t2):
if t1 is None and t2 is None:
return True
if t1 is None or t2 is None:
return False
return (t1.val == t2.val
... | from solution import TreeNode, is_symmetric
def test_is_symmetric_example1():
# Example 1: symmetric tree
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = Tree... | [] | [
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": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_sy... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010203",
"row_id": 10203,
"seed_ids": "[5113]"
} | 0.66708 | Algorithm_10203 | I | [
"is_mirror",
"is_symmetric"
] | 2 | [
[
"is_symmetric",
"is_mirror"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 27df1f79788b14e187d166c0a3af8307a1bd21e3 | 6ccd98bfca0c2f4ad9fdfa1c13922045aa919008 | |||
v1.0 | instruct | Algorithm | Algorithm_10216_I | ### Problem Statement
You are provided with a utility function that checks whether a given string is a palindrome. A string is considered a palindrome if it reads the same backward as forward (ignoring spaces, punctuation, and case).
Your task is to implement a new function `find_longest_palindrome` that takes a list... | import re
def is_palindrome(s: str) -> bool:
"""
Check if the input string is a palindrome, considering only
alphabetical characters and ignoring spaces, punctuation, and case.
"""
s = re.sub(r'[^a-zA-Z]', '', s).lower()
return s == s[::-1]
def find_longest_palindrome(strings: list) -> str:
... | from solution import find_longest_palindrome
def test_single_palindrome():
assert find_longest_palindrome(["racecar"]) == "racecar"
def test_multiple_palindromes():
assert find_longest_palindrome(["racecar", "Madam", "noon"]) == "racecar"
def test_mixed_case():
assert find_longest_palindrome(["Aba", "aBb... | [
{
"docstring": "Check if the input string is a palindrome, considering only\nalphabetical characters and ignoring spaces, punctuation, and case.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Finds the longest p... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_palindrome(s: str) -> bool:\n \"\"\"\n Checks if the given string s is a palindrome.\n A string is considered a palindrome if it rea... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000010216",
"row_id": 10216,
"seed_ids": "[4118]"
} | 0.800295 | Algorithm_10216 | I | [
"is_palindrome",
"find_longest_palindrome"
] | 2 | [
[
"find_longest_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9128c13b5b0c89910d8ffe10f513417e8223b41c | 89ede85733bf7af2bf12376834477fda6cd8798a | |||
v1.0 | instruct | Algorithm | Algorithm_10290_I | ### Coding Assessment: K-Nearest Neighbors (KNN) Algorithm Implementation
**Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. Use the provided structure and existing utility functions to create new components, demonstrating your understanding of the KNN approach.
### Probl... | from collections import Counter
import math
def compute_euclidean_distance(point1, point2):
"""
Returns the Euclidean distance between two points.
Parameters:
point1 (list of float): The first point.
point2 (list of float): The second point.
Returns:
float: The Euclidean distance ... | def test_compute_euclidean_distance():
assert math.isclose(compute_euclidean_distance([1.0, 2.0], [5.0, 8.0]), 7.211102550927978)
assert math.isclose(compute_euclidean_distance([0, 0], [0, 0]), 0.0)
assert math.isclose(compute_euclidean_distance([1, 1], [4, 5]), 5.0)
def test_determine_k_nearest_neighb... | [] | [
0,
1,
1,
1,
0,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\nfrom typing import List\n\ndef compute_euclidean_distance(point1: List[float], point2: List[float]) -> float:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000010290",
"row_id": 10290,
"seed_ids": "[468]"
} | 0.589986 | Algorithm_10290 | I | [
"compute_euclidean_distance",
"determine_k_nearest_neighbors",
"predict_class"
] | 3 | [
[
"determine_k_nearest_neighbors",
"compute_euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6ed2431bbd176d364ce7d7325c51a2a72df432c5 | 0666bd4cc905e8da263261a82dbcfc46adba0ce1 | |||
v1.0 | instruct | Algorithm | Algorithm_10291_I | ### Binary Search Tree (BST) Delete Operation
Implement a function to delete a specified value from a Binary Search Tree (BST). The BST is given with its root node, and the function should maintain the BST properties after deletion. The function should return the root node of the updated BST.
#### Function Signature
... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_minimum(node):
"""
Function to find the node with the minimum value in a BST.
"""
current = node
while current.left is not None:
current ... | import pytest
def test_tree_structure_1():
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(6)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
root.right.right = TreeNode(7)
new_root = delete_node(root, 3)
assert new_root.val == 5
assert new_root... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef delet... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000010291",
"row_id": 10291,
"seed_ids": "[1526]"
} | 0.594944 | Algorithm_10291 | I | [
"find_minimum",
"delete_node"
] | 2 | [
[
"delete_node",
"find_minimum"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | e68fcc1a435e57a486c6e6b58903cf073d05b1a9 | 0190e189305de81d8075fd25e804be43c7e06326 | |||
v1.0 | instruct | Algorithm | Algorithm_10346_I | ## Context
You are tasked with developing a recommendation system for an online bookstore. The system needs to suggest books to users based on their past reading history and ratings. A well-regarded approach to building such systems is using Collaborative Filtering, where predictions are made based on the preferences o... | from collections import defaultdict
import math
def pearson_correlation(user_ratings, user1, user2, min_ratings):
common_ratings = [book for book in user_ratings[user1] if book in user_ratings[user2]]
if len(common_ratings) < min_ratings:
return 0
ratings1 = [user_ratings[user1][book] for... | from solution import recommend_books
def test_recommend_books_no_common():
user_ratings = {
1: {101: 5.0},
2: {102: 4.0}
}
assert recommend_books(user_ratings, 1, 1, 1) == []
def test_recommend_books_single_user():
user_ratings = {
1: {101: 4.0, 102: 5.0}
}
assert recom... | [
{
"docstring": null,
"function_declaration": "def pearson_correlation(user_ratings, user1, user2, min_ratings):",
"function_name": "pearson_correlation",
"parameter_list": "(user_ratings, user1, user2, min_ratings)"
},
{
"docstring": null,
"function_declaration": "def recommend_books(use... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Dict, List\nimport numpy as np\nfrom collections import defaultdict\n\ndef pearson_correlation(user_ratings1: Dict[int, float], user_ratings2:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000010346",
"row_id": 10346,
"seed_ids": "[4756]"
} | 0.621901 | Algorithm_10346 | I | [
"pearson_correlation",
"recommend_books"
] | 2 | [
[
"recommend_books",
"pearson_correlation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 986d1f5773f253d64711ccd53a6228fc78705700 | 1fb2e55ea427a05751792d8ea8d3f2a37f3a92ee | |||
v1.0 | instruct | Algorithm | Algorithm_10349_I | ### Finding the Lowest Common Ancestor in a Binary Search Tree
**Objective**: Write a Python function to find the lowest common ancestor (LCA) of two given nodes in a Binary Search Tree (BST).
**Function Signature**:
```python
def lowest_common_ancestor(root: Node | None, node1: int, node2: int) -> int | None:
```
#... | from dataclasses import dataclass
from typing import Optional
@dataclass
class Node:
key: int
left: Optional['Node'] = None
right: Optional['Node'] = None
def find_node(root: Optional[Node], val: int) -> bool:
if root is None:
return False
if root.key == val:
return True
elif v... | import pytest
from solution import Node, lowest_common_ancestor
def test_example_scenario_1():
root = Node(10,
Node(5,
Node(3),
Node(7)),
Node(20,
Node(15),
Node(25)))
assert lowest_common_... | [] | [
0,
1,
1,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "@dataclass\nclass Node:\n key: int\n left: \"Node | None\" = None\n right: \"Node | None\" = None\n\ndef lowest_common_ancestor(root: Node | None, node1... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000010349",
"row_id": 10349,
"seed_ids": "[1550]"
} | 0.568896 | Algorithm_10349 | I | [
"find_node",
"lowest_common_ancestor"
] | 2 | [
[
"lowest_common_ancestor",
"find_node"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | dd2442fc980f92d8874de009c60a37605078ea27 | 0e2af2a07c604210e63de4282399f8263ebc4a9f | |||
v1.0 | instruct | Algorithm | Algorithm_10389_I | ### Coding Assessment Question
**Problem Context:**
You are developing a program to help a logistics company optimize their delivery routes. Given a set of delivery points, the objective is to determine the shortest route that visits each point exactly once and returns to the starting point. This problem evaluates yo... | from typing import List, Tuple
import math
def distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def shortest_delivery_route(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if len(points) <= 1:
re... | from solution import shortest_delivery_route
def test_shortest_delivery_route_case1():
assert shortest_delivery_route([(0, 0), (1, 1), (2, 2)]) == [(0, 0), (1, 1), (2, 2), (0, 0)]
def test_shortest_delivery_route_case2():
assert shortest_delivery_route([(2, 3), (5, 4), (1, 1)]) == [(2, 3), (1, 1), (5, 4), (2,... | [
{
"docstring": null,
"function_declaration": "def distance(point1, point2):",
"function_name": "distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def shortest_delivery_route(points):",
"function_name": "shortest_delivery_route",
"par... | [
1,
1,
1,
1,
0,
1,
0,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\"\"\n Returns the Eu... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000010389",
"row_id": 10389,
"seed_ids": "[2777]"
} | 0.627047 | Algorithm_10389 | I | [
"distance",
"shortest_delivery_route"
] | 2 | [
[
"shortest_delivery_route",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 143e96451eb9e00335e91403b2c1b4d5e279e7b6 | 907a92b3e051911aa5a84daed0a583ab8f7e8991 | |||
v1.0 | instruct | Algorithm | Algorithm_10461_I | ### Coding Question: Palindrome Product Detection
#### Objective
Write a function that finds the largest palindrome made from the product of two 3-digit numbers.
#### Function Signature
```python
def largest_palindrome_product() -> int:
"""
Return the largest palindrome made from the product of two 3-digit nu... | def is_palindrome(number: int) -> bool:
"""
Check if a given integer is a palindrome.
"""
return str(number) == str(number)[::-1]
def largest_palindrome_product() -> int:
"""
Return the largest palindrome made from the product of two 3-digit numbers.
"""
max_palindrome = 0
for i in ... | from solution import is_palindrome, largest_palindrome_product
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(111) == True
assert is_palindrome(1221) == True
assert is_palindrome(12321) == True
assert is_palindrome(12345) == F... | [
{
"docstring": "Check if a given integer is a palindrome.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Return the largest palindrome made from the product of two 3-digit numbers.",
"function_decl... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(number: int) -> bool:\n \"\"\"\n Check if a given integer is a palindrome.\n \"\"\"\n return str(number) == str(number)[::-1]\n\nde... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000010461",
"row_id": 10461,
"seed_ids": "[5168]"
} | 0.690236 | Algorithm_10461 | I | [
"is_palindrome",
"largest_palindrome_product"
] | 2 | [
[
"largest_palindrome_product",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 73cd76ebf7c0e2506378da02e8d818f430331b86 | 1e7efafb8b8786e756c79d67af63f04f83b9463c | |||
v1.0 | instruct | Algorithm | Algorithm_10480_I | ### Prime Sum Decomposition
Given a positive integer \( n \), return an array of the smallest prime numbers that sum up to \( n \). The solution should include the minimum number of prime numbers.
### Function Signature
```python
def prime_sum_decomposition(n: int) -> List[int]:
"""
Returns an array of the sm... | from typing import List
def is_prime(num: int) -> bool:
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
retur... | from solution import prime_sum_decomposition
def test_prime_sum_decomposition_10():
assert prime_sum_decomposition(10) == [2, 2, 2, 2, 2] or prime_sum_decomposition(10) == [5, 5]
def test_prime_sum_decomposition_11():
assert prime_sum_decomposition(11) == [11]
def test_prime_sum_decomposition_28():
asser... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def prime_sum_decomposition(n):",
"function_name": "prime_sum_decomposition",
"parameter_list": "(n)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef prime_sum_decomposition(n: int) -> List[int]:\n \"\"\"\n Returns an array of the smallest prime numbers that sum up to n wit... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000010480",
"row_id": 10480,
"seed_ids": "[2070]"
} | 0.642458 | Algorithm_10480 | I | [
"is_prime",
"prime_sum_decomposition"
] | 2 | [
[
"prime_sum_decomposition",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e549c19378956e37280539a8cb2136ebf80646f4 | f9d26ffaf0f3c8a76351c3f2502f7c5269a8f8ae | |||
v1.0 | instruct | Algorithm | Algorithm_10577_I | ### Coding Assessment Question
#### Context
In competitive programming, efficient sorting algorithms are paramount for optimizing performance, especially when dealing with large datasets. One such algorithm is the merge sort, a divide-and-conquer algorithm notable for its efficient handling of large arrays by breaking... | 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_with_positive_numbers():
assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_merge_sort_with_mixed_numbers():
assert merge_sort([3, 0, -1, 8, 7]) == [-1, 0, 3, 7, 8]
def test_merge_sort_with_single_element():
assert merge_sort([1]) == [... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
0,
0,
0,
0,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000010577",
"row_id": 10577,
"seed_ids": "[3886]"
} | 0.645172 | Algorithm_10577 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40b48759ef41ec16eaad375720df1f6ad17f0b08 | 5622e3487630f8019188ec59e8988a0f386c0efe | |||
v1.0 | instruct | Algorithm | Algorithm_10672_I | ### Coding Assessment Question
#### Context
You are working on a calendar application that needs to calculate the number of days between two given dates. The application should handle different months and leap years correctly.
#### Task
Implement a function `days_between_dates(date1: str, date2: str) -> int` that cal... | def is_leap_year(year):
"""
Determine if the given year is a leap year.
Args:
year (int): The year to check.
Returns:
bool: True if the year is a leap year, False otherwise.
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
... | from solution import days_between_dates
def test_days_between_dates_same_date():
assert days_between_dates("2000-01-01", "2000-01-01") == 0
def test_days_between_dates_start_year():
assert days_between_dates("2000-01-01", "2000-01-31") == 30
def test_days_between_dates_leap_year():
assert days_between_da... | [
{
"docstring": "Determine if the given year is a leap year.\n\nArgs:\nyear (int): The year to check.\n\nReturns:\nbool: True if the year is a leap year, False otherwise.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"doc... | [
0,
0,
1,
1,
0,
1,
0,
0,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_leap_year(year):\n if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):\n return True\n return False\n\ndef days_in_month(year, month... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000010672",
"row_id": 10672,
"seed_ids": "[3877]"
} | 0.715526 | Algorithm_10672 | I | [
"is_leap_year",
"days_in_month",
"date_to_ordinal",
"days_between_dates"
] | 4 | [
[
"date_to_ordinal",
"days_in_month"
],
[
"date_to_ordinal",
"is_leap_year"
],
[
"days_between_dates",
"date_to_ordinal"
],
[
"days_in_month",
"is_leap_year"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c1665042f251786e9d05b8157276cd35cf3d7e39 | 4548eaca43b67d25d87112f960fb14c68da101c7 | |||
v1.0 | instruct | Algorithm | Algorithm_10713_I | ### Maximum Subarray Sum with Divide and Conquer
**Problem Statement**:
Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Implement this using the divide and conquer approach to achieve O(n log n) time complexity.
Write a functi... | from typing import List
def max_crossing_sum(nums: List[int], left: int, mid: int, right: int) -> int:
left_sum = float('-inf')
total = 0
for i in range(mid, left - 1, -1):
total += nums[i]
if total > left_sum:
left_sum = total
right_sum = float('-inf')
total = 0
... | from solution import max_subarray_sum
def test_example_cases():
assert max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) == 6
assert max_subarray_sum([1]) == 1
assert max_subarray_sum([5,4,-1,7,8]) == 23
assert max_subarray_sum([-1,-2,-3,-4,-5]) == -1
assert max_subarray_sum([4,-1,2,1]) == 6
assert max... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(nums, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(nums, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_sum_util(nums, left, right):",
"function_n... | [
1,
0,
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\n\ndef max_subarray_sum(nums: List[int]) -> int:\n def find_max_crossing_sum(arr, left, mid, right):\n left_sum = float('-inf')... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010713",
"row_id": 10713,
"seed_ids": "[3252]"
} | 0.768815 | Algorithm_10713 | I | [
"max_crossing_sum",
"max_subarray_sum_util",
"max_subarray_sum"
] | 3 | [
[
"max_subarray_sum",
"max_subarray_sum_util"
],
[
"max_subarray_sum_util",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0fd2712aba29ceba033214bae5d7acfaee908496 | 8d4cf442a2702f2532a81bc26e3c254014dd6a01 | |||
v1.0 | instruct | Algorithm | Algorithm_10715_I | ### Coding Question: Sentence Reversal and Word Count Analysis
#### Objective:
You are given a function that reverses words in a sentence and another function that counts the words. Your task is to enhance these functions and write a new function that works with both to solve a given problem.
#### Problem Statement:
... | def reverse_words(sentence: str) -> str:
"""
Reverses the words in a sentence.
"""
return ' '.join(sentence.split()[::-1])
def count_words(sentence: str) -> int:
"""
Counts the words in a sentence.
"""
return len(sentence.split())
def analyze_sentence(sentence: str) -> tuple:
"""
... | from solution import reverse_words, count_words, analyze_sentence
def test_reverse_words():
assert reverse_words("hello world") == "world hello"
assert reverse_words("The quick brown fox") == "fox brown quick The"
assert reverse_words("single") == "single"
assert reverse_words("a b c d") == "d c b a"
... | [
{
"docstring": "Reverses the words in a sentence.",
"function_declaration": "def reverse_words(sentence):",
"function_name": "reverse_words",
"parameter_list": "(sentence)"
},
{
"docstring": "Counts the words in a sentence.",
"function_declaration": "def count_words(sentence):",
"fun... | [
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 reverse_words(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a sentence.\n \"\"\"\n return ' '.join(sentence.split()[::-1])\n\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010715",
"row_id": 10715,
"seed_ids": "[4064]"
} | 0.697646 | Algorithm_10715 | I | [
"reverse_words",
"count_words",
"analyze_sentence"
] | 3 | [
[
"analyze_sentence",
"count_words"
],
[
"analyze_sentence",
"reverse_words"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7747f22f2feb3928331c416c00369ecf0e76ce60 | 11fcabe3e418d826ddc5a80bbe33564f5adced42 | |||
v1.0 | instruct | Algorithm | Algorithm_10717_I | ## Question
Your task is to implement a function that generates the first `n` prime numbers in the Fibonacci sequence and calculates their sum. Specifically, you will:
1. Generate Fibonacci numbers until you have `n` prime numbers.
2. Return the sum of the first `n` prime Fibonacci numbers.
### Function Signature
```... | def is_prime(num):
"""Check if a number is prime."""
if num <= 1:
return False
if num == 2:
return True # 2 is the only even prime number
if num % 2 == 0:
return False # other even numbers are not primes
for i in range(3, int(num ** 0.5) + 1, 2):
if num % i == 0:
... | def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
assert is_prime(13) == True
assert is_prime(17) == True
assert is... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generate Fibonacci numbers indefinitely.",
"function_declaration": "def generate_fibonacci():",
"function_name": "gene... | [
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 is_prime(num):\n \"\"\"\n Determine if a number is prime.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000010717",
"row_id": 10717,
"seed_ids": "[4818]"
} | 0.806192 | Algorithm_10717 | I | [
"is_prime",
"generate_fibonacci",
"sum_of_prime_fibonacci_numbers"
] | 3 | [
[
"sum_of_prime_fibonacci_numbers",
"generate_fibonacci"
],
[
"sum_of_prime_fibonacci_numbers",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 1eba51b3eb290aaa0d8fde71c28a725aa8ae983b | 13d3ba6e21d2b2787c498cbae3ce403139e0246b | |||
v1.0 | instruct | Algorithm | Algorithm_10750_I | **Context**:
Suppose there is a problem involving the computation of prime factors and determining the smallest integer greater than or equal to a given number that has exactly a specified number of distinct prime factors. This problem requires handling number theory and optimization techniques to efficiently find the ... | import math
def prime_factors_count(x: int) -> int:
"""
Returns the count of distinct prime factors of x.
"""
count = 0
if x % 2 == 0:
count += 1
while x % 2 == 0:
x //= 2
for i in range(3, int(math.sqrt(x)) + 1, 2):
if x % i == 0:
count += 1
... | def test_prime_factors_count():
assert prime_factors_count(10) == 2
assert prime_factors_count(30) == 3
assert prime_factors_count(7) == 1
assert prime_factors_count(60) == 3
assert prime_factors_count(11) == 1
def test_find_number_with_k_prime_factors():
assert find_number_with_k_prime_factors... | [
{
"docstring": "Returns the count of distinct prime factors of x.",
"function_declaration": "def prime_factors_count(x):",
"function_name": "prime_factors_count",
"parameter_list": "(x)"
},
{
"docstring": "Finds the smallest integer greater than or equal to n\nthat has exactly k distinct pri... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def prime_factors_count(x: int) -> int:\n \"\"\"\n Returns the count of distinct prime factors of x.\n \"\"\"\n def is_prime(num):\n if num <=... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010750",
"row_id": 10750,
"seed_ids": "[2670]"
} | 0.663318 | Algorithm_10750 | I | [
"prime_factors_count",
"find_number_with_k_prime_factors"
] | 2 | [
[
"find_number_with_k_prime_factors",
"prime_factors_count"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | e2b67794a46b67e5578638a631125b601deec3e5 | c9211f9e5c83e07c3a6124e8a833741131a33244 | |||
v1.0 | instruct | Algorithm | Algorithm_10764_I | ### Checking for Symmetry in a Binary Tree
**Objective**: Write a Python function to check if a given binary tree is symmetric.
**Function Signature**:
```python
def is_symmetric(root: Node | None) -> bool:
```
#### Input:
1. **`root`** (Node | None): The root node of the binary tree.
#### Output:
A single boolean ... | from dataclasses import dataclass
from typing import Optional
@dataclass
class Node:
key: int
left: Optional['Node'] = None
right: Optional['Node'] = None
def is_mirror(left: Optional[Node], right: Optional[Node]) -> bool:
if left is None and right is None:
return True
if left is None or r... | import pytest
from solution import Node, is_symmetric
def test_symmetric_tree():
root = Node(1, Node(2, Node(3), Node(4)), Node(2, Node(4), Node(3)))
assert is_symmetric(root) == True
def test_asymmetric_tree():
root = Node(1, Node(2, None, Node(3)), Node(2, None, Node(3)))
assert is_symmetric(root) ... | [] | [
0,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from dataclasses import dataclass\n\n@dataclass\nclass Node:\n key: int\n left: 'Node' | None = None\n right: 'Node' | None = None\n\ndef is_symmetric(r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010764",
"row_id": 10764,
"seed_ids": "[1550]"
} | 0.702711 | Algorithm_10764 | I | [
"is_mirror",
"is_symmetric"
] | 2 | [
[
"is_symmetric",
"is_mirror"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | e263ca7326a2f8b1df1a20f1181962a74d9a7629 | b77836ef0b15e8b1d399bb90d0a874a9887b6e9d | |||
v1.0 | instruct | Algorithm | Algorithm_10774_I | ### Sum of Internal Nodes in BST
You are assigned the task of developing a new module for a tree management system that performs various calculations on a Binary Search Tree (BST). One of the tasks is to compute the sum of all internal nodes within the tree.
### Task:
Write a function `sum_internal_nodes(root: TreeNo... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_internal_node(node):
"""
Check if a given node is an internal node.
"""
return node.left is not None or node.right is not None
def sum_internal_nodes(... | from solution import TreeNode, sum_internal_nodes
def test_single_node():
root = TreeNode(10)
assert sum_internal_nodes(root) == 0
def test_two_levels():
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
assert sum_internal_nodes(root) == 10
def test_unbalanced_tree():
... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"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 sum_i... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010774",
"row_id": 10774,
"seed_ids": "[3779]"
} | 0.603106 | Algorithm_10774 | I | [
"is_internal_node",
"sum_internal_nodes"
] | 2 | [
[
"sum_internal_nodes",
"is_internal_node"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 49b03e97452a7787b65a91cd66ff837c5e066d30 | 4c035ac669988ba274f50282aa89400511dfd00f | |||
v1.0 | instruct | Algorithm | Algorithm_10797_I | ### Coding Question: Implement a Dynamic Config Validator
In modern software development, applications frequently rely on configuration files to manage their settings, support different environments, and enhance flexibility. As a developer, you need to implement a dynamic validation script to ensure that any new confi... | import requests
import json
import os
# Predefined schema for validation
SCHEMA = {
"database": {"required": True, "type": dict},
"logging": {"required": True, "type": dict},
"debug": {"required": False, "type": bool}
}
def fetch_changed_files(repo: str, pull_number: int, token: str) -> list:
url = f"... | import pytest
from unittest.mock import patch, MagicMock
from solution import validate_config_files, fetch_changed_files, load_file_content, validate_json_schema
def mock_requests_get(*args, **kwargs):
if "pulls" in args[0]:
return MagicMock(status_code=200, json=lambda: [
{"filename": "config... | [
{
"docstring": null,
"function_declaration": "def fetch_changed_files(repo, pull_number, token):",
"function_name": "fetch_changed_files",
"parameter_list": "(repo, pull_number, token)"
},
{
"docstring": null,
"function_declaration": "def load_file_content(repo, file_path, token):",
... | [
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": "import requests\nimport json\nimport os\n\n# Predefined schema for validation\nSCHEMA = {\n \"database\": {\"required\": True, \"type\": dict},\n \"logging... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000010797",
"row_id": 10797,
"seed_ids": "[3967]"
} | 0.665667 | Algorithm_10797 | I | [
"fetch_changed_files",
"load_file_content",
"validate_json_schema",
"validate_config_files"
] | 4 | [
[
"validate_config_files",
"fetch_changed_files"
],
[
"validate_config_files",
"load_file_content"
],
[
"validate_config_files",
"validate_json_schema"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | fac2907d0ef7158396e338c8f82c83e1cb091143 | c03213854edc5ea5c02e72f6b6c35cc3d32a28c5 | |||
v1.0 | instruct | Algorithm | Algorithm_10812_I | ### Frequency Counter and Maximum Occurrence
#### Context:
Analyzing the frequency of elements in a dataset is a common task in data analysis and programming, serving as the basis for various applications like mode finding, trend analysis, and more.
#### Problem:
1. **Frequency Counter**:
- Write a function `coun... | def count_frequencies(data):
"""
Given a list of integers, returns a dictionary with elements as keys and their frequencies as values.
"""
frequency_dict = {}
for element in data:
if element in frequency_dict:
frequency_dict[element] += 1
else:
frequency_dict[... | def test_count_frequencies_empty_list():
assert count_frequencies([]) == {}
def test_count_frequencies_single_element():
assert count_frequencies([5]) == {5: 1}
def test_count_frequencies_multiple_elements():
assert count_frequencies([1, 2, 2, 3, 3, 3, 4, 4]) == {1: 1, 2: 2, 3: 3, 4: 2}
assert count_f... | [
{
"docstring": "Given a list of integers, returns a dictionary with elements as keys and their frequencies as values.",
"function_declaration": "def count_frequencies(data):",
"function_name": "count_frequencies",
"parameter_list": "(data)"
},
{
"docstring": "Given a list of integers, return... | [
1,
1,
1,
1,
1,
0,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def count_frequencies(data):\n \"\"\"\n Returns a dictionary with the elements of the list as keys and their frequencies as values.\n \"\"\"\n freque... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000010812",
"row_id": 10812,
"seed_ids": "[4095]"
} | 0.736954 | Algorithm_10812 | I | [
"count_frequencies",
"find_max_occurrence"
] | 2 | [
[
"find_max_occurrence",
"count_frequencies"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | af4959ca08865bfb9d6c0dc61d4db40731712225 | 5227205827dbe1b2704261db7f9d2fb94c7662c3 | |||
v1.0 | instruct | Algorithm | Algorithm_10904_I | ### Given Problem
You are required to implement a function to convert a given number of seconds into a formatted string representing the equivalent duration in a combination of days, hours, minutes, and seconds.
### Requirements
1. **Function Name**: `format_duration`
2. **Arguments**:
- `seconds` (int): The tota... | def pluralize(value, unit):
return f"{value} {unit}" if value == 1 else f"{value} {unit}s"
def format_duration(seconds: int) -> str:
if seconds < 0:
raise ValueError("Seconds must be non-negative")
if seconds == 0:
return "0 seconds"
days, seconds = divmod(seconds, 86400)
... | from solution import format_duration
def test_format_duration_zero_seconds():
assert format_duration(0) == "0 seconds"
def test_format_duration_one_second():
assert format_duration(1) == "1 second"
def test_format_duration_seconds_only():
assert format_duration(59) == "59 seconds"
def test_format_durati... | [
{
"docstring": null,
"function_declaration": "def pluralize(value, unit):",
"function_name": "pluralize",
"parameter_list": "(value, unit)"
},
{
"docstring": null,
"function_declaration": "def format_duration(seconds):",
"function_name": "format_duration",
"parameter_list": "(sec... | [
0,
0,
1,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def format_duration(seconds):\n if seconds < 0:\n raise ValueError(\"Seconds cannot be negative.\")\n \n periods = [\n ('day', 86400),... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000010904",
"row_id": 10904,
"seed_ids": "[546]"
} | 0.567748 | Algorithm_10904 | I | [
"pluralize",
"format_duration"
] | 2 | [
[
"format_duration",
"pluralize"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8094af45b901344b832d301c02828adfc7a1164a | 8d2cdae4aaea195460fa7d86764a9cfd4b8e0139 | |||
v1.0 | instruct | Algorithm | Algorithm_10924_I | ### Coding Assessment Question
As a software developer, you are assigned the task of extending an e-commerce platform's payment gateway integration to support multiple payment providers. Your goal is to create a more flexible and fault-tolerant system that can handle payment processing through different providers whil... | import requests
class PaymentProvider:
def __init__(self, name, api_url, api_key):
self.name = name
self.api_url = api_url
self.api_key = api_key
def execute_payment(self, payment_details):
try:
response = requests.post(self.api_url, json=payment_details, headers={'... | from solution import process_payment, validate_payment_details
def test_validate_payment_details():
valid_details = {
'card_number': '1234567812345678',
'expiry_date': '12/23',
'cvv': '123',
'amount': 100.0,
'currency': 'USD'
}
invalid_details_empty_field = {
... | [] | [
0,
0,
1,
0,
0,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\nclass PaymentError(Exception):\n pass\n\ndef validate_payment_details(payment_details):\n \"\"\"\n Validate payment details such as car... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000010924",
"row_id": 10924,
"seed_ids": "[2421]"
} | 0.421237 | Algorithm_10924 | I | [
"validate_payment_details",
"process_payment"
] | 2 | [
[
"process_payment",
"validate_payment_details"
]
] | 1 | [] | false | [
"PaymentProvider"
] | true | pytest | true | [
"requests"
] | false | 03db196346cf04ab17472238185f3baf168f8f58 | baa3336e05e90d61a7a644727273fa2970bfbba8 | |||
v1.0 | instruct | Algorithm | Algorithm_10985_I | ### Environmental Data Analyzer
You are provided with a code snippet for retrieving and analyzing environmental data such as temperature, humidity, and air quality from a JSON API. The task is to enhance this code to handle potential issues and to extend its functionality to support retrieving data for a specific city... | import requests
def get_location_coordinates(city: str) -> dict:
"""
Get the latitude and longitude for the given city using a geolocation API.
Replace this with the actual implementation or mock it during tests.
"""
# Here, we use a placeholder implementation.
# In a real scenario, we would ca... | import pytest
from unittest.mock import patch
from solution import city_environment_data, get_location_coordinates
def mock_get_location_coordinates(city):
mock_data = {
"Berlin": {"latitude": 52.52, "longitude": 13.405},
"New York": {"latitude": 40.7128, "longitude": -74.0060},
"London": {... | [
{
"docstring": "Get the latitude and longitude for the given city using a geolocation API.\nReplace this with the actual implementation or mock it during tests.",
"function_declaration": "def get_location_coordinates(city):",
"function_name": "get_location_coordinates",
"parameter_list": "(city)"
... | [
0,
0,
1,
1,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\n\ndef city_environment_data(api_url: str, city: str) -> dict:\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000010985",
"row_id": 10985,
"seed_ids": "[2420]"
} | 0.612581 | Algorithm_10985 | I | [
"get_location_coordinates",
"city_environment_data"
] | 2 | [
[
"city_environment_data",
"get_location_coordinates"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 6e036b5c7f8a1788c2067410d232b05b542f316e | 0b83f485fe24c9d643b6caac592a48821784500b | |||
v1.0 | instruct | Algorithm | Algorithm_11007_I | ### Question: Implement a Flexible Number Series Generator
#### Context
Generating sequences of numbers is a common task in computer science, particularly in areas like cryptography, algorithms, and numerical analysis. The provided task will test your ability to create a customizable number series based on given param... | from typing import List
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def flex... | from solution import flexible_series
import pytest
def test_flexible_series_prime():
assert flexible_series(1, 10, "prime") == [2, 3, 5, 7]
def test_flexible_series_even():
assert flexible_series(1, 10, "even") == [2, 4, 6, 8, 10]
def test_flexible_series_odd():
assert flexible_series(1, 10, "odd") == [1... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def flexible_series(start, end, rule):",
"function_name": "flexible_series",
"parameter_list": "(start, end, rule... | [
1,
0,
1,
0,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011007",
"row_id": 11007,
"seed_ids": "[475]"
} | 0.589674 | Algorithm_11007 | I | [
"is_prime",
"flexible_series"
] | 2 | [
[
"flexible_series",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99c124091ec1601639f6eb22bec75e18c70cf936 | 9c5ed1eef2af32b02510d236d3925fac852b43a0 | |||
v1.0 | instruct | Algorithm | Algorithm_11087_I | ### Mini Markdown Compiler
You are asked to implement a simplified Markdown to HTML converter for a limited set of Markdown features. Given a string containing Markdown text, your task is to convert it to its HTML equivalent. The Markdown text will include the following features:
1. **Headers**:
- `#` for H1, `##`... | import re
def convert_headers(line: str) -> str:
"""
Converts Markdown headers to HTML headers.
"""
if line.startswith('### '):
return f'<h3>{line[4:].strip()}</h3>'
elif line.startswith('## '):
return f'<h2>{line[3:].strip()}</h2>'
elif line.startswith('# '):
return f'<... | import pytest
from solution import convert_headers, convert_bold_italic, markdown_to_html
def test_convert_headers():
assert convert_headers('# Header1') == '<h1>Header1</h1>'
assert convert_headers('## Header2') == '<h2>Header2</h2>'
assert convert_headers('### Header3') == '<h3>Header3</h3>'
assert c... | [
{
"docstring": "Converts Markdown headers to HTML headers.",
"function_declaration": "def convert_headers(line):",
"function_name": "convert_headers",
"parameter_list": "(line)"
},
{
"docstring": "Converts Markdown bold and italic text to HTML.",
"function_declaration": "def convert_bold... | [
0,
1,
1,
0,
0,
0,
0,
0,
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 convert_headers(line: str) -> str:\n if line.startswith('### '):\n return f\"<h3>{line[4:]}</h3>\"\n elif line.startswith('## '):\n retur... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000011087",
"row_id": 11087,
"seed_ids": "[5255]"
} | 0.521136 | Algorithm_11087 | I | [
"convert_headers",
"convert_bold_italic",
"markdown_to_html"
] | 3 | [
[
"markdown_to_html",
"convert_bold_italic"
],
[
"markdown_to_html",
"convert_headers"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a614954f8fd6074c460c8af32bc630497ec76c49 | b8858ef0c558098eb4b0402c668af6a2ce759db9 | |||
v1.0 | instruct | Algorithm | Algorithm_11090_I | ### Binary Search Tree (BST) Construction and Range Sum Query
You are given a list of integers representing node values. Your task is to construct a Binary Search Tree (BST) from this list and implement a function to find the sum of all node values within a given range [low, high].
#### Function Signature
```python
d... | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_into_bst(root, value):
if root is None:
return TreeNode(value)
if value < root.value:
root.left = insert_into_bst(root.left, value)
else:
root.righ... | from solution import bst_range_sum
def test_bst_range_sum_example1():
values = [10, 5, 15, 3, 7, 18]
low = 7
high = 15
assert bst_range_sum(values, low, high) == 32
def test_bst_range_sum_example2():
values = [10, 5, 15, 3, 7, 18]
low = 6
high = 10
assert bst_range_sum(values, low, hig... | [] | [
0,
0,
0,
1,
1,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = None\n\ndef insert_into_bst(root, val):\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000011090",
"row_id": 11090,
"seed_ids": "[861]"
} | 0.591105 | Algorithm_11090 | I | [
"insert_into_bst",
"build_bst",
"range_sum_bst",
"bst_range_sum"
] | 4 | [
[
"bst_range_sum",
"build_bst"
],
[
"bst_range_sum",
"range_sum_bst"
],
[
"build_bst",
"insert_into_bst"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 7eb42b2b83cc7392f0866ff037be9c77fa69ed62 | 146c26e462eb9a2d137ee1105119e9467ebc2969 | |||
v1.0 | instruct | Algorithm | Algorithm_11111_I | ### Huffman Coding Tree Implementation
#### Objective
Implement the Huffman Coding algorithm by completing the provided functions. This task assesses your understanding of data compression techniques and tree-based algorithms.
#### Scenario
In a data compression application, you are required to compress a string usin... | import heapq
from collections import defaultdict, namedtuple
class Node(namedtuple("Node", ["char", "freq", "left", "right"])):
def __lt__(self, other):
return self.freq < other.freq
def build_frequency_dict(message):
freq_dict = defaultdict(int)
for char in message:
freq_dict[char] +=... | import pytest
from solution import (
build_frequency_dict, build_min_heap, build_huffman_tree, build_codes,
encode_message, decode_message, huffman
)
def test_build_frequency_dict():
message = "huffman"
expected = {'h': 1, 'u': 1, 'f': 2, 'm': 1, 'a': 1, 'n': 1}
assert build_frequency_dict(message... | [] | [
1,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import defaultdict, Counter\n\nclass Node:\n def __init__(self, char='', freq=0):\n self.char = char\n self.freq ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000011111",
"row_id": 11111,
"seed_ids": "[3881]"
} | 0.584251 | Algorithm_11111 | I | [
"build_frequency_dict",
"build_min_heap",
"build_huffman_tree",
"build_codes",
"encode_message",
"decode_message",
"huffman"
] | 7 | [
[
"huffman",
"build_codes"
],
[
"huffman",
"build_frequency_dict"
],
[
"huffman",
"build_huffman_tree"
],
[
"huffman",
"build_min_heap"
],
[
"huffman",
"decode_message"
],
[
"huffman",
"encode_message"
]
] | 6 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 6ce89cb9a816b187c61eb8d05fdef06b73e6feb8 | 6522a0a8587c8795fbe43a31356ca057936130e7 | |||
v1.0 | instruct | Algorithm | Algorithm_11126_I | ### K-Means Clustering Implementation
You are tasked with implementing the K-Means clustering algorithm to categorize `n` data points into `k` clusters. The objective is to iteratively adjust the cluster centroids to minimize the total distance between points and their assigned centroids.
#### Task:
Implement a funct... | import random
from typing import List, Tuple
def euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
def k_means_clustering(points: List[Tuple[float, float]], k: int, max_iterations: int = 100) -> List[i... | from solution import k_means_clustering
def test_k_means_clustering_basic():
points = [(1.0, 2.0), (2.0, 1.0), (3.0, 4.0), (5.0, 7.0)]
k = 2
result = k_means_clustering(points, k)
assert len(result) == len(points)
assert sorted(set(result)) == [0, 1]
def test_k_means_single_cluster():
points =... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def k_means_clustering(points, k, max_iterations=100):",
"function_name... | [
1,
0,
0,
1,
1,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Tuple\nfrom math import sqrt\n\ndef k_means_clustering(points: List[Tuple[float, float]], k: int, max_iterations: int = 1... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000011126",
"row_id": 11126,
"seed_ids": "[4329]"
} | 0.760018 | Algorithm_11126 | I | [
"euclidean_distance",
"k_means_clustering"
] | 2 | [
[
"k_means_clustering",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e122e2dadca316bc6534b1babb9d36714416701f | 359b0687852b58fdb7b6ce68dba0338dc03d68cf | |||
v1.0 | instruct | Algorithm | Algorithm_11150_I | ### Question
Write a Python program to implement a K-Means clustering algorithm for a given dataset. The goal is to cluster the instances in the dataset into k clusters and evaluate the clustering performance using a silhouette score.
### Requirements:
- Implement the K-Means clustering using `KMeans` from the scikit-... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
def load_dataset(samples: int = 300, centers: int = 3, cluster_std: float = 0.60) -> np.ndarray:
... | import pytest
from solution import load_dataset, preprocess_data, kmeans_clustering
def test_load_dataset():
data = load_dataset(samples=100, centers=3, cluster_std=0.60)
assert data.shape == (100, 2)
def test_preprocess_data():
data = np.array([[1, 2], [3, 4], [5, 6]])
processed_data = preprocess_dat... | [
{
"docstring": "Generate a synthetic dataset with the given parameters.",
"function_declaration": "def load_dataset(samples=300, centers=3, cluster_std=0.6):",
"function_name": "load_dataset",
"parameter_list": "(samples=300, centers=3, cluster_std=0.6)"
},
{
"docstring": "Normalize the prov... | [
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": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nfrom sklearn.metrics import sil... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000011150",
"row_id": 11150,
"seed_ids": "[710]"
} | 0.751869 | Algorithm_11150 | I | [
"load_dataset",
"preprocess_data",
"kmeans_clustering",
"main"
] | 4 | [
[
"kmeans_clustering",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 72227162197bc3bcaaaf92508c65fd2d9bfb7fbb | 3e496fc8a64576ac790f53d0f676bb1ba3beff93 | |||
v1.0 | instruct | Algorithm | Algorithm_11155_I | ### Coding Assessment Question: Implementation of K-Means Clustering with SSE Calculation
#### Objective
Demonstrate an understanding of clustering algorithms by implementing the K-Means algorithm and calculating the Sum of Squared Errors (SSE) for the clusters formed.
#### Task Description
Given a list of data point... | import random
from typing import List, Tuple
def euclidean_distance(point1: List[float], point2: List[float]) -> float:
return sum((a - b) ** 2 for a, b in zip(point1, point2))
def calculate_sse(data_points: List[List[float]], centroids: List[List[float]], assignments: List[int]) -> float:
sse = 0.0
for p... | from solution import k_means_clustering
def test_k_means_clustering_basic():
data_points = [
[1.0, 2.0],
[1.5, 1.8],
[5.0, 8.0],
[8.0, 8.0],
[1.0, 0.6],
[9.0, 11.0]
]
k = 2
centroids, assignments, sse = k_means_clustering(data_points, k, 100)
assert l... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def calculate_sse(data_points, centroids, assignments):",
"function_nam... | [
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 random\nfrom typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1: List[float], point2: List[float]) -> float:\n return math.sqrt(su... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000011155",
"row_id": 11155,
"seed_ids": "[4370]"
} | 0.733999 | Algorithm_11155 | I | [
"euclidean_distance",
"calculate_sse",
"k_means_clustering"
] | 3 | [
[
"calculate_sse",
"euclidean_distance"
],
[
"k_means_clustering",
"calculate_sse"
],
[
"k_means_clustering",
"euclidean_distance"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 32e910ea4fd4dd38a25a6785cd5f7e9f502d33fa | a45e8532d4440533f240e8ed411d5f9f1d5fe4be | |||
v1.0 | instruct | Algorithm | Algorithm_11253_I | ### Question: Parallel Processing of Large Datasets
For a company dealing with large datasets, optimizing data processing time is crucial. One approach is to divide the workload among multiple processors executing in parallel. You are tasked with writing code to simulate such parallel processing and measure its effect... | from typing import List
def chunk_data(data: List[int], num_chunks: int) -> List[List[int]]:
"""
Divide a list of integers into num_chunks equal parts. Distribute remainders as evenly as possible.
:param data: List of integers to be divided
:param num_chunks: Number of chunks to divide the data in... | import pytest
from solution import chunk_data, parallel_process
def test_chunk_data_equal_chunks():
assert chunk_data([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def test_chunk_data_with_remainder():
assert chunk_data([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3) == [[1, 2, 3, 4], [5, 6, 7], [8... | [
{
"docstring": "Divide a list of integers into num_chunks equal parts. Distribute remainders as evenly as possible.\n\n:param data: List of integers to be divided\n:param num_chunks: Number of chunks to divide the data into\n:return: List of lists, where each list represents a chunk of the input data",
"fun... | [
0,
1,
1,
1,
0,
1,
0,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef chunk_data(data: List[int], num_chunks: int) -> List[List[int]]:\n \"\"\"\n Divide the list `data` into `num_chunks` equal p... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000011253",
"row_id": 11253,
"seed_ids": "[2358]"
} | 0.527223 | Algorithm_11253 | I | [
"chunk_data",
"parallel_process"
] | 2 | [
[
"parallel_process",
"chunk_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dac8757cbc10a3c61574f2035b40dc2c14c1232c | b758d247cb9c1621168996195e5e43e032c4dbbf | |||
v1.0 | instruct | Algorithm | Algorithm_11257_I | ### Problem Statement
Given a list of integers, find the maximum sum of a contiguous subarray using the Divide and Conquer approach. This approach should have a time complexity of \(O(n \log n)\).
### Requirements
1. Implement a function to divide the list and find the maximum sum of a subarray using the Divide and Co... | def max_crossing_sum(nums, left, mid, right):
left_sum = float('-inf')
curr_sum = 0
for i in range(mid, left - 1, -1):
curr_sum += nums[i]
if curr_sum > left_sum:
left_sum = curr_sum
right_sum = float('-inf')
curr_sum = 0
for i in range(mid + 1, right + 1):
... | from solution import max_subarray_sum
def test_max_subarray_sum_example1():
assert max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) == 6
def test_max_subarray_sum_example2():
assert max_subarray_sum([1]) == 1
def test_max_subarray_sum_example3():
assert max_subarray_sum([5,4,-1,7,8]) == 23
def test_max_subarra... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(nums, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(nums, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_sum_util(nums, left, right):",
"function_n... | [
1,
0,
1,
1,
1,
0,
1,
0,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(nums, left, mid, right):\n \"\"\"\n Helper function to find the maximum crossing sum which crosses the midpoint.\n \"\"\"\n left... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011257",
"row_id": 11257,
"seed_ids": "[2946]"
} | 0.756592 | Algorithm_11257 | I | [
"max_crossing_sum",
"max_subarray_sum_util",
"max_subarray_sum"
] | 3 | [
[
"max_subarray_sum",
"max_subarray_sum_util"
],
[
"max_subarray_sum_util",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8cd3cca23d0dff3ae279404fed0b45b3238ef8fe | 003bc734b42b14485e823bbc7eaea259785ca92e | |||
v1.0 | instruct | Algorithm | Algorithm_11313_I | ### AVL Tree Implementation and Rotations
An **AVL tree** is a self-balancing binary search tree (BST) where the difference in heights between the left and right subtrees of any node is at most one. To maintain this balance, rotations are used during insertions and deletions.
#### Task
Your task is to implement an A... | class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def get_height(node):
if not node:
return 0
return node.height
def update_height(node):
if node:
node.height = 1 + max(get_height(node.left), get_heigh... | from solution import insert_avl, preorder_traversal, Node
def test_insert_avl_single_node():
root = None
root = insert_avl(root, 10)
assert preorder_traversal(root) == [10]
def test_insert_avl_multiple_nodes():
root = None
root = insert_avl(root, 10)
root = insert_avl(root, 20)
root = inse... | [] | [
1,
1,
1,
0,
0,
0,
1,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n\ndef get_height... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000011313",
"row_id": 11313,
"seed_ids": "[1538]"
} | 0.548929 | Algorithm_11313 | I | [
"get_height",
"update_height",
"get_balance",
"right_rotate",
"left_rotate",
"insert_avl",
"preorder_traversal"
] | 7 | [
[
"get_balance",
"get_height"
],
[
"insert_avl",
"get_balance"
],
[
"insert_avl",
"left_rotate"
],
[
"insert_avl",
"right_rotate"
],
[
"insert_avl",
"update_height"
],
[
"left_rotate",
"update_height"
],
[
"right_rotate",
"update_height... | 8 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 22225ad139c0a8383b2986b72aee5b9807f5eb35 | cd1722dbffb75ba782a59eaed9731e07dd40a805 | |||
v1.0 | instruct | Algorithm | Algorithm_11346_I | ### Genetic Algorithm for Function Optimization
As a software developer in a high-tech R&D team, you have been tasked with implementing a genetic algorithm (GA) for optimizing a given mathematical function. Genetic algorithms are a class of optimization techniques based on principles of natural selection and genetics.... | import random
def initialize_population(pop_size, gene_length, min_val, max_val):
"""
Generates an initial population of individuals.
"""
return [[random.uniform(min_val, max_val) for _ in range(gene_length)] for _ in range(pop_size)]
def evaluate_population(population, fitness_function):
"""
... | from solution import (initialize_population, evaluate_population, selection, crossover, mutate, genetic_algorithm, fitness_function_example)
def test_initialize_population():
population = initialize_population(10, 5, -10, 10)
assert len(population) == 10
assert all(len(ind) == 5 for ind in population)
... | [
{
"docstring": "Generates an initial population of individuals.",
"function_declaration": "def initialize_population(pop_size, gene_length, min_val, max_val):",
"function_name": "initialize_population",
"parameter_list": "(pop_size, gene_length, min_val, max_val)"
},
{
"docstring": "Calculat... | [
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\ndef initialize_population(pop_size, gene_length, min_val, max_val):\n \"\"\"\n Generates and returns an initial population of individuals.... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011346",
"row_id": 11346,
"seed_ids": "[3890]"
} | 0.436999 | Algorithm_11346 | I | [
"initialize_population",
"evaluate_population",
"selection",
"crossover",
"mutate",
"genetic_algorithm",
"fitness_function_example"
] | 7 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"evaluate_population"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"selection"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | e0dfb0caad76be0ee435fb5e28ad85a2c44b9728 | d56675a40ff42a48ff42a13b4b06c4c6b4677194 | |||
v1.0 | instruct | Algorithm | Algorithm_11429_I | ### Question: Implement a String Palindrome Checker with Case Sensitivity Control
You are tasked with implementing a system that checks if a given string is a palindrome. The system should support case sensitivity configuration.
#### Functions to Implement:
1. **Is Palindrome Case Sensitive**
- Checks if the give... | def is_palindrome_case_sensitive(s: str) -> bool:
"""
Checks if the given string is a palindrome considering case sensitivity.
"""
# Compare the string with its reverse
return s == s[::-1]
def is_palindrome_case_insensitive(s: str) -> bool:
"""
Checks if the given string is a palindrome wit... | from solution import is_palindrome_case_sensitive, is_palindrome_case_insensitive, palindrome_checker
def test_is_palindrome_case_sensitive():
assert is_palindrome_case_sensitive("Madam") == False
assert is_palindrome_case_sensitive("madam") == True
assert is_palindrome_case_sensitive("12321") == True
... | [
{
"docstring": "Checks if the given string is a palindrome considering case sensitivity.",
"function_declaration": "def is_palindrome_case_sensitive(s):",
"function_name": "is_palindrome_case_sensitive",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the given string is a palindrome wi... | [
0,
1,
1,
0,
0,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome_case_sensitive(s: str) -> bool:\n \"\"\"\n Checks if the given string is a palindrome considering case sensitivity.\n \"\"\"\n retu... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011429",
"row_id": 11429,
"seed_ids": "[4583]"
} | 0.706771 | Algorithm_11429 | I | [
"is_palindrome_case_sensitive",
"is_palindrome_case_insensitive",
"palindrome_checker"
] | 3 | [
[
"palindrome_checker",
"is_palindrome_case_insensitive"
],
[
"palindrome_checker",
"is_palindrome_case_sensitive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e8afafb52457ee786b0b1b3cc674c33bbaaeb9a1 | 1d25f8f45c27e787f1df261b7f62d484d6cd37b1 | |||
v1.0 | instruct | Algorithm | Algorithm_11567_I | ### Prime Path Finder
#### Background
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to create a feature for a number analysis tool that determines the shortest path between two given prime numbers by changing one digit at a time, ensuring each int... | from collections import deque
from itertools import permutations
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +=... | def test_prime_shortest_path_same_prime():
assert prime_shortest_path(1033, 1033) == 0
def test_prime_shortest_path_one_step():
assert prime_shortest_path(1033, 1733) == 1
def test_prime_shortest_path_multiple_steps():
assert prime_shortest_path(1033, 8179) == 6
def test_prime_shortest_path_no_connection... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def get_all_primes():",
"function_name": "get_all_primes",
"parameter_list": "()"
},
{
"docstring": null,... | [
1,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom itertools import permutations\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000011567",
"row_id": 11567,
"seed_ids": "[1110]"
} | 0.626538 | Algorithm_11567 | I | [
"is_prime",
"get_all_primes",
"prime_neighbors",
"prime_shortest_path"
] | 4 | [
[
"get_all_primes",
"is_prime"
],
[
"prime_neighbors",
"is_prime"
],
[
"prime_shortest_path",
"get_all_primes"
],
[
"prime_shortest_path",
"prime_neighbors"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 250fc4fd3cee37575b7bbab0897a8162b1254263 | 1e30b13f906b526f062f16ba0d0055b9d7911500 | |||
v1.0 | instruct | Algorithm | Algorithm_11653_I | ### Sorting a Linked List
In this exercise, you will implement the `merge_sort_linked_list` function to sort a singly linked list using the merge sort algorithm. This algorithm should efficiently sort the list in ascending order by splitting the list into smaller lists and then merging them.
#### Function Signature
``... | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def find_middle(head):
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def merge_lists(l1, l2):
dummy = ListNode... | import pytest
def create_linked_list(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for value in arr[1:]:
current.next = ListNode(value)
current = current.next
return head
def linked_list_to_list(head):
arr = []
current = head
while current... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\ndef merge_sort_linked_list(head: ListNode) ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011653",
"row_id": 11653,
"seed_ids": "[3605]"
} | 0.534198 | Algorithm_11653 | I | [
"find_middle",
"merge_lists",
"merge_sort_linked_list"
] | 3 | [
[
"merge_sort_linked_list",
"find_middle"
],
[
"merge_sort_linked_list",
"merge_lists"
]
] | 2 | [] | false | [
"ListNode"
] | true | pytest | false | [] | true | 91bb4781f94404859e36b748f72471603f9b5411 | 28de036be734b04345e8b4812cd9ce234053f5a7 | |||
v1.0 | instruct | Algorithm | Algorithm_11662_I | **Context:** A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this problem, you need to find the largest prime number that is smaller than a given number `n`.
**Question:**
Write a function `largest_prime_below(n: int) -> int` that returns the largest prime nu... | def is_prime(num):
"""Helper function to check if a number is prime."""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
... | def test_largest_prime_below():
# Test cases
assert largest_prime_below(30) == 29
assert largest_prime_below(15) == 13
assert largest_prime_below(3) == 2
assert largest_prime_below(2) == -1
assert largest_prime_below(100) == 97
assert largest_prime_below(1) == -1 # edge case, though n shoul... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the largest prime number less than the given integer `n`. \nIf there is no prime less than `n`, ret... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000011662",
"row_id": 11662,
"seed_ids": "[950]"
} | 0.696289 | Algorithm_11662 | I | [
"is_prime",
"largest_prime_below"
] | 2 | [
[
"largest_prime_below",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 84cc4f58bb0e71d706e43435455f85ed3af09246 | d3381d06b3080ecdcd46bb4f7ce10118575047f6 | |||
v1.0 | instruct | Algorithm | Algorithm_11708_I | ### Problem Statement
A self-powering number is a four-digit number that equals the sum of its digits each raised to the power of the number itself. For example, 9474 is a self-powering number because \( 9^4 + 4^4 + 7^4 + 4^4 = 9474 \).
Write a function `find_self_powering_numbers()` that returns a list of all self-po... | from typing import List
def is_self_powering_number(num: int) -> bool:
"""
Check if a number is a self-powering number.
"""
digits = [int(d) for d in str(num)]
power_sum = sum(d ** len(digits) for d in digits)
return power_sum == num
def find_self_powering_numbers() -> List[int]:
"""
F... | from solution import find_self_powering_numbers, is_self_powering_number
def test_is_self_powering_number():
assert is_self_powering_number(1634) == True
assert is_self_powering_number(8208) == True
assert is_self_powering_number(9474) == True
assert is_self_powering_number(1234) == False
assert is... | [
{
"docstring": "Check if a number is a self-powering number.",
"function_declaration": "def is_self_powering_number(num):",
"function_name": "is_self_powering_number",
"parameter_list": "(num)"
},
{
"docstring": "Find all self-powering numbers within the range of four-digit numbers.",
"f... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_self_powering_number(num: int) -> bool:\n \"\"\"\n Check if the number is a self-powering number.\n \"\"\"\n digits... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011708",
"row_id": 11708,
"seed_ids": "[2422]"
} | 0.581626 | Algorithm_11708 | I | [
"is_self_powering_number",
"find_self_powering_numbers"
] | 2 | [
[
"find_self_powering_numbers",
"is_self_powering_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bb52203f34c56a0051d89c32788f7350b2e8ce5b | a5a585caeb1cdf0dba3dc883d65cfc7fc76d8374 | |||
v1.0 | instruct | Algorithm | Algorithm_11724_I | ### Coding Assessment Question:
#### Scenario:
You have been hired by a company developing a social media platform with various features, including text analysis and suggestions. One of your goals is to implement a system that checks whether a given post is a duplicate of any existing post in the database. Two posts a... | import string
from typing import List
def normalize_post(post: str) -> str:
"""
Normalizes the post by removing spaces, punctuation and converting to lowercase.
"""
return ''.join(char for char in post.lower() if char not in string.whitespace + string.punctuation)
def is_duplicate_post(new_post: str, ... | from solution import is_duplicate_post
def test_basic_duplicate():
new_post = "Hello World!"
existing_posts = ["!world hello", "Hi there", "Hello!"]
assert is_duplicate_post(new_post, existing_posts) == True
def test_no_duplicate():
new_post = "Hello World!"
existing_posts = ["Different post", "An... | [
{
"docstring": "Normalizes the post by removing spaces, punctuation and converting to lowercase.",
"function_declaration": "def normalize_post(post):",
"function_name": "normalize_post",
"parameter_list": "(post)"
},
{
"docstring": "Checks if new_post is a duplicate of any posts in existing_... | [
1,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import string\nfrom collections import Counter\nfrom typing import List\n\ndef normalize_post(post: str) -> str:\n # Remove spaces and punctuation, convert to... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011724",
"row_id": 11724,
"seed_ids": "[1233]"
} | 0.61911 | Algorithm_11724 | I | [
"normalize_post",
"is_duplicate_post"
] | 2 | [
[
"is_duplicate_post",
"normalize_post"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b3a862a7c0c8033cee7a65fe7aa6564335b66ee7 | 794c1b84d088b08256f773bdaee2de5f9249d4cb | |||
v1.0 | instruct | Algorithm | Algorithm_11760_I | ### Context:
In numerical computing and scientific simulations, it is often necessary to determine whether a given matrix is diagonally dominant. This property is crucial, for example, in ensuring the convergence of various iterative methods for solving linear systems, such as the Jacobi or Gauss-Seidel methods.
### P... | from typing import List
def sum_abs_non_diagonal(row: List[float], diag_index: int) -> float:
return sum(abs(row[j]) for j in range(len(row)) if j != diag_index)
def is_diagonally_dominant(matrix: List[List[float]]) -> bool:
n = len(matrix)
for i in range(n):
diag_element = abs(matrix[i][i])
... | from solution import is_diagonally_dominant
def test_is_diagonally_dominant_example_1():
matrix = [
[3, -2, 1],
[1, -4, 2],
[1, 2, -5]
]
assert is_diagonally_dominant(matrix) == True
def test_is_diagonally_dominant_example_2():
matrix = [
[1, 2, 3],
[4, 5, 6],
... | [
{
"docstring": null,
"function_declaration": "def sum_abs_non_diagonal(row, diag_index):",
"function_name": "sum_abs_non_diagonal",
"parameter_list": "(row, diag_index)"
},
{
"docstring": null,
"function_declaration": "def is_diagonally_dominant(matrix):",
"function_name": "is_diagon... | [
1,
1,
1,
0,
0,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef sum_abs_non_diagonal(row: List[float], diag_index: int) -> float:\n return sum(abs(row[j]) for j in range(len(row)) if j != dia... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000011760",
"row_id": 11760,
"seed_ids": "[3300]"
} | 0.537852 | Algorithm_11760 | I | [
"sum_abs_non_diagonal",
"is_diagonally_dominant"
] | 2 | [
[
"is_diagonally_dominant",
"sum_abs_non_diagonal"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a030ed23d5fc104ce70659835a7b183743de018 | 0578ecea1a5b77ce2e44faf7ff597dfb2f83a409 | |||
v1.0 | instruct | Algorithm | Algorithm_11781_I | ### Coding Assessment Question
#### Machine Learning Model Evaluation
**Scenario**: You have been working on a machine learning model that predicts house prices based on various features. The model was trained and tested on historical data, but now you need to improve its evaluation pipeline to make it more robust, a... | import numpy as np
import pandas as pd
from sklearn.model_selection import KFold
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
def cross_validation(model, X: pd.DataFrame, y: pd.Series, k: int = 5) -> dict:
"""
Perform k-fold cross-validation and return the... | from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
import pytest
def test_cross_validation():
X = pd.DataFrame({
'feature1': [1, 2, 3, 4, 5],
'feature2': [10, 20, 30, 40, 50]
})
y = pd.Series([2, 4, 6, 8, 10])
model = LinearRegression()
... | [
{
"docstring": "Perform k-fold cross-validation and return the evaluation metrics for each fold.",
"function_declaration": "def cross_validation(model, X, y, k=5):",
"function_name": "cross_validation",
"parameter_list": "(model, X, y, k=5)"
},
{
"docstring": "Calculate and return the import... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\n\ndef cr... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000011781",
"row_id": 11781,
"seed_ids": "[4027]"
} | 0.472258 | Algorithm_11781 | I | [
"cross_validation",
"feature_importance_analysis",
"custom_evaluation_metrics",
"evaluate_model"
] | 4 | [
[
"evaluate_model",
"cross_validation"
],
[
"evaluate_model",
"custom_evaluation_metrics"
],
[
"evaluate_model",
"feature_importance_analysis"
]
] | 3 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | 382f77ad3b6bd5df91bcdbb5a1db654be6188b61 | b8808a11ee20445ace9a10f8249e376ce0511af2 | |||
v1.0 | instruct | Algorithm | Algorithm_11810_I | ### Question: String Rotation Checker
#### Scenario:
String manipulation is a common task in various programming challenges. One specific operation involves determining if one string is a rotation of another string. This can be useful in real-world applications such as password checks, data normalization, and cyclic s... | def is_rotation(str1: str, str2: str) -> bool:
"""
Checks if str1 is a rotation of str2.
"""
if len(str1) != len(str2):
return False
return str2 in (str1 + str1)
def visualize_rotation_check(str1: str, str2: str) -> str:
"""
Provides a visual representation of the rotation check pro... | from solution import is_rotation, visualize_rotation_check
def test_is_rotation_true():
assert is_rotation("waterbottle", "erbottlewat") == True
assert is_rotation("waterbottle", "bottlewater") == True
assert is_rotation("rotation", "tationro") == True
def test_is_rotation_false():
assert is_rotation(... | [
{
"docstring": "Checks if str1 is a rotation of str2.",
"function_declaration": "def is_rotation(str1, str2):",
"function_name": "is_rotation",
"parameter_list": "(str1, str2)"
},
{
"docstring": "Provides a visual representation of the rotation check process.",
"function_declaration": "d... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_rotation(str1: str, str2: str) -> bool:\n \"\"\"\n Checks if str1 is a rotation of str2.\n \"\"\"\n if len(str1) != len(str2):\n return... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011810",
"row_id": 11810,
"seed_ids": "[5232]"
} | 0.66254 | Algorithm_11810 | I | [
"is_rotation",
"visualize_rotation_check"
] | 2 | [
[
"visualize_rotation_check",
"is_rotation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a889ff1564ba64bd86c09993829a7193696d4708 | 8f2c1899fb6e209c5ae94e3e7287a0aa417b3c76 | |||
v1.0 | instruct | Algorithm | Algorithm_11843_I | ### Coding Assessment Question
#### Context
A palindromic number reads the same both ways (left to right and right to left). For example, 121 is a palindromic number, but 123 is not. Given an integer \(n\), your task is to implement a function to find the largest palindromic number made from the product of two integer... | def is_palindrome(number: int) -> bool:
"""
Checks if a given number is a palindrome.
"""
return str(number) == str(number)[::-1]
def largest_palindromic_number(n: int) -> int:
"""
Returns the largest palindromic number that is a product of two integers both less than n.
"""
max_palindr... | import pytest
from solution import is_palindrome, largest_palindromic_number
def test_is_palindrome():
assert is_palindrome(121)
assert not is_palindrome(123)
assert is_palindrome(1221)
assert is_palindrome(1)
assert not is_palindrome(10)
def test_largest_palindromic_number():
assert largest_p... | [
{
"docstring": "Checks if a given number is a palindrome.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Returns the largest palindromic number that is a product of two integers both less than n.",
... | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(number):\n \"\"\"\n Helper function to check if a number is a palindrome.\n \"\"\"\n return str(number) == str(number)[::-1]\n\ndef... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000011843",
"row_id": 11843,
"seed_ids": "[2086]"
} | 0.768545 | Algorithm_11843 | I | [
"is_palindrome",
"largest_palindromic_number"
] | 2 | [
[
"largest_palindromic_number",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a461992cbfee148147eeef29a8cb51c427ff828d | 16b2c4d7dc81081c894c9a684546f43d969de28f | |||
v1.0 | instruct | Algorithm | Algorithm_11848_I | ### Coding Assessment Question: Palindrome Permutation Checker
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Write a function that determines if a given string is a permutation of a palindrome.
### R... | def char_frequency(s: str) -> dict:
"""
This function builds a frequency dictionary of the characters in the input string,
ignoring spaces and case.
"""
freq_dict = {}
for char in s.replace(" ", "").lower():
if char in freq_dict:
freq_dict[char] += 1
else:
... | from solution import char_frequency, can_form_palindrome, is_permutation_of_palindrome
def test_char_frequency():
assert char_frequency("Tact Coa") == {'t': 2, 'a': 2, 'c': 2, 'o': 1}
assert char_frequency("Hello World") == {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
assert char_frequency("aab... | [
{
"docstring": "This function builds a frequency dictionary of the characters in the input string,\nignoring spaces and case.",
"function_declaration": "def char_frequency(s):",
"function_name": "char_frequency",
"parameter_list": "(s)"
},
{
"docstring": "This function checks if the given ch... | [
1,
1,
0,
0,
1,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def char_frequency(s: str) -> dict:\n \"\"\"\n Builds a frequency dictionary of the characters in the input string\n (ignoring spaces and case).\n \"... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000011848",
"row_id": 11848,
"seed_ids": "[1798]"
} | 0.735251 | Algorithm_11848 | I | [
"char_frequency",
"can_form_palindrome",
"is_permutation_of_palindrome"
] | 3 | [
[
"is_permutation_of_palindrome",
"can_form_palindrome"
],
[
"is_permutation_of_palindrome",
"char_frequency"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3ac67785ff8f983ea3f9c4b2677fd133c6942a79 | ef4a47842097c5671f62b10b74d17b4a9b35af10 | |||
v1.0 | instruct | Algorithm | Algorithm_12070_I | ### Closest Pair of Points
**Problem Statement:**
Given a list of `n` points on the 2D plane, where each point is represented as a tuple of two integers `(x, y)`, write a function `closest_pair_of_points(points: list[tuple[int, int]]) -> float` that finds and returns the minimum distance between any two points from t... | import math
def euclidean_distance(p1, p2):
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y):
# Base case
if len(points_sorted_by_x) <= 3:
min_dist = float('inf')
for i in range(len(points_sorted_by_x)):
... | import pytest
from solution import closest_pair_of_points
def test_closest_pair_basic():
assert math.isclose(closest_pair_of_points([(0, 0), (1, 1), (4, 5), (2, 2)]), 1.4142135623730951, rel_tol=1e-9)
def test_closest_pair_less_than_two_points():
with pytest.raises(ValueError, match="At least two points are r... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y):",
"function_name": ... | [
1,
1,
1,
1,
1,
0,
0,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List, Tuple\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n return math.sqrt((point1[0... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012070",
"row_id": 12070,
"seed_ids": "[87]"
} | 0.7001 | Algorithm_12070 | I | [
"euclidean_distance",
"closest_pair_recursive",
"closest_pair_of_points"
] | 3 | [
[
"closest_pair_of_points",
"closest_pair_recursive"
],
[
"closest_pair_recursive",
"euclidean_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 595cd2851b5a97129e3f280bf58a65bcb3a0fde7 | e30b8bc4352d635126f75e9e044b269a7168a65d | |||
v1.0 | instruct | Algorithm | Algorithm_12077_I | ### Question: Implement Primes Sieve Using Segmented Sieve Algorithm
#### Context
The Segmented Sieve Algorithm is an extension of the Sieve of Eratosthenes, which can find all prime numbers in a given range [L, R]. This approach is more efficient when dealing with a large range.
#### Task
You are tasked with impleme... | import math
def simple_sieve(limit):
"""
A simple sieve of Eratosthenes up to a given limit.
"""
is_prime = [True] * (limit + 1)
p = 2
while p * p <= limit:
if is_prime[p] == True:
for i in range(p * p, limit + 1, p):
is_prime[i] = False
p += 1
pr... | def test_segmented_sieve_small_range():
assert segmented_sieve(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def test_segmented_sieve_single_prime():
assert segmented_sieve(29, 29) == [29]
def test_segmented_sieve_large_range():
expected_primes = [101, 103, 107, 109, 113, 127, 131, 137, 139,... | [
{
"docstring": "A simple sieve of Eratosthenes up to a given limit.",
"function_declaration": "def simple_sieve(limit):",
"function_name": "simple_sieve",
"parameter_list": "(limit)"
},
{
"docstring": "Segmented sieve algorithm to find primes in [L, R].",
"function_declaration": "def seg... | [
1,
1,
1,
1,
1,
0,
0,
1,
0
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl",
"solution_code": "def segmented_sieve(L, R):\n \"\"\"\n Returns a list of prime numbers in the range [L, R] using the segmented sieve algorithm.\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012077",
"row_id": 12077,
"seed_ids": "[968]"
} | 0.52939 | Algorithm_12077 | I | [
"simple_sieve",
"segmented_sieve"
] | 2 | [
[
"segmented_sieve",
"simple_sieve"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 04c75c60a99324ee32c33de4b59e11d973498c1a | 5e325edcd1adb9d58aa6bf2c3ced69bdaf4adfd2 | |||
v1.0 | instruct | Algorithm | Algorithm_12098_I | ### Question: Implement an Efficient Word Frequency Counter Using Concurrent Processing
#### Context:
You are tasked with creating a word frequency counter that efficiently processes large text files. The current implementation reads and counts the words in a single-threaded manner, which can be slow for large files.
... | import re
import os
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from typing import Dict
def read_chunks(file_path: str, chunk_size: int = 1024 * 1024):
"""Read a file in chunks"""
with open(file_path, 'r', encoding='utf-8') as f:
while True:
chunk = f.... | from solution import count_word_frequencies
import os
def create_test_file(file_path: str, content: str):
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
def test_count_word_frequencies():
input_file_path = 'test_file.txt'
test_content = "hello world, HELLO again! This is a test... | [
{
"docstring": "Read a file in chunks",
"function_declaration": "def read_chunks(file_path, chunk_size=1024 * 1024):",
"function_name": "read_chunks",
"parameter_list": "(file_path, chunk_size=1024 * 1024)"
},
{
"docstring": "Process a chunk of text and return a Counter of word frequencies",... | [
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 re\nfrom collections import defaultdict\nfrom concurrent.futures import ThreadPoolExecutor\nimport threading\n\ndef read_file_chunks(file_path, chunk_size... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000012098",
"row_id": 12098,
"seed_ids": "[2356]"
} | 0.676635 | Algorithm_12098 | I | [
"read_chunks",
"process_chunk",
"count_word_frequencies"
] | 3 | [
[
"count_word_frequencies",
"process_chunk"
],
[
"count_word_frequencies",
"read_chunks"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 20a1edb475f90c9ef7b17edc86952e986b69c5d0 | d3e92019c55263e7b2612340e010b89622bf131a | |||
v1.0 | instruct | Algorithm | Algorithm_12146_I | ### Question:
#### Problem Statement:
You are tasked with writing a function to simulate the behavior of a 4-bit ripple carry adder using only basic logic gates (AND, OR, and XOR). The 4-bit ripple carry adder will add two 4-bit binary numbers, producing a 4-bit sum and a carry-out.
#### Function Signature:
```pytho... | from typing import Tuple
def and_gate(input_1: int, input_2: int) -> int:
return input_1 & input_2
def or_gate(input_1: int, input_2: int) -> int:
return input_1 | input_2
def xor_gate(input_1: int, input_2: int) -> int:
return input_1 ^ input_2
def full_adder(bit_a: int, bit_b: int, carry_in: int) -> T... | def test_ripple_carry_adder():
assert ripple_carry_adder(3, 6) == (9, 0)
assert ripple_carry_adder(7, 8) == (15, 0)
assert ripple_carry_adder(15, 1) == (0, 1)
assert ripple_carry_adder(9, 6) == (15, 0)
assert ripple_carry_adder(0, 0) == (0, 0)
assert ripple_carry_adder(0, 15) == (15, 0)
asse... | [
{
"docstring": null,
"function_declaration": "def and_gate(input_1, input_2):",
"function_name": "and_gate",
"parameter_list": "(input_1, input_2)"
},
{
"docstring": null,
"function_declaration": "def or_gate(input_1, input_2):",
"function_name": "or_gate",
"parameter_list": "(in... | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def and_gate(input_1: int, input_2: int) -> int:\n return input_1 & input_2\n\ndef or_gate(input_1: int, input_2: int) -> int:\n return input_1 | input_2\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012146",
"row_id": 12146,
"seed_ids": "[4592]"
} | 0.607234 | Algorithm_12146 | I | [
"and_gate",
"or_gate",
"xor_gate",
"full_adder",
"ripple_carry_adder"
] | 5 | [
[
"full_adder",
"and_gate"
],
[
"full_adder",
"or_gate"
],
[
"full_adder",
"xor_gate"
],
[
"ripple_carry_adder",
"full_adder"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 9821907ba2fac320fb630e21aef6e18d30499c57 | 6a0cfd6bebb1ec36cde130ac2beb911559abf46b | |||
v1.0 | instruct | Algorithm | Algorithm_12151_I | You are working on an inventory management system that helps businesses track their stock levels and reorder products when necessary. The system should send an email notification when the stock level of an item falls below the reorder threshold. To ensure your code sends the correct email, you should write unit tests t... | def send_email_to_supplier(recipient, subject, body):
# This function would typically send an email
pass
def send_reorder_notification(recipient, item_name):
"""
Send a reorder notification email to a supplier.
Args:
recipient (str): The email of the recipient.
item_name (str): The nam... | import pytest
def fake_send_email(recipient, subject, body):
"""
A fake email sending function to mock sending email and return a controlled response.
"""
if not recipient or "@" not in recipient:
return {"status": "failed", "message": "Invalid recipient email format"}
if not subject:
... | [
{
"docstring": null,
"function_declaration": "def send_email_to_supplier(recipient, subject, body):",
"function_name": "send_email_to_supplier",
"parameter_list": "(recipient, subject, body)"
},
{
"docstring": "Send a reorder notification email to a supplier.\n\nArgs:\nrecipient (str): The e... | [
0,
0,
1,
0,
0,
1,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def send_email_to_supplier(recipient, subject, body):\n # This function would typically send an email\n pass\n\ndef send_reorder_notification(recipient, it... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000012151",
"row_id": 12151,
"seed_ids": "[2276]"
} | 0.687119 | Algorithm_12151 | I | [
"send_email_to_supplier",
"send_reorder_notification"
] | 2 | [
[
"send_reorder_notification",
"send_email_to_supplier"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9fc8a6c4bbcab76158971f2fd96b85e7a51c7076 | 1df84f9689cdc281fe540733f8f6292adf7411e3 | |||
v1.0 | instruct | Algorithm | Algorithm_12178_I | ### Problem Statement
Implement a function to perform integer division without using the division or multiplication operators. Additionally, implement another function to perform integer division and return the remainder as well.
### Function 1: `integer_divide(dividend: int, divisor: int) -> int`
* **Input Parameter... | def integer_divide(dividend: int, divisor: int) -> int:
if dividend == 0:
return 0
negative = (dividend < 0) != (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
quotient = 0
current_sum = divisor
while dividend >= current_sum:
current_quota = 1
while cur... | def test_integer_divide_positive_division():
assert integer_divide(10, 3) == 3
def test_integer_divide_negative_divisor():
assert integer_divide(43, -8) == -5
def test_integer_divide_negative_dividend():
assert integer_divide(-43, 8) == -5
def test_integer_divide_negative_both():
assert integer_divid... | [
{
"docstring": null,
"function_declaration": "def integer_divide(dividend, divisor):",
"function_name": "integer_divide",
"parameter_list": "(dividend, divisor)"
},
{
"docstring": null,
"function_declaration": "def integer_divide_with_remainder(dividend, divisor):",
"function_name": ... | [
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 integer_divide(dividend: int, divisor: int) -> int:\n if dividend == 0:\n return 0\n \n negative = (dividend < 0) != (divisor < 0)\n divid... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012178",
"row_id": 12178,
"seed_ids": "[3030]"
} | 0.703518 | Algorithm_12178 | I | [
"integer_divide",
"integer_divide_with_remainder"
] | 2 | [
[
"integer_divide_with_remainder",
"integer_divide"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ef1f3ed8e9d143dec8a7d80beb7bc49a7203ea83 | fc7ddc1a09cd25a75024f8e3c5f4d8c1cca1ce8e | |||
v1.0 | instruct | Algorithm | Algorithm_12185_I | ### Coding Assessment Question
#### Context:
You have been introduced to sorting techniques and improving algorithm performance. To evaluate your understanding of these concepts while leveraging dictionary operations, you'll implement an algorithm that efficiently counts word occurrences.
#### Task:
Implement a funct... | from typing import List, Dict, Tuple
def word_count(words: List[str]) -> Dict[str, int]:
"""
Takes a list of strings representing words and returns a dictionary where the keys are the words,
and the values are the number of times each word appears in the list.
"""
word_frequency = {}
for word i... | from solution import word_count, sorted_word_count
def test_word_count_empty():
assert word_count([]) == {}
def test_word_count_single_word():
assert word_count(["apple"]) == {"apple": 1}
def test_word_count_multiple_words():
assert word_count(["apple", "banana", "apple", "orange", "banana", "apple"]) ==... | [
{
"docstring": "Takes a list of strings representing words and returns a dictionary where the keys are the words,\nand the values are the number of times each word appears in the list.",
"function_declaration": "def word_count(words):",
"function_name": "word_count",
"parameter_list": "(words)"
},... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Tuple\n\ndef word_count(words: List[str]) -> Dict[str, int]:\n \"\"\"\n This function takes a list of words and returns a di... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012185",
"row_id": 12185,
"seed_ids": "[952]"
} | 0.80093 | Algorithm_12185 | I | [
"word_count",
"sorted_word_count"
] | 2 | [
[
"sorted_word_count",
"word_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2845f46861de5830c5ce3a35ce3e078f29a4ad7c | 7d35df82d716ba299212b1c7e7abe1d5dfc0bae8 | |||
v1.0 | instruct | Algorithm | Algorithm_12348_I | ### Question
You are tasked with implementing a spell checker feature for a text editor. This spell checker should:
1. Use a given dictionary of valid words.
2. Identify and correct possible misspellings in a given text.
3. Suggest the closest valid word for each misspelled word based on the Levenshtein distance.
4. ... | def levenshtein_distance(word1, word2):
"""
Computes the Levenshtein distance between two words.
"""
len1, len2 = len(word1), len(word2)
if len1 < len2:
return levenshtein_distance(word2, word1)
# len1 >= len2
previous_row = range(len2 + 1)
for i, c1 in enumerate(word1):
... | from solution import spell_check, update_dictionary, levenshtein_distance
def test_levenshtein_distance():
assert levenshtein_distance("kitten", "sitting") == 3
assert levenshtein_distance("flaw", "lawn") == 2
assert levenshtein_distance("algorithm", "altruistic") == 6
def test_spell_check():
dictiona... | [
{
"docstring": "Computes the Levenshtein distance between two words.",
"function_declaration": "def levenshtein_distance(word1, word2):",
"function_name": "levenshtein_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Finds the closest word in the dictionary to the given word ... | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef levenshtein_distance(word1, word2):\n len1, len2 = len(word1), len(word2)\n dp_matrix = np.zeros((len1 + 1, len2 + 1), dtype=int)... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000012348",
"row_id": 12348,
"seed_ids": "[4288]"
} | 0.548189 | Algorithm_12348 | I | [
"levenshtein_distance",
"find_closest_word",
"spell_check",
"update_dictionary"
] | 4 | [
[
"find_closest_word",
"levenshtein_distance"
],
[
"spell_check",
"find_closest_word"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 90b2d84431fe31de202f618c109b6ab599aab1ec | 752ae2bd0a4dd60757b67928ca04460546d654c1 | |||
v1.0 | instruct | Algorithm | Algorithm_12349_I | ### Binary Search Tree Removal Operations
You are given a basic implementation of a Binary Search Tree (BST). The BST supports common operations such as insertion and traversal. You are required to enhance the functionality of the BST by implementing the removal operation.
The removal operation should handle the foll... | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root... | from solution import Node, insert, inorder_traversal, remove
def test_remove_leaf_node():
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 10)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 14)
root = insert(root, 4)
root = insert(root... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef insert(root, key):\n if root is ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000012349",
"row_id": 12349,
"seed_ids": "[1928]"
} | 0.61109 | Algorithm_12349 | I | [
"insert",
"inorder_traversal",
"find_minimum",
"remove"
] | 4 | [
[
"remove",
"find_minimum"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 6a728f0158e927a284cf7109dcd663b7388233f9 | d9aefb75f27d7409adc8257699dea85fa0f2c688 | |||
v1.0 | instruct | Algorithm | Algorithm_12390_I | ### Context
You have been asked to implement a sorting algorithm that sorts a list of integers in ascending order. Notably, you are required to implement the Merge Sort algorithm. Merge Sort is a classic divide-and-conquer algorithm that effectively handles large lists with efficiency.
### Objective
Write a function `... | from typing import List
def merge(left: List[int], right: List[int]) -> List[int]:
"""
Merges two sorted lists (left and right) into a single sorted list.
"""
result = []
i = j = 0
# Merge the two lists while maintaining order
while i < len(left) and j < len(right):
if left[i] ... | from solution import merge, merge_sort
def test_merge_empty():
assert merge([], []) == []
def test_merge_single_element():
assert merge([1], []) == [1]
assert merge([], [1]) == [1]
def test_merge_sorted_lists():
assert merge([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]
def test_merge_left_longer():
... | [
{
"docstring": "Merges two sorted lists (left and right) into a single sorted list.",
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docstring": "Sorts a list of integers in ascending order using the Merge Sort algorithm."... | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge(left: List[int], right: List[int]) -> List[int]:\n \"\"\"\n Merges two sorted lists into one sorted list.\n \"\"\"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012390",
"row_id": 12390,
"seed_ids": "[1601]"
} | 0.657463 | Algorithm_12390 | I | [
"merge",
"merge_sort"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ab23fc3e5a605cc54dfa4eb54c7c47f27c85e1e9 | 9149222ec472c3426bc2ced84c239bac02934852 | |||
v1.0 | instruct | Algorithm | Algorithm_12416_I | ### Coding Assessment Question
#### Context
A delivery company wants to optimize its delivery routes to minimize the total distance traveled while ensuring all delivery locations are serviced. The company uses a fleet of delivery vehicles, each with limited capacity. The delivery locations need to be partitioned into ... | from typing import List, Tuple
import itertools
import math
def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def tsp_route(depot: Tuple[int, int], locations: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
n = len(locatio... | from solution import optimize_delivery_routes
import pytest
def test_simple_case():
depot = (0, 0)
locations = [(1, 3), (4, 5)]
demands = [4, 6]
vehicle_capacity = 10
routes = optimize_delivery_routes(depot, locations, demands, vehicle_capacity)
assert len(routes) == 1 # Single vehicle can han... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def tsp_route(depot, locations):",
"function_name": "tsp_route",
"parameter_list": ... | [
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": "def optimize_delivery_routes(depot, locations, demands, vehicle_capacity):\n from scipy.spatial.distance import euclidean\n import numpy as np\n \n d... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012416",
"row_id": 12416,
"seed_ids": "[517]"
} | 0.628183 | Algorithm_12416 | I | [
"calculate_distance",
"tsp_route",
"optimize_delivery_routes"
] | 3 | [
[
"optimize_delivery_routes",
"tsp_route"
],
[
"tsp_route",
"calculate_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 845d4ff973e90061afd54218f794ed3c1f751adc | 12f227598e431877a95aa2a975a2bd184559066d | |||
v1.0 | instruct | Algorithm | Algorithm_12470_I | ### Question:
You have been given an implementation of the Segment Tree data structure that supports point updates and range sum queries. Your task is to extend this data structure by introducing a new method to determine and return the k-th smallest element in a specified subarray range.
**Function Signature**:
```p... | class SegmentTreeNode:
def __init__(self, start, end, count):
self.start = start
self.end = end
self.count = count # Dictionary to store frequency of elements
self.left = None
self.right = None
def build_segment_tree(arr):
def build(start, end):
if start == end:... | import pytest
def test_range_kth_smallest():
arr = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
root = build_segment_tree(arr)
assert range_kth_smallest(root, 0, 4, 3) == 4
assert range_kth_smallest(root, 6, 10, 2) == 1
assert range_kth_smallest(root, 13, 18, 4) == 3
assert... | [] | [
0,
1,
0,
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": "class SegmentTreeNode:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.min_vals = []\n self.left = ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000012470",
"row_id": 12470,
"seed_ids": "[1913]"
} | 0.549834 | Algorithm_12470 | I | [
"build_segment_tree",
"query",
"range_kth_smallest"
] | 3 | [
[
"range_kth_smallest",
"query"
]
] | 1 | [] | false | [
"SegmentTreeNode"
] | true | pytest | false | [] | true | 6317faa29285603b2fa79960d5a923b0103b4a34 | be22b2dd3433cc2b8a9164355d8ce9da90a5e440 | |||
v1.0 | instruct | Algorithm | Algorithm_12475_I | ### Problem Description
You are tasked with implementing a simplified version of a file synchronization tool that can track file changes and synchronize them between two directories. The goal is to identify new, modified, and deleted files in one directory and mirror those changes in another directory.
### Function Sp... | import os
import hashlib
import shutil
def calculate_checksum(file_path):
"""
Calculates the MD5 checksum of a file.
"""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()... | import os
import pytest
import shutil
from solution import track_changes, synchronize
def setup_test_environment(src_structure, dest_structure):
"""
Sets up test environment directories based on the given folder structures.
"""
base_dir = os.path.abspath(os.getcwd())
src_dir = os.path.join(base_di... | [
{
"docstring": "Calculates the MD5 checksum of a file.",
"function_declaration": "def calculate_checksum(file_path):",
"function_name": "calculate_checksum",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def track_changes(src_dir, dest_dir):",
"func... | [
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 os\nimport hashlib\nimport shutil\n\ndef calculate_checksum(file_path):\n \"\"\"\n Calculates the MD5 checksum of a file.\n \"\"\"\n hash_md5 ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000012475",
"row_id": 12475,
"seed_ids": "[1667]"
} | 0.548219 | Algorithm_12475 | I | [
"calculate_checksum",
"track_changes",
"synchronize"
] | 3 | [
[
"synchronize",
"track_changes"
],
[
"track_changes",
"calculate_checksum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8ba9f22dfa6ceb2e411224477ddc129464c63e03 | 5a9f8369aa63f4b0efc78914904248165cffd788 | |||
v1.0 | instruct | Algorithm | Algorithm_12555_I | ### User Authentication System
In a secure application, user authentication is crucial to ensure that only authorized users can access sensitive data. Implement a user authentication system that supports two main operations: registering a new user and logging in an existing user. The system should utilize a hashing me... | import hashlib
# In-memory dictionary to store user credentials
user_credentials = {}
def hash_password(password: str) -> str:
"""Hash the given password using SHA-256."""
return hashlib.sha256(password.encode()).hexdigest()
def register_user(username: str, password: str) -> bool:
"""Register a new user ... | import pytest
from solution import register_user, login_user
def test_register_new_user_success():
assert register_user("user1", "password123") == True
def test_register_existing_user():
assert register_user("user1", "password123") == False
def test_register_with_empty_username():
assert register_user(""... | [
{
"docstring": "Hash the given password using SHA-256.",
"function_declaration": "def hash_password(password):",
"function_name": "hash_password",
"parameter_list": "(password)"
},
{
"docstring": "Register a new user with the given username and password.",
"function_declaration": "def re... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import hashlib\n\n# In-memory dictionary to store user credentials\nuser_database = {}\n\ndef hash_password(password: str) -> str:\n \"\"\"\n Hashes a pass... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012555",
"row_id": 12555,
"seed_ids": "[2233]"
} | 0.533417 | Algorithm_12555 | I | [
"hash_password",
"register_user",
"login_user"
] | 3 | [
[
"login_user",
"hash_password"
],
[
"register_user",
"hash_password"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3004d06108c5c468cc6bfd54ec876564818f7c88 | eaf34038c6f97bacfde6ccc2a20b274c3d5e78a0 | |||
v1.0 | instruct | Algorithm | Algorithm_12612_I | **Context**: You are working as a software engineer in a company that processes large volumes of text data. One common task is to determine the frequency of certain patterns, such as substrings, within this data. For this, efficiently locating all occurrences of a substring within a string is crucial.
**Task**: Write ... | from typing import List
def find_substring_occurrences(text: str, pat: str) -> List[int]:
if not pat:
return []
n, m = len(text), len(pat)
lps = compute_lps(pat)
result = []
i = 0 # index for text
j = 0 # index for pat
while i < n:
if pat[j] == text[i]:
... | from solution import find_substring_occurrences
def test_find_substring_occurrences():
assert find_substring_occurrences("abracadabra", "abra") == [0, 7]
assert find_substring_occurrences("aaaaa", "aa") == [0, 1, 2, 3]
assert find_substring_occurrences("hello world", "world") == [6]
assert find_substri... | [
{
"docstring": null,
"function_declaration": "def find_substring_occurrences(text, pat):",
"function_name": "find_substring_occurrences",
"parameter_list": "(text, pat)"
},
{
"docstring": null,
"function_declaration": "def compute_lps(pat):",
"function_name": "compute_lps",
"para... | [
0,
1,
1,
1,
1,
0,
0,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef find_substring_occurrences(text: str, pat: str) -> List[int]:\n \"\"\"\n Returns a list of all starting indices where the pa... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012612",
"row_id": 12612,
"seed_ids": "[4186]"
} | 0.620305 | Algorithm_12612 | I | [
"find_substring_occurrences",
"compute_lps"
] | 2 | [
[
"find_substring_occurrences",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d87acf68a838d8a0e59efbb3ece41c6acda48e90 | 9dd48167916a63f0915fd5da1a73e8e273215ed1 | |||
v1.0 | instruct | Algorithm | Algorithm_12620_I | ### Question
You are provided with helper functions that calculate the LCM (Least Common Multiple) and GCD (Greatest Common Divisor) of two integers.
Given this, write a function named `complex_integer_analysis` that accomplishes the following:
1. Calculate the GCD of two integers.
2. Calculate the LCM of two integer... | def complex_integer_analysis(a: int, b: int) -> dict:
"""
Analyzes two integers to compute
- GCD of the two integers.
- LCM of the two integers.
- Primality of the first integer.
Returns a dictionary with the results.
"""
result = {}
result['gcd'] = gcd(a, b)
result['lcm'] = lcm... | def test_complex_integer_analysis():
result = complex_integer_analysis(12, 15)
assert result == {'gcd': 3, 'lcm': 60, 'prime': False}
result = complex_integer_analysis(17, 23)
assert result == {'gcd': 1, 'lcm': 391, 'prime': True}
result = complex_integer_analysis(4, 24)
assert result ... | [
{
"docstring": "Analyzes two integers to compute\n- GCD of the two integers.\n- LCM of the two integers.\n- Primality of the first integer.\n\nReturns a dictionary with the results.",
"function_declaration": "def complex_integer_analysis(a, b):",
"function_name": "complex_integer_analysis",
"paramet... | [
1,
1,
1,
0,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def complex_integer_analysis(a: int, b: int) -> dict:\n def gcd(x: int, y: int) -> int:\n while y:\n x, y = y, x % y\n return x\n\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012620",
"row_id": 12620,
"seed_ids": "[3339]"
} | 0.673866 | Algorithm_12620 | I | [
"complex_integer_analysis",
"gcd",
"lcm",
"is_prime"
] | 4 | [
[
"complex_integer_analysis",
"gcd"
],
[
"complex_integer_analysis",
"is_prime"
],
[
"complex_integer_analysis",
"lcm"
],
[
"lcm",
"gcd"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 25067fc378306ee577928be669e190974761ba8c | 34a969cf005aaa1aeeb7aff851c8cf1055bd99cf | |||
v1.0 | instruct | Algorithm | Algorithm_12713_I | ### Program Description
Sorting can be a tricky process, especially dealing with both numbers and words in a list. Your task is to implement a function that sorts a mixed list containing both integers and strings. The function should first separate the integers and strings, sort them independently (integers in ascendin... | def quicksort(arr, key=None):
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2]
left = [x for x in arr if (key(x) if key else x) < (key(pivot) if key else pivot)]
middle = [x for x in arr if (key(x) if key else x) == (key(pivot) if key else pivot)]
right = [x ... | from solution import sort_mixed_list
def test_sort_mixed_list_1():
assert sort_mixed_list([3, 'apple', 1, 'Banana', 2, 'cherry']) == [1, 2, 3, 'apple', 'Banana', 'cherry']
def test_sort_mixed_list_2():
assert sort_mixed_list(['zebra', 'Apple', 'banana', 10, 5]) == [5, 10, 'Apple', 'banana', 'zebra']
def test... | [
{
"docstring": null,
"function_declaration": "def quicksort(arr, key=None):",
"function_name": "quicksort",
"parameter_list": "(arr, key=None)"
},
{
"docstring": "Sorts a mixed list containing both integers and strings.\nIntegers are sorted in ascending order.\nStrings are sorted in case-ins... | [
0,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def sort_mixed_list(mixed_list: list) -> list:\n def quicksort(arr, key=lambda x: x):\n \"\"\"Implements the quicksort algorithm.\"\"\"\n if len... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012713",
"row_id": 12713,
"seed_ids": "[2867]"
} | 0.75581 | Algorithm_12713 | I | [
"quicksort",
"sort_mixed_list"
] | 2 | [
[
"sort_mixed_list",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 314e7ae34290591bba0dface1720c42c76efc148 | a21058c7fdc68c375aeb766fee728284ba9c8582 | |||
v1.0 | instruct | Algorithm | Algorithm_12724_I | ### Maximum Subarray Sum Using Divide and Conquer
#### Context
You are given an array of integers, which can include both positive and negative numbers. Your task is to find the contiguous subarray that has the maximum sum using the divide-and-conquer approach, which is known as the Maximum Subarray Problem.
#### Tas... | def max_crossing_sum(nums, left, mid, right):
# Include elements on left of mid.
left_sum = float('-inf')
sum = 0
for i in range(mid, left - 1, -1):
sum += nums[i]
if sum > left_sum:
left_sum = sum
# Include elements on right of mid.
right_sum = float('-inf')
... | def test_max_subarray_sum():
assert max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
assert max_subarray_sum([1, 2, 3, 4, 5]) == 15
assert max_subarray_sum([-1, -2, -3, -4, -5]) == -1
assert max_subarray_sum([3, -1, 2, -1]) == 4
assert max_subarray_sum([1]) == 1
assert max_subarray_sum([-3... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(nums, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(nums, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_sum_recursive(nums, left, right):",
"funct... | [
1,
0,
1,
0,
1,
0,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(nums, left, mid, right):\n # Include elements on the left of mid\n left_sum = float('-inf')\n sum_ = 0\n for i in range(mid, lef... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012724",
"row_id": 12724,
"seed_ids": "[5265]"
} | 0.790657 | Algorithm_12724 | I | [
"max_crossing_sum",
"max_subarray_sum_recursive",
"max_subarray_sum"
] | 3 | [
[
"max_subarray_sum",
"max_subarray_sum_recursive"
],
[
"max_subarray_sum_recursive",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b1af1d5ccbb1cab58f14aa17d1e92f4e9453e3ce | 1a36bee82f2da8b51168da59ee99abd95cb761c9 | |||
v1.0 | instruct | Algorithm | Algorithm_12728_I | ### Coding Assessment Question: Implementing a Shift Cipher
#### Scenario:
You are working on an encryption module for a secure communication app. Your task is to implement the Shift Cipher (also known as the Caesar Cipher) to provide basic encryption and decryption of user messages. This simple cipher involves shifti... | def shift_encrypt(shift, message):
"""
Encrypt the given message using the Shift Cipher with the given shift value.
Args:
shift (int): The number of positions to shift each letter.
message (str): The message to encrypt.
Returns:
str: The encrypted message.
"""
encrypted_mes... | from solution import shift_encrypt, shift_decrypt
def test_shift_encrypt():
assert shift_encrypt(3, "Hello, World!") == "Khoor, Zruog!"
assert shift_encrypt(0, "Hello, World!") == "Hello, World!"
assert shift_encrypt(26, "Hello, World!") == "Hello, World!"
assert shift_encrypt(-3, "Hello, World!") == "... | [
{
"docstring": "Encrypt the given message using the Shift Cipher with the given shift value.\n\nArgs:\nshift (int): The number of positions to shift each letter.\nmessage (str): The message to encrypt.\n\nReturns:\nstr: The encrypted message.",
"function_declaration": "def shift_encrypt(shift, message):",
... | [
1,
1,
0,
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 shift_encrypt(shift: int, message: str) -> str:\n \"\"\"\n Encrypts the message using the Shift Cipher.\n \"\"\"\n encrypted_message = []\n fo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012728",
"row_id": 12728,
"seed_ids": "[410]"
} | 0.703755 | Algorithm_12728 | I | [
"shift_encrypt",
"shift_decrypt"
] | 2 | [
[
"shift_decrypt",
"shift_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b03cf5504df8ba556d82ad80b06abe18cc4d6a33 | da6d412edc5796f39139cce79ccee888cba519ab | |||
v1.0 | instruct | Algorithm | Algorithm_12739_I | ### Problem Description
In this coding challenge, you are required to implement a function that calculates and visualizes the Mandelbrot set. The Mandelbrot set is a famous fractal that is defined by the set of complex numbers \(c\) for which the function \(f(z) = z^2 + c\) does not diverge when iterated from \(z = 0\... | import numpy as np
from matplotlib import pyplot as plt
import multiprocessing as mp
def mandelbrot(c, max_iter, escape_radius):
z = 0
for i in range(max_iter):
if abs(z) > escape_radius:
return i
z = z * z + c
return max_iter
def compute_row(y, x_min, x_max, y_coord, nb_pixels... | def test_mandelbrot():
# this function will not return any value
# but we can ensure it doesn't raise any exceptions
try:
visualize_mandelbrot_set(50, 2.0, 2.0, 10)
except Exception as e:
assert False, f"visualize_mandelbrot_set raised an exception: {e}"
def test_mandelbrot_convergence(... | [
{
"docstring": null,
"function_declaration": "def mandelbrot(c, max_iter, escape_radius):",
"function_name": "mandelbrot",
"parameter_list": "(c, max_iter, escape_radius)"
},
{
"docstring": null,
"function_declaration": "def compute_row(y, x_min, x_max, y_coord, nb_pixels, max_iter, esca... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef mandelbrot(c, max_iter, escape_radius... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000012739",
"row_id": 12739,
"seed_ids": "[4853]"
} | 0.443549 | Algorithm_12739 | I | [
"mandelbrot",
"compute_row",
"visualize_mandelbrot_set"
] | 3 | [
[
"compute_row",
"mandelbrot"
],
[
"visualize_mandelbrot_set",
"compute_row"
]
] | 2 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy"
] | false | 1308be396303c2259386f992da0e25ce759e1d31 | 49207d8f3931798d7589bee008628486d2296c62 | |||
v1.0 | instruct | Algorithm | Algorithm_12750_I | ### Palindrome Permutation Check
A palindrome is a word or phrase that reads the same forward and backward, ignoring spaces, punctuation, and case. A permutation of a string is any arrangement of its characters. Given a string, determine if any permutation of it is a palindrome.
#### Part 1: Check for Palindrome Perm... | def can_form_palindrome(s: str) -> bool:
"""
Determine if any permutation of the input string can form a palindrome.
:param s: Input string containing alphanumeric characters and spaces
:return: True if any permutation of the input can form a palindrome, False otherwise
"""
import collectio... | def test_can_form_palindrome():
assert can_form_palindrome("Tact Coa") == True
assert can_form_palindrome("Hello") == False
assert can_form_palindrome("A man a plan a canal Panama") == True
assert can_form_palindrome("racecar") == True
assert can_form_palindrome("abc") == False
assert can_form_p... | [
{
"docstring": "Determine if any permutation of the input string can form a palindrome.\n\n:param s: Input string containing alphanumeric characters and spaces\n:return: True if any permutation of the input can form a palindrome, False otherwise",
"function_declaration": "def can_form_palindrome(s):",
"... | [
0,
0,
0,
0,
1,
0,
1,
0,
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 can_form_palindrome(s: str) -> bool:\n \"\"\"\n Check if any permutation of the input string can form a palindrome.\n \"\"\"\n from collections i... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012750",
"row_id": 12750,
"seed_ids": "[4941]"
} | 0.756841 | Algorithm_12750 | I | [
"can_form_palindrome",
"generate_palindrome"
] | 2 | [
[
"generate_palindrome",
"can_form_palindrome"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a049636a9c18f9deb2e222eaff8918be6b42bc63 | 42dc8c5ecd43f0e18f737231e6e46af6fc4a3cd4 | |||
v1.0 | instruct | Algorithm | Algorithm_12759_I | ### Coding Assessment Question
#### Context
A blockchain is a growing list of records, called blocks, linked using cryptography. Each block contains a timestamp, a reference to the previous block, and transaction data. For simplicity, we'll focus on a single aspect of blockchain validation — ensuring that the hash of ... | from typing import List, Dict, Any
import hashlib
def sha256_hash(data: str) -> str:
return hashlib.sha256(data.encode()).hexdigest()
def is_blockchain_valid(blocks: List[Dict[str, Any]]) -> bool:
for i, block in enumerate(blocks):
# Validate the hash of the current block
block_content = f"{bl... | def test_valid_blockchain():
blocks = [
{
"index": 0,
"timestamp": "2023-01-01T00:00:00",
"data": "Genesis Block",
"nonce": 100,
"previous_hash": "0",
"hash": sha256_hash("02023-01-01T00:00:00Genesis Block100")
},
{
... | [
{
"docstring": null,
"function_declaration": "def sha256_hash(data):",
"function_name": "sha256_hash",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def is_blockchain_valid(blocks):",
"function_name": "is_blockchain_valid",
"parameter_list": "(blocks... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Any\nimport hashlib\n\ndef calculate_hash(index: int, timestamp: str, data: str, nonce: int) -> str:\n \"\"\"\n Helper funct... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000012759",
"row_id": 12759,
"seed_ids": "[2217]"
} | 0.564405 | Algorithm_12759 | I | [
"sha256_hash",
"is_blockchain_valid"
] | 2 | [
[
"is_blockchain_valid",
"sha256_hash"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c2210b1f5727d7179c4c0ebcce9202bd6b6dcf93 | bffcf6650d572842217fcb11f775632f329764b4 | |||
v1.0 | instruct | Algorithm | Algorithm_12765_I | ### Problem Statement:
You need to develop a Python script that interacts with a weather API to fetch current weather data for a given city. The resulting data should be printed to the console and optionally saved to a file if a filename is provided. Your function should handle edge cases such as invalid API keys or ne... | import requests
from typing import Optional
def fetch_and_save_weather_data(api_key: str, city: str, filename: Optional[str] = None) -> None:
"""
Fetches current weather data for the specified city and prints the details.
Optionally, saves the data to a provided file.
Parameters:
api_key (str): W... | import pytest
from unittest.mock import patch, mock_open
from solution import fetch_and_save_weather_data
def test_blank_api_key():
with pytest.raises(ValueError):
fetch_and_save_weather_data('', 'London')
@patch('solution.requests.get')
def test_city_not_found(mock_get):
mock_get.return_value.status_... | [
{
"docstring": "Fetches current weather data for the specified city and prints the details. \nOptionally, saves the data to a provided file.\n\nParameters:\napi_key (str): Weather API key.\ncity (str): Name of the city to fetch weather data for.\nfilename (Optional[str]): Name of the file to save the weather da... | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom typing import Optional\n\ndef fetch_and_save_weather_data(api_key: str, city: str, filename: Optional[str] = None) -> None:\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000012765",
"row_id": 12765,
"seed_ids": "[2362]"
} | 0.594001 | Algorithm_12765 | I | [
"fetch_and_save_weather_data",
"print_weather_info"
] | 2 | [
[
"fetch_and_save_weather_data",
"print_weather_info"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | c560b3c11541d7336c58530272ed1ed7435e7c56 | b8acd865bc8b88e8d0b39be4753573c2ad551395 | |||
v1.0 | instruct | Algorithm | Algorithm_12778_I | ### Matrix Rotation: 90-Degree Challenge
Matrix rotation is a fundamental operation in computer graphics and image processing. In this challenge, you are tasked with rotating a given NxN matrix 90 degrees clockwise.
#### Task:
Implement the matrix rotation with two different approaches:
1. A direct element swap appr... | def rotate_in_place(matrix: list[list[int]]) -> None:
"""
Rotates the NxN matrix 90 degrees clockwise in place.
"""
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - i - 1):
temp = matrix[i][j]
matrix[i][j] = matrix[n - j - 1][i]
matrix[n - j -... | from solution import rotate, rotate_in_place, extract_new_matrix
def test_rotate_in_place():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotate_in_place(matrix)
assert matrix == [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
def test_extract_new_matrix():
... | [
{
"docstring": "Rotates the NxN matrix 90 degrees clockwise in place.",
"function_declaration": "def rotate_in_place(matrix):",
"function_name": "rotate_in_place",
"parameter_list": "(matrix)"
},
{
"docstring": "Creates a new NxN matrix representing the original matrix rotated 90 degrees clo... | [
0,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_in_place(matrix):\n \"\"\"\n Rotates the NxN matrix 90 degrees clockwise in place.\n \"\"\"\n n = len(matrix)\n for x in range(n // 2):... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012778",
"row_id": 12778,
"seed_ids": "[3961]"
} | 0.592515 | Algorithm_12778 | I | [
"rotate_in_place",
"extract_new_matrix",
"rotate"
] | 3 | [
[
"rotate",
"extract_new_matrix"
],
[
"rotate",
"rotate_in_place"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 84748ddf59a4d3a3bd6b11690febdb17b87d8da6 | 1270b72075ceec1132a624efbcde9e6f0d0d9f3d | |||
v1.0 | instruct | Algorithm | Algorithm_12815_I | ### Fine-tune Temperature Conversion Functionality
#### Context
You are improving an existing temperature conversion utility that converts temperatures between Celsius, Fahrenheit, and Kelvin. The primary goal is to extend its functionality allowing bulk conversions and robust error handling.
#### Objective
* Enhanc... | def convert_temperature(value: float, src_unit: str, tgt_unit: str) -> float:
"""Convert a temperature value from one unit to another."""
if src_unit == "C":
if tgt_unit == "F":
return value * 9.0 / 5.0 + 32
elif tgt_unit == "K":
return value + 273.15
elif src_unit ==... | def test_convert_bulk_temperatures_valid():
result = convert_bulk_temperatures([(100, 'C', 'F'), (273.15, 'K', 'C'), (-40, 'F', 'C')])
expected = {'conversions': [(100, 'C', 'F', 212.0), (273.15, 'K', 'C', 0.0), (-40, 'F', 'C', -40.0)], 'errors': []}
assert result == expected
def test_convert_bulk_temperat... | [
{
"docstring": "Convert a temperature value from one unit to another.",
"function_declaration": "def convert_temperature(value, src_unit, tgt_unit):",
"function_name": "convert_temperature",
"parameter_list": "(value, src_unit, tgt_unit)"
},
{
"docstring": null,
"function_declaration": "... | [
1,
0,
1,
0,
0,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def convert_temperature(value: float, src_unit: str, tgt_unit: str) -> float:\n \"\"\"Convert a temperature value from one unit to another.\"\"\"\n if src_... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000012815",
"row_id": 12815,
"seed_ids": "[761]"
} | 0.559147 | Algorithm_12815 | I | [
"convert_temperature",
"convert_bulk_temperatures"
] | 2 | [
[
"convert_bulk_temperatures",
"convert_temperature"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9653f9241a2b2a3fecf81df4df3c8ad1a52f0751 | 0f53e62c9631ca816fbc818bb023cb34cfe25469 | |||
v1.0 | instruct | Algorithm | Algorithm_12869_I | ### Question: Determine the Balance Factor of a Binary Tree
In this task, you need to write a Python function that takes the root of a binary tree and returns the balance factor of the tree. The balance factor of a binary tree is defined as the difference between the height of its left subtree and the height of its ri... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def balance_factor(root: TreeNode) -> int:
if root is N... | from solution import TreeNode, balance_factor
def test_empty_tree():
assert balance_factor(None) == 0
def test_single_node():
assert balance_factor(TreeNode(1)) == 0
def test_left_heavy_tree():
root = TreeNode(1, TreeNode(2, TreeNode(3)))
assert balance_factor(root) == 2
def test_right_heavy_tree():... | [] | [
1,
1,
1,
0,
0,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "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 heigh... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012869",
"row_id": 12869,
"seed_ids": "[2838]"
} | 0.750408 | Algorithm_12869 | I | [
"height",
"balance_factor"
] | 2 | [
[
"balance_factor",
"height"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 2b7415805d76c73af81ac88b2029fb7b25700dcb | 2381ec5ee8984b4c4033255f729471fd73e13d58 | |||
v1.0 | instruct | Algorithm | Algorithm_12919_I | ### Scenario
You are developing a string utility library for handling various string operations. One of the tasks in the library is to implement a function that finds the longest palindromic substring within a given string.
### Task
Implement a method `longest_palindromic_substring()` that processes a provided stri... | def longest_palindromic_substring(s: str) -> str:
"""
Find the longest palindromic substring in the given string.
Args:
s (str): The input string to search within.
Returns:
str: The longest palindromic substring.
"""
if not s:
return ""
start, end = 0, 0
for i in rang... | def test_longest_palindromic_substring():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
assert longest_palindromic_substring("cbbd") == "bb"
assert longest_palindromic_substring("a") == "a"
assert longest_palindromic_substring("ac") in ["a", "c"]
assert longest_palindromic_substrin... | [
{
"docstring": "Find the longest palindromic substring in the given string.\n\nArgs:\ns (str): The input string to search within.\n\nReturns:\nstr: The longest palindromic substring.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
... | [
1,
0,
0,
0,
1,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n Find the longest palindromic substring in the given string.\n\n Args:\n s (str): The inp... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012919",
"row_id": 12919,
"seed_ids": "[5174]"
} | 0.764091 | Algorithm_12919 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 38936b77408e83c79e5bdff027e5e42513e4eeb5 | 041b5b3805eee17b5d10c5a5fff233ba80ef3b8e | |||
v1.0 | instruct | Algorithm | Algorithm_12977_I | ### Coding Assessment Question
#### Context
You have been provided with an existing function `encode_string` that takes a string and returns its encoded variant using a custom algorithm. The encoded string may contain a combination of uppercase and lowercase letters but no digits. Your task is to decode a list of enco... | def inverse_encode_string(encoded_string):
"""
Decodes a single encoded string using the inverse of the encoding logic.
The actual implementation of this inverse logic depends on the details of the encoding process.
For the sake of illustration, we will assume a simple encoding logic where each let... | from solution import decode_strings
def test_single_string():
assert decode_strings(["BcDeF"]) == ["AbCdE"]
def test_multiple_strings():
assert decode_strings(["BcDeF", "XyZiK"]) == ["AbCdE", "WxYhJ"]
def test_empty_string():
assert decode_strings([""]) == [""]
def test_all_uppercase():
assert decod... | [
{
"docstring": "Decodes a single encoded string using the inverse of the encoding logic.\nThe actual implementation of this inverse logic depends on the details of the encoding process.\n\nFor the sake of illustration, we will assume a simple encoding logic where each letter was shifted\nby 1 position to the ri... | [
1,
1,
0,
0,
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 inverse_encode_string(encoded_str):\n \"\"\"\n Inverse encoding logic assumed from the 'encode_string' function.\n For demonstration purposes, we wi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012977",
"row_id": 12977,
"seed_ids": "[1887]"
} | 0.677252 | Algorithm_12977 | I | [
"inverse_encode_string",
"decode_strings"
] | 2 | [
[
"decode_strings",
"inverse_encode_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ff083481deaa879e366e0d8e16ea925325cd1e0d | 7025daa606d70ebd3c58dec0a5a2310bc4e8323c | |||
v1.0 | instruct | Algorithm | Algorithm_12983_I | ### Matrix Multiplication Optimization
You are to implement a naive matrix multiplication algorithm and improve it using the Strassen algorithm. Compare the performance of both algorithms using different sizes of square matrices.
### Function Descriptions
1. **naive_multiplication(mat1: List[List[int]], mat2: List[L... | import time
from typing import List, Dict
def naive_multiplication(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
"""
Perform matrix multiplication using the naive approach.
"""
size = len(mat1)
result = [[0] * size for _ in range(size)]
for i in range(size):
for j in... | import pytest
from solution import naive_multiplication, strassen_multiplication
def test_naive_multiplication():
mat1 = [
[1, 2],
[3, 4]
]
mat2 = [
[5, 6],
[7, 8]
]
expected_output = [
[19, 22],
[43, 50]
]
assert naive_multiplication(mat1, ma... | [
{
"docstring": "Perform matrix multiplication using the naive approach.",
"function_declaration": "def naive_multiplication(mat1, mat2):",
"function_name": "naive_multiplication",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Perform matrix multiplication using Strassen's algorithm.",
... | [
1,
1,
1,
0,
0,
1,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\nfrom typing import List, Dict\n\ndef naive_multiplication(mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Naive O... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012983",
"row_id": 12983,
"seed_ids": "[770]"
} | 0.497933 | Algorithm_12983 | I | [
"naive_multiplication",
"strassen_multiplication",
"performance_comparison"
] | 3 | [
[
"performance_comparison",
"naive_multiplication"
],
[
"performance_comparison",
"strassen_multiplication"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ada95f0bced96c78c94555ce1c7b4bfd2b03596f | ecfe46af6d34c6dec59e2c8adf1316760f5ea1c4 | |||
v1.0 | instruct | Algorithm | Algorithm_12990_I | ### Scenario
You have joined a software company that is building a new text processing library. One component of this library involves handling strings and implementing essential text manipulation functions. Your task is to create a set of string utility functions which will be crucial for various features across the l... | def reverse_string(s):
"""
Returns the given string reversed.
"""
return s[::-1]
def is_palindrome(s):
"""
Checks if the given string is a palindrome.
"""
reversed_s = reverse_string(s)
return s == reversed_s
def count_vowels(s):
"""
Counts the number of vowels (a, e, i, o,... | from solution import reverse_string, is_palindrome, count_vowels, find_substring, capitalize_words
def test_reverse_string():
assert reverse_string("hello") == "olleh"
assert reverse_string("") == ""
assert reverse_string("a") == "a"
assert reverse_string("racecar") == "racecar"
def test_is_palindrome... | [
{
"docstring": "Returns the given string reversed.",
"function_declaration": "def reverse_string(s):",
"function_name": "reverse_string",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"functio... | [
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def reverse_string(s):\n \"\"\"\n Reverses a given string.\n \"\"\"\n return s[::-1]\n\ndef is_palindrome(s):\n \"\"\"\n Checks if a given stri... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000012990",
"row_id": 12990,
"seed_ids": "[5349]"
} | 0.65741 | Algorithm_12990 | I | [
"reverse_string",
"is_palindrome",
"count_vowels",
"find_substring",
"capitalize_words"
] | 5 | [
[
"is_palindrome",
"reverse_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 14cbcea75b4218071b7fb76fe3581f724c45ceb1 | d6666aa1f84f072e12e26257072d71600e1528a6 | |||
v1.0 | instruct | Algorithm | Algorithm_13014_I | ### Coding Assessment Question
You are given a list of integers, which form a bitonic sequence — a sequence that is first strictly increasing and then strictly decreasing. Your task is to implement an efficient algorithm to find the k-th smallest element in the list using a modified binary search strategy.
#### Funct... | def find_peak(lst):
"""
Returns the index of the peak element in the bitonic sequence using binary search.
"""
left, right = 0, len(lst) - 1
while left < right:
mid = (left + right) // 2
if lst[mid] > lst[mid + 1]:
right = mid
else:
left = mid + 1
... | def test_find_kth_smallest_in_bitonic():
assert find_kth_smallest_in_bitonic([1, 3, 8, 12, 4, 2], 1) == 1
assert find_kth_smallest_in_bitonic([1, 3, 8, 12, 4, 2], 4) == 4
assert find_kth_smallest_in_bitonic([10, 20, 30, 40, 30, 20, 10], 5) == 30
assert find_kth_smallest_in_bitonic([1, 3, 5, 7, 9, 8, 6, ... | [
{
"docstring": "Returns the index of the peak element in the bitonic sequence using binary search.",
"function_declaration": "def find_peak(lst):",
"function_name": "find_peak",
"parameter_list": "(lst)"
},
{
"docstring": "Returns the index of the target element in the lst within the range [... | [
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 find_kth_smallest_in_bitonic(lst: list[int], k: int) -> int:\n def find_peak(lst):\n left, right = 0, len(lst) - 1\n while left < right:\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000013014",
"row_id": 13014,
"seed_ids": "[4737]"
} | 0.645817 | Algorithm_13014 | I | [
"find_peak",
"binary_search",
"find_kth_smallest_in_bitonic"
] | 3 | [
[
"find_kth_smallest_in_bitonic",
"find_peak"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 66b540818e7f45a49ec6fd604017101ef749a9fe | 61b2767e73ca4b3798985efda93800f3c523ed6f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.