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_13045_I | ### Maximum Subarray Sum with Circumference Wrap-Around
#### Scenario
You are given an array of integers that represents periodic measurements (say temperature readings throughout the day). Therefore, the array should be considered circular, where the last element is followed by the first element. You need to find the... | def max_subarray_sum(nums):
max_ending_here = max_so_far = nums[0]
for x in nums[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def max_circular_subarray_sum(nums: list[int]) -> int:
max_kadane = max_subarray_sum(nums)
... | from solution import max_circular_subarray_sum
def test_single_element():
assert max_circular_subarray_sum([1]) == 1
assert max_circular_subarray_sum([-1]) == -1
def test_all_positive():
assert max_circular_subarray_sum([1, 2, 3, 4, 5]) == 15
def test_all_negative():
assert max_circular_subarray_sum(... | [
{
"docstring": null,
"function_declaration": "def max_subarray_sum(nums):",
"function_name": "max_subarray_sum",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def max_circular_subarray_sum(nums):",
"function_name": "max_circular_subarray_sum",
"param... | [
1,
1,
0,
0,
0,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_circular_subarray_sum(nums: list[int]) -> int:\n if not nums:\n return 0\n\n def kadane(arr):\n local_max = global_max = arr[0]\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000013045",
"row_id": 13045,
"seed_ids": "[1221]"
} | 0.626289 | Algorithm_13045 | I | [
"max_subarray_sum",
"max_circular_subarray_sum"
] | 2 | [
[
"max_circular_subarray_sum",
"max_subarray_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee132c3d63b976ec26a068faaf42c2415bb5fd8c | 0358290d124de6cbd5bb9dce5120bcbf0ebacb49 | |||
v1.0 | instruct | Algorithm | Algorithm_13048_I | ### Binary Search Tree (BST) Insertion and Range Sum Query
You are tasked with implementing a Binary Search Tree (BST) and creating a function to calculate the sum of all values within a given range. This exercise will test your understanding of fundamental data structures and tree traversal algorithms.
#### Problem ... | class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return BSTNode(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.righ... | from solution import BSTNode, insert, range_sum_bst, build_bst_from_list
def test_insert():
root = None
values = [10, 5, 15, 3, 7, 18]
for value in values:
root = insert(root, value)
assert(root.value == 10)
assert(root.left.value == 5)
assert(root.right.value == 15)
assert(root.le... | [] | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef insert(root, value):\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013048",
"row_id": 13048,
"seed_ids": "[1704]"
} | 0.563717 | Algorithm_13048 | I | [
"insert",
"range_sum_bst",
"build_bst_from_list"
] | 3 | [
[
"build_bst_from_list",
"insert"
]
] | 1 | [] | false | [
"BSTNode"
] | true | pytest | true | [] | true | 5fa91dc6803bba6f82c8a7ec2b9aff0d037b3941 | c2d0c080bee51e54137f7f23fde94aa02518822e | |||
v1.0 | instruct | Algorithm | Algorithm_13055_I | ### Question
**Robot Path Navigator**
You are given a grid of `N x N` dimensions where each cell can either be empty (represented by `0`) or contain an obstacle (represented by `1`). Your task is to implement a function that determines if there exists a path for a robot to move from the top-left corner (0, 0) to the b... | from collections import deque
def is_valid(grid, x, y, N):
"""
Checks if the given coordinates are within the grid bounds and if the cell is not an obstacle.
"""
return 0 <= x < N and 0 <= y < N and grid[x][y] == 0
def bfs(grid, N):
"""
Performs BFS to find if there is a path from top-left cor... | from solution import robot_path_exists
def test_robot_path_exists_case1():
grid = [
[0, 1, 0],
[0, 0, 0],
[1, 0, 0]
]
updates = [(1, 1, 1), (2, 1, 1), (2, 2, 1)]
assert not robot_path_exists(grid, updates)
def test_robot_path_exists_case2():
grid = [
[0, 0, 1],
... | [
{
"docstring": "Checks if the given coordinates are within the grid bounds and if the cell is not an obstacle.",
"function_declaration": "def is_valid(grid, x, y, N):",
"function_name": "is_valid",
"parameter_list": "(grid, x, y, N)"
},
{
"docstring": "Performs BFS to find if there is a path... | [
1,
0,
0,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def robot_path_exists(grid: list[list[int]], updates: list[tuple[int, int, int]]) -> bool:\n from collections import deque\n\n def bfs(start, end, grid):\n... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000013055",
"row_id": 13055,
"seed_ids": "[3234]"
} | 0.657933 | Algorithm_13055 | I | [
"is_valid",
"bfs",
"robot_path_exists"
] | 3 | [
[
"bfs",
"is_valid"
],
[
"robot_path_exists",
"bfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b47574ae3c70d90d3737729af8d14d0ecad8aaf0 | 6c4e7dce33623ea89848862a3c480318cb62f048 | |||
v1.0 | instruct | Algorithm | Algorithm_13071_I | ### Coding Challenge: Fibonacci Sequence and Summation
#### Context:
You are doing research on mathematical sequences and need to implement functions related to the Fibonacci sequence. The Fibonacci numbers have applications in data structures, algorithms, and number theory.
#### Function 1: Efficient Fibonacci Gene... | from typing import List
def fibonacci_sequence(n: int) -> List[int]:
"""
Returns the first n Fibonacci numbers.
"""
if n == 1:
return [0]
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence
def fibonacci_sum_range(s... | from solution import fibonacci_sequence, fibonacci_sum_range
def test_fibonacci_sequence():
assert fibonacci_sequence(1) == [0]
assert fibonacci_sequence(2) == [0, 1]
assert fibonacci_sequence(5) == [0, 1, 1, 2, 3]
assert fibonacci_sequence(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def test_fibonacci_s... | [
{
"docstring": "Returns the first n Fibonacci numbers.",
"function_declaration": "def fibonacci_sequence(n):",
"function_name": "fibonacci_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of Fibonacci numbers in the range specified by start and end (inclusive, 1-based in... | [
1,
0,
0,
0,
1,
0,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef fibonacci_sequence(n: int) -> List[int]:\n \"\"\"\n Returns the first n Fibonacci numbers.\n \"\"\"\n if n <= 0:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013071",
"row_id": 13071,
"seed_ids": "[4272]"
} | 0.690176 | Algorithm_13071 | I | [
"fibonacci_sequence",
"fibonacci_sum_range"
] | 2 | [
[
"fibonacci_sum_range",
"fibonacci_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d8fe2c57a680720235cd43772d6af4be6042776f | 7a049abb618b7cbe6b1b7dabec058c5706bff844 | |||
v1.0 | instruct | Algorithm | Algorithm_13075_I | ### Binary Search Tree (BST) Level Order Traversal
A Binary Search Tree (BST) is a node-based binary tree data structure where each node has at most two children referred to as the left child and the right child. For this question, you need to implement the function which performs a level-order traversal on a BST. A l... | from typing import List, Optional
from collections import deque
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: Optional[TreeNode], val: int) -> TreeNode:
if root is None:
return Tree... | from solution import bst_level_order_traversal
def test_bst_level_order_traversal_example1():
assert bst_level_order_traversal([10, 6, 15, 3, 8, 12, 18]) == [[10], [6, 15], [3, 8, 12, 18]]
def test_bst_level_order_traversal_example2():
assert bst_level_order_traversal([7, 3, 9, 1, 4, 8, 10]) == [[7], [3, 9], ... | [] | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List, Optional\n\nclass TreeNode:\n def __init__(self, val: int):\n self.val = val\n self.left... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013075",
"row_id": 13075,
"seed_ids": "[3579]"
} | 0.551467 | Algorithm_13075 | I | [
"insert_into_bst",
"bst_level_order_traversal"
] | 2 | [
[
"bst_level_order_traversal",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 31daf0571b77bfeecf6c1313755f5af0384357c7 | 8675fa596e186ca5be0f9ca0c7b9d1b23c3f63ce | |||
v1.0 | instruct | Algorithm | Algorithm_13078_I | ### Reverse Words in a String
**Background**:
In natural language processing and communication systems, managing and manipulating text is a common requirement. Reversing the words in a string is a technique used in various applications, including data obfuscation, transformation, and certain text algorithms.
**Task**... | def reverse_words(sentence):
"""
Takes a string sentence containing multiple words and returns
a string with the words in reverse order.
Parameters:
sentence (str): Input string with multiple words.
Returns:
str: A string with the words in reverse order.
"""
words = sentenc... | from solution import reverse_words, match_pattern
def test_reverse_words_single_word():
assert reverse_words("hello") == "hello"
def test_reverse_words_multiple_words():
assert reverse_words("hello world") == "world hello"
assert reverse_words("my name is python") == "python is name my"
def test_reverse_... | [
{
"docstring": "Takes a string sentence containing multiple words and returns\na string with the words in reverse order.\n\nParameters:\nsentence (str): Input string with multiple words.\n\nReturns:\nstr: A string with the words in reverse order.",
"function_declaration": "def reverse_words(sentence):",
... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def reverse_words(sentence):\n \"\"\"\n Reverses the order of words in a given sentence.\n \n Args:\n sentence (str): A string containing multiple... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013078",
"row_id": 13078,
"seed_ids": "[1853]"
} | 0.673135 | Algorithm_13078 | I | [
"reverse_words",
"match_pattern"
] | 2 | [
[
"match_pattern",
"reverse_words"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f402ba3e03239f99b72e10e365f7be97c3294649 | edfdb7ca75628530e8c44fe3e8d8d1b359b3ffa2 | |||
v1.0 | instruct | Algorithm | Algorithm_13139_I | ### Checking a Binary Tree Symmetry
#### Problem Statement:
Given the root of a binary tree, check whether the tree is a mirror of itself (i.e., symmetric around its center).
#### Function Signature:
```python
def is_symmetric(root: 'TreeNode') -> bool:
```
#### Input:
* **root**: The root node of the binary tree. ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_mirror(left: 'TreeNode', right: 'TreeNode') -> bool:
# If both nodes are None, they are mirrors
if left is None and right is None:
return True
# If... | from solution import TreeNode, is_symmetric
def test_symmetric_tree():
root = TreeNode(1)
root.left = TreeNode(2, TreeNode(3), TreeNode(4))
root.right = TreeNode(2, TreeNode(4), TreeNode(3))
assert is_symmetric(root) == True
def test_non_symmetric_tree():
root = TreeNode(1)
root.left = TreeNod... | [] | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "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_mi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013139",
"row_id": 13139,
"seed_ids": "[4667]"
} | 0.641696 | Algorithm_13139 | I | [
"is_mirror",
"is_symmetric"
] | 2 | [
[
"is_symmetric",
"is_mirror"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 252bfe77f8c8874564bb17a2c0db75a5afa7ec5f | 74d6466c1389daf3a07facf45204a6cc7eecde51 | |||
v1.0 | instruct | Algorithm | Algorithm_13142_I | ### AVL Tree Implementation and Range Sum Query
You are to implement an AVL Tree and perform a range sum query. AVL Trees are self-balancing binary search trees that maintain height balance for efficient querying.
#### Task 1: AVL Tree Construction
Write a function, `insert(root: AVLNode, key: int) -> AVLNode`, that ... | class AVLNode:
def __init__(self, key):
self.key = key
self.height = 1
self.left = None
self.right = None
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)... | from solution import AVLNode, insert, range_sum
def test_insert_and_balance():
keys = [20, 4, 15, 10, 22, 18, 80]
root = None
for key in keys:
root = insert(root, key)
# Check the AVL tree properties
assert root.key == 15 # After balancing the tree
def test_range_sum():
keys = [20, 4... | [] | [
1,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class AVLNode:\n def __init__(self, key):\n self.key = key\n self.height = 1\n self.left = None\n self.right = None\n \ndef... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000013142",
"row_id": 13142,
"seed_ids": "[1641]"
} | 0.572574 | Algorithm_13142 | I | [
"get_height",
"update_height",
"get_balance",
"right_rotate",
"left_rotate",
"insert",
"range_sum"
] | 7 | [
[
"get_balance",
"get_height"
],
[
"insert",
"get_balance"
],
[
"insert",
"left_rotate"
],
[
"insert",
"right_rotate"
],
[
"insert",
"update_height"
],
[
"left_rotate",
"update_height"
],
[
"right_rotate",
"update_height"
],
[
"... | 8 | [] | false | [
"AVLNode"
] | true | pytest | true | [] | true | 36b1a2f39f9d29ac83a44ef8562b6d88c6664e72 | 558a5a3d6d9e5e7fabb87fee980c206568065913 | |||
v1.0 | instruct | Algorithm | Algorithm_13179_I | ### Coding Exercise: Identifying Primes in a Matrix
**Objective**:
Leverage the techniques from matrix operations and number theory to identify prime numbers within a 2D matrix and replace all prime numbers with their respective index pairs.
### Specification:
1. Implement a function `is_prime(n: int) -> bool` that ... | def is_prime(n: int) -> bool:
"""
Check if a number is a prime.
Parameters:
n (int): The number to check.
Returns:
bool: True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
... | from solution import is_prime, update_matrix
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(-3) == False
assert is_prime(13) == True... | [
{
"docstring": "Check if a number is a prime.\n\nParameters:\nn (int): The number to check.\n\nReturns:\nbool: True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Update the matrix... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is a prime.\n \n Parameters:\n n (int): The number to check.\n \n Returns:\n b... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013179",
"row_id": 13179,
"seed_ids": "[274]"
} | 0.597198 | Algorithm_13179 | I | [
"is_prime",
"update_matrix"
] | 2 | [
[
"update_matrix",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2f955f9faf31b4535e47a1dd75310a80b1c97602 | 195f942c673693d5435d82d33859ee07ae73ae93 | |||
v1.0 | instruct | Algorithm | Algorithm_13184_I | ### Coding Challenge
You are tasked with developing a feature for a library management system to enhance book recommendation accuracy based on previous borrower histories and genre preferences. The system shall analyze user borrowing patterns and deliver a tailored selection of recommended books.
#### Requirements:
1... | from collections import defaultdict
def collaborative_filtering_recommendation(borrowing_history, library_catalog, already_borrowed):
# Placeholder function: Assumes borrowed books influence recommendation based on genre popularity
genre_count = defaultdict(int)
for _, genre in borrowing_history:
g... | def test_collaborative_filtering_recommendation():
borrowing_history = [(1, 'Fiction'), (2, 'Science Fiction'), (3, 'Science')]
library_catalog = [(4, 'Fiction'), (5, 'Science Fiction'), (6, 'Science'), (7, 'Fantasy'), (8, 'Fiction')]
already_borrowed = [1, 3]
result = collaborative_filtering_recommenda... | [
{
"docstring": null,
"function_declaration": "def collaborative_filtering_recommendation(borrowing_history, library_catalog, already_borrowed):",
"function_name": "collaborative_filtering_recommendation",
"parameter_list": "(borrowing_history, library_catalog, already_borrowed)"
},
{
"docstr... | [
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": "from collections import defaultdict\n\ndef collaborative_filtering_recommendation(borrowing_history, K, already_borrowed):\n # Placeholder for a simple most p... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013184",
"row_id": 13184,
"seed_ids": "[716]"
} | 0.500602 | Algorithm_13184 | I | [
"collaborative_filtering_recommendation",
"content_based_recommendation",
"hybrid_recommendation",
"precision_at_k",
"recommendation_accuracy_checker"
] | 5 | [
[
"hybrid_recommendation",
"collaborative_filtering_recommendation"
],
[
"hybrid_recommendation",
"content_based_recommendation"
],
[
"recommendation_accuracy_checker",
"precision_at_k"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | fd0a1dc70128380e5302652c865f515837beff48 | c775e9b5945e38fad79a0fa6250a3160065f610b | |||
v1.0 | instruct | Algorithm | Algorithm_13185_I | ### Coding Assessment Question
Develop a program to manage and evaluate employees’ performance metrics in a company. Each employee has a unique ID and is evaluated based on three categories: productivity score, punctuality score, and teamwork score.
You are given five functions:
1. `average_score(employee_id: int) -... | # Sample employee data for demonstration purposes
employees_data = {
101: {'productivity': 90, 'punctuality': 88, 'teamwork': 82},
102: {'productivity': 75, 'punctuality': 80, 'teamwork': 78},
103: {'productivity': 85, 'punctuality': 88, 'teamwork': 90},
}
def average_score(employee_id):
data = employe... | import pytest
from solution import employee_evaluation, employees_data
def test_average_score():
assert employee_evaluation(101, "average") == pytest.approx(86.66, 0.01)
def test_highest_score_category():
assert employee_evaluation(101, "highest") == "productivity"
assert employee_evaluation(102, "highes... | [
{
"docstring": null,
"function_declaration": "def average_score(employee_id):",
"function_name": "average_score",
"parameter_list": "(employee_id)"
},
{
"docstring": null,
"function_declaration": "def highest_score_category(employee_id):",
"function_name": "highest_score_category",
... | [
0,
0,
0,
1,
0,
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": "# Define the employee database for testing purposes\nemployee_db = {\n 101: {'productivity': 88, 'punctuality': 85, 'teamwork': 87},\n 102: {'productivity'... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013185",
"row_id": 13185,
"seed_ids": "[639]"
} | 0.656988 | Algorithm_13185 | I | [
"average_score",
"highest_score_category",
"lowest_score_category",
"improve_score",
"is_promotion_eligible",
"employee_evaluation"
] | 6 | [
[
"employee_evaluation",
"average_score"
],
[
"employee_evaluation",
"highest_score_category"
],
[
"employee_evaluation",
"improve_score"
],
[
"employee_evaluation",
"is_promotion_eligible"
],
[
"employee_evaluation",
"lowest_score_category"
],
[
"is_p... | 6 | [] | false | [] | false | pytest | true | [] | true | f87b61199855567ebdb4929322b1a6d4ee314023 | 564a10bbab9595a88e121fcb6ec3fa85d1791210 | |||
v1.0 | instruct | Algorithm | Algorithm_13305_I | ### Prime Path Challenge
You are tasked with implementing a function to determine if there is a path of prime numbers between two given points in a matrix. A prime path is a sequence of moves from one cell to an adjacent cell (vertically or horizontally) where all cells in the path contain prime numbers.
#### Functi... | from typing import List, Tuple
from collections import deque
def is_prime(n: int) -> bool:
""" Check if a number is prime."""
if n <= 1:
return False
if n == 2:
return True # 2 is the only even prime number
if n % 2 == 0:
return False
max_divisor = int(n**0.5) + 1
for d... | from solution import is_prime_path
def test_is_prime_path():
matrix = [
[2, 4, 3],
[5, 9, 7],
[11, 13, 8]
]
start = (0, 0)
end = (2, 1)
assert is_prime_path(matrix, start, end) == True
start = (0, 0)
end = (2, 2)
assert is_prime_path(matrix, start, end) == False... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Determine if there is a prime path from start to end in the matrix. ",
"function_declaration": "def is_prime_path(matrix, star... | [
0,
0,
1,
1,
0,
1,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000013305",
"row_id": 13305,
"seed_ids": "[236]"
} | 0.605965 | Algorithm_13305 | I | [
"is_prime",
"is_prime_path"
] | 2 | [
[
"is_prime_path",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05c967eb783bd1965fa50b3cc5f11c4efd92e677 | 547d9a075997c94f9169551bc6c97513cd9046e6 | |||
v1.0 | instruct | Algorithm | Algorithm_13307_I | ### Color Palette Optimization
**Context**: You are developing a software for a digital artist who frequently changes the color palette in their work. The artist wishes to have their colors sorted in a way that they transition smoothly from one hue to another to facilitate better artistic workflow.
**Task**:
Write a... | import math
def color_distance(color1, color2):
"""
Helper function to calculate the Euclidean distance between two RGB colors.
"""
return math.sqrt((color2[0] - color1[0]) ** 2 + (color2[1] - color1[1]) ** 2 + (color2[2] - color1[2]) ** 2)
def smooth_color_sort(colors):
"""
Sorts a list of RG... | from solution import smooth_color_sort, color_distance
def test_color_distance():
assert color_distance((0, 0, 0), (0, 0, 0)) == 0
assert color_distance((0, 0, 0), (255, 255, 255)) == math.sqrt(3 * (255 ** 2))
assert color_distance((255, 0, 0), (0, 255, 0)) == math.sqrt(255 ** 2 + 255 ** 2)
assert colo... | [
{
"docstring": "Helper function to calculate the Euclidean distance between two RGB colors.",
"function_declaration": "def color_distance(color1, color2):",
"function_name": "color_distance",
"parameter_list": "(color1, color2)"
},
{
"docstring": "Sorts a list of RGB colors such that the tra... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(color1, color2):\n return math.sqrt((color2[0] - color1[0]) ** 2 +\n (color2[1] - color1[1]) ** 2 +\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013307",
"row_id": 13307,
"seed_ids": "[1301]"
} | 0.491446 | Algorithm_13307 | I | [
"color_distance",
"smooth_color_sort"
] | 2 | [
[
"smooth_color_sort",
"color_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 60a52998fd7d7cad1357358605f0f69db2b15c6c | 72b2415c9ff19a3c1fbd223d3a3224a1835ee391 | |||
v1.0 | instruct | Algorithm | Algorithm_13317_I | ### Question: Matrix Diagonal Sum and Trace
You are provided with two individual tasks. Write two functions to achieve the following:
#### Task 1: Sum of Matrix Diagonal
Write a function `sum_of_diagonal(matrix: List[List[int]]) -> int` that calculates the sum of all the elements on the main diagonal of a given squar... | def sum_of_diagonal(matrix: list) -> int:
if not matrix or any(len(row) != len(matrix) for row in matrix):
raise ValueError("Input must be a non-empty square matrix.")
return sum(matrix[i][i] for i in range(len(matrix)))
def matrix_trace(matrix: list) -> int:
return sum_of_diagonal(matrix) | import pytest
from solution import sum_of_diagonal, matrix_trace
def test_sum_of_diagonal():
assert sum_of_diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 15
assert sum_of_diagonal([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) == 15
assert sum_of_diagonal([[2, 1], [1, 2]]) == 4
def test_matrix_trace():
assert mat... | [
{
"docstring": null,
"function_declaration": "def sum_of_diagonal(matrix):",
"function_name": "sum_of_diagonal",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def matrix_trace(matrix):",
"function_name": "matrix_trace",
"parameter_list": "(matrix)"... | [
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 sum_of_diagonal(matrix: list) -> int:\n \"\"\"\n Returns the sum of the main diagonal elements of a given square matrix.\n \"\"\"\n if not matrix... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013317",
"row_id": 13317,
"seed_ids": "[3599]"
} | 0.504546 | Algorithm_13317 | I | [
"sum_of_diagonal",
"matrix_trace"
] | 2 | [
[
"matrix_trace",
"sum_of_diagonal"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fb8093d90b48b17741d1c9e0f3f9c2e41472a3db | d7cea8fa8d9cd48917351a3948079935a3a1b877 | |||
v1.0 | instruct | Algorithm | Algorithm_13346_I | ### Coding Assessment Question
**Title**: Build and Test a Recommendation System
**Task**:
Using the provided dataset management and collaborative filtering methods, implement a function to process a dataset, generate movie recommendations for a specific user, and evaluate the recommendations using precision and reca... | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, recall_score
def data_handling(data: pd.DataFrame) -> tuple:
"""
Handle the data processing step.
Args:
- data (pd.DataFrame): The dataset containing 'userId', '... | import pandas as pd
from solution import evaluate_recommendation_system
def test_valid_evaluation():
data = pd.DataFrame({
'userId': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'movieId': [10, 20, 30, 40, 50, 60, 70, 80, 90],
'rating': [4, 5, 3, 2, 5, 5, 4, 3, 2]
})
evaluate_recommendation_system(... | [
{
"docstring": "Handle the data processing step.\n\nArgs:\n- data (pd.DataFrame): The dataset containing 'userId', 'movieId', and 'rating' columns.\n\nReturns:\n- users (np.array): Unique user IDs.\n- movies (np.array): Unique movie IDs.",
"function_declaration": "def data_handling(data):",
"function_na... | [
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": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_score, recall_score\n\ndef data_handling(data: p... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013346",
"row_id": 13346,
"seed_ids": "[506]"
} | 0.608802 | Algorithm_13346 | I | [
"data_handling",
"collaborative_filtering",
"evaluate_recommendation_system"
] | 3 | [
[
"evaluate_recommendation_system",
"collaborative_filtering"
],
[
"evaluate_recommendation_system",
"data_handling"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | a41f399b1cc694c51b6a7c1487a61a94e66e575d | fe7d438c09bf30c0a87252dc6b4ee93ccf62bbeb | |||
v1.0 | instruct | Algorithm | Algorithm_13353_I | ### Question
#### Scenario:
You are developing a system to manage a collection of files and their related operations. One essential aspect of this system is organizing the files in such a way that allows for quick retrieval, insertion, and removal. To achieve this, you decide to implement a Min-Heap data structure, wh... | def insert(heap, new_value):
"""
Inserts a new_value into the Min-Heap and maintains the heap property.
"""
heap.append(new_value)
_bubble_up(heap, len(heap) - 1)
def remove_min(heap):
"""
Removes and returns the minimum element from the Min-Heap while maintaining the heap property.
"""... | from solution import insert, remove_min, heapify
def test_heapify():
assert heapify([15, 10, 25, 6, 14, 20, 60]) == [6, 10, 20, 15, 14, 25, 60]
assert heapify([3, 1, 2]) == [1, 3, 2]
assert heapify([]) == []
assert heapify([1]) == [1]
def test_insert():
heap = heapify([15, 10, 25, 6, 14, 20, 60])
... | [
{
"docstring": "Inserts a new_value into the Min-Heap and maintains the heap property.",
"function_declaration": "def insert(heap, new_value):",
"function_name": "insert",
"parameter_list": "(heap, new_value)"
},
{
"docstring": "Removes and returns the minimum element from the Min-Heap while... | [
1,
1,
0,
0,
1,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def insert(heap, new_value):\n \"\"\"\n Inserts a new_value into the Min-Heap and maintains the heap property.\n \"\"\"\n # Add the new value to the ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000013353",
"row_id": 13353,
"seed_ids": "[1495]"
} | 0.691396 | Algorithm_13353 | I | [
"insert",
"remove_min",
"heapify",
"_bubble_up",
"_bubble_down"
] | 5 | [
[
"heapify",
"_bubble_down"
],
[
"insert",
"_bubble_up"
],
[
"remove_min",
"_bubble_down"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f6edeba1b58fb43b4e378a46e89ca5b1d29bf8db | 48edb4a737ce9a98149bebc5e98077787b9ef421 | |||
v1.0 | instruct | Algorithm | Algorithm_13359_I | ### Number System Validation and Conversion
Implement a set of functions to validate and convert different representations of numbers: binary (base-2), octal (base-8), decimal (base-10), and hexadecimal (base-16). The functions should be able to:
1. Validate if a given string can be a valid representation of a number... | def is_valid_number(number_str: str, base: int) -> bool:
"""
Checks if the given string is a valid number in the specified base.
"""
try:
int(number_str, base)
return True
except ValueError:
return False
def convert_number(number_str: str, from_base: int, to_base: int) -> st... | def test_is_valid_number():
assert is_valid_number("1010", 2) == True
assert is_valid_number("123", 2) == False
assert is_valid_number("1F4", 16) == True
assert is_valid_number("1G4", 16) == False
assert is_valid_number("745", 8) == True
assert is_valid_number("985", 8) == False
assert is_va... | [
{
"docstring": "Checks if the given string is a valid number in the specified base.",
"function_declaration": "def is_valid_number(number_str, base):",
"function_name": "is_valid_number",
"parameter_list": "(number_str, base)"
},
{
"docstring": "Converts a number string from one base to anot... | [
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": "def is_valid_number(number_str: str, base: int) -> bool:\n \"\"\"\n This function takes a string `number_str` and an integer `base`\n It returns `True` ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000013359",
"row_id": 13359,
"seed_ids": "[4065]"
} | 0.624257 | Algorithm_13359 | I | [
"is_valid_number",
"convert_number"
] | 2 | [
[
"convert_number",
"is_valid_number"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | b566599b23e5a455358202973a2e33cfa8370e23 | d246895a29ad021ba1cddb444276fb65156715bf | |||
v1.0 | instruct | Algorithm | Algorithm_13436_I | ### Problem Statement
You are given a binary tree represented as a list of lists, where each list corresponds to a level of the tree. Your task is to write a function that, given this level-order representation, converts it into a binary tree data structure and then returns the post-order traversal of the tree.
**Fun... | from typing import List, Optional
from collections import deque
class TreeNode:
def __init__(self, x: int):
self.val = x
self.left = None
self.right = None
def build_tree(levels: List[List[int]]) -> Optional[TreeNode]:
if not levels:
return None
root = TreeNode(levels[... | from solution import post_order_traversal
def test_empty_tree():
assert post_order_traversal([]) == []
def test_single_node_tree():
assert post_order_traversal([[1]]) == [1]
def test_two_levels_tree():
assert post_order_traversal([[1], [2, 3]]) == [2, 3, 1]
def test_three_levels_tree():
levels = [
... | [] | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\n\nclass TreeNode:\n def __init__(self, x: int):\n self.val = x\n self.left = None\n self.right = None\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000013436",
"row_id": 13436,
"seed_ids": "[4550]"
} | 0.515449 | Algorithm_13436 | I | [
"build_tree",
"post_order_traversal"
] | 2 | [
[
"post_order_traversal",
"build_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1210851c624ff847992b68b79f7bed10a3478713 | 12d56ecf81b4f0629fd8b75e01532d85b9c7677c | |||
v1.0 | instruct | Algorithm | Algorithm_13532_I | ### Palindromic Product of Two 3-Digit Numbers
A palindromic number reads the same forward and backward (e.g., 121 or 989). Write a function to find the largest palindromic number that is a product of two 3-digit numbers.
**Function Signature**:
```python
def largest_palindromic_product() -> int:
```
#### Input/Outp... | def is_palindrome(number):
"""
Check if a number is a palindrome.
"""
return str(number) == str(number)[::-1]
def largest_palindromic_product():
"""
Finds the largest palindromic number that is a product of two 3-digit numbers.
"""
max_palindrome = 0
# Iterate over all pairs of... | from solution import largest_palindromic_product, is_palindrome
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(12321) == True
assert is_palindrome(123321) == True
assert is_palindrome(123421) == False
def test_largest_palindromic... | [
{
"docstring": "Check if a number is a palindrome.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Finds the largest palindromic number that is a product of two 3-digit numbers.",
"function_declarat... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(n):\n \"\"\"\n Checks if the integer n is a palindrome.\n \"\"\"\n s = str(n)\n return s == s[::-1]\n\ndef largest_palindromic_p... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013532",
"row_id": 13532,
"seed_ids": "[2826]"
} | 0.672696 | Algorithm_13532 | I | [
"is_palindrome",
"largest_palindromic_product"
] | 2 | [
[
"largest_palindromic_product",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7e09aad98a0fa817d7590c478d5cc2bcb91a658d | 13ce8d43d521cb48244e11da99f44560d5e3c60b | |||
v1.0 | instruct | Algorithm | Algorithm_13547_I | ### Problem Statement
You are tasked with developing an algorithm that validates and formats a given list of phone numbers based on certain rules. The phone numbers will be deemed valid if they adhere to one of the specified formats. If a phone number is valid, it should be reformatted according to a standard format f... | import re
def is_valid_phone_number(phone: str) -> bool:
"""
Returns True if the phone number is valid, False otherwise.
Valid formats:
- (xxx) xxx-xxxx
- xxx-xxx-xxxx
- xxx.xxx.xxxx
"""
pattern = re.compile(r"^(?:\(\d{3}\)\s|\d{3}[-.])\d{3}[-.]\d{4}$")
return bool(pattern.match(pho... | from solution import is_valid_phone_number, reformat_phone_number, validate_and_reformat
def test_is_valid_phone_number():
assert is_valid_phone_number("(123) 456-7890") == True
assert is_valid_phone_number("123-456-7890") == True
assert is_valid_phone_number("123.456.7890") == True
assert is_valid_pho... | [
{
"docstring": "Returns True if the phone number is valid, False otherwise.\nValid formats:\n- (xxx) xxx-xxxx\n- xxx-xxx-xxxx\n- xxx.xxx.xxxx",
"function_declaration": "def is_valid_phone_number(phone):",
"function_name": "is_valid_phone_number",
"parameter_list": "(phone)"
},
{
"docstring":... | [
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": "import re\n\ndef is_valid_phone_number(phone: str) -> bool:\n \"\"\"\n Validates if a phone number is in one of the specified formats:\n - (xxx) xxx-xxx... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013547",
"row_id": 13547,
"seed_ids": "[495]"
} | 0.508427 | Algorithm_13547 | I | [
"is_valid_phone_number",
"reformat_phone_number",
"validate_and_reformat"
] | 3 | [
[
"validate_and_reformat",
"is_valid_phone_number"
],
[
"validate_and_reformat",
"reformat_phone_number"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 701727d54dd5d33f45fd183056265661b52d5b19 | ec8dc5e9c1159d003581741f82cae9c28765fb7c | |||
v1.0 | instruct | Algorithm | Algorithm_13577_I | ### Coding Assessment Question
#### Problem Statement
You are given a linked list where each node contains an integer value. Your task is to reverse the linked list in groups of size `k` and return the modified list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it i... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_k_group(head: ListNode, k: int) -> ListNode:
if k == 1 or not head:
return head
dummy = ListNode()
dummy.next = head
prev_group_end = dummy
while True:
kth_node = ... | import pytest
from solution import ListNode, reverse_k_group
# Helper function to create a linked list from a list of values
def create_linked_list(lst):
dummy = ListNode(0)
curr = dummy
for val in lst:
curr.next = ListNode(val)
curr = curr.next
return dummy.next
# Helper function to c... | [] | [
1,
1,
1,
1,
0,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef reverse_k_group(head: ListNode, k: int) -> Li... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000013577",
"row_id": 13577,
"seed_ids": "[1128]"
} | 0.637281 | Algorithm_13577 | I | [
"reverse_k_group",
"get_kth_node"
] | 2 | [
[
"reverse_k_group",
"get_kth_node"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | c44c2c86eb7545699bbe1b81c7474853024cd26a | 0b7db73cf332695800b0562016e035df6c869057 | |||
v1.0 | instruct | Algorithm | Algorithm_13672_I | ### Coding Question
Your task is to implement a function that simulates a simplified version of a case-sensitive spell checker. The spell checker will suggest corrections for a given word based on a dictionary of valid words. If the word is a valid dictionary word, the function should return the word itself. Otherwise... | def levenshtein_distance(word1: str, word2: str) -> int:
"""
Helper function to calculate the Levenshtein distance between two words.
"""
if len(word1) < len(word2):
return levenshtein_distance(word2, word1)
# len(word1) >= len(word2)
previous_row = range(len(word2) + 1)
for i, c1 i... | from solution import spell_checker
def test_spell_checker_exact_match():
dictionary = ["example", "spelling", "checker"]
assert spell_checker("example", dictionary) == "example"
def test_spell_checker_closest_match():
dictionary = ["example", "spelling", "checker"]
assert spell_checker("examlpe", dict... | [
{
"docstring": "Helper function to calculate the Levenshtein distance between two words.",
"function_declaration": "def levenshtein_distance(word1, word2):",
"function_name": "levenshtein_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Returns the closest word from the dicti... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def levenshtein_distance(word1: str, word2: str) -> int:\n \"\"\"\n Helper function to calculate the Levenshtein distance between two words.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000013672",
"row_id": 13672,
"seed_ids": "[519]"
} | 0.617407 | Algorithm_13672 | I | [
"levenshtein_distance",
"spell_checker"
] | 2 | [
[
"spell_checker",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a8a0e4bb8fb85114caaefc083a151b21ad3b3be9 | 207550b9dfa8892b8a04893e8e045c1d1705f333 | |||
v1.0 | instruct | Algorithm | Algorithm_13734_I | ### Sorting Squares and Cubes
You are provided with a list of integers. Your task is to generate two new lists from the input list: one containing the squares and the other containing the cubes of the integers. You should then return a sorted version of both these lists.
#### Requirements:
1. **Square List**: Implem... | from typing import List, Tuple
def generate_square_list(numbers: List[int]) -> List[int]:
"""
Returns a sorted list of squares of the given numbers.
"""
squares = [x ** 2 for x in numbers]
squares.sort()
return squares
def generate_cube_list(numbers: List[int]) -> List[int]:
"""
Return... | from solution import generate_square_list, generate_cube_list, process_numbers
def test_generate_square_list():
assert generate_square_list([1, 2, 3, 4]) == [1, 4, 9, 16]
assert generate_square_list([-3, -1, 0, 2]) == [0, 1, 4, 9]
assert generate_square_list([]) == []
assert generate_square_list([-1, -... | [
{
"docstring": "Returns a sorted list of squares of the given numbers.",
"function_declaration": "def generate_square_list(numbers):",
"function_name": "generate_square_list",
"parameter_list": "(numbers)"
},
{
"docstring": "Returns a sorted list of cubes of the given numbers.",
"functio... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef generate_square_list(numbers: List[int]) -> List[int]:\n \"\"\"\n Generate a sorted list of squared values from the p... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000013734",
"row_id": 13734,
"seed_ids": "[4214]"
} | 0.582879 | Algorithm_13734 | I | [
"generate_square_list",
"generate_cube_list",
"process_numbers"
] | 3 | [
[
"process_numbers",
"generate_cube_list"
],
[
"process_numbers",
"generate_square_list"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0b972899fd6d4d6f3f89e8e82e2389fa2d9e79be | 0c4e65cd3b53e251f25f79370ae8c91f93eb9574 | |||
v1.0 | instruct | Algorithm | Algorithm_13740_I | ### Prime Number Generation with Multithreading
Write a function `generate_primes` that generates all prime numbers up to a given number `n`. To optimize the task, use multithreading to divide the work of checking for prime numbers among multiple threads.
### Function Signature:
```python
def generate_primes(n: int, ... | import threading
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
... | import pytest
from solution import generate_primes
def test_generate_primes_simple_case():
assert generate_primes(10, 2) == [2, 3, 5, 7]
def test_generate_primes_single_thread():
assert generate_primes(30, 1) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_generate_primes_multiple_threads():
assert gene... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def worker(start, end, primes, lock):",
"function_name": "worker",
"parameter_list": "(start, end, primes, lo... | [
0,
0,
0,
1,
1,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nimport threading\n\ndef is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 ==... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013740",
"row_id": 13740,
"seed_ids": "[3768]"
} | 0.609515 | Algorithm_13740 | I | [
"is_prime",
"worker",
"generate_primes"
] | 3 | [
[
"worker",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 01ca25b038d8f63b0f32af0b1d6bb31ba20cae90 | e76edeff8c82190a06592c4821ff79b84f540dab | |||
v1.0 | instruct | Algorithm | Algorithm_13759_I | ### Coding Assessment Question
#### Context
In this exercise, you will work with strings and devise an algorithm to discover the longest anagram substring between two given strings. An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
#### Problem S... | from collections import Counter
def is_anagram(s1, s2):
return Counter(s1) == Counter(s2)
def longest_anagram_substring(s1: str, s2: str) -> str:
max_len = 0
longest_anagram = ""
n1, n2 = len(s1), len(s2)
for length in range(1, min(n1, n2) + 1):
for i in range(n1 - length + 1):
... | def test_longest_anagram_substring():
assert longest_anagram_substring("listen", "silent") == "listen"
assert longest_anagram_substring("abc", "def") == ""
assert longest_anagram_substring("abcdef", "fedcba") == "abcdef"
assert longest_anagram_substring("anagram", "nagaram") == "anagram"
assert long... | [
{
"docstring": null,
"function_declaration": "def is_anagram(s1, s2):",
"function_name": "is_anagram",
"parameter_list": "(s1, s2)"
},
{
"docstring": null,
"function_declaration": "def longest_anagram_substring(s1, s2):",
"function_name": "longest_anagram_substring",
"parameter_l... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def get_letter_count(s):\n \"\"\"\n Helper function to get the count of each letter in the string\n \"\"\"\n count = [0] * 26 # There are 26 letters... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000013759",
"row_id": 13759,
"seed_ids": "[2842]"
} | 0.76984 | Algorithm_13759 | I | [
"is_anagram",
"longest_anagram_substring"
] | 2 | [
[
"longest_anagram_substring",
"is_anagram"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 4996f308cba2faa30fa9f6007390fc9ec225c62f | e03d4c75e302bc6a9e728a868193e18bdc1959b5 | |||
v1.0 | instruct | Algorithm | Algorithm_13786_I | ### Genetic Algorithm for Function Optimization
#### Scenario
You have been given the task of optimizing a mathematical function using a genetic algorithm. Your goal is to enhance the current implementation to support various optimization functions and constraints while visualizing the convergence of the algorithm ove... | import numpy as np
import matplotlib.pyplot as plt
def initialize_population(population_size, bounds):
return np.array([
[np.random.uniform(low, high) for low, high in bounds]
for _ in range(population_size)
])
def evaluate_population(population, objective_function):
return np.array([objec... | import numpy as np
from solution import (initialize_population, evaluate_population, select_parents,
crossover, mutate, genetic_algorithm_optimizer)
def objective_function_example(x):
return sum((xi - 5)**2 for xi in x)
def test_initialize_population():
bounds = [(-10, 10), (-10, 10)]
... | [
{
"docstring": null,
"function_declaration": "def initialize_population(population_size, bounds):",
"function_name": "initialize_population",
"parameter_list": "(population_size, bounds)"
},
{
"docstring": null,
"function_declaration": "def evaluate_population(population, objective_funct... | [
0,
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef genetic_algorithm_optimizer(configs: dict) -> None:\n objective_function = configs[\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000013786",
"row_id": 13786,
"seed_ids": "[4300]"
} | 0.462572 | Algorithm_13786 | I | [
"initialize_population",
"evaluate_population",
"select_parents",
"crossover",
"mutate",
"genetic_algorithm_optimizer"
] | 6 | [
[
"genetic_algorithm_optimizer",
"crossover"
],
[
"genetic_algorithm_optimizer",
"evaluate_population"
],
[
"genetic_algorithm_optimizer",
"initialize_population"
],
[
"genetic_algorithm_optimizer",
"mutate"
],
[
"genetic_algorithm_optimizer",
"select_parents"... | 5 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 80944d49510ccb9510cc4560859ff64a9c663443 | 1c551465acf5fb0d82bdce75a73fb731875650bd | |||
v1.0 | instruct | Algorithm | Algorithm_13811_I | ### Problem Statement:
Create a function that generates a summary report from a list of employee records. Each record contains details such as the employee's name, department, salary, and years of experience. Your task is to implement the following functions:
1. **`average_salary`**: Calculate the average salary for ... | def average_salary(records, department):
"""
Calculate the average salary for a specific department.
"""
salaries = [record['salary'] for record in records if record['department'] == department]
return sum(salaries) / len(salaries) if salaries else 0
def total_experience(records, department):
"... | import pytest
from solution import average_salary, total_experience, highest_earner, lowest_experience, department_summary
records = [
{'name': 'Alice', 'department': 'HR', 'salary': 50000, 'years_of_experience': 5},
{'name': 'Bob', 'department': 'IT', 'salary': 80000, 'years_of_experience': 10},
{'name': ... | [
{
"docstring": "Calculate the average salary for a specific department.",
"function_declaration": "def average_salary(records, department):",
"function_name": "average_salary",
"parameter_list": "(records, department)"
},
{
"docstring": "Compute the total years of experience for all employee... | [
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 average_salary(records, department):\n \"\"\"\n Calculate the average salary for a specific department.\n \"\"\"\n total_salary = 0\n count = ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013811",
"row_id": 13811,
"seed_ids": "[3298]"
} | 0.670528 | Algorithm_13811 | I | [
"average_salary",
"total_experience",
"highest_earner",
"lowest_experience",
"department_summary"
] | 5 | [
[
"department_summary",
"average_salary"
],
[
"department_summary",
"total_experience"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3d148f9efc3258f942e6331477ddf86ec207c858 | f67394dc3f560e37ebe4affcf3557f8b917f7074 | |||
v1.0 | instruct | Algorithm | Algorithm_13822_I | Write a Python function `linked_list_intersection(head1: Node, head2: Node) -> Optional[Node]` that determines the intersection point of two singly linked lists.
### Requirements:
1. **Input**:
- `head1`: The head node of the first singly linked list.
- `head2`: The head node of the second singly linked list.
2.... | class Node:
def __init__(self, x):
self.value = x
self.next = None
def get_length(head):
length = 0
current = head
while current:
length += 1
current = current.next
return length
def linked_list_intersection(head1, head2):
"""
Determines the intersection poi... | import pytest
from solution import Node, linked_list_intersection
def test_intersection_exists():
intersect_node = Node(6)
intersect_node.next = Node(7)
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = intersect_node
head2 = Node(4)
head2.next = No... | [] | [
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, x):\n self.value = x\n self.next = None\n\ndef linked_list_intersection(head1: Node, head2: Node):\n \"\"\"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013822",
"row_id": 13822,
"seed_ids": "[4418]"
} | 0.524955 | Algorithm_13822 | I | [
"get_length",
"linked_list_intersection"
] | 2 | [
[
"linked_list_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | f8ba223a20d250d5d5f26701a5ed5374774bd313 | 0b475f39a9f5ef572c0cdceb9decb5c478548549 | |||
v1.0 | instruct | Algorithm | Algorithm_13829_I | ### Prime Number Generator and Manipulations
As a software developer, you are tasked with generating prime numbers and performing various manipulations on them.
#### Task:
Implement the following functions:
1. **Generate Primes**: Generate all prime numbers up to a given number `n`.
2. **Check Prime**: Check if a g... | import math
def generate_primes(n):
"""
Generate all prime numbers up to n using the Sieve of Eratosthenes.
"""
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for start in range(2, int(math.sqrt(n)) + 1):
if sieve[start]:
for m... | from solution import generate_primes, is_prime, prime_factorize, sum_of_primes
def test_generate_primes_basic():
assert generate_primes(10) == [2, 3, 5, 7]
def test_generate_primes_edge_cases():
assert generate_primes(1) == []
assert generate_primes(0) == []
assert generate_primes(-5) == []
def test_... | [
{
"docstring": "Generate all prime numbers up to n using the Sieve of Eratosthenes.",
"function_declaration": "def generate_primes(n):",
"function_name": "generate_primes",
"parameter_list": "(n)"
},
{
"docstring": "Check if a number x is prime.",
"function_declaration": "def is_prime(x)... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef generate_primes(n):\n \"\"\"\n Generate all prime numbers up to a given number n.\n \"\"\"\n sieve = [True] * (n + 1)\n sieve[0... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000013829",
"row_id": 13829,
"seed_ids": "[5304]"
} | 0.599332 | Algorithm_13829 | I | [
"generate_primes",
"is_prime",
"prime_factorize",
"sum_of_primes"
] | 4 | [
[
"sum_of_primes",
"generate_primes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee27d1320b205f140777962021089a376d7d1749 | a29b5eca98385ae143955ee8e20d4b1fe9d0e224 | |||
v1.0 | instruct | Algorithm | Algorithm_13842_I | ### Context
You are working as a backend developer for a travel booking website. One of the features allows users to search for trips based on origin, destination, and date, and see available options. Users can also book trips and get recommendations for popular destinations.
### Problem Statement
Write a function `se... | import datetime
# Mock dataset of trips
TRIPS_DATA = [
{"trip_id": "T001", "origin": "New York", "destination": "Los Angeles", "date": "2023-11-15", "available_seats": 5},
{"trip_id": "T002", "origin": "New York", "destination": "Los Angeles", "date": "2023-11-16", "available_seats": 3},
{"trip_id": "T003"... | from solution import search_and_book_trip
def test_search_and_book_trip_successful_booking():
result = search_and_book_trip("New York", "Los Angeles", "2023-11-15", 2)
assert result["status"] == "success"
assert "booking_id" in result
def test_search_and_book_trip_insufficient_seats():
result = search... | [
{
"docstring": null,
"function_declaration": "def book_seats(trip_id, seats):",
"function_name": "book_seats",
"parameter_list": "(trip_id, seats)"
},
{
"docstring": null,
"function_declaration": "def search_and_book_trip(origin, destination, date, seats):",
"function_name": "search_... | [
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": "import datetime\n\n# Mock data for available trips\ntrips_data = [\n {\"origin\": \"New York\", \"destination\": \"Los Angeles\", \"date\": \"2023-11-15\", \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000013842",
"row_id": 13842,
"seed_ids": "[2345]"
} | 0.629216 | Algorithm_13842 | I | [
"book_seats",
"search_and_book_trip"
] | 2 | [
[
"search_and_book_trip",
"book_seats"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d30691b209534723a3458752049e7544646e6b73 | 1ad47c8e7755063daf07f9fe4b2f5acb4a7548e5 | |||
v1.0 | instruct | Algorithm | Algorithm_13847_I | ### Question: Implement a Financial Calculator with Different Compound Interest Methods
Your task is to implement a financial calculator that can compute the future value of an investment based on different compound interest methods. Specifically, you need to support annual, semi-annual, quarterly, and monthly compoun... | def compound_interest(principal: float, rate: float, years: float, comp_freq: int) -> float:
"""
Calculate the future value for a given principal, annual interest rate,
number of years, and compounding frequency.
:param principal: The initial amount of money invested (float).
:param rate: The ... | import pytest
from solution import compound_interest, calculate_future_value
def test_compound_interest():
assert round(compound_interest(1000.0, 0.05, 10, 1), 2) == 1628.89
assert round(compound_interest(1000.0, 0.05, 10, 2), 2) == 1638.62
assert round(compound_interest(1000.0, 0.05, 10, 4), 2) == 1643.62... | [
{
"docstring": "Calculate the future value for a given principal, annual interest rate, \nnumber of years, and compounding frequency.\n\n:param principal: The initial amount of money invested (float).\n:param rate: The annual interest rate in decimal form (float).\n:param years: The number of years the money is... | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def compound_interest(principal: float, rate: float, years: float, comp_freq: int) -> float:\n if principal <= 0 or rate < 0 or years <= 0:\n raise Val... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013847",
"row_id": 13847,
"seed_ids": "[4251]"
} | 0.468191 | Algorithm_13847 | I | [
"compound_interest",
"calculate_future_value"
] | 2 | [
[
"calculate_future_value",
"compound_interest"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a20b6e9c0b7fdd301d494f839cb235307e672e84 | 41f031457357560d1038323d1755c2eb9f284ecc | |||
v1.0 | instruct | Algorithm | Algorithm_13874_I | Implement a Python function `generate_safe_prime_sequence` that takes a single integer argument `terms`. The function should generate the first `terms` Safe Prime numbers. A Safe Prime is a prime number of the form `2p + 1` where `p` is also a prime.
### Requirements:
1. The function should handle edge cases such as n... | def is_prime(n):
"""
Helper function to check if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import generate_safe_prime_sequence
def test_generate_safe_prime_sequence_first_5():
assert generate_safe_prime_sequence(5) == [5, 7, 11, 23, 47]
def test_generate_safe_prime_sequence_first_3():
assert generate_safe_prime_sequence(3) == [5, 7, 11]
def test_generate_safe_prime_sequence_first_7()... | [
{
"docstring": "Helper function to check if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate the first `terms` Safe Prime numbers.",
"function_declaration": "def generate_safe_prime_sequenc... | [
1,
0,
0,
1,
1,
1,
1,
1,
0
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000013874",
"row_id": 13874,
"seed_ids": "[3492]"
} | 0.63915 | Algorithm_13874 | I | [
"is_prime",
"generate_safe_prime_sequence"
] | 2 | [
[
"generate_safe_prime_sequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d62bdac905d86de1491ae63de14bcee1f3736cb0 | 759b550dc393160385c1bd7c616e764c9833c354 | |||
v1.0 | instruct | Algorithm | Algorithm_13877_I | ### Sorting Algorithms Performance Analyzer
#### Context
You are tasked with implementing and comparing the performance of three different sorting algorithms: Quicksort, Mergesort, and Heapsort. This will help ensure comprehension of how these algorithms operate and their computational complexity.
#### Task
1. **Imp... | def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
def mergesort(arr):
if len(arr) <= 1:
... | from solution import quicksort, mergesort, heapsort, measure_performance
def test_quicksort():
assert quicksort([3,6,8,10,1,2,1]) == [1,1,2,3,6,8,10]
assert quicksort([]) == []
assert quicksort([1]) == [1]
assert quicksort([5,3,8,4,2]) == [2,3,4,5,8]
def test_mergesort():
assert mergesort([3,6,8,1... | [
{
"docstring": null,
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def mergesort(arr):",
"function_name": "mergesort",
"parameter_list": "(arr)"
},
{
"docstring": nul... | [
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 quicksort(arr: list) -> list:\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middl... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000013877",
"row_id": 13877,
"seed_ids": "[4704]"
} | 0.555685 | Algorithm_13877 | I | [
"quicksort",
"mergesort",
"merge",
"heapsort",
"measure_performance"
] | 5 | [
[
"measure_performance",
"heapsort"
],
[
"measure_performance",
"mergesort"
],
[
"measure_performance",
"quicksort"
],
[
"mergesort",
"merge"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 670269027f4d9b445b27ef6188a088718a9b75a9 | fcbeec2b92d42715c1130121f173c72e24a199d7 | |||
v1.0 | instruct | Algorithm | Algorithm_13964_I | ### Coding Assessment Question
**Title**: Implement Linked List Sorting
**Objective**:
Sort a singly linked list using merge sort. The task is to create functions to build the linked list from an array and sort the linked list in ascending order.
**Context**:
Bob has been studying linked lists and sorting algorithms... | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def build_linked_list(arr: list[int]) -> ListNode:
"""
Create a linked list from an array.
Args:
arr (list[int]): The array to be converted into a linked list.
Returns:
List... | from solution import ListNode, build_linked_list, sort_linked_list
def linked_list_to_list(head: ListNode) -> list[int]:
"""
Helper function to convert linked list to list for easy testing.
"""
result = []
current = head
while current:
result.append(current.value)
current = curr... | [] | [
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 build_linked_list(arr):\n \"\"\"\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000013964",
"row_id": 13964,
"seed_ids": "[220]"
} | 0.522148 | Algorithm_13964 | I | [
"build_linked_list",
"sort_linked_list",
"merge_sort",
"get_middle",
"merge"
] | 5 | [
[
"merge_sort",
"get_middle"
],
[
"merge_sort",
"merge"
],
[
"sort_linked_list",
"merge_sort"
]
] | 3 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | bea8aa5acf04a7ff4995f8e1220e7c6fffd09ac5 | 4f0f19399bbe2c23f1fab65ce76937c9296816c4 | |||
v1.0 | instruct | Algorithm | Algorithm_14059_I | ### Balanced Parentheses Checker with Custom Rules
#### Problem Statement
You are asked to implement a parser for checking if a string containing different types of parentheses (`{}`, `[]`, `()`, `<>`) is balanced. A string is considered balanced if every opening parenthesis has a corresponding closing parenthesis in... | def is_match(opening, closing):
"""
Returns True if the opening and closing parenthesis are a matching pair.
"""
matches = {
'(': ')',
'{': '}',
'[': ']',
'<': '>'
}
return matches.get(opening) == closing
def is_balanced(expression):
"""
Returns True if t... | from solution import is_balanced, is_match
def test_is_match():
assert is_match('(', ')') == True
assert is_match('{', '}') == True
assert is_match('[', ']') == True
assert is_match('<', '>') == True
assert is_match('(', '}') == False
assert is_match('{', ')') == False
assert is_match('[', ... | [
{
"docstring": "Returns True if the opening and closing parenthesis are a matching pair.",
"function_declaration": "def is_match(opening, closing):",
"function_name": "is_match",
"parameter_list": "(opening, closing)"
},
{
"docstring": "Returns True if the input string with parentheses is ba... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_match(opening: str, closing: str) -> bool:\n \"\"\"\n Determines if the given opening parenthesis matches the closing parenthesis.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014059",
"row_id": 14059,
"seed_ids": "[278]"
} | 0.792475 | Algorithm_14059 | I | [
"is_match",
"is_balanced"
] | 2 | [
[
"is_balanced",
"is_match"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84e8100d04f588b56ed1238c2cc4b359c5b87b66 | 6b18e5eb10772958105ee0089c1ea73070b0798f | |||
v1.0 | instruct | Algorithm | Algorithm_14109_I | ### Problem Statement
You are tasked with implementing a function that sorts a list of integers into ascending order using the Merge Sort algorithm. Your implementation should divide the list into smaller sublists and merge them back together in sorted order.
### Function Specifications
**Function Name**: `merge_sor... | def merge_sort(arr):
"""
Sorts a list of integers into ascending order using the Merge Sort algorithm.
"""
if len(arr) <= 1:
return arr
# Finding the middle of the array
mid = len(arr) // 2
# Dividing the elements into two halves
left_half = merge_sort(arr[:mid])
right_... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([3]) == [3]
def test_merge_sort_multiple_elements():
assert merge_sort([3, 1, 2]) == [1, 2, 3]
def test_merge_sort_with_duplicates():
assert merge_sort([3,... | [
{
"docstring": "Sorts a list of integers into ascending order using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaratio... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers in ascending order using merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n retur... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014109",
"row_id": 14109,
"seed_ids": "[4254]"
} | 0.666814 | Algorithm_14109 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b05db4bb4109b79151f4c93a81a27d6c6efc2426 | 815889fc08ed43fe551b02d7e06bd6d5ee91fe9a | |||
v1.0 | instruct | Algorithm | Algorithm_14204_I | ### **Problem Statement:**
You are charged with writing functions to preprocess, transform, and validate email addresses based on predefined rules. The goal is to create a standardized format for a list of email addresses, and to determine the validity of each based on specific criteria.
### **Function Specification:... | def clean_email(email: str) -> str:
"""
This function returns the email after lowercasing and trimming leading/trailing spaces.
"""
return email.strip().lower()
def parse_email(email: str) -> (str, str):
"""
This function splits the cleaned email into local and domain parts.
"""
local, ... | from solution import clean_email, parse_email, validate_email, standardize_emails
def test_clean_email():
assert clean_email(' Example@Domain.COM ') == 'example@domain.com'
assert clean_email('User@Example.com') == 'user@example.com'
assert clean_email('\tUSER@TEST.COM\n') == 'user@test.com'
def test_pa... | [
{
"docstring": "This function returns the email after lowercasing and trimming leading/trailing spaces.",
"function_declaration": "def clean_email(email):",
"function_name": "clean_email",
"parameter_list": "(email)"
},
{
"docstring": "This function splits the cleaned email into local and do... | [
0,
1,
0,
0,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def clean_email(email: str) -> str:\n \"\"\"\n Returns the email lowercased and stripped of leading/trailing whitespace.\n \"\"\"\n return email.stri... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000014204",
"row_id": 14204,
"seed_ids": "[438]"
} | 0.613718 | Algorithm_14204 | I | [
"clean_email",
"parse_email",
"validate_email",
"standardize_emails"
] | 4 | [
[
"standardize_emails",
"clean_email"
],
[
"standardize_emails",
"parse_email"
],
[
"standardize_emails",
"validate_email"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 042d50b3c202c30d25730943e63bfb396b81cbb3 | 641cc89aefdf4e2484f94256c35d31629af14745 | |||
v1.0 | instruct | Algorithm | Algorithm_14244_I | ### Domains and Depths in a Graph
Given an undirected graph with `n` nodes and `m` edges, you need to find out the maximum depth of each connected component in the graph. The depth of a node in a component is the maximum distance from that node to any other node in the same component.
Implement a function:
```python... | from typing import List, Tuple
from collections import defaultdict, deque
def bfs_max_depth(start, graph):
""" Perform BFS to find the farthest node and its distance from the start node """
visited = set()
queue = deque([(start, 0)])
farthest_node, max_distance = start, 0
while queue:
node... | from solution import find_max_depths
def test_single_node():
assert find_max_depths(1, []) == [0]
def test_disconnected_nodes():
assert find_max_depths(3, []) == [0, 0, 0]
def test_single_edge():
assert find_max_depths(2, [(0, 1)]) == [1, 1]
def test_connected_component():
assert find_max_depths(3, ... | [
{
"docstring": "Perform BFS to find the farthest node and its distance from the start node ",
"function_declaration": "def bfs_max_depth(start, graph):",
"function_name": "bfs_max_depth",
"parameter_list": "(start, graph)"
},
{
"docstring": null,
"function_declaration": "def find_max_dep... | [
1,
0,
0,
0,
1,
1,
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": "from typing import List, Tuple\nfrom collections import defaultdict, deque\n\ndef bfs_max_depth(n, graph, start):\n visited = [-1] * n\n queue = deque([(st... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000014244",
"row_id": 14244,
"seed_ids": "[2114]"
} | 0.638029 | Algorithm_14244 | I | [
"bfs_max_depth",
"find_max_depths"
] | 2 | [
[
"find_max_depths",
"bfs_max_depth"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e045a501e9a61bb8219c45279c1128302ee38603 | 2f8cc44dc043594ba1ff48a7a47380bea757e557 | |||
v1.0 | instruct | Algorithm | Algorithm_14281_I | ### Question: Currency Converter
You are required to create a function that converts an amount of money from one currency to another using exchange rates from two different APIs: ExchangeRate-API and CurrencyLayer. The function should handle cases where no valid API keys are provided, or the APIs return invalid data o... | import requests
EXCHANGERATE_API_KEY = "your_exchangerate_api_key"
CURRENCY_LAYER_API_KEY = "your_currency_layer_api_key"
EXCHANGERATE_URL_BASE = "https://v6.exchangerate-api.com/v6/{key}/latest/{from_currency}"
CURRENCY_LAYER_URL_BASE = "http://api.currencylayer.com/live?access_key={key}¤cies={to_currency}&sour... | import pytest
from unittest.mock import patch
from solution import convert_currency, fetch_exchange_rate_exchangerate_api, fetch_exchange_rate_currency_layer
@patch('solution.requests.get')
def test_fetch_exchange_rate_exchangerate_api(mock_get):
mock_response_data = {
'conversion_rates': {
'EU... | [
{
"docstring": null,
"function_declaration": "def fetch_exchange_rate_exchangerate_api(from_currency, to_currency):",
"function_name": "fetch_exchange_rate_exchangerate_api",
"parameter_list": "(from_currency, to_currency)"
},
{
"docstring": null,
"function_declaration": "def fetch_excha... | [
0,
1,
1,
0,
1,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\n\nEXCHANGERATE_API_KEY = \"YOUR_EXCHANGERATE_API_KEY\"\nCURRENCY_LAYER_API_KEY = \"YOUR_CURRENCY_LAYER_API_KEY\"\nEXCHANGERATE_URL_BASE = \"http... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000014281",
"row_id": 14281,
"seed_ids": "[1996]"
} | 0.595286 | Algorithm_14281 | I | [
"fetch_exchange_rate_exchangerate_api",
"fetch_exchange_rate_currency_layer",
"convert_currency"
] | 3 | [
[
"convert_currency",
"fetch_exchange_rate_currency_layer"
],
[
"convert_currency",
"fetch_exchange_rate_exchangerate_api"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | e1ce029cdc636312708f5c1838f0b62c8e6acf9b | 8b8a8d955dede60db16ae96b116eb07245caf5e4 | |||
v1.0 | instruct | Algorithm | Algorithm_14288_I | ### Coding Assessment Question: String Permutation Checker
#### Context:
In many applications, it is necessary to determine if two strings are permutations of each other. A string permutation is another string that contains the same characters in a different order. Checking for string permutations is a fundamental pro... | def is_permutation(string1, string2):
"""
Checks if two strings are permutations of each other.
Input:
string1 (str): The first string.
string2 (str): The second string.
Output:
bool: True if the strings are permutations of each other, False otherwise.
"""
if string1 is Non... | import pytest
from solution import is_permutation, all_permutations, permutation_index
def test_is_permutation_basic():
assert is_permutation("abc", "bca") == True
assert is_permutation("abc", "acb") == True
assert is_permutation("abc", "abc") == True
assert is_permutation("abc", "abcd") == False
a... | [
{
"docstring": "Checks if two strings are permutations of each other.\n\nInput:\nstring1 (str): The first string.\nstring2 (str): The second string.\n\nOutput:\nbool: True if the strings are permutations of each other, False otherwise.",
"function_declaration": "def is_permutation(string1, string2):",
"... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_permutation(string1, string2):\n \"\"\"\n Returns True if string1 and string2 are permutations of each other, otherwise False.\n \"\"\"\n if s... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000014288",
"row_id": 14288,
"seed_ids": "[4028]"
} | 0.738007 | Algorithm_14288 | I | [
"is_permutation",
"all_permutations",
"permutation_index"
] | 3 | [
[
"permutation_index",
"all_permutations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | df55a4f6faaff28152d684cf3d19676abc205909 | 692cda87466346527a81f03ec815ec016820ccfc | |||
v1.0 | instruct | Algorithm | Algorithm_14298_I | ### Question
You are tasked with finding the smallest prime number greater than or equal to a given integer. A prime number is defined as a number greater than 1 that has no positive divisors other than 1 and itself.
#### Problem Statement
Write a function `find_smallest_prime(n: int) -> int` that returns the smalle... | 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 F... | def test_find_smallest_prime_example_cases():
assert find_smallest_prime(10) == 11
assert find_smallest_prime(15) == 17
assert find_smallest_prime(17) == 17
assert find_smallest_prime(1) == 2
def test_find_smallest_prime_edge_cases():
assert find_smallest_prime(0) == 2
assert find_smallest_prim... | [
{
"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 smallest prime number greater than or equal to the given integer n.",
"function_declaration... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000014298",
"row_id": 14298,
"seed_ids": "[3101]"
} | 0.641877 | Algorithm_14298 | I | [
"is_prime",
"find_smallest_prime"
] | 2 | [
[
"find_smallest_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 367be2d56235b6ae665f7edc854906a14bae17c6 | afa4de95bdce8388fe2a4b361c197cc55281cc31 | |||
v1.0 | instruct | Algorithm | Algorithm_14302_I | ### Problem Statement
Create a function that checks if a given string is a palindrome. A palindrome is a word, number, phrase, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Implement three different methods:
1. Simple comparison.
2. Using ... | import re
def normalize_string(s: str) -> str:
"""
Normalize the string by converting to lowercase and removing non-alphanumeric characters.
"""
return re.sub(r'[^A-Za-z0-9]', '', s.lower())
def is_palindrome(s: str) -> bool:
"""
Check if a given string is a palindrome using simple comparison.... | from solution import is_palindrome, is_palindrome_recursion, is_palindrome_two_pointer
def test_is_palindrome():
assert is_palindrome("A man, a plan, a canal, Panama") == True
assert is_palindrome("racecar") == True
assert is_palindrome("hello") == False
assert is_palindrome("") == True
assert is_p... | [
{
"docstring": "Normalize the string by converting to lowercase and removing non-alphanumeric characters.",
"function_declaration": "def normalize_string(s):",
"function_name": "normalize_string",
"parameter_list": "(s)"
},
{
"docstring": "Check if a given string is a palindrome using simple... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef normalize_string(s: str) -> str:\n \"\"\"\n Normalize the string by converting to lowercase and removing non-alphanumeric characters.\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014302",
"row_id": 14302,
"seed_ids": "[3159]"
} | 0.780882 | Algorithm_14302 | I | [
"normalize_string",
"is_palindrome",
"is_palindrome_recursion",
"is_palindrome_two_pointer"
] | 4 | [
[
"is_palindrome",
"normalize_string"
],
[
"is_palindrome_recursion",
"normalize_string"
],
[
"is_palindrome_two_pointer",
"normalize_string"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8c2f67859d607559a5ce4600ea8a7ea9620c05dc | 7626d9e39f37ef246a7b5d8196cd529cd99d2f9b | |||
v1.0 | instruct | Algorithm | Algorithm_14356_I | ### Coding Question: String Compression and Verification
#### Objective:
You are given two functions: one that compresses a string and another that verifies the compression. Your task is to enhance these functions and write a new function that uses both to solve a given problem.
#### Problem Statement:
Write a functi... | def compress_string(input_string: str) -> str:
"""
Compresses the input string by reducing consecutive repeating characters
to the character followed by the count of repetitions.
Example:
"aaabb" -> "a3b2"
"""
if not input_string:
return ""
compressed = []
current_c... | def test_compress_and_verify():
assert compress_and_verify("aaabb", "a3b2") == True
assert compress_and_verify("aaabbc", "a3b2c1") == True
assert compress_and_verify("aabccc", "a2b1c3") == True
assert compress_and_verify("aabb", "a2b3") == False
assert compress_and_verify("", "") == True
assert ... | [
{
"docstring": "Compresses the input string by reducing consecutive repeating characters\nto the character followed by the count of repetitions.\n\nExample:\n\"aaabb\" -> \"a3b2\"",
"function_declaration": "def compress_string(input_string):",
"function_name": "compress_string",
"parameter_list": "(... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def compress_string(input_string: str) -> str:\n \"\"\"\n Compresses the input string by reducing consecutive repeating characters\n to the character fo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014356",
"row_id": 14356,
"seed_ids": "[4064]"
} | 0.682501 | Algorithm_14356 | I | [
"compress_string",
"verify_compression",
"compress_and_verify"
] | 3 | [
[
"compress_and_verify",
"compress_string"
],
[
"compress_and_verify",
"verify_compression"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | d06858390fcd1bb47b7aff1169cc6c28f1ac59b9 | 70b28a9eeef05247e94fa7163b2ba2f4ba5a0104 | |||
v1.0 | instruct | Algorithm | Algorithm_14407_I | ## Task
You are provided with a simplified version of a matrix multiplication function. Your task is to complete the `strassen_matrix_multiplication` function using Strassen's algorithm for matrix multiplication to achieve more efficient O(n^2.81) time complexity compared to conventional O(n^3) matrix multiplication.
... | import numpy as np
def conventional_matrix_multiplication(A: np.ndarray, B: np.ndarray) -> np.ndarray:
return np.dot(A, B)
def add_matrix(A: np.ndarray, B: np.ndarray) -> np.ndarray:
return A + B
def subtract_matrix(A: np.ndarray, B: np.ndarray) -> np.ndarray:
return A - B
def split_matrix(A: np.ndarray... | import numpy as np
from solution import strassen_matrix_multiplication
def test_basic_case_2x2():
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
expected_result = np.array([[19, 22], [43, 50]])
assert np.array_equal(strassen_matrix_multiplication(A, B), expected_result)
def test_identit... | [
{
"docstring": null,
"function_declaration": "def conventional_matrix_multiplication(A, B):",
"function_name": "conventional_matrix_multiplication",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def add_matrix(A, B):",
"function_name": "add_matrix",
... | [
1,
1,
1,
1,
0,
1,
1,
0,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef conventional_matrix_multiplication(A: np.ndarray, B: np.ndarray) -> np.ndarray:\n return np.dot(A, B)\n\ndef add_matrix(A: np.ndarra... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014407",
"row_id": 14407,
"seed_ids": "[4589]"
} | 0.496525 | Algorithm_14407 | I | [
"conventional_matrix_multiplication",
"add_matrix",
"subtract_matrix",
"split_matrix",
"strassen_matrix_multiplication"
] | 5 | [
[
"strassen_matrix_multiplication",
"add_matrix"
],
[
"strassen_matrix_multiplication",
"conventional_matrix_multiplication"
],
[
"strassen_matrix_multiplication",
"split_matrix"
],
[
"strassen_matrix_multiplication",
"subtract_matrix"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 4ff02cc6a97f81ed57ac4e809649ec9d005f4b89 | 77b16b6de4a97c1a14173b594e3d66500f6e2cd7 | |||
v1.0 | instruct | Algorithm | Algorithm_14449_I | ### Scenario
You are developing a route optimization module for a ride-sharing app that helps users find the quickest route between two locations in a city. The city’s road network is represented as a weighted directed graph where intersections are nodes, and roads are edges with weights representing the travel time.
... | import heapq
from collections import defaultdict, deque
def construct_graph(edges):
graph = defaultdict(list)
for start, end, travel_time in edges:
graph[start].append((end, travel_time))
graph[end].append((start, travel_time)) # Assuming bidirectional travel
return graph
def dijkstra(gra... | from solution import shortest_path_queries
def test_shortest_path_basic():
edges = [
(0, 1, 4),
(0, 2, 2),
(1, 2, 5),
(1, 3, 10),
(2, 4, 3),
(4, 3, 4)
]
queries = [
(0, 3),
(2, 3)
]
results = shortest_path_queries(edges, queries)
a... | [
{
"docstring": null,
"function_declaration": "def construct_graph(edges):",
"function_name": "construct_graph",
"parameter_list": "(edges)"
},
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start, end):",
"function_name": "dijkstra",
"parameter_list": "(graph, ... | [
0,
1,
1,
1,
1,
1,
0,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef shortest_path_queries(edges, queries):\n def dijkstra(graph, start_node):\n \"\"\"\n Implement Dijkstra's algorithm to find ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000014449",
"row_id": 14449,
"seed_ids": "[1958]"
} | 0.716343 | Algorithm_14449 | I | [
"construct_graph",
"dijkstra",
"shortest_path_queries"
] | 3 | [
[
"shortest_path_queries",
"construct_graph"
],
[
"shortest_path_queries",
"dijkstra"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 75de32ad6e0f1810538353f8f2fca33112cb0edf | f3d8e463032f1d44417578fa3cfe16b09c8bf214 | |||
v1.0 | instruct | Algorithm | Algorithm_14513_I | ### Traffic Light Simulation
#### Background
You are tasked with creating a simple traffic light simulation program. A traffic light cycles through three stages: "Green", "Yellow", and "Red". Each stage lasts for a fixed number of seconds before transitioning to the next stage. The program should simulate the traffic ... | def current_light_state(seconds: int) -> str:
"""
Returns the current state of the traffic light at the given time in seconds.
"""
# The total cycle time for Green, Yellow, and Red lights
cycle_time = 60 + 5 + 55
# Calculate the position within one cycle
cycle_position = seconds % cycle_time... | from solution import current_light_state, run_simulation
def test_current_light_state():
assert current_light_state(0) == "Green"
assert current_light_state(59) == "Green"
assert current_light_state(60) == "Yellow"
assert current_light_state(64) == "Yellow"
assert current_light_state(65) == "Red"
... | [
{
"docstring": "Returns the current state of the traffic light at the given time in seconds.",
"function_declaration": "def current_light_state(seconds):",
"function_name": "current_light_state",
"parameter_list": "(seconds)"
},
{
"docstring": "Simulates the traffic light for the provided to... | [
0,
0,
1,
0,
0,
0,
1,
1,
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 current_light_state(seconds: int) -> str:\n \"\"\"\n Returns the current state of the traffic light at the given number of seconds.\n \n Argument... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000014513",
"row_id": 14513,
"seed_ids": "[453]"
} | 0.548646 | Algorithm_14513 | I | [
"current_light_state",
"run_simulation"
] | 2 | [
[
"run_simulation",
"current_light_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | af01d81e53b85c2262302b51f7e4c20932348824 | 62665ac6363c258f34400cb932c096ce38bb5f39 | |||
v1.0 | instruct | Algorithm | Algorithm_14522_I | ### Implement a Custom Sorting Algorithm and Measure Performance
In this coding problem, you will implement a custom sorting algorithm to sort a given list of integers and compare its performance with Python's built-in Timsort algorithm.
#### Problem Description
You are given a list of integers and are required to i... | from typing import List, Tuple
import time
def merge_sort(lst: List[int]) -> List[int]:
if len(lst) <= 1:
return lst
mid = len(lst) // 2
left = merge_sort(lst[:mid])
right = merge_sort(lst[mid:])
return merge(left, right)
def merge(left: List[int], right: List[int]) -> List[int]:... | from solution import merge_sort, compare_sorting_algorithms
import random
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 merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_merge_sort_random_list():
random_lis... | [
{
"docstring": null,
"function_declaration": "def merge_sort(lst):",
"function_name": "merge_sort",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docst... | [
1,
1,
1,
0,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport time\n\ndef merge_sort(lst: List[int]) -> List[int]:\n \"\"\"\n Custom implementation of the merge sort algorithm.\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014522",
"row_id": 14522,
"seed_ids": "[4036]"
} | 0.56367 | Algorithm_14522 | I | [
"merge_sort",
"merge",
"compare_sorting_algorithms"
] | 3 | [
[
"compare_sorting_algorithms",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3034f933bf29f8192e7fae337f5efeb8081955b6 | 7055188563562b99cd17d41552e204094f2e8964 | |||
v1.0 | instruct | Algorithm | Algorithm_14531_I | ### Prime Number Retrieval Challenge
#### Problem Statement
You are tasked with implementing a function to find and return all prime numbers less than a given integer \( n \). Your implementation should ensure efficient computation and handle large values of \( n \) effectively.
#### Function Specifications
```pyth... | def is_prime(num: int) -> bool:
"""
Determines if a given integer is a prime number.
:param num: An integer to check for primality
:return: True if the number is prime, otherwise False
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:... | from solution import is_prime, get_primes_less_than
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(18) == False
def test_get_primes_less_than_small():
assert get_primes_less_than(10) == [2, 3, 5,... | [
{
"docstring": "Determines if a given integer is a prime number.\n:param num: An integer to check for primality\n:return: True if the number is prime, otherwise False",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Ret... | [
1,
1,
1,
1,
0,
0,
1,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num: int) -> bool:\n \"\"\"\n Determines if a given integer is a prime number.\n :param num: An integer to check for primality\n :return... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000014531",
"row_id": 14531,
"seed_ids": "[3747]"
} | 0.742467 | Algorithm_14531 | I | [
"is_prime",
"get_primes_less_than"
] | 2 | [
[
"get_primes_less_than",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c668e92a02b812c2aab4348f8078f53eb1a4f8d | 68ea0b35f497d724f0e3b9b0054e569ffab0e19f | |||
v1.0 | instruct | Algorithm | Algorithm_14654_I | ### Coding Assessment Question
#### Scenario
You are developing an analytics tool that performs various statistical operations on a set of numbers. Given a list of integers, your tool should be able to calculate the mean, median, mode, and variance of the numbers.
#### Problem Statement
Implement functions to calcula... | from typing import List
from collections import Counter
import numpy as np
def calculate_mean(numbers: List[int]) -> float:
if not numbers:
return 0.0
return sum(numbers) / len(numbers)
def calculate_median(numbers: List[int]) -> float:
if not numbers:
return 0.0
numbers.sort()
n =... | from solution import (
calculate_mean,
calculate_median,
calculate_mode,
calculate_variance
)
def test_calculate_mean():
assert calculate_mean([1, 2, 3, 4, 5]) == 3.0
assert calculate_mean([1, 1, 1, 1, 1]) == 1.0
assert calculate_mean([-1, -2, -3, -4, -5]) == -3.0
assert calculate_me... | [
{
"docstring": null,
"function_declaration": "def calculate_mean(numbers):",
"function_name": "calculate_mean",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def calculate_median(numbers):",
"function_name": "calculate_median",
"parameter_list": "... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import Counter\nimport statistics\n\ndef calculate_mean(numbers: List[int]) -> float:\n \"\"\"\n Calculate the me... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000014654",
"row_id": 14654,
"seed_ids": "[1068]"
} | 0.777197 | Algorithm_14654 | I | [
"calculate_mean",
"calculate_median",
"calculate_mode",
"calculate_variance"
] | 4 | [
[
"calculate_variance",
"calculate_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | de9b573dba1f9094a794417a31c6e546a0d9ad9c | 13900f1f97de861c46363ac8f1bd0f0cd015bb1d | |||
v1.0 | instruct | Algorithm | Algorithm_14683_I | ### Problem Description
You are required to design a function that generates a complex Mandelbrot fractal visualization. The function should be able to handle different types of complex transformations, efficiently support high-resolution grids, and optimize performance using parallel processing techniques.
### Funct... | import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
from typing import Callable, Tuple
def mandelbrot_point(c: complex, transform: Callable[[complex], complex], max_iter: int, escape_radius: float) -> int:
z = c
for i in range(max_iter):
z = transform(z)
if abs(z... | import pytest
from solution import generate_mandelbrot_fractal
import numpy as np
def basic_transformation(z):
return z**2 + 0.355 + 0.355j
def test_mandelbrot_basic_scenario():
generate_mandelbrot_fractal(basic_transformation, 10, 2.0, (-2.0, 1.0), (-1.5, 1.5), 100)
def test_large_grid_parallel_processing()... | [
{
"docstring": null,
"function_declaration": "def mandelbrot_point(c, transform, max_iter, escape_radius):",
"function_name": "mandelbrot_point",
"parameter_list": "(c, transform, max_iter, escape_radius)"
},
{
"docstring": null,
"function_declaration": "def compute_row(args):",
"fun... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Callable, Tuple\n\ndef mandelbrot(c: c... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000014683",
"row_id": 14683,
"seed_ids": "[4853]"
} | 0.451134 | Algorithm_14683 | I | [
"mandelbrot_point",
"compute_row",
"generate_mandelbrot_fractal"
] | 3 | [
[
"compute_row",
"mandelbrot_point"
],
[
"generate_mandelbrot_fractal",
"compute_row"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | f16cdfd50bd2164456fa4a4a77c90a6cd321b5f9 | d0144279588b8d4ff677de11aaa1d0799eb42506 | |||
v1.0 | instruct | Algorithm | Algorithm_14753_I | ### Problem: Weather Data Analyzer
You are provided with a function that retrieves weather data from an API. The API returns a JSON object that includes various data points such as temperature, humidity, wind speed, and a weather description. Your task is to enhance this function in the following ways:
1. **Error Han... | import requests
def calculate_feels_like(temp_f, humidity):
"""
Calculate the 'feels like' temperature using a basic heat index formula.
This is simplified and for more accurate results, more complex equations can be used.
"""
feels_like = temp_f + 0.33 * humidity - 0.7
return feels_like
def e... | import pytest
import requests
from unittest.mock import patch
from solution import enhanced_weather_report
def test_success_response():
# Mock response data
mock_response = {
"current": {
"temp_f": 75,
"humidity": 50,
"wind_mph": 10.0,
"condition": {
... | [
{
"docstring": "Calculate the 'feels like' temperature using a basic heat index formula.\nThis is simplified and for more accurate results, more complex equations can be used.",
"function_declaration": "def calculate_feels_like(temp_f, humidity):",
"function_name": "calculate_feels_like",
"parameter... | [
0,
0,
1,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\n\ndef enhanced_weather_report(location, api_key):\n \"\"\"\n Fetches weather data for the given location and returns a detailed report.\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000014753",
"row_id": 14753,
"seed_ids": "[1850]"
} | 0.571996 | Algorithm_14753 | I | [
"calculate_feels_like",
"enhanced_weather_report"
] | 2 | [
[
"enhanced_weather_report",
"calculate_feels_like"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 441b9d0f65e279182dbbb66289d1a7d06f922252 | 2f2be8ed05184985afa8e723266056791dbb86e5 | |||
v1.0 | instruct | Algorithm | Algorithm_14771_I | ### Prime Product Checker
You need to implement a function that checks whether a given positive integer `n` (greater than 1) can be expressed as the product of two distinct prime numbers. If it can, the function should return the two primes as a tuple. If it cannot, the function should return `None`.
For example:
* T... | from typing import Optional, Tuple
def is_prime(x: int) -> bool:
"""
Helper function to check if a number is prime.
"""
if x <= 1:
return False
if x <= 3:
return True
if x % 2 == 0 or x % 3 == 0:
return False
i = 5
while i * i <= x:
if x % i == 0 or x % (... | from solution import prime_product_checker
def test_prime_product_checker():
assert prime_product_checker(15) == (3, 5)
assert prime_product_checker(20) is None
assert prime_product_checker(21) == (3, 7)
assert prime_product_checker(35) == (5, 7)
assert prime_product_checker(77) == (7, 11)
asse... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(x):",
"function_name": "is_prime",
"parameter_list": "(x)"
},
{
"docstring": "Function to check if the given number n can be expressed as a product\nof two distinct prime numbers.",
"fu... | [
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 Optional, Tuple\nimport math\n\ndef is_prime(x: int) -> bool:\n \"\"\"Checks if a number is prime.\"\"\"\n if x <= 1:\n return Fa... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000014771",
"row_id": 14771,
"seed_ids": "[2541]"
} | 0.71028 | Algorithm_14771 | I | [
"is_prime",
"prime_product_checker"
] | 2 | [
[
"prime_product_checker",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54ddaddc183d3cf82a55c3137ce45013a93cb975 | 511a75c68e5fe3d1266d0b2199d54c89bcd1cc2f | |||
v1.0 | instruct | Algorithm | Algorithm_14774_I | ### Compiling Large-Scale Statistical Summaries
#### Scenario
You have a large log file composed of individual records, each containing an entry for a user, a timestamp, and an associated numeric value. You need to process this file to compute statistical summaries for each user efficiently, leveraging multi-threading... | import csv
import os
import threading
from collections import defaultdict
from statistics import mean, median, stdev
from concurrent.futures import ThreadPoolExecutor
def compute_statistics(values):
return {
'mean': mean(values),
'median': median(values),
'std_dev': stdev(values) if len(val... | import os
import pytest
from solution import compute_user_statistics
def create_log_file(content, filename="test_logfile.txt"):
with open(filename, "w") as f:
f.write(content)
def remove_log_file(filename="test_logfile.txt"):
if os.path.exists(filename):
os.remove(filename)
def test_compute_u... | [
{
"docstring": null,
"function_declaration": "def compute_statistics(values):",
"function_name": "compute_statistics",
"parameter_list": "(values)"
},
{
"docstring": null,
"function_declaration": "def process_chunk(chunk, user_data):",
"function_name": "process_chunk",
"parameter... | [
1,
1,
0,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom concurrent.futures import ThreadPoolExecutor\nimport threading\n\ndef compute_user_statistics(logfile, num_threads):\n \"\"\"\n Pr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000014774",
"row_id": 14774,
"seed_ids": "[900]"
} | 0.699049 | Algorithm_14774 | I | [
"compute_statistics",
"process_chunk",
"read_in_chunks",
"compute_user_statistics"
] | 4 | [
[
"compute_user_statistics",
"compute_statistics"
],
[
"compute_user_statistics",
"process_chunk"
],
[
"compute_user_statistics",
"read_in_chunks"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | fd4eea0614b78d347b824a008fd410d15519d3fc | e7e19381811e84afd1ea73f4dc78c8114bd3d9c0 | |||
v1.0 | instruct | Algorithm | Algorithm_14806_I | ### Scenario:
You are working as a software engineer to optimize a search feature for a travel booking website. One requirement is to quickly find the n-th longest flight duration from a list of all available flight durations. Considering the potential large number of flights and the necessity for a fast response time,... | def partition(arr, left, right, pivot_index):
pivot_value = arr[pivot_index]
arr[pivot_index], arr[right] = arr[right], arr[pivot_index]
store_index = left
for i in range(left, right):
if arr[i] > pivot_value:
arr[store_index], arr[i] = arr[i], arr[store_index]
store_ind... | from solution import find_nth_longest
def test_find_nth_longest():
assert find_nth_longest([300, 400, 700, 600, 200], 2) == 600
assert find_nth_longest([120, 180, 240, 200, 300], 1) == 300
assert find_nth_longest([90, 45, 180, 150, 60], 3) == 90
assert find_nth_longest([350, 600, 350, 900, 870], 4) == ... | [
{
"docstring": null,
"function_declaration": "def partition(arr, left, right, pivot_index):",
"function_name": "partition",
"parameter_list": "(arr, left, right, pivot_index)"
},
{
"docstring": null,
"function_declaration": "def quick_select(arr, left, right, n):",
"function_name": "... | [
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def quick_select(arr, left, right, k):\n if left == right:\n return arr[left]\n\n pivot_index = partition(arr, left, right)\n if k == pivot_index... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000014806",
"row_id": 14806,
"seed_ids": "[4919]"
} | 0.561432 | Algorithm_14806 | I | [
"partition",
"quick_select",
"find_nth_longest"
] | 3 | [
[
"find_nth_longest",
"quick_select"
],
[
"quick_select",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8da24d1ddf61a94ba586950a26934972ac3f844d | 071769656c96821dc0386d5289d0971dd45add90 | |||
v1.0 | instruct | Algorithm | Algorithm_14822_I | ### Student Marks Analysis with Different Evaluation Models
You are tasked with implementing evaluation algorithms to analyze student marks using various models: average calculation, weighted average calculation, and standard deviation calculation. The provided functions must handle various input scenarios and edge ca... | from math import sqrt
def average_marks(marks: list[float]) -> float:
"""
Calculate the average of a list of marks.
:param marks: list of float, the marks to calculate the average of.
:return: float, the average of the marks.
"""
if not marks:
raise ValueError("Marks list should no... | import pytest
from solution import average_marks, weighted_average_marks, standard_deviation
def test_average_marks():
assert average_marks([85, 90, 78, 92]) == 86.25
assert average_marks([100, 100, 100]) == 100.0
with pytest.raises(ValueError, match="Marks list should not be empty."):
average_mark... | [
{
"docstring": "Calculate the average of a list of marks.\n\n:param marks: list of float, the marks to calculate the average of.\n:return: float, the average of the marks.",
"function_declaration": "def average_marks(marks):",
"function_name": "average_marks",
"parameter_list": "(marks)"
},
{
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nimport math\n\ndef average_marks(marks: List[float]) -> float:\n if not marks:\n raise ValueError(\"Marks list cannot be empty... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000014822",
"row_id": 14822,
"seed_ids": "[5059]"
} | 0.689679 | Algorithm_14822 | I | [
"average_marks",
"weighted_average_marks",
"standard_deviation"
] | 3 | [
[
"standard_deviation",
"average_marks"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed1640466e14fd23437c3560605ca77f1778e5ba | fe962b24f2bde1c9e0fe0dcf53d811399809e294 | |||
v1.0 | instruct | Algorithm | Algorithm_14871_I | ### Question: Smallest Multiple of Primes Up to N
Given a positive integer `n`, write a function `smallest_prime_multiple(n: int) -> int` that returns the smallest positive number that is divisible by all prime numbers less than or equal to `n`.
You will need to implement two functions: `is_prime(num: int) -> bool` ... | def is_prime(num: int) -> bool:
"""
Returns True if num is a prime number, False otherwise.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
... | def test_is_prime():
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_smallest_prime_multiple():
assert smallest_prime_multiple(1) == 1
assert smallest_prim... | [
{
"docstring": "Returns True if num is a prime number, False otherwise.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the smallest positive number that is divisible by all prime numbers less than or equal to ... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \n Args:\n num (int): The number to check.\n \n Returns:\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014871",
"row_id": 14871,
"seed_ids": "[2081]"
} | 0.720339 | Algorithm_14871 | I | [
"is_prime",
"smallest_prime_multiple"
] | 2 | [
[
"smallest_prime_multiple",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | aaf2965bbd5458dbbc701ffda0831f89bf28ae15 | 618dd40b8542e2d9911e12b96e37f1a11fb5551a | |||
v1.0 | instruct | Algorithm | Algorithm_14905_I | ### Coding Assessment Question
#### Scenario & Context
You are developing a traffic simulation program that models the behavior of vehicles at intersections. One of the critical components of this simulation is to ensure that all vehicles follow the traffic light rules properly and do not collide. Specifically, you ne... | def can_proceed_through_red(vehicle_speed, distance_to_intersection):
"""
Determines if a vehicle can legally proceed through an intersection when the light is red.
Parameters:
- vehicle_speed (float): Speed of the vehicle in meters per second.
- distance_to_intersection (float): Distance from ... | from solution import can_proceed_through_red, distance_to_stop
import pytest
def test_can_proceed_through_red_vehicle_can_stop():
assert not can_proceed_through_red(15.0, 100.0), "Vehicle should be able to stop"
def test_can_proceed_through_red_vehicle_cannot_stop():
assert can_proceed_through_red(15.0, 10.0)... | [
{
"docstring": "Determines if a vehicle can legally proceed through an intersection when the light is red.\n\nParameters:\n- vehicle_speed (float): Speed of the vehicle in meters per second.\n- distance_to_intersection (float): Distance from the vehicle to the intersection in meters.\n\nReturns:\n- bool: True i... | [
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": "def can_proceed_through_red(vehicle_speed, distance_to_intersection):\n \"\"\"\n Determines if a vehicle can legally proceed through a red light based on i... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000014905",
"row_id": 14905,
"seed_ids": "[765]"
} | 0.553713 | Algorithm_14905 | I | [
"can_proceed_through_red",
"distance_to_stop"
] | 2 | [
[
"can_proceed_through_red",
"distance_to_stop"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f50d00ead145828b1662c3160eb82a7714584ffe | 31f9eb5a4b2c562138faaaab6bb29c436eb34c67 | |||
v1.0 | instruct | Algorithm | Algorithm_14913_I | ### Coding Assessment Question
#### Scenario:
You're working with a database system and often need to calculate the Least Common Multiple (LCM) of large sets of integers. This is particularly important for synchronizing processes running at different intervals. You need to create a function that efficiently computes t... | from typing import List
from math import gcd
from functools import reduce
def lcm(a, b):
return abs(a * b) // gcd(a, b)
def compute_lcm(arr: List[int]) -> int:
return reduce(lcm, arr) | from solution import compute_lcm
def test_single_element():
assert compute_lcm([5]) == 5
assert compute_lcm([10]) == 10
def test_multiple_elements():
assert compute_lcm([2, 7, 3, 9, 4]) == 252
assert compute_lcm([5, 10, 20]) == 20
assert compute_lcm([1, 1, 1]) == 1
assert compute_lcm([3, 15, 2... | [
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def compute_lcm(arr):",
"function_name": "compute_lcm",
"parameter_list": "(arr)"
}
] | [
1,
0,
1,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\nfrom typing import List\n\ndef lcm(a, b):\n return abs(a * b) // math.gcd(a, b)\n\ndef compute_lcm(arr: List[int]) ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000014913",
"row_id": 14913,
"seed_ids": "[3207]"
} | 0.664893 | Algorithm_14913 | I | [
"lcm",
"compute_lcm"
] | 2 | [
[
"compute_lcm",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f938485bbfef97c553929aa106143409f0a2f2f0 | 798592403212d07009529273f5c7d336074f1dc5 | |||
v1.0 | instruct | Algorithm | Algorithm_14931_I | ### Question: Smallest Divisible Number
#### Context
Finding the smallest number that is divisible by a subset of integers enhances understanding of number theory and efficient algorithm design.
#### Task
Write a function `smallest_divisible(max_divisor: int) -> int` that computes the smallest positive number that is... | import math
from functools import reduce
def lcm(a, b):
"""
Compute the least common multiple of a and b.
"""
return abs(a * b) // math.gcd(a, b)
def smallest_divisible(max_divisor: int) -> int:
"""
Returns the smallest positive number that is evenly divisible by all numbers from 1 to max_divi... | from solution import smallest_divisible
def test_smallest_divisible_edge_cases():
assert smallest_divisible(1) == 1
assert smallest_divisible(2) == 2
def test_smallest_divisible_typical_cases():
assert smallest_divisible(3) == 6
assert smallest_divisible(4) == 12
assert smallest_divisible(5) == 60... | [
{
"docstring": "Compute the least common multiple of a and b.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the smallest positive number that is evenly divisible by all numbers from 1 to max_divisor.",
"function_... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef lcm(a, b):\n return abs(a*b) // math.gcd(a, b)\n\ndef smallest_divisible(max_divisor: int) -> int:\n if ma... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014931",
"row_id": 14931,
"seed_ids": "[2637]"
} | 0.763342 | Algorithm_14931 | I | [
"lcm",
"smallest_divisible"
] | 2 | [
[
"smallest_divisible",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 33023e3d2043c77d0d1d2fce91b79ad0fe0891df | 2efa30bd09c12bb1f75a851f7188d61d91546adc | |||
v1.0 | instruct | Algorithm | Algorithm_14961_I | ### Question: Validate and Parse URL Components
#### Scenario
You are part of a network management team and frequently need to handle and validate URLs in your system. The ability to extract meaningful information from a URL and verify its validity is essential for your tasks, such as parsing domain names, query param... | import re
from urllib.parse import urlparse
def is_valid_url(url: str) -> bool:
"""
Validates if the input string is a correctly formatted URL.
"""
# Regular expression for validating a URL
# Scheme (http, https, ftp, ftps)
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://... | from solution import is_valid_url, parse_url
def test_is_valid_url():
assert is_valid_url("https://www.example.com") == True
assert is_valid_url("http://www.example.com") == True
assert is_valid_url("ftp://example.com") == True
assert is_valid_url("ftps://example.com") == True
assert is_valid_url("... | [
{
"docstring": "Validates if the input string is a correctly formatted URL.",
"function_declaration": "def is_valid_url(url):",
"function_name": "is_valid_url",
"parameter_list": "(url)"
},
{
"docstring": "Parses the URL into its components and returns a dictionary containing\nthe scheme, ne... | [
1,
1,
0,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from urllib.parse import urlparse\n\ndef is_valid_url(url: str) -> bool:\n \"\"\"\n Validates if the input string is a correctly formatted URL.\n \n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000014961",
"row_id": 14961,
"seed_ids": "[3524]"
} | 0.651764 | Algorithm_14961 | I | [
"is_valid_url",
"parse_url"
] | 2 | [
[
"parse_url",
"is_valid_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c32af4b2b00b4b24439e2953397c4f002a04eca | 2837af3a3ca409c0d09fa6da6fbaa561e1763f3d | |||
v1.0 | instruct | Algorithm | Algorithm_14963_I | ### Trip Planner Optimization
**Context**: You are building a trip planning application that helps users plan a round trip to visit a set of cities efficiently. Given a list of cities with distances between them, your task is to determine the shortest possible route that visits each city exactly once and returns to th... | import itertools
def calculate_route_distance(route, distances):
total_distance = 0
for i in range(len(route) - 1):
total_distance += distances[(route[i], route[i+1])]
total_distance += distances[(route[-1], route[0])] # Return to the starting city
return total_distance
def find_shortest_rout... | from solution import find_shortest_route
def test_find_shortest_route_four_cities():
cities = ["A", "B", "C", "D"]
distances = {
("A", "B"): 10,
("A", "C"): 15,
("A", "D"): 20,
("B", "C"): 35,
("B", "D"): 25,
("C", "D"): 30
}
route = find_shortest_route(c... | [
{
"docstring": null,
"function_declaration": "def calculate_route_distance(route, distances):",
"function_name": "calculate_route_distance",
"parameter_list": "(route, distances)"
},
{
"docstring": null,
"function_declaration": "def find_shortest_route(cities, distances):",
"function... | [
1,
1,
1,
1,
0,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_shortest_route(cities, distances):\n import itertools\n\n def calculate_route_distance(route):\n total_distance = sum(distances[(route[i], ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014963",
"row_id": 14963,
"seed_ids": "[2029]"
} | 0.723731 | Algorithm_14963 | I | [
"calculate_route_distance",
"find_shortest_route"
] | 2 | [
[
"find_shortest_route",
"calculate_route_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 618fb4b1264dd6a40eca2a727e32c425ae7f0195 | 756273efec3c3f25e0e7ebebc664c5bbd02f522c | |||
v1.0 | instruct | Algorithm | Algorithm_14965_I | ### Problem Statement
You are tasked with enhancing the current implementation of a program that processes and analyzes log files from web servers. The existing implementation lacks efficiency and robustness when dealing with large log files and diverse log formats.
### Objective
Implement a function `process_server_l... | import re
import asyncio
from collections import defaultdict
LOG_PATTERN1 = re.compile(r'(?P<ip>\d+\.\d+\.\d+\.\d+) - \[(?P<timestamp>.+?)\] "(?P<method>\w+) (?P<resource>.+?) (?P<http_version>HTTP/\d+\.\d+)" (?P<status>\d+) (?P<size>\d+)')
LOG_PATTERN2 = re.compile(r'(?P<ip>\d+\.\d+\.\d+\.\d+) - - \[(?P<timestamp>.+?... | import pytest
import asyncio
from solution import process_server_logs
@pytest.mark.asyncio
async def test_process_server_logs():
test_logs = """127.0.0.1 - [12/Mar/2023:12:45:23 +0000] "GET /index.html HTTP/1.1" 200 1024
192.168.1.1 - - [12/Mar/2023:12:45:24 +0000] "POST /submit HTTP/1.1" 404 512
127.0.0.1 - [12/M... | [] | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiofiles\nimport re\nfrom collections import defaultdict\n\nasync def process_server_logs(file_path: str) -> dict:\n ip_counts = defaul... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000014965",
"row_id": 14965,
"seed_ids": "[2277]"
} | 0.632619 | Algorithm_14965 | I | [
"process_line",
"process_server_logs"
] | 2 | [
[
"process_server_logs",
"process_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8b4db297f2b0fc015e09ef6d11717b5faaa26915 | c8c7b668063133b976b4f6bb2ab654ff8446849f | |||
v1.0 | instruct | Algorithm | Algorithm_14981_I | ### Shortest Path in a Weighted Directed Acyclic Graph
#### Objective
Implement a function to determine the shortest path from a given source vertex to all other vertices in a Weighted Directed Acyclic Graph (DAG) using a topological sorting approach and dynamic programming.
#### Function Signature
```python
def find... | from typing import List, Dict, Tuple
def topological_sort(graph: Dict[int, List[Tuple[int, int]]]) -> List[int]:
in_degree = {u: 0 for u in graph}
for u in graph:
for v, w in graph[u]:
in_degree[v] += 1
zero_in_degree = [u for u in graph if in_degree[u] == 0]
topo_order = []
w... | from solution import find_shortest_path
def test_example_case():
graph = {
0: [(1, 1), (2, 4)],
1: [(2, 2), (3, 6)],
2: [(3, 3)],
3: []
}
source = 0
assert find_shortest_path(graph, source) == {0: 0, 1: 1, 2: 3, 3: 6}
def test_single_vertex():
graph = {
0: [... | [
{
"docstring": null,
"function_declaration": "def topological_sort(graph):",
"function_name": "topological_sort",
"parameter_list": "(graph)"
},
{
"docstring": null,
"function_declaration": "def find_shortest_path(graph, source):",
"function_name": "find_shortest_path",
"paramete... | [
1,
0,
1,
0,
1,
1,
1,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Dict, List, Tuple\nimport sys\n\ndef find_shortest_path(graph: Dict[int, List[Tuple[int, int]]], source: int) -> Dict[int, int]:\n def topo... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000014981",
"row_id": 14981,
"seed_ids": "[4444]"
} | 0.698268 | Algorithm_14981 | I | [
"topological_sort",
"find_shortest_path"
] | 2 | [
[
"find_shortest_path",
"topological_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed489ea759ad4ec1afcf3bc2a7336b25509fe3b3 | 80f6e85c317ddcfd2bb758249b3d748a6f5dcab6 | |||
v1.0 | instruct | Algorithm | Algorithm_14983_I | ### Task: Create a Simple CLI Task Manager
#### Scenario
You are required to develop a simple Command-Line Interface (CLI) Task Manager application that allows users to manage their to-do tasks. The tool should support adding, listing, and marking tasks as completed.
#### Requirements
1. **Implementation**: Implement... | import json
import os
# Define the file name for storing tasks
TASKS_FILE = 'tasks.json'
def load_tasks():
if not os.path.isfile(TASKS_FILE):
return []
with open(TASKS_FILE, 'r') as file:
return json.load(file)
def save_tasks(tasks):
with open(TASKS_FILE, 'w') as file:
json.dump(t... | import os
import pytest
from solution import add_task, list_tasks, complete_task, load_tasks, save_tasks
@pytest.fixture(autouse=True)
def setup_and_teardown():
# Setup: Backup pre-existing tasks file and create a fresh one.
if os.path.isfile('tasks.json'):
os.rename('tasks.json', 'tasks_backup.json')
... | [
{
"docstring": null,
"function_declaration": "def load_tasks():",
"function_name": "load_tasks",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def save_tasks(tasks):",
"function_name": "save_tasks",
"parameter_list": "(tasks)"
},
{
"docstring": n... | [
1,
1,
1,
1,
0,
1,
1,
0,
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 json\nimport os\n\nTASKS_FILE = 'tasks.json'\n\ndef load_tasks():\n if os.path.exists(TASKS_FILE):\n with open(TASKS_FILE, 'r') as file:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000014983",
"row_id": 14983,
"seed_ids": "[1880]"
} | 0.539525 | Algorithm_14983 | I | [
"load_tasks",
"save_tasks",
"add_task",
"list_tasks",
"complete_task"
] | 5 | [
[
"add_task",
"load_tasks"
],
[
"add_task",
"save_tasks"
],
[
"complete_task",
"load_tasks"
],
[
"complete_task",
"save_tasks"
],
[
"list_tasks",
"load_tasks"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 1375d6a6cc4ceaf1876e959f469d91e826a952f9 | 135cd65ba61ec2872c6fbdcc90c25052192c6060 | |||
v1.0 | instruct | Algorithm | Algorithm_15078_I | ### Challenge: Analyzing Time Complexity of Custom Sorting Algorithm
**Background**:
A new sorting algorithm called "Odd-Even Merge Sort" has been developed, which sorts an array by repeatedly merging two sorted subsequences, one containing elements at odd indices and the other at even indices.
### Task
Write a funct... | def merge(a, b):
"""
Merges two sorted lists into one sorted list.
"""
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result.e... | from solution import odd_even_merge_sort
def test_empty_array():
assert odd_even_merge_sort([]) == []
def test_single_element():
assert odd_even_merge_sort([1]) == [1]
def test_two_elements():
assert odd_even_merge_sort([2, 1]) == [1, 2]
assert odd_even_merge_sort([1, 2]) == [1, 2]
def test_multiple... | [
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def merge(a, b):",
"function_name": "merge",
"parameter_list": "(a, b)"
},
{
"docstring": "Recursively merges subarrays defined by odd and even indexed elements.",
"function_declaration": "def odd_ev... | [
1,
1,
0,
0,
0,
1,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def odd_even_merge_sort(arr: list) -> list:\n def odd_even_merge(arr, left, right, tmp):\n if right - left > 1:\n middle = (left + right) //... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015078",
"row_id": 15078,
"seed_ids": "[3078]"
} | 0.610302 | Algorithm_15078 | I | [
"merge",
"odd_even_merge",
"odd_even_merge_sort"
] | 3 | [
[
"odd_even_merge",
"merge"
],
[
"odd_even_merge_sort",
"odd_even_merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 18bfcf8059961f979b3110f7ea34c9a706a06d62 | eec3742dec7fa5fedf4c9beaab0b4592d501d12e | |||
v1.0 | instruct | Algorithm | Algorithm_15080_I | ## Image Padding and Convolution
### Context:
You are provided with a basic implementation of image padding and convolution for grayscale images. Your task is to extend and optimize this implementation to handle colored images and include different padding types (zero-padding, reflect-padding, and replicate-padding).
... | import numpy as np
def pad_image(img, kernel_shape, padding_type):
pad_height = kernel_shape[0] // 2
pad_width = kernel_shape[1] // 2
if padding_type == 'zero':
return np.pad(img, pad_width=((pad_height, pad_height), (pad_width, pad_width), (0, 0)), mode='constant')
elif padding_type == 'reflec... | import numpy as np
from solution import conv2d_colored
def test_conv2d_colored_zero_padding():
img = np.random.rand(5, 5, 3).astype('float32')
kernel = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]], dtype='float32')
output = conv2d_colored(img, kernel, padding_type='zero')
assert output.shape == (5, 5,... | [
{
"docstring": null,
"function_declaration": "def pad_image(img, kernel_shape, padding_type):",
"function_name": "pad_image",
"parameter_list": "(img, kernel_shape, padding_type)"
},
{
"docstring": null,
"function_declaration": "def conv2d_colored(img, kernel, padding_type='zero'):",
... | [
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 numpy as np\n\ndef conv2d_colored(img: np.ndarray, kernel: np.ndarray, padding_type: str = 'zero') -> np.ndarray:\n \"\"\"\n Applies a 2D convolutio... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000015080",
"row_id": 15080,
"seed_ids": "[3851]"
} | 0.621511 | Algorithm_15080 | I | [
"pad_image",
"conv2d_colored"
] | 2 | [
[
"conv2d_colored",
"pad_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | d5cfaf73f9740d51cc1cdb22ad6632fe0da76925 | 23e6c5b20f997233e451ef9d674508d66e6dad1f | |||
v1.0 | instruct | Algorithm | Algorithm_15224_I | ### Question: Anagram Grouping and Counting
#### Objective
Implement a solution to group a list of words by their anagram groups and return the count of unique anagram groups in the list.
#### Task
1. **Implement a function, `group_anagrams(words: List[str]) -> List[List[str]]`,** that groups a list of words into an... | from collections import defaultdict
from typing import List
def group_anagrams(words: List[str]) -> List[List[str]]:
"""
Groups a list of words into anagram groups.
:param words: List of words
:return: List of anagram groups
"""
anagrams = defaultdict(list)
for word in words:
... | from solution import group_anagrams, count_unique_anagram_groups
def test_group_anagrams_basic():
result = group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
expected = [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
assert sorted([sorted(group) for group in result]) == sorted([sorted(group) for g... | [
{
"docstring": "Groups a list of words into anagram groups.\n\n:param words: List of words\n:return: List of anagram groups",
"function_declaration": "def group_anagrams(words):",
"function_name": "group_anagrams",
"parameter_list": "(words)"
},
{
"docstring": "Counts the number of unique an... | [
0,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import defaultdict\n\ndef group_anagrams(words: List[str]) -> List[List[str]]:\n \"\"\"\n Groups a list of words ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015224",
"row_id": 15224,
"seed_ids": "[3096]"
} | 0.636513 | Algorithm_15224 | I | [
"group_anagrams",
"count_unique_anagram_groups"
] | 2 | [
[
"count_unique_anagram_groups",
"group_anagrams"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2f548f3c73ae72a22373f7531c626f38228ee71 | 09613350715233144da57ec6e1a1fb16468da1df | |||
v1.0 | instruct | Algorithm | Algorithm_15228_I | ### Question: Customizable Dataframe Filter
#### Objective:
As part of a data analysis tool, you are tasked with implementing a customizable dataframe filtering functionality. The implementation should allow for dynamic filtering based on various criteria specified by the user.
#### Part 1: Implementing the Filters
1... | import pandas as pd
def filter_based_on_column_value(df: pd.DataFrame, column: str, value) -> pd.DataFrame:
"""
Filter dataframe based on a specific column and a value condition.
Parameters:
df (pd.DataFrame): The dataframe to filter.
column (str): The column name to apply the filter on.
v... | import pandas as pd
from solution import filter_based_on_column_value, filter_based_on_value_range, apply_multiple_filters
def test_filter_based_on_column_value():
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [24, 30, 22, 27],
'Salary': [50000, 60000, 45000, 7000... | [
{
"docstring": "Filter dataframe based on a specific column and a value condition.\n\nParameters:\ndf (pd.DataFrame): The dataframe to filter.\ncolumn (str): The column name to apply the filter on.\nvalue: The value to filter the column by.\n\nReturns:\npd.DataFrame: Filtered dataframe.",
"function_declarat... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef filter_based_on_column_value(df: pd.DataFrame, column: str, value) -> pd.DataFrame:\n \"\"\"\n Filter dataframe based on a speci... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015228",
"row_id": 15228,
"seed_ids": "[5046]"
} | 0.595842 | Algorithm_15228 | I | [
"filter_based_on_column_value",
"filter_based_on_value_range",
"apply_multiple_filters"
] | 3 | [
[
"apply_multiple_filters",
"filter_based_on_column_value"
],
[
"apply_multiple_filters",
"filter_based_on_value_range"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | fe2b1e8b433d343aa31217367caac522a42944ef | 555f11fa6e4292f7a3887faa1ac1ba58cb316945 | |||
v1.0 | instruct | Algorithm | Algorithm_15251_I | ### Interval Tree - Implementation and Overlapping Intervals Search
#### Background:
An Interval Tree is a data structure to store intervals efficiently and allows for fast retrieving of all intervals that overlap with a given interval. It is particularly useful in applications such as computational geometry and DNA s... | class IntervalTreeNode:
def __init__(self, interval, max_end, left=None, right=None):
"""
Initializes an Interval Tree node.
:param interval: The interval represented by this node.
:param max_end: The maximum end value of all intervals in the subtree rooted at this node.
... | import pytest
from solution import IntervalTreeNode, build_interval_tree, find_overlapping_intervals
def test_build_interval_tree_empty():
assert build_interval_tree([]) is None
def test_build_interval_tree_single_interval():
interval = (1, 5)
tree = build_interval_tree([interval])
assert tree is not ... | [] | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class IntervalTreeNode:\n def __init__(self, interval):\n self.interval = interval\n self.left = None\n self.right = None\n self.m... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000015251",
"row_id": 15251,
"seed_ids": "[1333]"
} | 0.642694 | Algorithm_15251 | I | [
"build_interval_tree",
"do_intervals_overlap",
"find_overlapping_intervals"
] | 3 | [
[
"find_overlapping_intervals",
"do_intervals_overlap"
]
] | 1 | [] | false | [
"IntervalTreeNode"
] | true | pytest | true | [] | true | d59ba7f64c5d3a68b7d65651a5d5c728a936c0b3 | 6e99413c22f857999357b19fdb47bd1ada7a6c04 | |||
v1.0 | instruct | Algorithm | Algorithm_15271_I | ### Problem Statement:
You are given a collection of numbers, each represented as a list of digits. Your task is to write a function `find_largest_number(arr: list) -> str` that arranges the numbers in such a way that they form the largest possible concatenated number.
### Function Signature:
```python
def find_large... | def custom_compare(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
def find_largest_number(arr: list) -> str:
"""
Rearranges the numbers to form the largest possible concatenated number.
"""
from functools import cmp_to_key
# C... | from solution import find_largest_number
def test_find_largest_number_basic():
assert find_largest_number([10, 2]) == "210"
def test_find_largest_number_longer_list():
assert find_largest_number([3, 30, 34, 5, 9]) == "9534330"
def test_find_largest_number_with_zeros():
assert find_largest_number([0, 0, 0... | [
{
"docstring": null,
"function_declaration": "def custom_compare(x, y):",
"function_name": "custom_compare",
"parameter_list": "(x, y)"
},
{
"docstring": "Rearranges the numbers to form the largest possible concatenated number.",
"function_declaration": "def find_largest_number(arr):",
... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from functools import cmp_to_key\n\ndef compare(a, b):\n \"\"\"\n Custom comparator for sorting.\n If a + b is greater than b + a, then a should come be... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015271",
"row_id": 15271,
"seed_ids": "[4926]"
} | 0.711779 | Algorithm_15271 | I | [
"custom_compare",
"find_largest_number"
] | 2 | [
[
"find_largest_number",
"custom_compare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27b995bd1aec4b38ce99f6abc1561efb28a298f7 | 1177d75b05a4e67b500b305be402012ed87417dc | |||
v1.0 | instruct | Algorithm | Algorithm_15356_I | ### Palindrome Checker Implementation Challenge
#### Objective
You are tasked to implement a function to check if a given string is a palindrome using both iterative and recursive approaches.
#### Scenario
Consider a program that needs to check whether a string is a palindrome as part of its string manipulation tasks... | import re
def preprocess_string(s):
"""
Preprocess the string by converting to lowercase, and removing non-alphanumeric characters.
"""
return re.sub(r'[^a-z0-9]', '', s.lower())
def is_palindrome_iterative(s):
"""
Check if a given string is a palindrome using an iterative approach.
"""
... | from solution import is_palindrome_iterative, is_palindrome_recursive
def test_is_palindrome_iterative():
assert is_palindrome_iterative("A man, a plan, a canal, Panama") == True
assert is_palindrome_iterative("Racecar") == True
assert is_palindrome_iterative("Hello, world!") == False
assert is_palindr... | [
{
"docstring": "Preprocess the string by converting to lowercase, and removing non-alphanumeric characters.",
"function_declaration": "def preprocess_string(s):",
"function_name": "preprocess_string",
"parameter_list": "(s)"
},
{
"docstring": "Check if a given string is a palindrome using an... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef clean_string(s):\n \"\"\" Helper function to remove non-alphanumeric characters and convert to lower case. \"\"\"\n return re.sub(r'[^a-zA... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015356",
"row_id": 15356,
"seed_ids": "[3172]"
} | 0.745105 | Algorithm_15356 | I | [
"preprocess_string",
"is_palindrome_iterative",
"is_palindrome_recursive"
] | 3 | [
[
"is_palindrome_iterative",
"preprocess_string"
],
[
"is_palindrome_recursive",
"preprocess_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c539376050b4d1b008fb0a96cd0b901e1a2e0860 | c5f27311781da33ef0fdd7a0ea93300339cde4d0 | |||
v1.0 | instruct | Algorithm | Algorithm_15369_I | ### Scenario
You are managing a logistics company and need to develop a software solution to optimize the delivery routes. The goal is to ensure that each delivery vehicle starts from the warehouse, visits a set of designated delivery points, and returns to the warehouse. The route should be optimized for the shortest ... | from itertools import permutations
from typing import List, Tuple
def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
"""
Calculate the Euclidean distance between two points.
"""
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
def total_distance(route: List[Tuple[int... | from solution import optimize_route
def test_single_delivery():
warehouse = (0, 0)
deliveries = [(2, 2)]
assert optimize_route(warehouse, deliveries) == [(0, 0), (2, 2), (0, 0)]
def test_two_deliveries():
warehouse = (0, 0)
deliveries = [(1, 1), (2, 2)]
assert optimize_route(warehouse, deliver... | [
{
"docstring": "Calculate the Euclidean distance between two points.",
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Calculate the total distance of the given route.",
"function_declaratio... | [
1,
0,
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 itertools\nfrom typing import List, Tuple\n\ndef calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\"\"\n Calculate... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000015369",
"row_id": 15369,
"seed_ids": "[4376]"
} | 0.67863 | Algorithm_15369 | I | [
"calculate_distance",
"total_distance",
"optimize_route"
] | 3 | [
[
"optimize_route",
"total_distance"
],
[
"total_distance",
"calculate_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5179e1bac0a3bf34ece5964a4c4958353aad9472 | 2f29bddc004b8b9596d600dcf6d89ebd3b11e9f1 | |||
v1.0 | instruct | Algorithm | Algorithm_15371_I | ### Question: Implement K-Means Clustering and Silhouette Score
You are given a dataset with multiple features. Write code to implement the K-Means clustering algorithm and compute the silhouette score to evaluate the clustering performance. The silhouette score should be calculated for a range of cluster numbers to d... | import numpy as np
from typing import List, Tuple
from scipy.spatial.distance import cdist
from sklearn.metrics import silhouette_score
def k_means_clustering(features: np.ndarray, num_clusters: int, max_iters: int = 300) -> Tuple[np.ndarray, np.ndarray]:
"""
Perform K-Means clustering
Args:
featu... | import numpy as np
from solution import k_means_clustering, compute_silhouette_score, optimal_clusters
def test_k_means_clustering():
features = np.array([[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0], [8.0, 2.0]])
centroids, labels = k_means_clustering(features, 3)
assert centroi... | [
{
"docstring": "Perform K-Means clustering\n\nArgs:\nfeatures: 2D NumPy array of shape (n_samples, n_features)\nnum_clusters: Integer, number of clusters to form\nmax_iters: Integer, maximum number of iterations\n\nReturns:\ncentroids: 2D NumPy array of shape (num_clusters, n_features)\ncluster_labels: 1D NumPy... | [
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 numpy as np\nfrom typing import List, Tuple\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.cluster import KMeans\n\ndef k_means_clustering(fe... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000015371",
"row_id": 15371,
"seed_ids": "[510]"
} | 0.690574 | Algorithm_15371 | I | [
"k_means_clustering",
"compute_silhouette_score",
"optimal_clusters"
] | 3 | [
[
"optimal_clusters",
"compute_silhouette_score"
],
[
"optimal_clusters",
"k_means_clustering"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy",
"sklearn"
] | false | ac5c2846c70d4c10d749ce2c991daad416384cd8 | 9a28f49d29839d6bcd7f99539bff10ae35016245 | |||
v1.0 | instruct | Algorithm | Algorithm_15374_I | ### Coding Problem: Optimal Delivery Path for Parcels
#### Context:
Logistics companies often face the challenge of optimizing delivery routes to ensure timely and cost-efficient parcel deliveries. They must determine the shortest path through a series of stops while considering various constraints such as road condit... | import heapq
def calculate_delivery_costs(start, road_conditions):
# Initialize cost and time tables
cost = {start: 0}
time = {start: 0}
pq = [(0, 0, start)] # priority queue: (current_cost, current_time, current_node)
while pq:
current_cost, current_time, current_node = heapq.heappop... | from solution import find_optimal_delivery_path
def test_find_optimal_delivery_path_basic():
road_conditions = {
("A", "B"): (3, 15), # (cost, time)
("A", "C"): (5, 10),
("B", "C"): (2, 5),
("B", "D"): (6, 20),
("C", "D"): (4, 10)
}
assert find_optimal_delivery_path... | [
{
"docstring": null,
"function_declaration": "def calculate_delivery_costs(start, road_conditions):",
"function_name": "calculate_delivery_costs",
"parameter_list": "(start, road_conditions)"
},
{
"docstring": null,
"function_declaration": "def derive_optimal_path(start, delivery_locatio... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef calculate_delivery_costs(start, delivery_locations, road_conditions):\n # Initialize the data structures to store the minimum costs and mi... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000015374",
"row_id": 15374,
"seed_ids": "[1598]"
} | 0.669958 | Algorithm_15374 | I | [
"calculate_delivery_costs",
"derive_optimal_path",
"find_optimal_delivery_path"
] | 3 | [
[
"find_optimal_delivery_path",
"calculate_delivery_costs"
],
[
"find_optimal_delivery_path",
"derive_optimal_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3f0ae7b3f1a8f926767dc13c137fa923357d8079 | 3228866df6845c2bb9555be238e5f200197d368f | |||
v1.0 | instruct | Algorithm | Algorithm_15376_I | ### Problem Statement
#### Objective
Write a program in any language of your choice that generates the nth number in the Fibonacci sequence. Implement the solution using both an iterative and a recursive approach within the same program.
#### Motivation
This task assesses your understanding of the Fibonacci sequence,... | def fib_iterative(n):
"""
Returns the nth Fibonacci number using an iterative approach.
"""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
def fib_recursive(n):
"""
Returns the nth Fibonacci number using a recursive approach.
"""
if n == 0:
return 0
... | from solution import fib_iterative, fib_recursive, get_fibonacci_number
def test_fib_iterative():
assert fib_iterative(0) == 0
assert fib_iterative(1) == 1
assert fib_iterative(10) == 55
assert fib_iterative(20) == 6765
def test_fib_recursive():
assert fib_recursive(0) == 0
assert fib_recursiv... | [
{
"docstring": "Returns the nth Fibonacci number using an iterative approach.",
"function_declaration": "def fib_iterative(n):",
"function_name": "fib_iterative",
"parameter_list": "(n)"
},
{
"docstring": "Returns the nth Fibonacci number using a recursive approach.",
"function_declarati... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def fib_iterative(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n a, b = 0, 1\n for _ in range(2, n + 1):\n a, b = b, a ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000015376",
"row_id": 15376,
"seed_ids": "[4888]"
} | 0.749967 | Algorithm_15376 | I | [
"fib_iterative",
"fib_recursive",
"get_fibonacci_number"
] | 3 | [
[
"get_fibonacci_number",
"fib_iterative"
],
[
"get_fibonacci_number",
"fib_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9c68fcefd8f1015b73fece870d4da1d71d92e5c1 | cb0d9bf277c8181322cd8e3ae2280bb6957a9ad0 | |||
v1.0 | instruct | Algorithm | Algorithm_15389_I | ### Coding Assessment Question
You are given a function `optimize_route` that determines the shortest path between two points in a weighted directed graph representing a city's transportation network. This function adheres to Dijkstra's algorithm for shortest path calculation and includes validation to ensure no negat... | import heapq
def dijkstra(graph, start, end):
# Initialize distances and priority queue
distances = {node: float('inf') for node in graph}
distances[start] = 0
priority_queue = [(0, start)]
paths = {node: [] for node in graph}
paths[start].append(start)
while priority_queue:
cu... | def test_dijkstra():
graph = {
'A': {'B': 1, 'C': 4},
'B': {'C': 2, 'D': 5},
'C': {'D': 1},
'D': {}
}
distance, path = dijkstra(graph, 'A', 'D')
assert distance == 4
assert path == ['A', 'B', 'C', 'D']
def test_enhanced_optimize_route():
graph = {
'A': {'... | [
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start, end):",
"function_name": "dijkstra",
"parameter_list": "(graph, start, end)"
},
{
"docstring": null,
"function_declaration": "def enhanced_optimize_route(graph, route_requests):",
"function_name": "enhanced_opti... | [
0,
1,
1,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef optimize_route(graph, start, end):\n \"\"\"\n Dijkstra's algorithm to find the shortest path from start to end in the graph.\n \"\"\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000015389",
"row_id": 15389,
"seed_ids": "[740]"
} | 0.690484 | Algorithm_15389 | I | [
"dijkstra",
"enhanced_optimize_route"
] | 2 | [
[
"enhanced_optimize_route",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | eda97a0f73a5ea0af2baa3d6a1def91021405280 | 08d13ad10dfa55b551ddc55a1b084c0230506042 | |||
v1.0 | instruct | Algorithm | Algorithm_15474_I | ### Maze Pathfinding with A*
**Scenario**:
You are assigned to implement a pathfinding algorithm for a maze-solving robot. The robot needs to navigate through a grid-based maze from a start point to an end point using the A* search algorithm.
**Objective**:
Write a function `astar_maze_solver(maze: List[List[int]], s... | from heapq import heappop, heappush
from typing import List, Tuple
def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def astar_maze_solver(maze: List[List[int]], start: Tuple[int, int], end: Tuple[int, int]) -> List[Tuple[int, int]]:
rows = len(maze)
... | from solution import astar_maze_solver
def test_astar_maze_solver_simple_path():
maze = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[1, 1, 0, 1, 0],
[0, 0, 0, 0, 0]
]
start = (0, 0)
end = (4, 4)
result = astar_maze_solver(maze, start, end)
expect... | [
{
"docstring": null,
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def astar_maze_solver(maze, start, end):",
"function_name": "astar_maze_solver",
"parameter_list": "(maze... | [
0,
1,
0,
0,
1,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport heapq\n\ndef astar_maze_solver(maze: List[List[int]], start: Tuple[int, int], end: Tuple[int, int]) -> List[Tuple[int, int... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015474",
"row_id": 15474,
"seed_ids": "[4001]"
} | 0.643665 | Algorithm_15474 | I | [
"heuristic",
"astar_maze_solver"
] | 2 | [
[
"astar_maze_solver",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 66b5667cc64c8392ffbde7d5b56eeda759358241 | 6598a1bcd7c02bdf8b47cf462aeaea4822520202 | |||
v1.0 | instruct | Algorithm | Algorithm_15538_I | ## Question
Sorting algorithms are fundamental in computer science, playing a crucial role in data organization and retrieval. Implement the QuickSort algorithm to sort a list of integers in ascending order. The function should modify the input list in-place and not return any value.
### Function Signature
```python
d... | from typing import List
def partition(arr: List[int], low: int, high: int) -> int:
pivot = arr[high] # choosing the last element as pivot
i = low - 1 # index of smaller element
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i] # swap el... | from solution import quicksort
def test_quicksort_example1():
arr = [10, 7, 8, 9, 1, 5]
quicksort(arr, 0, len(arr) - 1)
assert arr == [1, 5, 7, 8, 9, 10]
def test_quicksort_example2():
arr = [3, -1, 2, 1, 0, 3, 2]
quicksort(arr, 0, len(arr) - 1)
assert arr == [-1, 0, 1, 2, 2, 3, 3]
def test_q... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quicksort(arr, low, high):",
"function_name": "quicksort",
"parameter_list": "(ar... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef partition(arr: List[int], low: int, high: int) -> int:\n pivot = arr[high]\n i = low - 1\n \n for j in range(low, high... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015538",
"row_id": 15538,
"seed_ids": "[2073]"
} | 0.645684 | Algorithm_15538 | I | [
"partition",
"quicksort"
] | 2 | [
[
"quicksort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 43cea46e6d22d3b3556e6e128e4998e6d4bee14e | 1a0428b362ce7f7c2d17ef92dcd333eb11beb461 | |||
v1.0 | instruct | Algorithm | Algorithm_15597_I | ### Merge Sort - Recursive Sorting Algorithm
You are a software engineer at a company focused on developing efficient sorting algorithms. Your latest task involves implementing the "Merge Sort" algorithm, which is a classic divide-and-conquer algorithm.
#### Merge Sort
Merge Sort works by recursively dividing the uns... | def merge_sort(arr: list[int]) -> list[int]:
"""
Sorts an array of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def... | from solution import merge_sort
def test_merge_sort_with_positive_numbers():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_unsorted_list():
assert merge_sort([1, 5, 3, 2, 8, 7, 6, 4]) == [1, 2, 3, 4, 5, 6, 7, 8]
def test_merge_sort_with_empty_list():
... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def merge(left... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr: list[int]) -> list[int]:\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \n Parameters:\n arr (list[in... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015597",
"row_id": 15597,
"seed_ids": "[4865]"
} | 0.623752 | Algorithm_15597 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0591c8ef28d3f3e4254301cd5437a10d5c6689dd | 19f6256941959d9de0a34ace64fa093237ea96c4 | |||
v1.0 | instruct | Algorithm | Algorithm_15738_I | ### Problem Statement
In a database system, we often need to keep track of data insertion events and the timestamps associated with them. One efficient way to manage this is by using a binary search tree (BST) where each node contains a timestamp and an associated value. For this problem, you will implement a function... | class Node:
def __init__(self, timestamp: int, value: int):
self.timestamp = timestamp
self.value = value
self.left = None
self.right = None
self.size = 1 # Size of the subtree including this node
def insert_bst(root: Node, timestamp: int, value: int) -> Node:
if root i... | import pytest
def create_bst_with_values():
root = None
root = insert_bst(root, 50, 1)
root = insert_bst(root, 30, 2)
root = insert_bst(root, 70, 3)
root = insert_bst(root, 20, 4)
root = insert_bst(root, 40, 5)
root = insert_bst(root, 60, 6)
root = insert_bst(root, 80, 7)
return roo... | [] | [
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": "class Node:\n def __init__(self, timestamp: int, value: int):\n self.timestamp = timestamp\n self.value = value\n self.left = None\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015738",
"row_id": 15738,
"seed_ids": "[4016]"
} | 0.490336 | Algorithm_15738 | I | [
"insert_bst",
"find_nth_largest",
"find_kth_smallest"
] | 3 | [
[
"find_nth_largest",
"find_kth_smallest"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | false | [] | true | 6384374715e33d98b1f0d4bce40bdcd49c9d8978 | ee43d4cf1bf512548c2446a30660acfe18682543 | |||
v1.0 | instruct | Algorithm | Algorithm_15757_I | ### Array Intersection Finder
**Objective**: In this task, you will implement a function that reads a file containing multiple pairs of arrays and determines the intersection of each pair.
### Problem Statement:
You are given a text file with `n` lines, each containing two arrays of integers separated by a pipe (`|`)... | from typing import List
def array_intersection(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Find the intersection of two arrays and return it as a sorted list.
"""
# Convert both lists to sets to find the intersection
set1 = set(arr1)
set2 = set(arr2)
# Find the intersection and... | import pytest
from solution import array_intersection, find_all_intersections
def test_array_intersection():
assert array_intersection([1, 2, 3, 4], [3, 4, 5, 6]) == [3, 4]
assert array_intersection([5, 6, 7], [7, 8, 9]) == [7]
assert array_intersection([1, 2, 3], [4, 5, 6]) == []
assert array_intersec... | [
{
"docstring": "Find the intersection of two arrays and return it as a sorted list.",
"function_declaration": "def array_intersection(arr1, arr2):",
"function_name": "array_intersection",
"parameter_list": "(arr1, arr2)"
},
{
"docstring": "Read the file and return a list of intersections for... | [
1,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef array_intersection(arr1: List[int], arr2: List[int]) -> List[int]:\n \"\"\"\n Find the intersection of two arrays and return... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015757",
"row_id": 15757,
"seed_ids": "[2511]"
} | 0.658638 | Algorithm_15757 | I | [
"array_intersection",
"find_all_intersections"
] | 2 | [
[
"find_all_intersections",
"array_intersection"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a7506b03e3c2bad8c39eee668a82894e51566053 | d6d9b7d3b08c8040ced1e8cf69348d075b29f1c3 | |||
v1.0 | instruct | Algorithm | Algorithm_15797_I | You are required to implement a function that computes the Greatest Common Divisor (GCD) of an array of integers using the Euclidean algorithm. Specifically, implement a function that takes a list of integers and returns their GCD.
### Function Signature:
```python
def gcd_of_array(nums: List[int]) -> int:
"""
... | from typing import List
def gcd(a: int, b: int) -> int:
"""
Helper function to compute the GCD of two integers using the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def gcd_of_array(nums: List[int]) -> int:
"""
Calculate the GCD of an array of integers using the Eucl... | def test_gcd_of_array():
assert gcd_of_array([24, 36, 48]) == 12
assert gcd_of_array([5, 10, 15]) == 5
assert gcd_of_array([17, 19, 23]) == 1
assert gcd_of_array([27]) == 27
assert gcd_of_array([4, 8, 16]) == 4
assert gcd_of_array([7, 14, 21, 28]) == 7
assert gcd_of_array([100, 200, 300]) ==... | [
{
"docstring": "Helper function to compute the GCD of two integers using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the GCD of an array of integers using the Euclidean algorithm.",
"... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef gcd_of_array(nums: List[int]) -> int:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000015797",
"row_id": 15797,
"seed_ids": "[4141]"
} | 0.75137 | Algorithm_15797 | I | [
"gcd",
"gcd_of_array"
] | 2 | [
[
"gcd_of_array",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f9c25b57959977f9377c285990179e48f4acef3f | 3ee0e4866934439fcaa5038d2939cc9c315a5096 | |||
v1.0 | instruct | Algorithm | Algorithm_15799_I | **Context**: Your task is to refactor a system that processes client transactions. The current method employs a single-threaded approach, processing one transaction at a time. This has led to significant processing delays. Your aim is to improve the performance and reduce latency by implementing a multithreaded solutio... | from concurrent.futures import ThreadPoolExecutor
from typing import List, Tuple
def process_single_transaction(transaction: Tuple[int, str, float]) -> str:
transaction_id, transaction_type, amount = transaction
return f"Transaction {transaction_id}: {transaction_type} {amount} processed"
def process_transact... | from solution import process_transactions
def test_process_single_transaction_deposit():
transaction = (1, "deposit", 100.0)
result = process_transactions([transaction], max_workers=1)
assert result == ["Transaction 1: deposit 100.0 processed"]
def test_process_single_transaction_withdrawal():
transac... | [
{
"docstring": null,
"function_declaration": "def process_single_transaction(transaction):",
"function_name": "process_single_transaction",
"parameter_list": "(transaction)"
},
{
"docstring": null,
"function_declaration": "def process_transactions(transaction_list, max_workers):",
"f... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport concurrent.futures\n\ndef process_transactions(transaction_list: List[Tuple[int, str, float]], max_workers: int) -> List[s... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015799",
"row_id": 15799,
"seed_ids": "[516]"
} | 0.524074 | Algorithm_15799 | I | [
"process_single_transaction",
"process_transactions"
] | 2 | [
[
"process_transactions",
"process_single_transaction"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 059cece8e5a734d07d7e189a9295ec045001ae2d | 75cc69993e9ad4521c29e6b33e2435974805dd21 | |||
v1.0 | instruct | Algorithm | Algorithm_15818_I | ### Tiling a Floor with L-shaped Tiles
Given a 2D grid representing a floor of size `m x n`, write a function `can_tile_fully(m: int, n: int) -> bool` that checks if the floor can be fully tiled by L-shaped tiles of size 2x2 with one square removed (forming an L shape). Each L-shaped tile covers exactly 3 squares.
Ne... | def can_tile_fully(m: int, n: int) -> bool:
"""
Returns True if a m x n grid can be fully tiled by L-shaped tiles of size 2x2 with one square removed (each covering 3 squares), False otherwise.
"""
# Check if the total number of squares is divisible by 3
return (m * n) % 3 == 0
def find_full_tiling... | from solution import can_tile_fully, find_full_tiling_grids
def test_can_tile_fully():
assert can_tile_fully(3, 3) == True
assert can_tile_fully(2, 2) == False
assert can_tile_fully(3, 1) == True
assert can_tile_fully(4, 4) == False
def test_find_full_tiling_grids():
result = find_full_tiling_grid... | [
{
"docstring": "Returns True if a m x n grid can be fully tiled by L-shaped tiles of size 2x2 with one square removed (each covering 3 squares), False otherwise.",
"function_declaration": "def can_tile_fully(m, n):",
"function_name": "can_tile_fully",
"parameter_list": "(m, n)"
},
{
"docstri... | [
0,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def can_tile_fully(m: int, n: int) -> bool:\n \"\"\"\n Returns True if the floor of size m x n can be fully tiled with L-shaped tiles,\n otherwise retur... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000015818",
"row_id": 15818,
"seed_ids": "[2187]"
} | 0.73048 | Algorithm_15818 | I | [
"can_tile_fully",
"find_full_tiling_grids"
] | 2 | [
[
"find_full_tiling_grids",
"can_tile_fully"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ea49b411e1ee9e0f21eaee1402a098af42668f1 | fbd42cf8cf9b04701ab6a5b07f8007976fd7b5a7 | |||
v1.0 | instruct | Algorithm | Algorithm_15882_I | ### Context:
You need to optimize a large dataset processing task using multi-threading. Given a list of integers, you will split the list into chunks and compute the sum of squares of the integers in each chunk using multiple threads concurrently. Finally, you will combine the partial results from each thread to obtai... | import threading
def sum_of_squares(arr):
"""
Computes the sum of squares of the integers in the array.
"""
return sum(x ** 2 for x in arr)
def sum_of_squares_multithreaded(data, num_threads):
"""
Computes the sum of squares of the integers in the data array
using multi-threading.
... | import pytest
from solution import sum_of_squares_multithreaded
def test_sum_of_squares_empty_list():
assert sum_of_squares_multithreaded([], 4) == 0
def test_sum_of_squares_single_element():
assert sum_of_squares_multithreaded([3], 2) == 9
def test_sum_of_squares_two_even_chunks():
assert sum_of_squares... | [
{
"docstring": "Computes the sum of squares of the integers in the array.",
"function_declaration": "def sum_of_squares(arr):",
"function_name": "sum_of_squares",
"parameter_list": "(arr)"
},
{
"docstring": "Computes the sum of squares of the integers in the data array \nusing multi-threadin... | [
1,
0,
1,
0,
0,
1,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import threading\n\ndef sum_of_squares(arr):\n \"\"\"\n Returns the sum of squares of all integers in the array.\n \"\"\"\n return sum(x ** 2 for x i... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000015882",
"row_id": 15882,
"seed_ids": "[4235]"
} | 0.618252 | Algorithm_15882 | I | [
"sum_of_squares",
"sum_of_squares_multithreaded"
] | 2 | [
[
"sum_of_squares_multithreaded",
"sum_of_squares"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5837771c94b20afa7a706e3d6a79a33bfee7f67b | 213a08419d0a488a074ade22017f652b8bc77976 | |||
v1.0 | instruct | Algorithm | Algorithm_15918_I | ### Scenario
You are developing software for a company that processes large sets of geographical data. One task is to find the closest pair of coordinates among a given set of coordinates.
### Function Details
Implement a function `find_closest_pair` that takes a list of tuples where each tuple contains two floating... | import math
def euclidean_distance(coord1, coord2):
return math.sqrt((coord1[0] - coord2[0])**2 + (coord1[1] - coord2[1])**2)
def find_closest_pair(coordinates):
if len(coordinates) < 2:
raise ValueError("At least two coordinates are required")
min_distance = float('inf')
closest_pair = N... | from solution import find_closest_pair
def test_find_closest_pair_basic():
coords = [(0, 0), (1, 1), (2, 2)]
assert find_closest_pair(coords) == ((0, 0), (1, 1))
def test_find_closest_pair_identical_points():
coords = [(1, 1), (1, 1), (2, 2)]
assert find_closest_pair(coords) == ((1, 1), (1, 1))
def t... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(coord1, coord2):",
"function_name": "euclidean_distance",
"parameter_list": "(coord1, coord2)"
},
{
"docstring": null,
"function_declaration": "def find_closest_pair(coordinates):",
"function_name": "find_closest_pa... | [
1,
1,
0,
1,
0,
1,
1,
1,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl",
"solution_code": "def euclidean_distance(coord1, coord2):\n \"\"\"\n Computes the Euclidean distance between two coordinates.\n \"\"\"\n retur... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000015918",
"row_id": 15918,
"seed_ids": "[655]"
} | 0.721042 | Algorithm_15918 | I | [
"euclidean_distance",
"find_closest_pair"
] | 2 | [
[
"find_closest_pair",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 45c2f9d2e2e180d26d532588c7489a507a0754bf | db9306127eeb6f6ebf4858d99affe91cc0beefc9 | |||
v1.0 | instruct | Algorithm | Algorithm_15925_I | You are asked to enhance an existing function `fetch_openweather_city_data` to improve its capability to handle various edge cases and optimize performance. The function should collect weather data from the OpenWeatherMap API and process the information as specified. Ensure to include the following improvements:
1. **... | import aiohttp
import asyncio
from typing import List, Dict, Union
async def fetch_weather_for_city(session, city, api_key, retries=3, delay=1):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
for attempt in range(retries):
try:
async with sessi... | import pytest
import asyncio
from solution import fetch_openweather_city_data_async
@pytest.mark.asyncio
async def test_fetch_openweather_city_data_async_success():
cities = ["London"]
api_key = "your_valid_api_key"
results = await fetch_openweather_city_data_async(cities, api_key)
assert len(results)... | [] | [
0,
1,
1,
0,
1,
1,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Dict, Union\n\nasync def fetch_weather(city: str, api_key: str, session: aiohttp.ClientSession) -> Dict[... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000015925",
"row_id": 15925,
"seed_ids": "[1907]"
} | 0.580212 | Algorithm_15925 | I | [
"fetch_weather_for_city",
"fetch_openweather_city_data_async"
] | 2 | [
[
"fetch_openweather_city_data_async",
"fetch_weather_for_city"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 8b00b52a62bed7d80c4df5c8f7270757ebe234cb | c400578837e4f3083085e609c082993644e14178 | |||
v1.0 | instruct | Algorithm | Algorithm_16033_I | ### Coding Assessment Question
#### Objective:
Implement a function that rotates a square matrix 90 degrees clockwise. Then, create another function that verifies if two matrices are identical after rotation.
#### Problem Statement:
You need to create a function `rotate_matrix(matrix: List[List[int]]) -> List[List[in... | from typing import List
def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotates a given NxN matrix 90 degrees clockwise.
"""
n = len(matrix)
new_matrix = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n-i-1] = matrix[i][... | from solution import rotate_matrix, are_matrices_identical_after_rotation
def test_rotate_matrix_3x3():
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
expected = [[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
assert rotate_matrix(matrix) == expected
... | [
{
"docstring": "Rotates a given NxN matrix 90 degrees clockwise.",
"function_declaration": "def rotate_matrix(matrix):",
"function_name": "rotate_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Checks if the original matrix is identical to the rotated matrix after a 90 degrees rotat... | [
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 rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates an N x N matrix by 90 degrees clockwise.\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000016033",
"row_id": 16033,
"seed_ids": "[1409]"
} | 0.629832 | Algorithm_16033 | I | [
"rotate_matrix",
"are_matrices_identical_after_rotation"
] | 2 | [
[
"are_matrices_identical_after_rotation",
"rotate_matrix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2eb80e991df0c49940af29b7de717b7bdb534222 | ad780279d82d91fc13c7f18d3cb6ad1e7cb4b100 | |||
v1.0 | instruct | Algorithm | Algorithm_16062_I | ### Sudoku Solver
You have been tasked with creating a Sudoku solver. Using Python, you will write a function to solve a given 9x9 Sudoku puzzle. The puzzle will be provided as a list of lists where empty cells are represented by 0.
### Requirements:
1. **Sudoku Solver Function**
- Write a function to solve the S... | def solve_sudoku(board: list[list[int]]) -> bool:
"""
Solves the given 9x9 Sudoku puzzle.
:param board: 2D list representing the sudoku table with 0s as empty spaces.
:return: True if the puzzle is solved correctly, otherwise False.
"""
empty = find_empty(board)
if not empty:
return ... | from solution import solve_sudoku, is_valid, find_empty, read_sudoku_from_file, write_sudoku_to_file
def test_solve_sudoku():
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, ... | [
{
"docstring": "Solves the given 9x9 Sudoku puzzle.\n:param board: 2D list representing the sudoku table with 0s as empty spaces.\n:return: True if the puzzle is solved correctly, otherwise False.",
"function_declaration": "def solve_sudoku(board):",
"function_name": "solve_sudoku",
"parameter_list"... | [
1,
0,
1,
0,
0,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def solve_sudoku(board: list[list[int]]) -> bool:\n empty = find_empty(board)\n if not empty:\n return True\n row, col = empty\n\n for num in ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000016062",
"row_id": 16062,
"seed_ids": "[308]"
} | 0.649563 | Algorithm_16062 | I | [
"solve_sudoku",
"is_valid",
"find_empty",
"read_sudoku_from_file",
"write_sudoku_to_file"
] | 5 | [
[
"solve_sudoku",
"find_empty"
],
[
"solve_sudoku",
"is_valid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 45f59b18202bffe1dfacb3b59d7c524d5b85a54d | 95a0045c2f882b4ef566dffca1418a079a84ecc4 | |||
v1.0 | instruct | Algorithm | Algorithm_16105_I | ### Coding Assessment Question
**Background**:
Sorting algorithms are fundamental in computer science, often serving as building blocks for more complex algorithms. One such algorithm is the "Merge Sort", a divide-and-conquer algorithm that splits the array into halves, sorts them recursively, and then merges the sor... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
This function implements the Merge Sort algorithm to sort a list of integers.
"""
if len(arr) <= 1:
return arr
# Divide the array into two halves
middle = len(arr) // 2
left_half = merge_sort(arr[:middle])
... | from solution import merge_sort
def test_merge_sort_with_positive_numbers():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_mixed_numbers():
assert merge_sort([5, 1, 4, 2, -8]) == [-8, 1, 2, 4, 5]
def test_merge_sort_with_duplicates():
assert merge_so... | [
{
"docstring": "This function implements the Merge Sort algorithm to sort a list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "This helper function merges two sorted lists into a single sorted list."... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000016105",
"row_id": 16105,
"seed_ids": "[4547]"
} | 0.588012 | Algorithm_16105 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b48203ae7ab27f4c35cfdf40b49f92b86e983a44 | 019f4ffe011c526be1ea869d1b6a05460df2e76b | |||
v1.0 | instruct | Algorithm | Algorithm_16114_I | ### Coding Assessment: Implementing K-Nearest Neighbors (KNN)
**Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. This will demonstrate your understanding of distance measures and classification based on neighborhood voting.
### Problem Statement
Given a series of steps an... | import math
from collections import Counter
def calculate_euclidean_distance(point1: list[float], point2: list[float]) -> float:
"""
Calculate the Euclidean distance between two points.
"""
return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))
def fit_knn_model(features: list[list[float]... | from solution import calculate_euclidean_distance, fit_knn_model, predict_instances, calculate_accuracy
def test_calculate_euclidean_distance():
assert calculate_euclidean_distance([0, 0], [3, 4]) == 5.0
assert calculate_euclidean_distance([1, 1], [4, 5]) == 5.0
assert calculate_euclidean_distance([1, 2], ... | [] | [
1,
0,
1,
0,
1,
1,
0,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef calculate_euclidean_distance(point1, point2):\n \"\"\"\n Calculates Euclidean distance between two poin... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000016114",
"row_id": 16114,
"seed_ids": "[468]"
} | 0.635798 | Algorithm_16114 | I | [
"calculate_euclidean_distance",
"fit_knn_model",
"predict_instances",
"calculate_accuracy"
] | 4 | [
[
"predict_instances",
"calculate_euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d5b47ed7f8999868ccd7db784c0c37a664ac3260 | ff678e245acbd6e189d85fa73a32b8391ffc34e7 | |||
v1.0 | instruct | Algorithm | Algorithm_16145_I | ### FizzBuzz with a Twist
You are tasked with creating a modified version of the classic FizzBuzz problem. Your function should print numbers from 1 to a given integer `n`. However, for multiples of a given divisor `x`, print "Fizz" instead of the number, for multiples of another given divisor `y`, print "Buzz", and f... | 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
... | import pytest
from solution import fizz_buzz_prime
def test_fizz_buzz_prime_basic():
assert fizz_buzz_prime(15, 3, 5) == None
# Expected output
# 1
# Prime
# Fizz
# Prime
# Buzz
# Fizz
# 7
# Prime
# Fizz
# Buzz
# 11
# Fizz
# Prime
# 14
# FizzBuzz
def... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Prints numbers from 1 to n with specific rules:\n- Print \"Fizz\" for multiples of x\n- Print \"Buzz\" for ... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n for i in range... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000016145",
"row_id": 16145,
"seed_ids": "[3900]"
} | 0.763328 | Algorithm_16145 | I | [
"is_prime",
"fizz_buzz_prime"
] | 2 | [
[
"fizz_buzz_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 317da644ad09da449592033794c7724aa74e474f | 3e9afe588df12a484cdeafe00e4bc1fc9a0915c9 | |||
v1.0 | instruct | Algorithm | Algorithm_16247_I | ### Coding Assessment Question: Sorting a Linked List in Place
**Problem Statement**:
You are tasked with implementing an algorithm to sort a singly linked list in ascending order. A linked list is a data structure composed of nodes where each node contains a value and a reference (or link) to the next node in the se... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_sort(head):
if not head or not head.next:
return head
def split_list(head):
slow, fast = head, head
pre_slow = None
while fast and fast.next:
pre_... | import pytest
from solution import ListNode, sort_linked_list
def linked_list_to_list(head):
"""Helper function to convert linked list to list for easy comparison in test cases"""
result = []
while head:
result.append(head.val)
head = head.next
return result
def list_to_linked_list(lst... | [] | [
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, val=0, next=None):\n self.val = val\n self.next = next\n\ndef sort_linked_list(head: ListNode) -> ListNode:... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000016247",
"row_id": 16247,
"seed_ids": "[731]"
} | 0.553521 | Algorithm_16247 | I | [
"merge_sort",
"sort_linked_list"
] | 2 | [
[
"sort_linked_list",
"merge_sort"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | ae18352eb65b687d2f6700d0415f57b877d64abd | 38ac10d722274a783b126ec74b132658f3ecc696 | |||
v1.0 | instruct | Algorithm | Algorithm_16319_I | ### Problem Statement
You are given an array of integers. Your task is to implement the quicksort algorithm to sort the array in ascending order. Your implementation should handle arrays containing negative numbers as well as positive numbers, and should be optimized for efficient in-place sorting.
### Input Format
* ... | def quicksort(array, low, high):
if low < high:
pi = partition(array, low, high)
quicksort(array, low, pi - 1)
quicksort(array, pi + 1, high)
def partition(array, low, high):
pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i +... | from solution import quicksort_wrapper
def test_quick_sort_empty_array():
assert quicksort_wrapper([]) == []
def test_quick_sort_single_element():
assert quicksort_wrapper([1]) == [1]
def test_quick_sort_sorted_array():
assert quicksort_wrapper([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_quick_sort_rev... | [
{
"docstring": null,
"function_declaration": "def quicksort(array, low, high):",
"function_name": "quicksort",
"parameter_list": "(array, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(array, low, high):",
"function_name": "partition",
"parameter_list"... | [
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def quicksort(array, low, high):\n if low < high:\n pi = partition(array, low, high)\n quicksort(array, low, pi - 1)\n quicksort(array, p... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000016319",
"row_id": 16319,
"seed_ids": "[1247]"
} | 0.671897 | Algorithm_16319 | I | [
"quicksort",
"partition",
"quicksort_wrapper"
] | 3 | [
[
"quicksort",
"partition"
],
[
"quicksort_wrapper",
"quicksort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fc2fac9fe6378bb585fc14898bf90c89ab49b420 | e2932e0e43535f6668c0c0e41d6ce9ceada4a1fc | |||
v1.0 | instruct | Algorithm | Algorithm_16322_I | ### Coding Question: Implement a Products Price Aggregator
**Scenario:**
You are tasked with implementing a function to aggregate product prices from different e-commerce websites. Your task involves fetching price data from various sources, normalizing it, and providing an aggregated view. To facilitate testing, you ... | from typing import Dict
def get_price_from_site1(product: str) -> float:
pass
def get_price_from_site2(product: str) -> float:
pass
def get_price_from_site3(product: str) -> float:
pass
def aggregate_prices(product: str) -> Dict[str, float]:
site1_price = get_price_from_site1(product)
site2_pric... | import pytest
from unittest.mock import patch
from solution import aggregate_prices
def test_aggregate_prices():
with patch('solution.get_price_from_site1') as mock_site1, \
patch('solution.get_price_from_site2') as mock_site2, \
patch('solution.get_price_from_site3') as mock_site3:
... | [
{
"docstring": null,
"function_declaration": "def get_price_from_site1(product):",
"function_name": "get_price_from_site1",
"parameter_list": "(product)"
},
{
"docstring": null,
"function_declaration": "def get_price_from_site2(product):",
"function_name": "get_price_from_site2",
... | [
0,
0,
0,
0,
0,
1,
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 get_price_from_site1(product: str) -> float:\n # Mocked function\n pass\n\ndef get_price_from_site2(product: str) -> float:\n # Mocked function\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000016322",
"row_id": 16322,
"seed_ids": "[3964]"
} | 0.543234 | Algorithm_16322 | I | [
"get_price_from_site1",
"get_price_from_site2",
"get_price_from_site3",
"aggregate_prices"
] | 4 | [
[
"aggregate_prices",
"get_price_from_site1"
],
[
"aggregate_prices",
"get_price_from_site2"
],
[
"aggregate_prices",
"get_price_from_site3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b9b4de40431cd9c234bc33e43898b26df7ec0421 | 871a298970cf22e24bf0fdd3bcccda31c9c154c6 | |||
v1.0 | instruct | Algorithm | Algorithm_16368_I | ### Coding Assessment Task:
#### Context:
You are working on a logistics software system and need to design a function that can calculate the optimal route for package delivery in a city. The city is modeled as a grid, and you need to find the shortest path from a warehouse to multiple customer locations.
#### Proble... | from collections import deque
def bfs(grid, start):
rows, cols = len(grid), len(grid[0])
distances = [[float('inf')] * cols for _ in range(rows)]
distances[start[0]][start[1]] = 0
queue = deque([start])
while queue:
x, y = queue.popleft()
for dx, dy in [(-1, 0), (1, 0), (0, -1)... | from solution import shortest_delivery_route
def test_shortest_delivery_route_example1():
grid = [
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 1, 0, 0]
]
warehouse = (0, 0)
customers = [(2, 3), (3, 2)]
assert shortest_delivery_route(grid, warehouse, customers) == 1... | [
{
"docstring": null,
"function_declaration": "def bfs(grid, start):",
"function_name": "bfs",
"parameter_list": "(grid, start)"
},
{
"docstring": null,
"function_declaration": "def shortest_delivery_route(grid, warehouse, customers):",
"function_name": "shortest_delivery_route",
... | [
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 collections import deque\n\ndef bfs(grid, start):\n rows, cols = len(grid), len(grid[0])\n distances = [[float('inf')] * cols for _ in range(rows)]\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000016368",
"row_id": 16368,
"seed_ids": "[1027]"
} | 0.666636 | Algorithm_16368 | I | [
"bfs",
"shortest_delivery_route"
] | 2 | [
[
"shortest_delivery_route",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fa96a71c347525e399a0a6b84575c807f59f2981 | fb7026e0dfaa5ab1fe4d878e21e6184467c57326 | |||
v1.0 | instruct | Algorithm | Algorithm_16408_I | ### Question
You are required to implement a function that finds the longest streak of consecutive prime numbers that add up to a prime number less than or equal to a given integer.
### Objective
Write a function `longest_prime_sum(n: int) -> int` that returns the length of the longest streak of consecutive prime num... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def sieve_of_eratosthenes(n):
... | def test_is_prime():
assert is_prime(2) == True
assert is_prime(29) == True
assert is_prime(1) == False
assert is_prime(4) == False
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_longe... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000016408",
"row_id": 16408,
"seed_ids": "[3060]"
} | 0.618686 | Algorithm_16408 | I | [
"is_prime",
"sieve_of_eratosthenes",
"longest_prime_sum"
] | 3 | [
[
"longest_prime_sum",
"is_prime"
],
[
"longest_prime_sum",
"sieve_of_eratosthenes"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 95169f574a2e7566caa621019542a26ec0cf493f | c65b8183d1561f893017e95f145b30b1af99a2f2 | |||
v1.0 | instruct | Algorithm | Algorithm_16443_I | **Merged Sorted Lists**
You are given two functions that merge two sorted lists into a single sorted list and find the kth smallest element in a sorted list, respectively. Your task is to write a function `merged_kth_element` that takes three arguments: two sorted lists and an integer k, and returns the kth smallest e... | def merged_kth_element(list1, list2, k):
"""
Merges two sorted lists and returns the k-th smallest element.
Parameters:
list1 (List[int]): The first sorted list.
list2 (List[int]): The second sorted list.
k (int): The 1-based index of the desired element in the merged sorted list.
... | def test_merged_kth_element():
assert merged_kth_element([1, 3, 5], [2, 4, 6], 4) == 4
assert merged_kth_element([0, 2, 9], [1, 3, 7], 5) == 7
assert merged_kth_element([10, 20, 30], [5, 15, 25], 3) == 15
assert merged_kth_element([], [1, 2, 3, 4], 2) == 2
assert merged_kth_element([1, 2, 3], [], 1)... | [
{
"docstring": "Merges two sorted lists and returns the k-th smallest element.\n\nParameters:\nlist1 (List[int]): The first sorted list.\nlist2 (List[int]): The second sorted list.\nk (int): The 1-based index of the desired element in the merged sorted list.\n\nReturns:\nint: The k-th smallest element in the me... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sorted_lists(list1, list2):\n merged_list = []\n i, j = 0, 0\n \n while i < len(list1) and j < len(list2):\n if list1[i] <= list2[j]... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000016443",
"row_id": 16443,
"seed_ids": "[1094]"
} | 0.553575 | Algorithm_16443 | I | [
"merged_kth_element",
"merge_sorted_lists",
"find_kth_element"
] | 3 | [
[
"merged_kth_element",
"find_kth_element"
],
[
"merged_kth_element",
"merge_sorted_lists"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2961c3118547345624f2e5a410b6b936c77b0b3a | 29de146f15df1a0f76c39c8d0db9a2d458f6da52 | |||
v1.0 | instruct | Algorithm | Algorithm_16449_I | ### Coding Question: Find and Verify Palindromic Prime Numbers
#### Context
Palindromic primes are primes that remain the same when their digits are reversed. This exercise requires understanding of prime number algorithms and string manipulation to efficiently verify palindromic primes and find them within specified ... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def is_palindromic_prime(n):
if not isinst... | from solution import is_palindromic_prime, find_palindromic_primes
def test_is_palindromic_prime():
assert is_palindromic_prime(101) == True
assert is_palindromic_prime(131) == True
assert is_palindromic_prime(10) == False
assert is_palindromic_prime(11) == True
assert is_palindromic_prime(2) == Tr... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_palindromic_prime(n):",
"function_name": "is_palindromic_prime",
"parameter_list": "(n)"
},
{
"doc... | [
1,
1,
1,
0,
0,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000016449",
"row_id": 16449,
"seed_ids": "[3459]"
} | 0.660744 | Algorithm_16449 | I | [
"is_prime",
"is_palindromic_prime",
"find_palindromic_primes"
] | 3 | [
[
"find_palindromic_primes",
"is_palindromic_prime"
],
[
"is_palindromic_prime",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | afa0f5af1ca47327f8bebd64b50e7f18ed52dc51 | d42a36a0351f3fdca6b230d4dee05cbe72a7bcd9 | |||
v1.0 | instruct | Algorithm | Algorithm_16466_I | Prime Sum Checker
You are tasked with writing a function that checks whether there exist two distinct prime numbers that add up to a given integer `n`. If there are multiple such pairs, return any one of them.
To solve this:
* Iterate through all prime numbers less than `n`.
* Check if the difference between `n` and ... | from typing import Optional, Tuple
import math
def sieve_of_eratosthenes(max_num: int) -> list:
is_prime = [True] * (max_num + 1)
is_prime[0] = is_prime[1] = False
for num in range(2, int(math.isqrt(max_num)) + 1):
if is_prime[num]:
for multiple in range(num * num, max_num + 1, num... | from solution import find_prime_pair
def test_find_prime_pair():
result = find_prime_pair(10)
assert result == (3, 7) or result == (5, 5)
result = find_prime_pair(26)
assert result == (3, 23) or result == (13, 13)
result = find_prime_pair(44)
assert result == (3, 41) or result == (17, 27)... | [
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(max_num):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(max_num)"
},
{
"docstring": null,
"function_declaration": "def find_prime_pair(n):",
"function_name": "find_prime_pair",
"parameter_li... | [
1,
0,
1,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Optional, Tuple\n\ndef find_prime_pair(n: int) -> Optional[Tuple[int, int]]:\n \"\"\"\n Function to find two distinct prime numbers that... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000016466",
"row_id": 16466,
"seed_ids": "[2551]"
} | 0.76879 | Algorithm_16466 | I | [
"sieve_of_eratosthenes",
"find_prime_pair"
] | 2 | [
[
"find_prime_pair",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2fb4e3254ecdcaf6ebc7c2ce8a58963eb26b2ed8 | 19e38b4d2201a359242dd3f404d6aaef92fbe835 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.