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_16473_I
### Coding Assessment Question Write a function to implement a simple neural network for binary classification using NumPy only (no TensorFlow or PyTorch). The neural network should have one hidden layer with ReLU activation and one output layer with sigmoid activation. Initialize weights using small random numbers an...
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def relu(x): return np.maximum(0, x) def relu_derivative(x): return np.where(x > 0, 1, 0) def cross_entropy_loss(y_true, y_pred): eps = 1e-12 # to avoid log(0) y_pred = np.clip(y_pred, eps, 1 - eps) loss = - (y_true * np.log(y_p...
import numpy as np from solution import train_neural_network def test_train_neural_network_shapes(): np.random.seed(0) X_train = np.random.randn(100, 20) y_train = np.random.randint(0, 2, 100) X_val = np.random.randn(20, 20) y_val = np.random.randint(0, 2, 20) hidden_layer_size = 10 we...
[ { "docstring": null, "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def relu(x):", "function_name": "relu", "parameter_list": "(x)" }, { "docstring": null, "function_decla...
[ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\ndef relu(x):\n return np.maxim...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016473", "row_id": 16473, "seed_ids": "[4757]" }
0.662646
Algorithm_16473
I
[ "sigmoid", "relu", "relu_derivative", "cross_entropy_loss", "accuracy", "train_neural_network" ]
6
[ [ "train_neural_network", "accuracy" ], [ "train_neural_network", "cross_entropy_loss" ], [ "train_neural_network", "relu" ], [ "train_neural_network", "relu_derivative" ], [ "train_neural_network", "sigmoid" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
e0e646b4c4d4b5b6d359a53cd93e6245dfd6b1d2
ef3181c506e601bc0fb2920822b7931dbaff452e
v1.0
instruct
Algorithm
Algorithm_16477_I
Consider a scenario where you are designing an online shopping website. One important feature is to allow users to search for available products quickly, based on certain keywords. To help with this, you want to implement a search functionality that matches products based on provided prefixes efficiently. You are give...
from typing import List, Dict, Tuple from collections import defaultdict def build_trie(products: List[str]) -> Dict: trie = {} for product in products: node = trie for char in product: if char not in node: node[char] = {} node = node[char] node['...
from solution import build_trie, search_prefix, search_multiple_prefixes def test_build_trie(): products = ["apple", "appetizer", "banana", "bandana", "band"] trie = build_trie(products) assert '#' in trie['a']['p']['p']['l']['e'] assert '#' in trie['a']['p']['p']['e']['t']['i']['z']['e']['r'] asse...
[ { "docstring": null, "function_declaration": "def build_trie(products):", "function_name": "build_trie", "parameter_list": "(products)" }, { "docstring": null, "function_declaration": "def search_prefix(trie, prefix):", "function_name": "search_prefix", "parameter_list": "(trie, ...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import defaultdict, Counter\nfrom typing import List, Dict, Tuple\n\ndef build_trie(products: List[str]) -> Dict:\n \"\"\"\n Build a Trie ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016477", "row_id": 16477, "seed_ids": "[1204]" }
0.563386
Algorithm_16477
I
[ "build_trie", "search_prefix", "search_multiple_prefixes" ]
3
[ [ "search_multiple_prefixes", "build_trie" ], [ "search_multiple_prefixes", "search_prefix" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8d909cc832163123a0593f6e252eeca295e52ea6
05fc449203f3339c642bb54e01f66db8569580dd
v1.0
instruct
Algorithm
Algorithm_16515_I
Coding Assessment Question #### Context: Merge sort is a classic divide-and-conquer algorithm that efficiently sorts an array by recursively dividing it into two halves, sorting each half, and then merging the sorted halves. Your task is to implement the merge sort algorithm to sort an array of integers. #### Problem...
def merge_sort(arr: list[int]) -> list[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left: list[int], right: list[int]) -> list[int]: result = [] i = j = 0 while i < le...
def test_merge_sort_with_duplicates(): assert merge_sort([9, 9, 9, 9]) == [9, 9, 9, 9] def test_merge_sort_with_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_with_empty_list(): assert merge_sort([]) == [] def test_merge_sort_with_mixed_elements(): assert merge_sort([-10, 0, 5, -...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n def merge(left, right):\n sorted_list = []\n left_index, right_index = 0, 0\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016515", "row_id": 16515, "seed_ids": "[3415]" }
0.629467
Algorithm_16515
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
false
[]
true
caad990dbf3b130366be2c9e2c16f2ef6a8b8a94
0715fee5efc5dcdfe5b4a2a864f51fdcc0903067
v1.0
instruct
Algorithm
Algorithm_16563_I
### Problem Statement You are tasked with implementing a simple spell checker that identifies and suggests corrections to misspelled words in a given sentence, using a provided list of valid words. The suggestions should be words from the list that are closest to the misspelled word, with "closeness" defined by the mi...
from typing import List, Dict import re def levenshtein_distance(s1: str, s2: str) -> int: """ Compute the Levenshtein distance between two strings s1 and s2. """ if len(s1) < len(s2): return levenshtein_distance(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len...
from solution import check_spelling def test_basic_sentence(): assert check_spelling("Ths is a simpl sentence", ["This", "is", "a", "simple", "sentence"]) == {'Ths': ['This'], 'simpl': ['simple']} def test_another_sentence(): assert check_spelling("I hav a dreem", ["I", "have", "a", "dream"]) == {'hav': ['hav...
[ { "docstring": "Compute the Levenshtein distance between two strings s1 and s2.", "function_declaration": "def levenshtein_distance(s1, s2):", "function_name": "levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": "Identifies and suggests corrections to misspelled words in a...
[ 1, 1, 0, 0, 0, 0, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Dict\nimport re\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n \"\"\"\n Compute the Levenshtein distance between two stri...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000016563", "row_id": 16563, "seed_ids": "[4427]" }
0.557079
Algorithm_16563
I
[ "levenshtein_distance", "check_spelling" ]
2
[ [ "check_spelling", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
627e642a8486c446291e1c7ea39423baba4c9427
844544ff3f18a954ac7592ef7c27054260f84dd9
v1.0
instruct
Algorithm
Algorithm_16618_I
### Problem Statement You are given the task of creating a function that calculates the nth Fibonacci number using two different techniques: dynamic programming and matrix exponentiation. Examine the strengths and weaknesses of each approach based on time and space complexity. ### Requirements 1. **Dynamic Programmi...
def dp_fibonacci(n: int) -> int: if n < 0: return "Error: Input must be a non-negative integer." if n == 0: return 0 if n == 1: return 1 fib = [0, 1] for i in range(2, n + 1): fib.append(fib[-1] + fib[-2]) return fib[n] def matrix_mult(A, B): return [[A[...
def test_dp_fibonacci(): assert dp_fibonacci(0) == 0 assert dp_fibonacci(1) == 1 assert dp_fibonacci(2) == 1 assert dp_fibonacci(3) == 2 assert dp_fibonacci(4) == 3 assert dp_fibonacci(5) == 5 assert dp_fibonacci(10) == 55 assert dp_fibonacci(-1) == "Error: Input must be a non-negative i...
[ { "docstring": null, "function_declaration": "def dp_fibonacci(n):", "function_name": "dp_fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def matrix_mult(A, B):", "function_name": "matrix_mult", "parameter_list": "(A, B)" }, { "docstri...
[ 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 dp_fibonacci(n: int) -> int:\n if n < 0:\n return \"Error: Input must be a non-negative integer.\"\n if n == 0:\n return 0\n if n == 1...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016618", "row_id": 16618, "seed_ids": "[53]" }
0.64834
Algorithm_16618
I
[ "dp_fibonacci", "matrix_mult", "matrix_pow", "matrix_fibonacci" ]
4
[ [ "matrix_fibonacci", "matrix_pow" ], [ "matrix_pow", "matrix_mult" ] ]
2
[]
false
[]
false
pytest
false
[]
true
0a2082a4a8b07c16ad0c3cb0625f1b0cfc9c2dea
f2b3fd8f144b0eb035d9921f759766b92176e531
v1.0
instruct
Algorithm
Algorithm_16634_I
### Coding Assessment Question #### Context You are developing a system for a library to manage and track the borrowing of its books. Each book has a unique International Standard Book Number (ISBN), and the library needs functions to manipulate and validate these ISBNs. ### Objective Implement the required functions...
def extract_group_identifier(isbn): """ Extract the group identifier from a given 13-digit ISBN. Parameters: isbn (str): A string representation of a 13-digit ISBN. Returns: str: The group identifier (first digit of the ISBN). """ if len(isbn) != 13 or not isbn.isdigit(): raise...
import pytest from solution import extract_group_identifier, validate_isbn, format_isbn def test_extract_group_identifier_valid(): assert extract_group_identifier("9781234567890") == "978" def test_extract_group_identifier_invalid(): with pytest.raises(ValueError): extract_group_identifier("1234567890...
[ { "docstring": "Extract the group identifier from a given 13-digit ISBN.\n\nParameters:\nisbn (str): A string representation of a 13-digit ISBN.\n\nReturns:\nstr: The group identifier (first digit of the ISBN).", "function_declaration": "def extract_group_identifier(isbn):", "function_name": "extract_gr...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef extract_group_identifier(isbn):\n \"\"\"\n Extract the group identifier from a given 13-digit ISBN.\n \"\"\"\n if len(isbn) != 13 or...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000016634", "row_id": 16634, "seed_ids": "[1516]" }
0.57399
Algorithm_16634
I
[ "extract_group_identifier", "validate_isbn", "validate_isbn_10", "validate_isbn_13", "format_isbn", "format_isbn_10", "format_isbn_13" ]
7
[ [ "format_isbn", "format_isbn_10" ], [ "format_isbn", "format_isbn_13" ], [ "validate_isbn", "validate_isbn_10" ], [ "validate_isbn", "validate_isbn_13" ] ]
4
[]
false
[]
false
pytest
true
[]
true
f6bdf6dc69a58abad7470afd2bfa18e586c1f833
e56aa431f2dd3a3999fae91199565a3b38324e70
v1.0
instruct
Algorithm
Algorithm_16678_I
### Problem Statement: You are given a list of integers and your goal is to sort this list using the Merge Sort algorithm. Merge Sort is a divide-and-conquer algorithm that recursively splits the list into halves, sorts each half, and then merges the sorted halves back together. Implement the `merge_sort` function whi...
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left, right): sorted_list = [] left_index, right_index = 0, 0 while left_index ...
from solution import merge_sort def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_list(): assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] def test_merge_sort_random_list(): assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32,...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Recursively sorts the list using the Merge Sort algorithm.\n \n Parameters:\n arr (list): A list of integers t...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016678", "row_id": 16678, "seed_ids": "[565]" }
0.662353
Algorithm_16678
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6abf6826cdb08e974141431a5109f339d2a7eb04
9bb55700aa1098ef2d63a5b8ebbf0b679acb7358
v1.0
instruct
Algorithm
Algorithm_16680_I
### Question: String Manipulation and Pattern Matching **Context:** You are developing a string manipulation library and need to include functionality that addresses common text processing tasks. This library will handle operations involving word patterns, character sequences, and special conditions in text data. **O...
def longest_palindromic_substring(s: str) -> str: """ Find the longest palindromic substring in s. """ if len(s) == 0: return "" start, end = 0, 0 for i in range(len(s)): len1 = expand_around_center(s, i, i) len2 = expand_around_center(s, i, i + 1) max_len = max...
from solution import longest_palindromic_substring, word_pattern, character_frequency def test_longest_palindromic_substring(): assert longest_palindromic_substring("babad") in ["bab", "aba"] assert longest_palindromic_substring("cbbd") == "bb" assert longest_palindromic_substring("a") == "a" assert lo...
[ { "docstring": "Find the longest palindromic substring in s.", "function_declaration": "def longest_palindromic_substring(s):", "function_name": "longest_palindromic_substring", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def expand_around_center(s, left, rig...
[ 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 longest_palindromic_substring(s: str) -> str:\n n = len(s)\n if n == 0:\n return \"\"\n \n def expand_around_center(left: int, right: int)...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016680", "row_id": 16680, "seed_ids": "[3591]" }
0.65899
Algorithm_16680
I
[ "longest_palindromic_substring", "expand_around_center", "word_pattern", "character_frequency" ]
4
[ [ "longest_palindromic_substring", "expand_around_center" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e32a687c2d17f211c80cb4564bbb5db7636e5f62
362c8660d30914792e27e4d5ef6ba99575c4315b
v1.0
instruct
Algorithm
Algorithm_16710_I
### Binary Search Tree Balancing #### Context: A Binary Search Tree (BST) is a node-based binary tree data structure that has the following properties: the left subtree of a node contains only nodes with values less than the node's key, the right subtree of a node contains only nodes with values greater than the node'...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorder_traversal(root): """Helper function for in-order traversal of BST and returns elements in sorted order.""" return inorder_traversal(root.left) + [root.val...
import pytest def test_inorder_traversal(): root = TreeNode(1, None, TreeNode(2, None, TreeNode(3))) assert inorder_traversal(root) == [1, 2, 3] root = TreeNode(3, TreeNode(2, TreeNode(1)), None) assert inorder_traversal(root) == [1, 2, 3] def test_sorted_array_to_bst(): nums = [1, 2, 3] root...
[]
[ 0, 1, 0, 1, 1, 0, 0, 1, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "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 balan...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016710", "row_id": 16710, "seed_ids": "[920]" }
0.746566
Algorithm_16710
I
[ "inorder_traversal", "sorted_array_to_bst", "balance_bst" ]
3
[ [ "balance_bst", "inorder_traversal" ], [ "balance_bst", "sorted_array_to_bst" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
9fda4c392b8382937381f155a7865eb0427af4ac
06d65d15c689077ed157651ed25ac486cf84b7ca
v1.0
instruct
Algorithm
Algorithm_16723_I
### Coding Assessment Question In a software application, you might need to process a list of integers to segregate the prime numbers from the non-prime ones, performing this task efficiently given the potential size of the data. #### Function Definition ```python def segregate_primes(arr: List[int]) -> Tuple[List[i...
import math from typing import List, Tuple def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 ...
from solution import segregate_primes def test_segregate_primes_basic(): assert segregate_primes([10, 29, 15, 23, 8, 1]) == ([29, 23], [10, 15, 8, 1]) assert segregate_primes([2, 3, 4, 5, 6]) == ([2, 3, 5], [4, 6]) def test_segregate_primes_edge_cases(): assert segregate_primes([]) == ([], []) assert ...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Given a list of integers, segregate them into two lists: one containing the prime numbers,\nand the other conta...
[ 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 is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if a number is a prime.\n \n Args:\n n : i...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000016723", "row_id": 16723, "seed_ids": "[3219]" }
0.624619
Algorithm_16723
I
[ "is_prime", "segregate_primes" ]
2
[ [ "segregate_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
da1eb20261c70eb604d0bb7ebc2a5b91f54edb13
80b6a43216963139a3e166efa75cffa1d261b9e6
v1.0
instruct
Algorithm
Algorithm_16727_I
### Coding Assessment Question #### Context Sorting algorithms are fundamental to computer science and are widely used in various applications. One of the common problems is sorting an array of integers. Each sorting algorithm has its own strengths and weaknesses in terms of time complexity and space complexity. ####...
def custom_sort(arr): """ Return the list sorted in ascending order while maintaining the position of zeros. :param arr: List[int]: The list of integers to be sorted. :return: List[int]: The sorted list with zeroes in their original positions. """ # Store the original positions of all zeroe...
from solution import custom_sort def test_custom_sort_example1(): assert custom_sort([0, 3, 1, 0, 2, 5, 4, 0]) == [0, 1, 2, 0, 3, 4, 5, 0] def test_custom_sort_example2(): assert custom_sort([4, 0, 7, 0, 2, 5]) == [2, 0, 4, 0, 5, 7] def test_custom_sort_example3(): assert custom_sort([0, 0, 1]) == [0, 0,...
[ { "docstring": "Return the list sorted in ascending order while maintaining the position of zeros.\n\n:param arr: List[int]: The list of integers to be sorted.\n:return: List[int]: The sorted list with zeroes in their original positions.", "function_declaration": "def custom_sort(arr):", "function_name"...
[ 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 custom_sort(arr):\n \"\"\"\n Return the list sorted in ascending order while maintaining the position of zeros.\n \n :param arr: List[int]: The l...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000016727", "row_id": 16727, "seed_ids": "[2493]" }
0.684196
Algorithm_16727
I
[ "custom_sort", "merge_sort", "merge" ]
3
[ [ "custom_sort", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c6a7b4bbe9c65afb491c2bcb946c1336f88e6ff3
8a6f2ced80ce1ec2e53a1f7c8c809d46a8ec0879
v1.0
instruct
Algorithm
Algorithm_16763_I
**Palindrome Prime Problem** #### Problem Statement: You are asked to find all prime numbers within a specified range that are also palindromes. A number is considered a palindrome if it reads the same forwards as it does backwards. Your function should iterate through the specified range, check for prime numbers, and...
def is_prime(number: int) -> bool: """ Returns True if the number is a prime, else False. """ if number <= 1: return False if number <= 3: return True if number % 2 == 0 or number % 3 == 0: return False i = 5 while i * i <= number: if number % i == 0 or nu...
from solution import is_prime, is_palindrome, find_palindrome_primes def test_is_prime(): assert is_prime(11) == True assert is_prime(15) == False assert is_prime(2) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-5) == False def test_is_palindrome(): asser...
[ { "docstring": "Returns True if the number is a prime, else False.", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Returns True if the number is a palindrome, else False.", "function_declaration": "def is_pal...
[ 1, 0, 0, 1, 1, 1, 0, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(number: int) -> bool:\n \"\"\"\n Check if a given number is a prime.\n \"\"\"\n if number <= 1:\n return False\n if number <= ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000016763", "row_id": 16763, "seed_ids": "[2479]" }
0.642513
Algorithm_16763
I
[ "is_prime", "is_palindrome", "find_palindrome_primes" ]
3
[ [ "find_palindrome_primes", "is_palindrome" ], [ "find_palindrome_primes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
52da61ce20021fa122d6d0e2df1119f64ef9c5cd
9f3cfe9340674cb65feaf4888d99272cd64d3074
v1.0
instruct
Algorithm
Algorithm_16769_I
### Scenario: As a software developer for a logistics company, you are tasked with optimizing the route for delivering packages. The company maintains records of delivery points as a series of geographical coordinates. To facilitate the planning, you need to implement a function that calculates the shortest path to vis...
from typing import List, Tuple import itertools def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float: """ Helper function to calculate the Euclidean distance between two points. """ return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 def total_route_distance(route: List[Tu...
from solution import shortest_route def test_shortest_route_single_point(): assert shortest_route([(0, 0)]) == [(0, 0), (0, 0)] def test_shortest_route_two_points(): assert shortest_route([(0, 0), (1, 1)]) == [(0, 0), (1, 1), (0, 0)] def test_shortest_route_three_points(): assert shortest_route([(0, 0), ...
[ { "docstring": "Helper function to calculate the Euclidean distance between two points.", "function_declaration": "def calculate_distance(p1, p2):", "function_name": "calculate_distance", "parameter_list": "(p1, p2)" }, { "docstring": "Helper function to calculate the total distance of a giv...
[ 1, 0, 0, 0, 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": "from typing import List, Tuple\nfrom itertools import permutations\n\ndef calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000016769", "row_id": 16769, "seed_ids": "[1390]" }
0.679104
Algorithm_16769
I
[ "calculate_distance", "total_route_distance", "shortest_route" ]
3
[ [ "shortest_route", "total_route_distance" ], [ "total_route_distance", "calculate_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
824d4eb3ff2299bd35c92982f90cd7cd66270a97
b9239cccf31a4e85a18f5d8fd4eec2e0d7826275
v1.0
instruct
Algorithm
Algorithm_16874_I
### Problem Statement A logistic company uses a unique way to manage its delivery trucks. Each truck can only carry a certain number of packages based on the truck's capacity, preferred weather conditions, and distance constraints. Write a program to determine which trucks can be utilized for a given set of packages, ...
def can_use_truck(truck_capacity, preferred_weather, max_distance, packages, current_weather, delivery_distance): """ Determines if a truck can be used for the given packages under the current conditions. """ if current_weather != preferred_weather: return False if delivery_distance > m...
from solution import can_use_truck, assign_trucks def test_can_use_truck_valid_conditions(): packages = [{'weight': 10.5}, {'weight': 5.2}, {'weight': 8.8}] assert can_use_truck(3, 'Sunny', 100, packages, 'Sunny', 80) == True def test_can_use_truck_invalid_weather(): packages = [{'weight': 10.5}, {'we...
[ { "docstring": "Determines if a truck can be used for the given packages under the current conditions.", "function_declaration": "def can_use_truck(truck_capacity, preferred_weather, max_distance, packages, current_weather, delivery_distance):", "function_name": "can_use_truck", "parameter_list": "(...
[ 1, 1, 0, 0, 1, 1, 1, 0, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def can_use_truck(truck_capacity: int, preferred_weather: str, max_distance: int, packages: list[dict], current_weather: str, delivery_distance: int) -> bool:\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000016874", "row_id": 16874, "seed_ids": "[603]" }
0.653994
Algorithm_16874
I
[ "can_use_truck", "assign_trucks" ]
2
[ [ "assign_trucks", "can_use_truck" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0684d33978e2bce17eb071a8139cb99c94d1ffc
8d2ca8e5ee166972fea84fcf210b31cf67cb4a33
v1.0
instruct
Algorithm
Algorithm_16877_I
### Question You are tasked with devising a strategy to balance a binary search tree (BST) using a list of integers as input. The objective is to ensure that the BST is height-balanced, meaning the depth of the left and right subtrees of every node differ by at most 1. Given the following requirements: - Implement a P...
from typing import List, Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def sorted_array_to_bst(nums: List[int]) -> Optional[TreeNode]: if not nums: return None mid = len(nums) // 2 root = Tr...
from solution import balance_bst, TreeNode def is_balanced(root: TreeNode) -> bool: def height(node): if not node: return 0 left_height = height(node.left) right_height = height(node.right) if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1...
[]
[ 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": "from typing import List, Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000016877", "row_id": 16877, "seed_ids": "[5335]" }
0.677135
Algorithm_16877
I
[ "sorted_array_to_bst", "balance_bst" ]
2
[ [ "balance_bst", "sorted_array_to_bst" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
750c033bde432346b402bb0e8a33da2e65b0621d
c8c53590547f35218d165d7bc43c092038b4ab72
v1.0
instruct
Algorithm
Algorithm_16923_I
## Additional Coding Assessment: Implementing K-Nearest Neighbors (KNN) **Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. You will use the provided KNN model and utility functions as a reference to create new components to demonstrate your understanding. ### Problem Stat...
import math from collections import Counter def fit_knn_model(features, labels, k): """ Fits the KNN model given features, labels, and the number of neighbors (k). Returns a tuple representing the model. """ return (features, labels, k) def euclidean_distance(point1, point2): """ Calculate...
import pytest from solution import fit_knn_model, predict_instances, calculate_accuracy def test_knn_basic(): features = [ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], ] labels = [0, 0, 1, 1] k = 3 model = fit_knn_model(features, labels, k) unknown_features ...
[ { "docstring": "Fits the KNN model given features, labels, and the number of neighbors (k).\nReturns a tuple representing the model.", "function_declaration": "def fit_knn_model(features, labels, k):", "function_name": "fit_knn_model", "parameter_list": "(features, labels, k)" }, { "docstrin...
[ 0, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom collections import Counter\n\ndef fit_knn_model(features, labels, k):\n \"\"\"\n Fit the KNN model using the provided features and...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000016923", "row_id": 16923, "seed_ids": "[468]" }
0.524248
Algorithm_16923
I
[ "fit_knn_model", "euclidean_distance", "predict_instances", "calculate_accuracy" ]
4
[ [ "predict_instances", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7f1c3bf14da2762999ff0ba6b3b0c88b42504421
ca63d5ba18647eb2aeaefd229d0675884b01f88f
v1.0
instruct
Algorithm
Algorithm_17192_I
### Question: Neural Network From Scratch In this task, you will implement a simple neural network with forward and backward propagation. Understanding and implementing these mechanisms are crucial for building and optimizing neural network models. #### Objectives: 1. Implement a simple feedforward neural network ca...
import numpy as np def initialize_parameters(n_features: int, n_hidden_units: int) -> dict: """ Initialize the parameters of the network. Parameters: - n_features: Number of features in the input data - n_hidden_units: Number of units in the hidden layer Returns: - dict: Dictionar...
import numpy as np from solution import initialize_parameters, forward_propagation, backward_propagation, update_parameters def test_initialize_parameters(): params = initialize_parameters(2, 3) assert params['W1'].shape == (3, 2) assert params['b1'].shape == (3, 1) assert params['W2'].shape == (1, 3) ...
[ { "docstring": "Initialize the parameters of the network.\n\nParameters:\n- n_features: Number of features in the input data\n- n_hidden_units: Number of units in the hidden layer\n\nReturns:\n- dict: Dictionary containing the initialized weights and biases", "function_declaration": "def initialize_paramete...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef initialize_parameters(n_features: int, n_hidden_units: int) -> dict:\n \"\"\"\n Initialize the parameters of the network.\n \n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000017192", "row_id": 17192, "seed_ids": "[498]" }
0.565176
Algorithm_17192
I
[ "initialize_parameters", "sigmoid", "forward_propagation", "backward_propagation", "update_parameters" ]
5
[ [ "forward_propagation", "sigmoid" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
3f578844854134e7c5c147f6f85a4656d9031918
529b9fb9f99d863159b1be0aa09aa139672053ca
v1.0
instruct
Algorithm
Algorithm_17231_I
### Coding Assessment Question #### Context: You are working on a customer relationship management (CRM) system that needs to send personalized email campaigns to a large number of users. To improve the system's efficiency, you are tasked with implementing a batch processing feature that collects user data and sends e...
import smtplib from typing import List, Dict import logging # Configure logging to capture email failures logging.basicConfig(filename='email_failures.log', level=logging.ERROR) def send_individual_email(to_email: str, content: str) -> None: # This function mocks the actual email sending process. # Replace th...
from solution import send_emails_batch class MockSMTPException(Exception): pass # Mocking the send_individual_email function within the test file def send_individual_email(to_email: str, content: str) -> None: if 'fail' in to_email: raise MockSMTPException("Simulated email sending failure") def test_...
[ { "docstring": null, "function_declaration": "def send_individual_email(to_email, content):", "function_name": "send_individual_email", "parameter_list": "(to_email, content)" }, { "docstring": "Send emails in batches of specified size with personalized content.\n\n:param users: List of user...
[ 1, 1, 1, 1, 0, 0, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import smtplib\nimport logging\n\nlogging.basicConfig(level=logging.ERROR, filename=\"email_failures.log\", filemode=\"w\")\n\ndef send_email(email, content):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017231", "row_id": 17231, "seed_ids": "[1990]" }
0.621791
Algorithm_17231
I
[ "send_individual_email", "send_emails_batch" ]
2
[ [ "send_emails_batch", "send_individual_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b0aaec8c1e699339ef1020e485b92da9ac1de344
dea1336ff2b464f035f4f8770a971a41770e0317
v1.0
instruct
Algorithm
Algorithm_17236_I
### City Walk Simulation - Optimized Pathfinding You are tasked with improving the efficiency of a city walk simulation, focusing on the pathfinding algorithm. The provided `city_walk.py` script simulates walking through a city represented as a grid, and you need to enhance the pathfinding algorithm to find the shorte...
import heapq def heuristic(a, b): """ Calculates the Manhattan distance heuristic between point a and point b. """ return abs(a[0] - b[0]) + abs(a[1] - b[1]) def find_shortest_path(grid, start, end): """ Optimized implementation of finding the shortest path using A* algorithm. :param grid...
from solution import find_shortest_path def test_find_shortest_path_simple(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] start = (0, 0) end = (2, 2) assert find_shortest_path(grid, start, end) == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)] def test_find_shortest_path_with_obst...
[ { "docstring": "Calculates the Manhattan distance heuristic between point a and point b.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Optimized implementation of finding the shortest path using A* algorithm.\n\n...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\n\ndef heuristic(a, b):\n \"\"\"\n Heuristic function for A* algorithm using Manhattan distance.\n \n :param a: Tuple (x, y) coordinates...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000017236", "row_id": 17236, "seed_ids": "[4958]" }
0.639323
Algorithm_17236
I
[ "heuristic", "find_shortest_path" ]
2
[ [ "find_shortest_path", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f584050eff45f103b9793a44cfbc244450258d25
ac8396d9d04bd91920795676bd5d75194f9e3b3c
v1.0
instruct
Algorithm
Algorithm_17293_I
### JSON Validation Assessment Create a function that validates whether a given JSON string adheres to a specified schema. The function should return `True` if the JSON string is valid according to the schema, and `False` otherwise. **Function Signature**: ```python def validate_json(json_str: str, schema: dict) -> b...
import json def validate_json(json_str: str, schema: dict) -> bool: try: data = json.loads(json_str) except json.JSONDecodeError: return False return validate_schema(data, schema) def validate_schema(data, schema): if not isinstance(data, dict): return False for key, ...
from solution import validate_json def test_basic_valid_json(): json_str = '{"name": "Alice", "age": 30, "email": "alice@example.com"}' schema = {"name": str, "age": int, "email": str} assert validate_json(json_str, schema) == True def test_basic_invalid_json(): json_str = '{"name": "Alice", "age": "3...
[ { "docstring": null, "function_declaration": "def validate_json(json_str, schema):", "function_name": "validate_json", "parameter_list": "(json_str, schema)" }, { "docstring": null, "function_declaration": "def validate_schema(data, schema):", "function_name": "validate_schema", ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl", "solution_code": "import json\n\ndef validate_json(json_str: str, schema: dict) -> bool:\n try:\n data = json.loads(json_str)\n except json.J...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000017293", "row_id": 17293, "seed_ids": "[1383]" }
0.696352
Algorithm_17293
I
[ "validate_json", "validate_schema" ]
2
[ [ "validate_json", "validate_schema" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b7d89a0fa5b4207592a009f475c63460e10b589e
68cec12c2364b3852ea82211acfc5234247b609e
v1.0
instruct
Algorithm
Algorithm_17318_I
### Problem Statement: Prime Number Rotation A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A number is considered to be a "rotatable prime" if each rotation of its digits forms a valid prime number. For example, 197 is a rotatable prime because rot...
def is_prime(n): """ Checks if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def ...
from solution import is_rotatable_prime def test_single_digit_primes(): assert is_rotatable_prime(2) == True assert is_rotatable_prime(3) == True assert is_rotatable_prime(5) == True assert is_rotatable_prime(7) == True def test_non_prime_single_digits(): assert is_rotatable_prime(1) == False ...
[ { "docstring": "Checks if a number is prime. ", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generate all rotations of the digits of a number ", "function_declaration": "def get_rotations(number):", "function_name...
[ 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 sympy import isprime\n\ndef rotate_number(number):\n \"\"\"\n Generator function which yields all rotations of a number's digits.\n \"\"\"\n num...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000017318", "row_id": 17318, "seed_ids": "[824]" }
0.650732
Algorithm_17318
I
[ "is_prime", "get_rotations", "is_rotatable_prime" ]
3
[ [ "is_rotatable_prime", "get_rotations" ], [ "is_rotatable_prime", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
25831ca0dbde19f008310a31cf9bba8aceb97457
cde163f0c3959aa6520e90f796edc6bbbb1a5881
v1.0
instruct
Algorithm
Algorithm_17469_I
### Coding Assessment Question #### Context You have been given a utility function `merge_intervals` that merges a list of overlapping intervals and returns a new list of the merged intervals. Your task is to use this function effectively to create new functionality for scheduling resources. #### Task Write a functio...
def merge_intervals(intervals): """ Merges overlapping intervals. """ if not intervals: return [] intervals.sort(key=lambda x: x[0]) merged = [intervals[0]] for current in intervals[1:]: last = merged[-1] if current[0] <= last[1]: # Overlap mer...
from solution import schedule_resources def test_no_tasks(): maintenance = (6, 10) tasks = [] assert schedule_resources(tasks, maintenance) == [(0, 6), (10, float('inf'))] def test_no_overlap(): tasks = [(1, 5), (8, 10)] maintenance = (12, 15) assert schedule_resources(tasks, maintenance) == [...
[ { "docstring": "Merges overlapping intervals.", "function_declaration": "def merge_intervals(intervals):", "function_name": "merge_intervals", "parameter_list": "(intervals)" }, { "docstring": "Subtract one interval from a list of intervals.", "function_declaration": "def subtract_interv...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_intervals(intervals):\n \"\"\" Merges overlapping intervals and returns a new list of the merged intervals. \"\"\"\n if not intervals:\n r...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000017469", "row_id": 17469, "seed_ids": "[1887]" }
0.567792
Algorithm_17469
I
[ "merge_intervals", "subtract_intervals", "schedule_resources" ]
3
[ [ "schedule_resources", "merge_intervals" ] ]
1
[]
false
[]
false
pytest
true
[]
true
30f8f1a53fdca585f9fc057a3a32b3432f5c8d71
5ab47b49665463c7cd1926251a8b239f84d72b21
v1.0
instruct
Algorithm
Algorithm_17480_I
### Coding Problem: Volleyball Points Tracker #### Context: In a volleyball game, teams score points using a basic set of rules. A point is scored whenever a team wins a rally. Your task is to track the points and determine the winner based on the number of points scored by each team. #### Task: Write a function `tra...
from typing import List, Tuple def compute_scores(rallies: List[str]) -> Tuple[int, int]: score_a = 0 score_b = 0 for rally in rallies: if rally == 'A': score_a += 1 elif rally == 'B': score_b += 1 return score_a, score_b def determine_winner(score_a: ...
def test_compute_scores(): assert compute_scores(["A", "B", "A", "A"]) == (3, 1) assert compute_scores(["B", "B", "B", "A"]) == (1, 3) assert compute_scores([]) == (0, 0) def test_determine_winner(): assert determine_winner(3, 1, "TeamA", "TeamB") == "TeamA" assert determine_winner(1, 3, "TeamA", "...
[ { "docstring": null, "function_declaration": "def compute_scores(rallies):", "function_name": "compute_scores", "parameter_list": "(rallies)" }, { "docstring": null, "function_declaration": "def determine_winner(score_a, score_b, team_a, team_b):", "function_name": "determine_winner"...
[ 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 compute_scores(rallies: List[str]) -> Tuple[int, int]:\n team_a_score = 0\n team_b_score = 0\n \n for rally in ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017480", "row_id": 17480, "seed_ids": "[1598]" }
0.646966
Algorithm_17480
I
[ "compute_scores", "determine_winner", "track_volleyball_points" ]
3
[ [ "track_volleyball_points", "compute_scores" ], [ "track_volleyball_points", "determine_winner" ] ]
2
[]
false
[]
false
pytest
false
[]
true
e74dc958560b5faecf83105106ba7f00ec009021
2645658ca10b4f1df40968772c10cea5bd1c6daa
v1.0
instruct
Algorithm
Algorithm_17494_I
### Task Write a function that identifies the largest prime palindrome less than a given integer `n`. A palindrome is a number that reads the same forward and backward, and a prime number is only divisible by 1 and itself. ### Input and Output * **Function Signature**: ```python def largest_prime_palindrome(n: i...
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 is_palindrome(num): re...
from solution import largest_prime_palindrome def test_largest_prime_palindrome_1000(): assert largest_prime_palindrome(1000) == 929 def test_largest_prime_palindrome_10(): assert largest_prime_palindrome(10) == 7 def test_largest_prime_palindrome_100(): assert largest_prime_palindrome(100) == 11 def te...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def is_palindrome(num):", "function_name": "is_palindrome", "parameter_list": "(num)" }, { "docstring...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(num):\n if num <= 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_0
{ "original_instruction": "", "prompt_id": "0000017494", "row_id": 17494, "seed_ids": "[3053]" }
0.71699
Algorithm_17494
I
[ "is_prime", "is_palindrome", "largest_prime_palindrome" ]
3
[ [ "largest_prime_palindrome", "is_palindrome" ], [ "largest_prime_palindrome", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c4450c9fc41078c844a00f69ede0d54ac641aba3
73a0d3d49273564dd4a9c77f17fc4d8e3a4b5da1
v1.0
instruct
Algorithm
Algorithm_17525_I
### Implement a K-Nearest Neighbors Classifier Your task is to implement a K-Nearest Neighbors (KNN) algorithm from scratch. You will need to provide an implementation for the classification process using KNN. ### Function Descriptions 1. **euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float** * T...
import numpy as np def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float: """ Computes the Euclidean distance between two points. Args: point1 (np.ndarray): First point. point2 (np.ndarray): Second point. Returns: float: Euclidean distance. """ return np.sqrt(np....
import numpy as np from solution import euclidean_distance, get_neighbors, knn_classify def test_euclidean_distance(): assert np.isclose(euclidean_distance(np.array([0, 0]), np.array([3, 4])), 5.0) assert np.isclose(euclidean_distance(np.array([1, 1]), np.array([4, 5])), 5.0) assert np.isclose(euclidean_di...
[ { "docstring": "Computes the Euclidean distance between two points.\n\nArgs:\npoint1 (np.ndarray): First point.\npoint2 (np.ndarray): Second point.\n\nReturns:\nfloat: Euclidean distance.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "par...
[ 1, 0, 1, 1, 1, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float:\n \"\"\"\n Computes the Euclidean distance between two point...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000017525", "row_id": 17525, "seed_ids": "[770]" }
0.673233
Algorithm_17525
I
[ "euclidean_distance", "get_neighbors", "knn_classify" ]
3
[ [ "get_neighbors", "euclidean_distance" ], [ "knn_classify", "get_neighbors" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
2062ced67618bfaf3773448e5a132e110c90ac4e
70dcd4bab091c9e76a6343277b2cdcfef22d6a37
v1.0
instruct
Algorithm
Algorithm_17687_I
### Array Rotation by d Positions #### Problem Statement Implement a function to rotate an array by `d` positions. The rotation should be performed in place, meaning you should not use any extra space for another array (other than a few extra variables). The function should be able to handle both left and right rotat...
def rotate_array(arr: list[int], d: int, direction: str) -> None: """ Rotate an array by `d` positions in the specified direction. """ n = len(arr) if n == 0 or d == 0: return d = d % n # Handle cases where d is larger than the length of the array if direction == "left": ...
from solution import rotate_array def test_left_rotation(): arr = [1, 2, 3, 4, 5, 6, 7] rotate_array(arr, 2, "left") assert arr == [3, 4, 5, 6, 7, 1, 2] def test_right_rotation(): arr = [1, 2, 3, 4, 5, 6, 7] rotate_array(arr, 3, "right") assert arr == [5, 6, 7, 1, 2, 3, 4] def test_empty_arra...
[ { "docstring": "Rotate an array by `d` positions in the specified direction.", "function_declaration": "def rotate_array(arr, d, direction):", "function_name": "rotate_array", "parameter_list": "(arr, d, direction)" }, { "docstring": "Helper function to reverse elements in the array from sta...
[ 1, 1, 1, 0, 0, 1, 1, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rotate_array(arr: list[int], d: int, direction: str) -> None:\n \"\"\"\n Rotates the elements of the array to the left or right by `d` positions.\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000017687", "row_id": 17687, "seed_ids": "[628]" }
0.648001
Algorithm_17687
I
[ "rotate_array", "reverse" ]
2
[ [ "rotate_array", "reverse" ] ]
1
[]
false
[]
false
pytest
true
[]
true
984920d00ae50a163646d0976a71f89302435581
264bc07b91e13f3650ac92e84052f1239c7c63fc
v1.0
instruct
Algorithm
Algorithm_17718_I
### Binary Search Tree (BST) Operations and Depth Calculation #### Context You are tasked with implementing and enhancing a Binary Search Tree (BST) data structure that supports standard insertion, search, and deletion operations, as well as calculating the depth of the tree. This will help ensure comprehension of tre...
class TreeNode: def __init__(self, key: int): self.key = key self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, key: int): self.root = self._insert(self.root, key) def _insert(self, node: TreeNode, k...
from solution import BinarySearchTree, tree_depth, process_operations def test_insert_and_search(): bst = BinarySearchTree() bst.insert(5) bst.insert(3) bst.insert(7) assert bst.search(5) == True assert bst.search(3) == True assert bst.search(7) == True assert bst.search(4) == False de...
[]
[ 1, 0, 1, 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": "class TreeNode:\n def __init__(self, key: int):\n self.key = key\n self.left = None\n self.right = None\n\nclass BinarySearchTree:\n d...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000017718", "row_id": 17718, "seed_ids": "[4704]" }
0.575364
Algorithm_17718
I
[ "tree_depth", "process_operations" ]
2
[ [ "process_operations", "tree_depth" ] ]
1
[]
false
[ "TreeNode", "BinarySearchTree" ]
true
pytest
true
[]
true
1a9edacd516b5638ea8623f99870f333b38d63a7
016bb6636c3f62fa8ad5c967919242197240a107
v1.0
instruct
Algorithm
Algorithm_17738_I
### Matrix Transpose and Sum **Problem Statement**: You are required to implement two functions: one to transpose a given matrix and another to compute the sum of elements in the transposed matrix. Your task is to create functions `transpose_matrix` and `sum_transposed_matrix` to achieve this. **Function Signatures...
from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Transposes the given 2D matrix. Params: - matrix (List[List[int]]): A 2D list representing the matrix. Returns: - List[List[int]]: A 2D list representing the transposed matrix. """ return...
def test_transpose_matrix(): matrix_1 = [ [1, 2, 3], [4, 5, 6] ] assert transpose_matrix(matrix_1) == [[1, 4], [2, 5], [3, 6]] matrix_2 = [ [7] ] assert transpose_matrix(matrix_2) == [[7]] matrix_3 = [ [1, 4], [2, 5], [3, 6] ] ...
[ { "docstring": "Transposes the given 2D matrix.\n\nParams:\n- matrix (List[List[int]]): A 2D list representing the matrix.\n\nReturns:\n- List[List[int]]: A 2D list representing the transposed matrix.", "function_declaration": "def transpose_matrix(matrix):", "function_name": "transpose_matrix", "pa...
[ 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 transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Transpose the given matrix (2D list).\n \n Pa...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017738", "row_id": 17738, "seed_ids": "[3844]" }
0.591702
Algorithm_17738
I
[ "transpose_matrix", "sum_transposed_matrix" ]
2
[ [ "sum_transposed_matrix", "transpose_matrix" ] ]
1
[]
false
[]
false
pytest
false
[]
true
6dd8e10bfc8653427f1465d92764ba9a512b0077
87b5d0188e1b6ed66d96e7d45a94078459c3eb42
v1.0
instruct
Algorithm
Algorithm_17749_I
## Prime Factorization and GCD ### Context: Finding the greatest common divisor (GCD) of two numbers is essential in various areas of computer science and mathematics. A common method to determine the GCD is by using Euclid's algorithm, but another interesting way can be derived from the prime factorization of the num...
def prime_factors(n: int) -> dict: i = 2 factors = {} # Check for number of 2s while n % i == 0: factors[i] = factors.get(i, 0) + 1 n //= i # Check for other primes for i in range(3, int(n**0.5) + 1, 2): while n % i == 0: factors[i] = factors.get(i, 0) + 1 ...
from solution import prime_factorization_gcd def test_prime_factorization_gcd(): assert prime_factorization_gcd(48, 180) == 12 assert prime_factorization_gcd(100, 75) == 25 assert prime_factorization_gcd(101, 103) == 1 # both are prime numbers assert prime_factorization_gcd(1, 10) == 1 # one input is 1...
[ { "docstring": null, "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": "Computes the GCD of a and b using their prime factorizations.", "function_declaration": "def prime_factorization_gcd(a, b):", "function_n...
[ 0, 1, 1, 1, 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": "import math\nfrom collections import Counter\n\ndef prime_factors(n: int) -> dict:\n factors = Counter()\n # Check for the number of 2s\n while n % 2 ==...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017749", "row_id": 17749, "seed_ids": "[3782]" }
0.715871
Algorithm_17749
I
[ "prime_factors", "prime_factorization_gcd" ]
2
[ [ "prime_factorization_gcd", "prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c5e7d1162dd6dc30761cf5ea3210da8de9f5bd06
83c93c11cfabb4598ffe1390acf4a935b1d84fce
v1.0
instruct
Algorithm
Algorithm_17774_I
Maximum Bipartite Matching - Graph Algorithm The Bipartite Matching problem involves finding the maximum matching in a bipartite graph. A Matching is a set of edges without common vertices. In a bipartite graph, the vertices can be divided into two disjoint sets such that every edge connects a vertex in the first set ...
def bpm(graph, u, matchR, seen): """ A DFS based recursive function that returns True if a matching for vertex u is possible. """ for v in graph[u]: # If vertex v is not seen and u-v is an edge in the graph if not seen[v]: # Mark v as seen seen[v] = True ...
from solution import max_bipartite_matching def test_bipartite_matching_simple_case(): graph = {0: [3, 4], 1: [3], 2: [4, 5], 3: [0, 1], 4: [0, 2], 5: [2]} set1 = {0, 1, 2} set2 = {3, 4, 5} assert max_bipartite_matching(graph, set1, set2) == 3 def test_bipartite_matching_no_edges(): graph = {0: []...
[ { "docstring": "A DFS based recursive function that returns True if a matching for vertex u is possible.", "function_declaration": "def bpm(graph, u, matchR, seen):", "function_name": "bpm", "parameter_list": "(graph, u, matchR, seen)" }, { "docstring": "Returns the maximum number of matchin...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def max_bipartite_matching(graph, set1, set2):\n def bpm(u, match_r, seen):\n for v in graph.get(u, []):\n if v not in seen:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017774", "row_id": 17774, "seed_ids": "[4551]" }
0.587956
Algorithm_17774
I
[ "bpm", "max_bipartite_matching" ]
2
[ [ "max_bipartite_matching", "bpm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cbcfa7577494582642cb746efeab4d7f3b51fd96
6e304305b53752b300749ffbc347a91714aa4e15
v1.0
instruct
Algorithm
Algorithm_17795_I
### Scenario You are developing a file management system that needs to keep track of several files and directories. As part of this system, you want to check if the current directory has a specific path, and if that path exists, retrieve its complete relative path from the root directory. ### Task You need to write tw...
def path_exists(path, current_directory): """ Checks if the given path exists in the current directory structure. """ parts = path.strip("/").split("/") current = current_directory for part in parts: if part not in current: return False current = current[part] ...
from solution import path_exists, get_full_path def test_path_exists_existing_path(): current_directory = { "home": { "user": { "documents": {}, "photos": { "2021": {}, "2022": {} } }, ...
[ { "docstring": "Checks if the given path exists in the current directory structure.", "function_declaration": "def path_exists(path, current_directory):", "function_name": "path_exists", "parameter_list": "(path, current_directory)" }, { "docstring": "Returns the full relative path from the ...
[ 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": "def path_exists(path: str, current_directory: dict) -> bool:\n \"\"\"\n Checks if the given path exists in the current directory.\n \"\"\"\n componen...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000017795", "row_id": 17795, "seed_ids": "[260]" }
0.723734
Algorithm_17795
I
[ "path_exists", "get_full_path" ]
2
[ [ "get_full_path", "path_exists" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bf44eed16665920aa61f0edaa1177e864b5997e6
2e82c6b18164f0fffbd5bcde37d38c436b236421
v1.0
instruct
Algorithm
Algorithm_17796_I
### Scenario You are a software engineer for a company that manages electronic health records (EHRs). Your team is tasked with developing a feature that identifies the most common medical diagnoses for a given set of patients over a specified time period. Your company has an API that provides diagnosis data, but the da...
from typing import List from datetime import date from collections import Counter def fetch_diagnoses(patient_id: int, start: date, end: date) -> List[str]: """ Mock function to represent the fetching of diagnoses data. In a real scenario, this function would query a database or an API. """ # This ...
from datetime import date from solution import most_frequent_diagnosis def test_most_frequent_diagnosis(): patient_ids = [101, 102, 103] start_date = date(2021, 1, 1) end_date = date(2021, 12, 31) assert most_frequent_diagnosis(patient_ids, start_date, end_date) == "Cold" def test_most_frequent_d...
[ { "docstring": "Mock function to represent the fetching of diagnoses data.\nIn a real scenario, this function would query a database or an API.", "function_declaration": "def fetch_diagnoses(patient_id, start, end):", "function_name": "fetch_diagnoses", "parameter_list": "(patient_id, start, end)" ...
[ 1, 0, 0, 1, 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": "from datetime import date\nfrom typing import List\nfrom collections import Counter\n\n# Mock function to simulate fetching diagnoses.\ndef fetch_diagnoses(patie...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017796", "row_id": 17796, "seed_ids": "[1963]" }
0.575273
Algorithm_17796
I
[ "fetch_diagnoses", "most_frequent_diagnosis" ]
2
[ [ "most_frequent_diagnosis", "fetch_diagnoses" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a31d9055733ba556fadf790e056cfe01a08c37d
94c4497e440217cbbd3636be83ba1be438dcd594
v1.0
instruct
Algorithm
Algorithm_17797_I
### Optimizing Matrix Multiplication #### Background Matrix multiplication is a fundamental operation in linear algebra with applications in numerous fields, including computer graphics, machine learning, and scientific computing. The naive approach of multiplying two matrices, each of size \( n \times n \), has a ti...
def add_matrices(A, B): return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(A))] def subtract_matrices(A, B): return [[A[i][j] - B[i][j] for j in range(len(A))] for i in range(len(A))] def split_matrix(matrix): n = len(matrix) mid = n // 2 A11 = [[matrix[i][j] for j in range(mid)...
from solution import strassen_matrix_mult def test_small_matrices(): A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] expected = [ [19, 22], [43, 50] ] assert strassen_matrix_mult(A, B) == expected def test_identity_matrix(): A = [ [...
[ { "docstring": null, "function_declaration": "def add_matrices(A, B):", "function_name": "add_matrices", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def subtract_matrices(A, B):", "function_name": "subtract_matrices", "parameter_list": "(A, B)" }...
[ 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def add_matrices(A, B):\n return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(A))]\n\ndef subtract_matrices(A, B):\n return [[A[i][j] - B...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000017797", "row_id": 17797, "seed_ids": "[4216]" }
0.525857
Algorithm_17797
I
[ "add_matrices", "subtract_matrices", "split_matrix", "combine_matrices", "strassen_matrix_mult" ]
5
[ [ "strassen_matrix_mult", "add_matrices" ], [ "strassen_matrix_mult", "combine_matrices" ], [ "strassen_matrix_mult", "split_matrix" ], [ "strassen_matrix_mult", "subtract_matrices" ] ]
4
[]
false
[]
false
pytest
true
[]
true
68fb649d268243725ebaa3203438a1afb2657022
6bdfdcc67db3c2e43196f87b140f9315f604185c
v1.0
instruct
Algorithm
Algorithm_17838_I
### Context Optimizing data storage and retrieval is a fundamental challenge in computer science, particularly when dealing with large datasets. Be familiar with algorithms for efficient data manipulation like sorting, searching, and updating collections. ### Problem Statement Given a list of integers, write a functio...
def solution(arr: list, k: int) -> int: """ Returns the k-th smallest number in the list. :param arr: A list of integers from which to find the k-th smallest element. :param k: An integer representing the 1-based position of the desired smallest element. :return: The k-th smallest integer in th...
from solution import solution import pytest def test_solution_valid_k(): assert solution([7, 10, 4, 3, 20, 15], 3) == 7 assert solution([7, 10, 4, 3, 20, 15], 4) == 10 assert solution([1, 2, 3, 4, 5], 1) == 1 assert solution([1, 2, 3, 4, 5], 5) == 5 def test_solution_invalid_k(): with pytest.raise...
[ { "docstring": "Returns the k-th smallest number in the list.\n\n:param arr: A list of integers from which to find the k-th smallest element.\n:param k: An integer representing the 1-based position of the desired smallest element.\n:return: The k-th smallest integer in the list.", "function_declaration": "d...
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def solution(arr, k):\n \"\"\"\n Returns the k-th smallest number in the list.\n \n :param arr: A list of integers from which to find the k-th smalle...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017838", "row_id": 17838, "seed_ids": "[2745]" }
0.70688
Algorithm_17838
I
[ "solution", "quickselect", "partition" ]
3
[ [ "quickselect", "partition" ], [ "solution", "quickselect" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d26a7256ddca3a00b8b5636a0b13fef2ed0a065b
31bd7ec5221810a3153e25a56bba4d3241befd7d
v1.0
instruct
Algorithm
Algorithm_17893_I
### Coding Assessment Question #### Context: A company desires a secure way to store and check passwords using hashing, which involves creating a hash of the password and storing it. When a user logs in, the system hashes the entered password and compares it to the stored hash. For security, we will use the SHA-256 ha...
import hashlib def hash_password(password): """ Generate a SHA-256 hash for the given password. Parameters: password (str): The password to be hashed. Returns: str: The SHA-256 hash of the password. """ if not (1 <= len(password) <= 100): raise ValueError("Password len...
from solution import hash_password, check_password def test_hash_password_valid(): assert hash_password("password123") == hashlib.sha256("password123".encode()).hexdigest() def test_hash_password_min_length(): assert hash_password("a") == hashlib.sha256("a".encode()).hexdigest() def test_hash_password_max_le...
[ { "docstring": "Generate a SHA-256 hash for the given password.\n\nParameters:\npassword (str): The password to be hashed.\n\nReturns:\nstr: The SHA-256 hash of the password.", "function_declaration": "def hash_password(password):", "function_name": "hash_password", "parameter_list": "(password)" ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef hash_password(password):\n \"\"\"\n Generates a SHA-256 hash for the given password.\n \"\"\"\n if not isinstance(password, str...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000017893", "row_id": 17893, "seed_ids": "[648]" }
0.72074
Algorithm_17893
I
[ "hash_password", "check_password" ]
2
[ [ "check_password", "hash_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6083171d5053bfc6f750684e72563e8994c932d4
d837a9f28bad0928d9ea5a49790c9808ed486f0e
v1.0
instruct
Algorithm
Algorithm_17923_I
You are tasked with implementing the Merge Sort algorithm, a classic divide-and-conquer sorting method. Please follow the requirements below: ### Scenario You are given an unsorted list of integers. You need to write a Python function that sorts this list using the Merge Sort algorithm. ### Function Signature ```pyth...
def merge(left, right): """ Merges two sorted lists into a single sorted list. """ merged = [] i = j = 0 # Traverse both lists and append smaller element from either list while i < len(left) and j < len(right): if left[i] < right[j]: merged.append(left[i]) i ...
def test_merge_both_empty(): assert merge([], []) == [] def test_merge_left_empty(): assert merge([], [1, 2, 3]) == [1, 2, 3] def test_merge_right_empty(): assert merge([1, 2, 3], []) == [1, 2, 3] def test_merge_sorted_lists(): assert merge([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6] def test_merge_...
[ { "docstring": "Merges two sorted lists into a single sorted list.", "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docstring": "Sorts an array of integers using the Merge Sort algorithm.", "function_declaration": "def...
[ 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(left, right):\n \"\"\"\n Merges two sorted lists into a single sorted list.\n\n Parameters:\n - left: A sorted list of integers.\n - rig...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017923", "row_id": 17923, "seed_ids": "[4218]" }
0.619395
Algorithm_17923
I
[ "merge", "merge_sort" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
false
[]
true
f2f17df60871ba99fd4f0bbbd5912bf41b3d97de
8e73ae485bb1a34f6fe8492d2e48d1a6b4f3997f
v1.0
instruct
Algorithm
Algorithm_17957_I
### Problem Statement A logistics company needs to ensure that its delivery trucks operate efficiently by optimizing the routes they take from a warehouse to multiple delivery points. They decide to use the Genetic Algorithm (GA) approach to solve this problem. Your task is to implement a function that uses a Genetic A...
import random import math import matplotlib.pyplot as plt from itertools import combinations class Route: def __init__(self, points: list): self.points = points random.shuffle(self.points) def total_distance(self) -> float: distance = 0.0 for i in range(len(self.points)): ...
from solution import Route, genetic_algorithm def test_total_distance(): points = [(0, 0), (3, 4), (3, 0)] route = Route(points) assert math.isclose(route.total_distance(), 12.0, rel_tol=1e-5) def test_mutate(): points = [(0, 0), (3, 4), (3, 0)] route = Route(points) route.mutate(1.0) asse...
[]
[ 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 random\nimport math\nfrom typing import List, Tuple\n\nclass Route:\n def __init__(self, points: List[Tuple[int, int]]):\n self.points = points\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000017957", "row_id": 17957, "seed_ids": "[4964]" }
0.504603
Algorithm_17957
I
[ "crossover", "genetic_algorithm" ]
2
[ [ "genetic_algorithm", "crossover" ] ]
1
[]
false
[ "Route" ]
true
pytest
true
[ "matplotlib" ]
false
e20dd2abb483bdc6e9154305bc0f422fb9a7319b
96c1bb5c40a39055a34b66238a059bd1f3c3eb56
v1.0
instruct
Algorithm
Algorithm_18033_I
### Problem Statement Write a program that simulates a simple file system using a tree structure. Each node in the tree can represent either a file or a directory. The root node represents the root directory. Your task is to implement functionality to add files/directories, retrieve the list of files/directories, and g...
class TreeNode: def __init__(self, name, node_type): self.name = name self.node_type = node_type self.children = {} def add_child(self, child_node): self.children[child_node.name] = child_node def get_children(self): return sorted(self.children.keys()) def get_...
import pytest from solution import TreeNode, add_node, filesystem_operations def test_filesystem_operations(): operations = [ ('add_dir', '/', 'home'), ('add_dir', '/home', 'user'), ('add_file', '/home/user', 'file1.txt'), ('add_file', '/home/user', 'file2.txt'), ('ls', '/ho...
[]
[ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, name, node_type):\n self.name = name\n self.node_type = node_type\n self.children = {}\n self...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000018033", "row_id": 18033, "seed_ids": "[1371]" }
0.580752
Algorithm_18033
I
[ "add_node", "filesystem_operations" ]
2
[ [ "filesystem_operations", "add_node" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
124a9c4668cfcddf95256aafcaf4d088a5dc6c09
f930fe68f16014c64fc24bc6feffe7618d50f00d
v1.0
instruct
Algorithm
Algorithm_18058_I
### Log File Analysis and Cleaning You are asked to build a utility that processes and cleans a web server log file. The log file contains entries in the Common Log Format (CLF), and your task is to filter and clean invalid entries, count the number of requests per status code, and save the cleaned log to a new file. ...
import re def filter_valid_entries(file_path): """ Reads the log file and filters out invalid entries. Returns a list of valid log entries. """ valid_entries = [] clf_pattern = re.compile( r'^\S+ \S+ \S+ \[\S+ \S+\] "\S+ \S+ \S+" \d{3} \d+' ) try: with open(file_path, 'r...
import pytest from solution import filter_valid_entries, count_requests_per_status, save_cleaned_log def test_filter_valid_entries(tmp_path): data = [ '127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326\n', 'invalid log entry that does not conform\n', '127...
[ { "docstring": "Reads the log file and filters out invalid entries.\nReturns a list of valid log entries.", "function_declaration": "def filter_valid_entries(file_path):", "function_name": "filter_valid_entries", "parameter_list": "(file_path)" }, { "docstring": "Takes a list of valid log en...
[ 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef filter_valid_entries(file_path):\n \"\"\"\n Reads a log file, filters out invalid entries, and returns a list of valid log entries.\n \...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000018058", "row_id": 18058, "seed_ids": "[2361]" }
0.62632
Algorithm_18058
I
[ "filter_valid_entries", "count_requests_per_status", "save_cleaned_log" ]
3
[ [ "save_cleaned_log", "filter_valid_entries" ] ]
1
[]
false
[]
false
pytest
true
[]
true
454c8e7524d8322b7e76bb0958973ccff269d23d
05ed20bcf86af614787226e8111b01378afe3cbe
v1.0
instruct
Algorithm
Algorithm_18076_I
### Coding Assessment Question #### Context You are developing a tool to assist civil engineers in calculating various parameters for cylindrical tanks used in water supply systems. The tool needs to accurately compute the surface area, volume, and lateral surface area of a cylindrical tank. A cylindrical tank is de...
import math def cylindrical_tank_surface_area(radius: float, height: float) -> float: if radius <= 0 or height <= 0: raise ValueError("Radius and height must be positive.") return 2 * math.pi * radius * (radius + height) def cylindrical_tank_volume(radius: float, height: float) -> float: if radius...
import pytest from solution import cylindrical_tank_surface_area, cylindrical_tank_volume, cylindrical_tank_lateral_surface_area, describe_cylindrical_tank def test_cylindrical_tank_surface_area(): assert cylindrical_tank_surface_area(3, 5) == pytest.approx(150.79644737231007) assert cylindrical_tank_surface_a...
[ { "docstring": null, "function_declaration": "def cylindrical_tank_surface_area(radius, height):", "function_name": "cylindrical_tank_surface_area", "parameter_list": "(radius, height)" }, { "docstring": null, "function_declaration": "def cylindrical_tank_volume(radius, height):", "f...
[ 1, 0, 1, 0, 1, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom typing import Dict\n\ndef cylindrical_tank_surface_area(radius: float, height: float) -> float:\n if radius <= 0 or height <= 0:\n ra...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000018076", "row_id": 18076, "seed_ids": "[3595]" }
0.593272
Algorithm_18076
I
[ "cylindrical_tank_surface_area", "cylindrical_tank_volume", "cylindrical_tank_lateral_surface_area", "describe_cylindrical_tank" ]
4
[ [ "describe_cylindrical_tank", "cylindrical_tank_lateral_surface_area" ], [ "describe_cylindrical_tank", "cylindrical_tank_surface_area" ], [ "describe_cylindrical_tank", "cylindrical_tank_volume" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3a2cb8294ac6d2b7363c0078dfec62af316d1c0b
960f4f985f7e83f754e200dbc48cfe4bd8bca979
v1.0
instruct
Algorithm
Algorithm_18146_I
### Fibonacci Sequence and Even Sum Calculation #### Context You need to work with the Fibonacci sequence and perform operations on its even-valued terms. The Fibonacci sequence is defined as: - \( F_0 = 0, F_1 = 1 \) - \( F_n = F_{n-1} + F_{n-2} \) for \( n \geq 2 \) #### Task 1. Implement a function, `generate_fib...
def generate_fibonacci(n: int) -> list: """ Generate the first n terms of the Fibonacci sequence. Args: n: An integer representing the number of terms to generate Returns: list: A list containing the first n terms of the Fibonacci sequence Raises: ValueError: If n is not a positive in...
from solution import generate_fibonacci, sum_of_even_fibonacci def test_generate_fibonacci_standard_cases(): assert generate_fibonacci(1) == [0] assert generate_fibonacci(2) == [0, 1] assert generate_fibonacci(5) == [0, 1, 1, 2, 3] assert generate_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] def...
[ { "docstring": "Generate the first n terms of the Fibonacci sequence.\n\nArgs:\nn: An integer representing the number of terms to generate\n\nReturns:\nlist: A list containing the first n terms of the Fibonacci sequence\n\nRaises:\nValueError: If n is not a positive integer", "function_declaration": "def ge...
[ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def generate_fibonacci(n: int) -> list:\n \"\"\"\n Generate the first n terms of the Fibonacci sequence.\n\n Args:\n n: An integer representing the n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000018146", "row_id": 18146, "seed_ids": "[3645]" }
0.696112
Algorithm_18146
I
[ "generate_fibonacci", "sum_of_even_fibonacci" ]
2
[ [ "sum_of_even_fibonacci", "generate_fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7cea84731aee57dea06c39c592f4f6e6060d6ad3
e86f143e554e7888cb962e38032a7a0395445b94
v1.0
instruct
Algorithm
Algorithm_18215_I
### Suffix Array Construction and Searching Design a function `suffix_array_search` that constructs a suffix array from a given string and uses it to search for a pattern within the string. #### Function Signature: ```python def suffix_array_search(text: str, pattern: str) -> list[int]: ``` #### Input: * `text`: A s...
def build_suffix_array(text): # Generate suffixes along with their starting indices suffixes = sorted((text[i:], i) for i in range(len(text))) # Extract and return only the starting indices sorted by the suffixes return [suffix[1] for suffix in suffixes] def binary_search(suffix_array, text, pattern): ...
from solution import suffix_array_search def test_suffix_array_search_single_occurrence(): text = "banana" pattern = "ana" assert suffix_array_search(text, pattern) == [1, 3] def test_suffix_array_search_multiple_occurrences(): text = "mississippi" pattern = "issi" assert suffix_array_search(t...
[ { "docstring": null, "function_declaration": "def build_suffix_array(text):", "function_name": "build_suffix_array", "parameter_list": "(text)" }, { "docstring": null, "function_declaration": "def binary_search(suffix_array, text, pattern):", "function_name": "binary_search", "pa...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def build_suffix_array(text):\n # Generate suffixes along with their starting indices\n suffixes = sorted((text[i:], i) for i in range(len(text)))\n # E...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000018215", "row_id": 18215, "seed_ids": "[1596]" }
0.656911
Algorithm_18215
I
[ "build_suffix_array", "binary_search", "suffix_array_search" ]
3
[ [ "suffix_array_search", "binary_search" ], [ "suffix_array_search", "build_suffix_array" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4baaf05a1c5af68fa072fc70e4993a2eecd27bf5
bbd4ec397d460260f0503bc765f8261068683a6e
v1.0
instruct
Algorithm
Algorithm_18234_I
### Question You are tasked with implementing a function that finds the smallest positive integer that is evenly divisible by all the numbers from 1 to a given limit. ### Function Signature ```python def smallest_multiple(limit: int) -> int: # Your code here ``` ### Input The function will have a single input: *...
import math def lcm(a, b): return abs(a * b) // math.gcd(a, b) def smallest_multiple(limit: int) -> int: result = 1 for i in range(1, limit + 1): result = lcm(result, i) return result
from solution import smallest_multiple def test_smallest_multiple_1(): assert smallest_multiple(1) == 1 def test_smallest_multiple_5(): assert smallest_multiple(5) == 60 def test_smallest_multiple_10(): assert smallest_multiple(10) == 2520 def test_smallest_multiple_15(): assert smallest_mul...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def smallest_multiple(limit):", "function_name": "smallest_multiple", "parameter_list": "(limit)" } ]
[ 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 math import gcd\n\ndef lcm(a, b):\n return a * b // gcd(a, b)\n\ndef smallest_multiple(limit: int) -> int:\n result = 1\n for i in range(2, limit +...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000018234", "row_id": 18234, "seed_ids": "[2864]" }
0.653138
Algorithm_18234
I
[ "lcm", "smallest_multiple" ]
2
[ [ "smallest_multiple", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b4492656646f5f3a52fc8d455b368ef14baf39c0
72aec2747fd26aacd0a7354d0d6b30601874ffaf
v1.0
instruct
Algorithm
Algorithm_18239_I
### Sudoku Solver Implement a Sudoku solver that fills an empty or partially filled Sudoku board. The function should use a backtracking algorithm to ensure that the board respects the Sudoku rules. Every row, column, and 3x3 subgrid must contain distinct numbers from 1 to 9. ### Input and Output #### Input * A 9x9 ...
def is_valid(board, row, col, num): """ Check if placing the number at the given row and column is valid according to Sudoku rules. """ # Check if the number is already in the row for x in range(9): if board[row][x] == num: return False # Check if the number is already i...
from solution import sudoku_solver def test_sudoku_solver_solvable_board(): board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], ...
[ { "docstring": "Check if placing the number at the given row and column is valid\naccording to Sudoku rules.", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Solve the Sudoku puzzle usi...
[ 0, 1, 1, 1, 0, 1, 0, 1, 1 ]
6
easy
0.667
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl", "solution_code": "def is_valid(board, row, col, num):\n # Check if the number is already in the row\n for x in range(9):\n if board[row][x] =...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000018239", "row_id": 18239, "seed_ids": "[5085]" }
0.653757
Algorithm_18239
I
[ "is_valid", "solve_sudoku", "sudoku_solver" ]
3
[ [ "solve_sudoku", "is_valid" ], [ "sudoku_solver", "solve_sudoku" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d124d4aa698215f52e5a00dd3fdf1f228a1e531a
0e8db07b50d1b0a8d0910ff371733d9dfa3dd43e
v1.0
instruct
Algorithm
Algorithm_18319_I
### Software Development Assessment Question #### Scenario: Concurrent Prime Number Search You are developing a concurrent system that involves finding prime numbers within a specified range. Your objective is to implement an efficient solution that leverages parallel processing to speed up the execution of the prime...
from typing import List import multiprocessing as mp def is_prime(n: int) -> bool: """Check if a number is a 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) ...
from solution import concurrent_prime_search def test_concurrent_prime_search_basic(): assert concurrent_prime_search(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_concurrent_prime_search_large_range(): primes = concurrent_prime_search(1, 100) expected_primes = [2, 3, 5, 7, 11, 13, 17, ...
[ { "docstring": "Check if a number is a prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find all prime numbers in the given range", "function_declaration": "def find_primes_in_range(start, end):", "function_n...
[ 1, 1, 1, 0, 0, 0, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport multiprocessing as mp\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is a prime.\"\"\"\n if n <= 1:\n re...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000018319", "row_id": 18319, "seed_ids": "[898]" }
0.551651
Algorithm_18319
I
[ "is_prime", "find_primes_in_range", "concurrent_prime_search" ]
3
[ [ "concurrent_prime_search", "find_primes_in_range" ], [ "find_primes_in_range", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f43e27c57721ad294ed19a73d3604f6e170e57e8
86fec54150a828cb80e74495cf2e8d6f30f8b702
v1.0
instruct
Algorithm
Algorithm_18328_I
### File Cleaner You are tasked with developing a script that scans a directory for text files, processes their contents, and outputs a cleaned version of each file. The files may contain extraneous whitespace, special characters, and lines of non-text data. Your job is to clean these files and save the processed data...
import os import re def clean_text(file_content: str) -> str: """ Removes all special characters except spaces, periods, commas, question marks, and exclamation marks. Removes extra whitespace, ensuring a single space between words and no leading/trailing spaces. Converts all text to lowercase. "...
import pytest import os from solution import clean_text, process_files def test_clean_text(): assert clean_text("Hello!!! This is a test.") == "hello!!! this is a test." assert clean_text("Multiple spaces and special$$ chars!!") == "multiple spaces and special chars!!" assert clean_text("1234 5678! Clea...
[ { "docstring": "Removes all special characters except spaces, periods, commas, question marks, \nand exclamation marks. Removes extra whitespace, ensuring a single space between \nwords and no leading/trailing spaces. Converts all text to lowercase.", "function_declaration": "def clean_text(file_content):",...
[ 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": "import os\nimport re\n\ndef clean_text(file_content: str) -> str:\n \"\"\"\n Cleans the given text by removing unwanted characters, extra spaces,\n and ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000018328", "row_id": 18328, "seed_ids": "[2448]" }
0.614376
Algorithm_18328
I
[ "clean_text", "process_files" ]
2
[ [ "process_files", "clean_text" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6195e7ab5c754ee359ec21f6f007d7936dfd8903
f5f50ff4b9ce283f0d74f81989443aacfd9893d9
v1.0
instruct
Algorithm
Algorithm_18386_I
### Coding Assessment Question: Maximum Circular Subarray Sum **Objective:** Write a function, `max_circular_subarray_sum(arr: List[int]) -> int`, to find the maximum sum of a circular subarray. A circular subarray means the end of the array wraps around to the start. **Input:** - A list of integers `arr` where $(1...
from typing import List def max_subarray_sum(arr: List[int]) -> int: max_ending_here = max_so_far = arr[0] for x in arr[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 min_subarray_sum(arr: List[int]) -> int: min_en...
from solution import max_circular_subarray_sum def test_example1(): assert max_circular_subarray_sum([5, -3, 5]) == 10 def test_example2(): assert max_circular_subarray_sum([1, -2, 3, -2]) == 3 def test_example3(): assert max_circular_subarray_sum([3, -1, 2, -1]) == 4 def test_example4(): assert max...
[ { "docstring": null, "function_declaration": "def max_subarray_sum(arr):", "function_name": "max_subarray_sum", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def min_subarray_sum(arr):", "function_name": "min_subarray_sum", "parameter_list": "(arr)" ...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef max_subarray_sum(arr: List[int]) -> int:\n max_ending_here = max_so_far = arr[0]\n for x in arr[1:]:\n max_ending_her...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000018386", "row_id": 18386, "seed_ids": "[2748]" }
0.623113
Algorithm_18386
I
[ "max_subarray_sum", "min_subarray_sum", "max_circular_subarray_sum" ]
3
[ [ "max_circular_subarray_sum", "max_subarray_sum" ], [ "max_circular_subarray_sum", "min_subarray_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7b8ebed9bb2db178b9b48ae505e2688c073f14d6
4bdd8c63eafbfaade03003168aae34e81e2b971b
v1.0
instruct
Algorithm
Algorithm_18399_I
### Coding Assessment Question: Implement K-Means Clustering You are required to implement a K-Means Clustering algorithm. The model must be capable of training on a given dataset and assigning clusters to the given data points. Your implementation should leverage the principles discussed in the clustering algorithms....
import random import numpy as np def initialize_centroids(data_points, num_clusters): """ Randomly initialize centroids by selecting random points from the data_points. """ return random.sample(data_points, num_clusters) def assign_clusters(data_points, centroids): """ Assign each data point t...
from solution import ( initialize_centroids, assign_clusters, update_centroids, calculate_sse, train_kmeans, predict_clusters ) def test_initialize_centroids(): data_points = [[1, 2], [3, 4], [5, 6], [7, 8]] centroids = initialize_centroids(data_points, 2) assert len(centroids)...
[ { "docstring": "Randomly initialize centroids by selecting random points from the data_points.", "function_declaration": "def initialize_centroids(data_points, num_clusters):", "function_name": "initialize_centroids", "parameter_list": "(data_points, num_clusters)" }, { "docstring": "Assign ...
[ 1, 1, 0, 0, 0, 1, 1, 0, 0 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\nimport numpy as np\n\ndef initialize_centroids(data_points, num_clusters):\n \"\"\"\n Randomly initialize centroids by selecting random poin...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000018399", "row_id": 18399, "seed_ids": "[479]" }
0.724278
Algorithm_18399
I
[ "initialize_centroids", "assign_clusters", "update_centroids", "calculate_sse", "train_kmeans", "predict_clusters" ]
6
[ [ "predict_clusters", "assign_clusters" ], [ "train_kmeans", "assign_clusters" ], [ "train_kmeans", "calculate_sse" ], [ "train_kmeans", "initialize_centroids" ], [ "train_kmeans", "update_centroids" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
6d0c0a0183a3ec60e3b6f68c17dfce9ddb5b15f7
22caf541c4c72f5abc36baf166422c2c1b53d500
v1.0
instruct
Algorithm
Algorithm_18454_I
### Longest Path in a Directed Acyclic Graph (DAG) You are given a Directed Acyclic Graph (DAG) represented as an adjacency list. Each node has a unique identifier, and each edge has a non-negative weight. Your task is to find the longest path from a given source node to a given destination node. Implement the functi...
from collections import defaultdict, deque def topological_sort(graph): in_degree = defaultdict(int) for node in graph: if node not in in_degree: in_degree[node] = 0 for neighbor, weight in graph[node]: in_degree[neighbor] += 1 zero_in_degree_queue = deque([node...
from solution import longest_path_dag def test_no_path(): graph = { 0: [(1, 2)], 1: [(2, 3)], 2: [], 3: [] } assert longest_path_dag(graph, 0, 3) == (-1, []) def test_single_path(): graph = { 0: [(1, 2)], 1: [(2, 3)], 2: [(3, 4)], 3: [] ...
[ { "docstring": null, "function_declaration": "def topological_sort(graph):", "function_name": "topological_sort", "parameter_list": "(graph)" }, { "docstring": null, "function_declaration": "def longest_path_dag(graph, source, destination):", "function_name": "longest_path_dag", ...
[ 0, 0, 0, 1, 1, 0, 1, 1, 0 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import defaultdict, deque\n\ndef longest_path_dag(graph, source, destination):\n # Step 1: Perform topological sort using Kahn's algorithm\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000018454", "row_id": 18454, "seed_ids": "[5069]" }
0.637757
Algorithm_18454
I
[ "topological_sort", "longest_path_dag" ]
2
[ [ "longest_path_dag", "topological_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9b66219aee075338d2f1694750616bc460ce6c00
1579adb05f7608885b42c32e66ce9d8949b1b34c
v1.0
instruct
Algorithm
Algorithm_18576_I
### Real-Time Educational Quiz Application with WebSocket You are tasked with developing the backend for a real-time educational quiz application that allows multiple clients to participate in a quiz simultaneously. The server needs to broadcast questions to all connected clients and handle responses in real-time usin...
import asyncio import websockets import logging from typing import List logging.basicConfig(level=logging.INFO) connected_clients = set() async def broadcast_questions(websocket, path, question_list): connected_clients.add(websocket) logging.info(f"New client connected. Total clients: {len(connected_clients)...
import asyncio import websockets import pytest import threading import time from solution import run_server @pytest.fixture def start_server(): questions = [ "What is the capital of France?", "What is the sum of 2 and 2?", "Name the largest planet in our solar system." ] server_thr...
[ { "docstring": null, "function_declaration": "def run_server(question_list):", "function_name": "run_server", "parameter_list": "(question_list)" } ]
[ 1, 0, 1, 1, 0, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import asyncio\nimport websockets\nimport logging\nfrom typing import List\nimport signal\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO)\n\nclie...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000018576", "row_id": 18576, "seed_ids": "[4273]" }
0.575566
Algorithm_18576
I
[ "broadcast_questions", "start_quiz_server", "run_server" ]
3
[ [ "run_server", "start_quiz_server" ], [ "start_quiz_server", "broadcast_questions" ] ]
2
[]
false
[]
false
pytest
true
[ "websockets" ]
false
5d86e9b776c849d6fe537cad8344162ec9d268d8
02d65b3f444c34fadbc3d7b8ca64bde5a76f04d8
v1.0
instruct
Algorithm
Algorithm_18613_I
### Hash Table Manipulation: Implement Collision-Handled Hash Table with Double Hashing In this task, you are required to handle collisions in a hash table using a double hashing technique. #### Scenario: You are developing a library system to store book titles based on their unique ISBN numbers. The ISBN numbers nee...
def h1(key, table_size): """Primary hash function""" return key % table_size def h2(key, table_size): """Secondary hash function""" return 1 + (key % (table_size - 1)) def insert_into_book_hash_table(hash_table, isbn_title_pairs): """Inserts book titles into the hash table using double hashing."""...
from solution import insert_into_book_hash_table, retrieve_from_book_hash_table def test_insert_and_retrieve_single_entry(): hash_table = [None] * 10 insert_into_book_hash_table(hash_table, [(12345, 'Book A')]) assert retrieve_from_book_hash_table(hash_table, 12345) == 'Book A' def test_insert_and_retriev...
[ { "docstring": "Primary hash function", "function_declaration": "def h1(key, table_size):", "function_name": "h1", "parameter_list": "(key, table_size)" }, { "docstring": "Secondary hash function", "function_declaration": "def h2(key, table_size):", "function_name": "h2", "parame...
[ 0, 1, 1, 0, 0, 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": "def h1(key, table_size):\n \"\"\"\n Primary hash function.\n \"\"\"\n return key % table_size\n\ndef h2(key, table_size):\n \"\"\"\n Secondary ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000018613", "row_id": 18613, "seed_ids": "[2282]" }
0.462084
Algorithm_18613
I
[ "h1", "h2", "insert_into_book_hash_table", "retrieve_from_book_hash_table" ]
4
[ [ "insert_into_book_hash_table", "h1" ], [ "insert_into_book_hash_table", "h2" ], [ "retrieve_from_book_hash_table", "h1" ], [ "retrieve_from_book_hash_table", "h2" ] ]
4
[]
false
[]
false
pytest
true
[]
true
aafe21f8700da17058e8f8f9c92fde5268bd2ad1
e26b8513aeca68fa8506e46f7e59b6e5bcc1a839
v1.0
instruct
Algorithm
Algorithm_18632_I
### Scenario You are tasked with improving the delivery system for a courier service. Specifically, you need to optimize the delivery routes to minimize the total distance traveled while ensuring all deliveries are completed. This is a variant of the well-known Traveling Salesman Problem (TSP). ### Task Implement a fu...
from typing import List, Tuple from itertools import permutations import math def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float: return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) def total_route_distance(route: List[int], locations: List[Tuple[int, int]]) -> float: total_distan...
from solution import optimize_routes def test_optimize_routes_case1(): locations = [(0, 0), (2, 2), (1, 1), (6, 6)] result = optimize_routes(locations) expected = [0, 2, 1, 3, 0] # Note: This is one possible correct route, ensure the distance is minimal assert set(result) == set(expected) # Check if ...
[ { "docstring": null, "function_declaration": "def calculate_distance(p1, p2):", "function_name": "calculate_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def total_route_distance(route, locations):", "function_name": "total_route_distance", ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import itertools\nfrom typing import List, Tuple\n\ndef calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:\n \"\"\"\n Calculate the Euc...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000018632", "row_id": 18632, "seed_ids": "[1586]" }
0.664757
Algorithm_18632
I
[ "calculate_distance", "total_route_distance", "optimize_routes" ]
3
[ [ "optimize_routes", "total_route_distance" ], [ "total_route_distance", "calculate_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
67472b0be72c22bd6c41b8228b60fb67a1450d53
34d7b766d6f9d3acb8d7952b21ee34d975999c9b
v1.0
instruct
Algorithm
Algorithm_18671_I
**Prime Sum Pairs** Given a positive integer `n`, write a function to find all unique pairs of prime numbers `(p1, p2)` such that `p1 + p2 = n`. Each pair in the output should be sorted in ascending order. Implement the function `prime_sum_pairs(n: int) -> List[Tuple[int, int]]` that returns a list of tuples where ea...
from typing import List, Tuple def is_prime(num: int) -> bool: if num < 2: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True def prime_sum_pairs(n: int) -> List[Tuple[int, int]]: primes = [i for i in range(2, n) if is_prime(i)] ...
from solution import prime_sum_pairs def test_prime_sum_pairs(): assert prime_sum_pairs(10) == [(3, 7), (5, 5)] assert prime_sum_pairs(26) == [(3, 23), (7, 19), (13, 13)] assert prime_sum_pairs(4) == [(2, 2)] assert prime_sum_pairs(1) == [] assert prime_sum_pairs(18) == [(5, 13), (7, 11)] asser...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def prime_sum_pairs(n):", "function_name": "prime_sum_pairs", "parameter_list": "(n)" } ]
[ 0, 0, 1, 1, 1, 0, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "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_2
{ "original_instruction": "", "prompt_id": "0000018671", "row_id": 18671, "seed_ids": "[181]" }
0.803485
Algorithm_18671
I
[ "is_prime", "prime_sum_pairs" ]
2
[ [ "prime_sum_pairs", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
12dc9e9b736451be4e45d6c374c6027375bc5ca4
a3d03f2ebea61bd4767cda19c56b30ff06c7b3e0
v1.0
instruct
Algorithm
Algorithm_18676_I
### Coding Assessment Question In this exercise, you will work with sorting algorithms and optimize a given function to efficiently sort a list of integers. Your task is to implement a merge sort algorithm, which is a popular divide and conquer algorithm used for sorting. ### Scenario Your task is to implement the me...
from typing import List def merge_sort(lst: List[int]) -> List[int]: """ Recursively divides the list into halves and merges them in sorted order. """ if len(lst) <= 1: return lst mid = len(lst) // 2 left_half = merge_sort(lst[:mid]) right_half = merge_sort(lst[mid:]) ...
from solution import merge_sort def test_merge_sort_with_positive_numbers(): assert merge_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62] def test_merge_sort_with_mixed_numbers(): assert merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13] def test_merge_sort_with_negative_numbers(): assert ...
[ { "docstring": "Recursively divides the list into halves and merges them in sorted order.", "function_declaration": "def merge_sort(lst):", "function_name": "merge_sort", "parameter_list": "(lst)" }, { "docstring": "Merges two sorted lists into one sorted list.", "function_declaration": ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(lst: List[int]) -> List[int]:\n if len(lst) <= 1:\n return lst\n \n mid = len(lst) // 2\n left_half ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000018676", "row_id": 18676, "seed_ids": "[4100]" }
0.58802
Algorithm_18676
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fee7758c8a58ecb38d126cdcfd5b042c19d1d1b6
08e1643e5f1e53a98cc2b7525fe07631cac13196
v1.0
instruct
Algorithm
Algorithm_18763_I
### Coding Assessment Question #### Problem Statement You are given the task of implementing a function to solve a system of linear equations using both the LU decomposition and the Gauss-Seidel iterative method. Your function should compare the results of these two methods with the built-in NumPy solver to ensure ac...
import numpy as np from scipy.linalg import lu def lu_solve(A: np.ndarray, b: np.ndarray) -> np.ndarray: P, L, U = lu(A) y = np.linalg.solve(L, np.dot(P.T, b)) x = np.linalg.solve(U, y) return x def gauss_seidel_solve(A: np.ndarray, b: np.ndarray, tolerance: float, max_iterations: int) -> np.ndarray: ...
import numpy as np from solution import validate_linear_solvers def test_validate_linear_solvers(): matrices = [ np.array([[4, 1], [2, 3]]), np.array([[10, 2, 3], [2, 10, 4], [3, 4, 6]]) ] vectors = [ np.array([1, 2]), np.array([7, 8, 9]) ] assert validate_linear_s...
[ { "docstring": null, "function_declaration": "def lu_solve(A, b):", "function_name": "lu_solve", "parameter_list": "(A, b)" }, { "docstring": null, "function_declaration": "def gauss_seidel_solve(A, b, tolerance, max_iterations):", "function_name": "gauss_seidel_solve", "paramete...
[ 1, 1, 1, 0, 1, 0, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.linalg import lu\n\ndef lu_solve(A: np.ndarray, b: np.ndarray) -> np.ndarray:\n \"\"\" Solve system of linear equations using L...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000018763", "row_id": 18763, "seed_ids": "[3982]" }
0.451946
Algorithm_18763
I
[ "lu_solve", "gauss_seidel_solve", "validate_linear_solvers" ]
3
[ [ "validate_linear_solvers", "gauss_seidel_solve" ], [ "validate_linear_solvers", "lu_solve" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
5807acec34cff3aa434914ab2eec162eaa2cd275
90e327730d8dc71c46cd8654628eb8ee6ab831cb
v1.0
instruct
Algorithm
Algorithm_18847_I
### Problem Statement: You are tasked with enhancing a basic Genetic Algorithm to solve the Travelling Salesperson Problem (TSP). The aim is to improve its efficacy by introducing new functionalities and optimizations. ### Requirements: 1. **Function to Generate Initial Population:** - Implement a function `gener...
import random import math from typing import List, Tuple # Type aliases for better readability TPos = Tuple[int, int] TCandidate = List[int] def generate_population(cities: List[TPos], population_size: int) -> List[TCandidate]: """Generates an initial population of candidate solutions.""" population = [] ...
import random from solution import generate_population, crossover, mutate, evaluate_fitness, select_parents, enhanced_genetic_algorithm random.seed(42) def test_generate_population(): cities = [(0,0), (1,1), (2,2)] population_size = 5 population = generate_population(cities, population_size) assert le...
[ { "docstring": "Generates an initial population of candidate solutions.", "function_declaration": "def generate_population(cities, population_size):", "function_name": "generate_population", "parameter_list": "(cities, population_size)" }, { "docstring": "Performs crossover between two paren...
[ 0, 0, 0, 1, 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": "import random\nimport math\nfrom typing import List, Tuple\n\nTPos = Tuple[float, float]\nTCandidate = List[int]\n\ndef generate_population(cities: List[TPos], p...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000018847", "row_id": 18847, "seed_ids": "[5123]" }
0.481028
Algorithm_18847
I
[ "generate_population", "crossover", "mutate", "evaluate_fitness", "select_parents", "enhanced_genetic_algorithm" ]
6
[ [ "enhanced_genetic_algorithm", "crossover" ], [ "enhanced_genetic_algorithm", "evaluate_fitness" ], [ "enhanced_genetic_algorithm", "generate_population" ], [ "enhanced_genetic_algorithm", "mutate" ], [ "enhanced_genetic_algorithm", "select_parents" ] ]
5
[]
false
[]
false
pytest
true
[]
true
3d03016268bded7885878e5139905ed411d36343
b6d889c02a769e9125bea8b5590262d7bf7182e1
v1.0
instruct
Algorithm
Algorithm_18867_I
### Coding Assessment Question #### Context Sorting algorithms are fundamental in computer science and have a wide range of applications, from data processing to efficient searching. Understanding and implementing sorting algorithms is crucial for optimizing performance in various computational tasks. #### Task Write...
from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left: List[int], right: List[int]) -> List[int]: so...
from solution import merge_sort def test_merge_sort_basic_cases(): assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] assert merge_sort([8, 3, 7, 4, 2, 6]) == [2, 3, 4, 6, 7, 8] def test_merge_sort_single_element(): assert merge_sort([10]) == [10] def test_merge_sort_empty_list(): assert mer...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000018867", "row_id": 18867, "seed_ids": "[2904]" }
0.609114
Algorithm_18867
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f07c8cf2da75e5cc12a207db37e01207b78fad8e
dfd9942089e33a0dbd334299b8521f6963f4b7fe
v1.0
instruct
Algorithm
Algorithm_18874_I
### Problem Statement Given the concept of palindromic numbers and their interesting properties, your task is to implement two functions that handle palindromic numbers in different scenarios. ### Function 1: is_palindrome Write a function `is_palindrome(num: int) -> bool` that determines whether the given integer is...
def is_palindrome(num: int) -> bool: """ Determines if the given number is a palindrome. Args: - num: An integer (0 ≤ num ≤ 10^6). Returns: - True if num is a palindrome, False otherwise. """ str_num = str(num) return str_num == str_num[::-1] def smallest_palindrome_produc...
from solution import is_palindrome, smallest_palindrome_product def test_is_palindrome_single_digit(): assert is_palindrome(1) == True def test_is_palindrome_multiple_digits(): assert is_palindrome(121) == True assert is_palindrome(123) == False def test_is_palindrome_edge_cases(): assert is_palindro...
[ { "docstring": "Determines if the given number is a palindrome.\n\nArgs:\n- num: An integer (0 ≤ num ≤ 10^6).\n\nReturns:\n- True if num is a palindrome, False otherwise.", "function_declaration": "def is_palindrome(num):", "function_name": "is_palindrome", "parameter_list": "(num)" }, { "do...
[ 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_palindrome(num: int) -> bool:\n \"\"\"\n Determine whether the given integer is a palindrome.\n \n Args:\n num (int): The integer to check....
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000018874", "row_id": 18874, "seed_ids": "[2521]" }
0.760292
Algorithm_18874
I
[ "is_palindrome", "smallest_palindrome_product" ]
2
[ [ "smallest_palindrome_product", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f436d32c877bd78fba7bbf6537abb886863d85c8
4adadb28ca85eb1612a3eff8e3573cc3ead527a6
v1.0
instruct
Algorithm
Algorithm_19097_I
### Pathfinding in a Grid using A* Algorithm #### Overview You have been tasked with developing a part of a navigation system that uses the A* algorithm to find the shortest path in a grid. The grid is represented as a 2D list where each element indicates whether it's a walkable cell (0) or an obstacle (1). The syste...
from typing import List, Tuple, Union import heapq def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int: """ Calculate the Manhattan distance between points a and b. """ return abs(a[0] - b[0]) + abs(a[1] - b[1]) def find_shortest_path(grid: List[List[int]], start: Tuple[int, int], target: Tup...
from solution import find_shortest_path def test_example_case(): grid = [ [0, 0, 0, 0], [1, 1, 0, 1], [0, 0, 0, 0], [0, 1, 1, 0] ] start = (0, 0) target = (3, 3) expected_path = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3), (3, 3)] assert find_shortest_path(gr...
[ { "docstring": "Calculate the Manhattan distance between points a and b.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Finds the shortest path from start to target in a grid using the A* algorithm.", "functio...
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport heapq\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:\n \"\"\"\n Heuristic function for A* algorith...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000019097", "row_id": 19097, "seed_ids": "[4210]" }
0.708409
Algorithm_19097
I
[ "heuristic", "find_shortest_path" ]
2
[ [ "find_shortest_path", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d2cdd5c38d7e5c3810347e81a4dc7718e7e44c92
519b6542d61551c3afe211f4e2ca62e87692b0bc
v1.0
instruct
Algorithm
Algorithm_19143_I
### Problem: Advanced Sorting Algorithms Implementation Your task is to implement advanced sorting algorithms that handle various data structures and ordering requirements efficiently. You'll implement functions for each sorting algorithm and validate their accuracy and performance. #### Task Requirements: 1. **Func...
def sort_quick(arr): """ Quick Sort algorithm implementation. """ if not all(isinstance(x, int) for x in arr): raise TypeError("sort_quick() only accepts lists of integers") if len(arr) < 2: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] m...
def test_sort_quick(): assert sort_quick([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] assert sort_quick([1, 2, 3]) == [1, 2, 3] assert sort_quick([3, 2, 1]) == [1, 2, 3] assert sort_quick([]) == [] assert sort_quick([-1, -10, 5, 3, 0]) == [-10, -1, 0, 3, 5] try: sort_quick([1, 'two'...
[ { "docstring": "Quick Sort algorithm implementation.", "function_declaration": "def sort_quick(arr):", "function_name": "sort_quick", "parameter_list": "(arr)" }, { "docstring": "Merge Sort algorithm implementation.", "function_declaration": "def sort_merge(arr):", "function_name": "...
[ 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def sort_quick(arr):\n if not all(isinstance(x, int) for x in arr):\n raise TypeError(\"sort_quick() only accepts lists of integers\")\n if len(arr)...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019143", "row_id": 19143, "seed_ids": "[3259]" }
0.602192
Algorithm_19143
I
[ "sort_quick", "sort_merge", "sort_heap", "sort_counting", "sort_bucket" ]
5
[ [ "sort_bucket", "sort_quick" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b4066259842f97d8da1eb8664a1771e52ea0faa0
81715733b63cc1e52b3030bcf80c65da0bf7690d
v1.0
instruct
Algorithm
Algorithm_19167_I
### K-Nearest Neighbors (KNN) Classifier Enhancement You are provided with a basic implementation of the K-Nearest Neighbors (KNN) classifier, a fundamental algorithm used in classification tasks. The classifier labels a data point based on the majority vote from its k nearest neighbors. ### Task Enhance the given KN...
import numpy as np from collections import defaultdict from scipy.spatial import distance def calculate_distance(instance1, instance2, metric='euclidean', p=3): if metric == 'euclidean': return np.linalg.norm(instance1 - instance2) elif metric == 'manhattan': return np.sum(np.abs(instance1 - in...
import numpy as np from solution import enhanced_knn_classifier def test_knn_euclidean(): X_train = np.array([[1, 2], [2, 3], [3, 4], [4, 5]]) y_train = np.array([0, 1, 0, 1]) X_test = np.array([[1.5, 2.5]]) k = 2 distance_metric = 'euclidean' num_folds = 2 y_pred, cv_scores = enhanced_knn_...
[]
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom collections import defaultdict\nfrom scipy.spatial import distance\n\ndef calculate_distance(instance1, instance2, metric='euclidean', p...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000019167", "row_id": 19167, "seed_ids": "[3794]" }
0.645959
Algorithm_19167
I
[ "calculate_distance", "knn_predict", "k_fold_cross_validation", "enhanced_knn_classifier" ]
4
[ [ "enhanced_knn_classifier", "k_fold_cross_validation" ], [ "enhanced_knn_classifier", "knn_predict" ], [ "k_fold_cross_validation", "knn_predict" ], [ "knn_predict", "calculate_distance" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
df1f7218fcfdabf279ba79c4d3c06fb90104862f
70d7b544a25ee43e0f7b349f05399332087171a0
v1.0
instruct
Algorithm
Algorithm_19193_I
### Coding Task: Factorial Digit Sum Calculation **Objective**: Implement an algorithm to compute the sum of digits of the factorial of a given number `n`. Additionally, implement a method to check if a given number is equal to the sum of the digits of any factorial of a given `m`. #### Functions to Implement: 1. **`...
import math def factorial_digit_sum(n: int) -> int: """ Returns the sum of the digits of the factorial of n. :param n: Non-negative integer :return: Sum of digits of factorial of n :raises ValueError: If n is negative :raises TypeError: If n is not an integer """ if not isinstance(...
from solution import factorial_digit_sum, is_sum_of_factorial_digits def test_factorial_digit_sum_positive(): assert factorial_digit_sum(5) == 3 # 5! = 120 and 1 + 2 + 0 = 3 def test_factorial_digit_sum_large(): assert factorial_digit_sum(10) == 27 # 10! = 3628800 and 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 def tes...
[ { "docstring": "Returns the sum of the digits of the factorial of n.\n\n:param n: Non-negative integer\n:return: Sum of digits of factorial of n\n:raises ValueError: If n is negative\n:raises TypeError: If n is not an integer", "function_declaration": "def factorial_digit_sum(n):", "function_name": "fac...
[ 1, 0, 1, 0, 0, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef factorial_digit_sum(n: int) -> int:\n \"\"\"\n Returns the sum of the digits of the factorial of n.\n \n :param n: Integer, the nu...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000019193", "row_id": 19193, "seed_ids": "[3559]" }
0.644333
Algorithm_19193
I
[ "factorial_digit_sum", "is_sum_of_factorial_digits" ]
2
[ [ "is_sum_of_factorial_digits", "factorial_digit_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
663b9e40e4e0601382b59483c8fc250dd9d173f0
71e5ae3333d5f930bb6a8d6cba4db400b9c764d2
v1.0
instruct
Algorithm
Algorithm_19225_I
### Scenario You are tasked with developing a system to measure and evaluate the performance of software applications. One of the key metrics is the average response time of a system over a specific period. You have access to predefined functions that fetch system response times. ### Task Create a function that calcul...
from datetime import datetime from typing import List def get_response_times(start: datetime, end: datetime) -> List[float]: """ Mock function to simulate fetching of response times. In an actual implementation, this function would fetch data from a database or monitoring system. """ # Sample ...
from datetime import datetime from solution import average_response_time def test_average_response_time_valid_period_1(): start_time = datetime(2023, 1, 1, 0, 0, 0) end_time = datetime(2023, 1, 1, 23, 59, 59) assert average_response_time(start_time, end_time) == 205.0 def test_average_response_time_valid_...
[ { "docstring": "Mock function to simulate fetching of response times.\nIn an actual implementation, this function would \nfetch data from a database or monitoring system.", "function_declaration": "def get_response_times(start, end):", "function_name": "get_response_times", "parameter_list": "(start...
[ 0, 1, 0, 1, 1, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from datetime import datetime\nfrom typing import List\n\ndef get_response_times(start: datetime, end: datetime) -> List[float]:\n \"\"\"\n Mock function t...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000019225", "row_id": 19225, "seed_ids": "[1963]" }
0.6103
Algorithm_19225
I
[ "get_response_times", "average_response_time" ]
2
[ [ "average_response_time", "get_response_times" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dd602a0ccf98327ed8cb04583a5fb0f5caacf8bf
b90fee4b32b00f683afefd2fa1d37742cfa668ea
v1.0
instruct
Algorithm
Algorithm_19227_I
### Coding Assessment Question As a data analyst at a logistics company, you have been tasked with developing a program to optimize delivery routes for a fleet of delivery vehicles. The program should identify the shortest route that a delivery vehicle can take, from the starting point to the final destination, passin...
import math from itertools import permutations def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def calculate_distance(route, locations): """ Calculate the total travel...
def test_euclidean_distance(): assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5.0) def test_calculate_distance(): locations = [(0, 0), (1, 0), (1, 1), (0, 1)] route = [0, 1, 2, 3] assert math.isclose(calculate_distance(route, locations), 4.0) def test_nearest_neighbor(): locations = [(0, ...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Calculate the total travel distance for the given route.", ...
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom itertools import permutations\n\ndef calculate_distance(locations, route):\n \"\"\"\n Calculate the total travel distance for a given rou...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000019227", "row_id": 19227, "seed_ids": "[2421]" }
0.638143
Algorithm_19227
I
[ "euclidean_distance", "calculate_distance", "nearest_neighbor", "two_opt", "optimize_route" ]
5
[ [ "calculate_distance", "euclidean_distance" ], [ "nearest_neighbor", "euclidean_distance" ], [ "optimize_route", "calculate_distance" ], [ "optimize_route", "nearest_neighbor" ], [ "optimize_route", "two_opt" ], [ "two_opt", "calculate_distance" ...
6
[]
false
[]
false
pytest
false
[]
true
91e8900f071314022abf61def4ed35477b592576
7284998917cab66571b4ab4fbb3f193a621300ed
v1.0
instruct
Algorithm
Algorithm_19270_I
### Question: You are to implement a system that encodes and decodes messages using a simple substitution cipher with a twist based on a given shift value and a coded message. **Objective:** Write two functions, `shift_encode` and `shift_decode`. 1. `shift_encode(plain_text: str, shift: int) -> str`: - Encodes th...
def shift_encode(plain_text: str, shift: int) -> str: def shift_char(c, shift): if 'a' <= c <= 'z': return chr((ord(c) - ord('a') + shift) % 26 + ord('a')) return c return ''.join(shift_char(c, shift) for c in plain_text) def shift_decode(encoded_text: str, shift: int) -> str: ...
from solution import shift_encode, shift_decode def test_shift_encode_basic(): assert shift_encode("abc", 1) == "bcd" assert shift_encode("xyz", 3) == "abc" assert shift_encode("hello, world!", 3) == "khoor, zruog!" def test_shift_decode_basic(): assert shift_decode("bcd", 1) == "abc" assert shift...
[ { "docstring": null, "function_declaration": "def shift_encode(plain_text, shift):", "function_name": "shift_encode", "parameter_list": "(plain_text, shift)" }, { "docstring": null, "function_declaration": "def shift_decode(encoded_text, shift):", "function_name": "shift_decode", ...
[ 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
7
easy
0.778
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def shift_encode(plain_text: str, shift: int) -> str:\n def shift_char(c, shift):\n if c.isalpha():\n return chr((ord(c) - ord('a') + shift)...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019270", "row_id": 19270, "seed_ids": "[435]" }
0.706186
Algorithm_19270
I
[ "shift_encode", "shift_decode" ]
2
[ [ "shift_decode", "shift_encode" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3d95bc7331625a6b8006cb525358097e9580f655
f795007135d4bde5207e07f51ffe1266dfc8193c
v1.0
instruct
Algorithm
Algorithm_19329_I
### Palindrome Partitions with Constraints #### Context: Partitioning a string such that each substring is a palindrome is a common problem. In this variation, you must consider additional constraints on which characters can be used in forming palindrome substrings. This added restriction will test your understanding ...
from typing import List def is_palindrome(s: str) -> bool: """ Helper function to check if a given string is a palindrome. """ return s == s[::-1] def partition_with_constraints(s: str, allowed_chars: List[str]) -> List[List[str]]: """ Returns all possible palindrome partitioning of the string...
from solution import partition_with_constraints def test_partition_with_constraints_example(): s = "aab" allowed_chars = ["a", "b"] expected_output = [["a", "a", "b"], ["aa", "b"]] assert partition_with_constraints(s, allowed_chars) == expected_output def test_partition_with_constraints_empty_string()...
[ { "docstring": "Helper function to check if a given string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Returns all possible palindrome partitioning of the string `s` such that \nonly allowed ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef partition_with_constraints(s: str, allowed_chars: List[str]) -> List[List[str]]:\n if not s or not allowed_chars:\n retu...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000019329", "row_id": 19329, "seed_ids": "[850]" }
0.760424
Algorithm_19329
I
[ "is_palindrome", "partition_with_constraints" ]
2
[ [ "partition_with_constraints", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b2e2b61c0971dec7838d514825e7012746038e19
0f0ba311b43386dce829c262aac850b8fa080b08
v1.0
instruct
Algorithm
Algorithm_19387_I
### Coding Assessment Question #### Network Packet Routing Simulation with Dijkstra's Algorithm As a network engineer, you are tasked with designing a tool to simulate packet routing in a network. The goal is to find the shortest path for a packet to travel from a given source node to a destination node using Dijkstr...
import heapq from typing import List, Tuple, Dict import sys def dijkstra_shortest_path(file_path: str, start: str, end: str) -> Tuple[List[str], int]: graph = build_graph(file_path) # If start or end node does not exist in the graph if start not in graph or end not in graph: return ([], -1) ...
from solution import dijkstra_shortest_path import pytest # Create a helper function to generate test files def create_test_file(file_path, content): with open(file_path, 'w') as f: f.write(content) def setup_module(module): create_test_file('test_network.txt', "A B 5\nA C 10\nB C 2\nB D 4\nC ...
[ { "docstring": null, "function_declaration": "def dijkstra_shortest_path(file_path, start, end):", "function_name": "dijkstra_shortest_path", "parameter_list": "(file_path, start, end)" }, { "docstring": null, "function_declaration": "def build_graph(file_path):", "function_name": "b...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef dijkstra_shortest_path(file_path: str, start: str, end: str) -> Tuple[List[str], int]:\n # Read the graph ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000019387", "row_id": 19387, "seed_ids": "[5347]" }
0.698829
Algorithm_19387
I
[ "dijkstra_shortest_path", "build_graph", "reconstruct_path" ]
3
[ [ "dijkstra_shortest_path", "build_graph" ], [ "dijkstra_shortest_path", "reconstruct_path" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7599a040e095c4efe5f4d50cdca9917631fec1e9
7fe102b9cd914a1717b36913c06485388ab9cdcb
v1.0
instruct
Algorithm
Algorithm_19389_I
**[Question 2]: String Parsing and Analysis** You are tasked with developing a system to parse and analyze customer reviews from an e-commerce platform. This system should extract and normalize critical information, detect sentiment, and summarize review contents. **Objective:** Implement the functions required to p...
import re from typing import List, Dict, Tuple def parse_reviews(raw_reviews: List[str]) -> List[Dict[str, str]]: parsed_reviews = [] for raw_review in raw_reviews: # Split the review by '-' to separate the main body from the username review_parts = raw_review.rsplit(" - ", 1) body_and_...
from solution import parse_reviews, detect_sentiment, summarize_reviews def test_parse_reviews(): raw_reviews = [ "Great product! Totally worth the money. 5 - JohnDoe", "Not what I expected, quite disappointing. 2 - JaneSmith", "It's okay, does the job. 3 - AlexBrown" ] parsed_revie...
[ { "docstring": null, "function_declaration": "def parse_reviews(raw_reviews):", "function_name": "parse_reviews", "parameter_list": "(raw_reviews)" }, { "docstring": null, "function_declaration": "def detect_sentiment(review_text, rating):", "function_name": "detect_sentiment", "...
[ 0, 1, 1, 1, 0, 0, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\nfrom typing import List, Dict\n\ndef parse_reviews(raw_reviews: List[str]) -> List[Dict[str, str]]:\n parsed_reviews = []\n \n for review in ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000019389", "row_id": 19389, "seed_ids": "[4303]" }
0.733698
Algorithm_19389
I
[ "parse_reviews", "detect_sentiment", "summarize_reviews" ]
3
[ [ "summarize_reviews", "detect_sentiment" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e7bd882157a069b90ed35e7ee3f2bce386ff0743
babd2580133163ef20dd2419d1ec25cbe78cd2ab
v1.0
instruct
Algorithm
Algorithm_19423_I
### Question: Efficient Matrix Exponentiation You are given a square matrix represented as a list of lists, with each inner list containing the matrix rows. The matrix size is \(N \times N\). **Objective:** Write a function `matrix_exponentiation(mat: List[List[int]], exp: int) -> List[List[int]]` that computes the e...
from typing import List def matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: """ Multiplies two square matrices A and B. """ N = len(A) C = [[0] * N for _ in range(N)] for i in range(N): for j in range(N): C[i][j] = sum(A[i][k] * B[k][j]...
from solution import matrix_exponentiation def test_matrix_exponentiation(): assert matrix_exponentiation([[1, 1], [1, 0]], 5) == [[8, 5], [5, 3]] assert matrix_exponentiation([[2, 0], [0, 2]], 3) == [[8, 0], [0, 8]] assert matrix_exponentiation([[1, 2], [3, 4]], 2) == [[7, 10], [15, 22]] def test_matrix_...
[ { "docstring": "Multiplies two square matrices A and B.", "function_declaration": "def matrix_multiplication(A, B):", "function_name": "matrix_multiplication", "parameter_list": "(A, B)" }, { "docstring": "Returns an N x N identity matrix.", "function_declaration": "def identity_matrix(N...
[ 0, 1, 0, 1, 0, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two matrices A and B and r...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000019423", "row_id": 19423, "seed_ids": "[3235]" }
0.51585
Algorithm_19423
I
[ "matrix_multiplication", "identity_matrix", "matrix_exponentiation" ]
3
[ [ "matrix_exponentiation", "identity_matrix" ], [ "matrix_exponentiation", "matrix_multiplication" ] ]
2
[]
false
[]
false
pytest
true
[]
true
06322cb07a2e42d263a0eeb15526f6187768ac58
cb96b7b86236c110e780da8e1702baf4d2668fcb
v1.0
instruct
Algorithm
Algorithm_19432_I
### Quicksort with Dual Pivot Partitioning You are required to implement the Quicksort algorithm using a dual pivot partitioning method. This variation of Quicksort uses two pivots and can offer improved performance over the classic single pivot Quicksort. ### Function Signature ```python def dual_pivot_quicksort(arr...
def dual_pivot_quicksort(arr, low, high): if low < high: # partition the array and get the indices of the pivots lp, rp = dual_pivot_partition(arr, low, high) # recursively sort the subarrays dual_pivot_quicksort(arr, low, lp - 1) dual_pivot_quicksort(arr, lp + 1, rp - 1) ...
from solution import dual_pivot_quicksort def test_small_array(): arr = [24, -34, 5, 0, 17, -5, 10, 23] sorted_arr = [-34, -5, 0, 5, 10, 17, 23, 24] assert dual_pivot_quicksort(arr, 0, len(arr) - 1) == sorted_arr def test_large_array(): arr = [34, 7, 23, 32, 5, 62, 32, 7, 5, 32, 23, 7, 34] sorted_...
[ { "docstring": null, "function_declaration": "def dual_pivot_quicksort(arr, low, high):", "function_name": "dual_pivot_quicksort", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def dual_pivot_partition(arr, low, high):", "function_name": "dual_...
[ 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 dual_pivot_quicksort(arr: List[int], low: int, high: int) -> List[int]:\n if low < high:\n # lp is the index of the lowe...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019432", "row_id": 19432, "seed_ids": "[4196]" }
0.602406
Algorithm_19432
I
[ "dual_pivot_quicksort", "dual_pivot_partition" ]
2
[ [ "dual_pivot_quicksort", "dual_pivot_partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e2d56cb1eaf8b0e40d140a8d135e3f4c029df9fd
31ebcf5906b3f338ed430cab83ddb8a594d8d37b
v1.0
instruct
Algorithm
Algorithm_19435_I
### K-nearest Neighbors (KNN) Classifier Implementation **Problem Statement**: Implement a K-nearest Neighbors (KNN) classifier from scratch in Python. Your task is to understand and implement the key functions necessary for the KNN algorithm. Demonstrate your coding proficiency by writing correct, optimized, and test...
import numpy as np def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return np.sqrt(np.sum((np.array(point1) - np.array(point2)) ** 2)) def get_neighbors(X_train, y_train, test_point, k): """ Identify the K-nearest neighbors of a given test da...
import numpy as np from solution import euclidean_distance, get_neighbors, predict_class def test_euclidean_distance(): assert np.isclose(euclidean_distance([1, 2], [4, 6]), 5.0, atol=1e-5) assert np.isclose(euclidean_distance([0, 0], [0, 0]), 0.0, atol=1e-5) assert np.isclose(euclidean_distance([1, 1], [4...
[]
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return np.sq...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000019435", "row_id": 19435, "seed_ids": "[385]" }
0.648668
Algorithm_19435
I
[ "euclidean_distance", "get_neighbors", "predict_class" ]
3
[ [ "get_neighbors", "euclidean_distance" ], [ "predict_class", "get_neighbors" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
99660340319958e6558aa84791286ca9fc5a64b4
00006f18c00b92e75846a92494b40dec54c55b5e
v1.0
instruct
Algorithm
Algorithm_19451_I
### Problem Statement Write a function `is_bst_symmetric()` that determines if a given Binary Search Tree (BST) is symmetric. A symmetric tree is a mirror image of itself around its center. ### Function Signature ```python def is_bst_symmetric(root: TreeNode) -> bool: ``` ### Input 1. `root` (TreeNode): The root n...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_symmetric(left: TreeNode, right: TreeNode) -> bool: if not left and not right: return True if not left or not right: return False return (l...
from solution import TreeNode, is_bst_symmetric def test_empty_tree(): assert is_bst_symmetric(None) == True def test_single_node_tree(): root = TreeNode(1) assert is_bst_symmetric(root) == True def test_symmetric_tree(): root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) ...
[]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_bs...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019451", "row_id": 19451, "seed_ids": "[418]" }
0.66458
Algorithm_19451
I
[ "is_symmetric", "is_bst_symmetric" ]
2
[ [ "is_bst_symmetric", "is_symmetric" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
532c815d8c0dea997e29fb8124fe8167a4c24fe3
d18a7cf4b73ad660041702ddd9a6e046b69e8600
v1.0
instruct
Algorithm
Algorithm_19478_I
### Coding Assessment Question **Scenario**: You are developing a feature for a booking system that tracks the availability of conference rooms. One of the functionalities includes finding available time slots for a given duration. Your team asks you to implement a solution to handle this requirement efficiently. ###...
from typing import List, Tuple def time_to_minutes(time: str) -> int: """Convert HH:MM time format to minutes since midnight.""" hh, mm = map(int, time.split(":")) return hh * 60 + mm def minutes_to_time(minutes: int) -> str: """Convert minutes since midnight to HH:MM time format.""" hh = minutes ...
from solution import find_available_slots def test_find_available_slots_example_1(): assert find_available_slots([("09:00", "09:30"), ("10:00", "10:45"), ("12:00", "12:30")], 30, "08:00", "13:00") == [("08:00", "09:00"), ("09:30", "10:00"), ("10:45", "12:00"), ("12:30", "13:00")] def test_find_available_slots_exa...
[ { "docstring": "Convert HH:MM time format to minutes since midnight.", "function_declaration": "def time_to_minutes(time):", "function_name": "time_to_minutes", "parameter_list": "(time)" }, { "docstring": "Convert minutes since midnight to HH:MM time format.", "function_declaration": "d...
[ 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": "from typing import List, Tuple\n\ndef time_to_minutes(t: str) -> int:\n h, m = map(int, t.split(':'))\n return h * 60 + m\n\ndef minutes_to_time(m: int) ->...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019478", "row_id": 19478, "seed_ids": "[120]" }
0.639987
Algorithm_19478
I
[ "time_to_minutes", "minutes_to_time", "find_available_slots" ]
3
[ [ "find_available_slots", "minutes_to_time" ], [ "find_available_slots", "time_to_minutes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e2c54c017b9dc357ae2cdb65b236b841a488f4ee
a2e4cf0b419f51439f2aeac6174f1b4af2d9d445
v1.0
instruct
Algorithm
Algorithm_19480_I
### Programming Question: Synchronization of Bells In a village, there are several churches, each having a bell that rings at a fixed interval in minutes. The intervals can vary from church to church. The bell in the first church rings every `a` minutes, the bell in the second church rings every `b` minutes, and so on...
from math import gcd from functools import reduce from typing import List def lcm(a: int, b: int) -> int: """ Helper function to calculate least common multiple (LCM) of two numbers. """ return abs(a * b) // gcd(a, b) def lcm_of_list(nums: List[int]) -> int: """ Helper function to calculate th...
from solution import find_sync_time def test_single_bell(): assert find_sync_time([5]) == 5 def test_multiple_bells(): assert find_sync_time([5, 7, 11]) == 385 assert find_sync_time([2, 3, 4]) == 12 assert find_sync_time([6, 8, 12]) == 24 def test_prime_intervals(): assert find_sync_time([3, 5, 7...
[ { "docstring": "Helper function to calculate least common multiple (LCM) of two numbers.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Helper function to calculate the LCM of a list of numbers.", "function_declaration": ...
[ 1, 1, 0, 0, 0, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import gcd\nfrom functools import reduce\nfrom typing import List\n\ndef lcm(x, y):\n return x * y // gcd(x, y)\n\ndef find_sync_time(intervals: Lis...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000019480", "row_id": 19480, "seed_ids": "[2738]" }
0.508074
Algorithm_19480
I
[ "lcm", "lcm_of_list", "find_sync_time" ]
3
[ [ "find_sync_time", "lcm_of_list" ], [ "lcm_of_list", "lcm" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e17aab5b15f5de562215134a226dd7eb0bdd23a3
90c91dee4cd0816cf3ad904b53ba3420849af2c2
v1.0
instruct
Algorithm
Algorithm_19484_I
### Coding Assessment Question #### Scenario & Context You are developing a software for managing a virtual library system. The system tracks the availability of books and allows users to reserve books under certain conditions. Your task is to write a set of functions to handle book reservations, checking book availab...
def check_availability(book_collection, book_title): """ Check if a book is available for reservation. """ if book_title not in book_collection: raise ValueError("Book title not found in collection") return book_collection[book_title] > 0 def reserve_book(book_collection, reserves, user_nam...
import pytest from solution import check_availability, reserve_book, cancel_reservation def test_check_availability(): book_collection = { "The Great Gatsby": 3, "1984": 2, "To Kill a Mockingbird": 0 } assert check_availability(book_collection, "1984") == True assert check_avai...
[ { "docstring": "Check if a book is available for reservation.", "function_declaration": "def check_availability(book_collection, book_title):", "function_name": "check_availability", "parameter_list": "(book_collection, book_title)" }, { "docstring": "Reserve a book for a user if it is avail...
[ 1, 1, 1, 0, 1, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def check_availability(book_collection, book_title):\n \"\"\"\n Checks if the given book is available in the collection.\n \"\"\"\n if book_title not...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000019484", "row_id": 19484, "seed_ids": "[765]" }
0.546586
Algorithm_19484
I
[ "check_availability", "reserve_book", "cancel_reservation" ]
3
[ [ "reserve_book", "check_availability" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a266d9bcfe70215a0a640c4c5b3cc459a89d507b
8e7f5d2671ba97519d1e8ff4f2767f80ae6fb400
v1.0
instruct
Algorithm
Algorithm_19539_I
### Coding Question: Find the Index and Value of the Most Frequent Element Given an array of integers, your task is to implement two functions that return the index and value of the most frequent element and the element that appears the first time in the list if there are multiple elements with the same frequency. 1....
from collections import Counter def index_most_frequent(lst): """ Returns the index and value of the most frequent element in the list. If there are multiple elements with the same frequency, returns the one that appears first. """ counter = Counter(lst) most_common_value, _ = counter.most_comm...
from solution import index_most_frequent, first_occurrence def test_index_most_frequent_single_element(): lst = [7] assert index_most_frequent(lst) == (0, 7) def test_first_occurrence_single_element(): lst = [7] assert first_occurrence(lst) == 0 def test_index_most_frequent_multiple_frequent_elements...
[ { "docstring": "Returns the index and value of the most frequent element in the list.\nIf there are multiple elements with the same frequency, returns the one that appears first.", "function_declaration": "def index_most_frequent(lst):", "function_name": "index_most_frequent", "parameter_list": "(ls...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def index_most_frequent(lst: list[int]) -> tuple[int, int]:\n \"\"\"\n Returns the index and value of the most frequently occurring element in the list.\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000019539", "row_id": 19539, "seed_ids": "[3746]" }
0.653923
Algorithm_19539
I
[ "index_most_frequent", "first_occurrence" ]
2
[ [ "first_occurrence", "index_most_frequent" ] ]
1
[]
false
[]
false
pytest
true
[]
true
81163e66efed5b71da805c37de4dac18a319f9bc
4071e6f97188a30e49f765eb329cf868b99df4d7
v1.0
instruct
Algorithm
Algorithm_19542_I
### Coding Assessment Question #### Context A logistics company wants to optimize the sorting of its delivery routes based on distance. Their current system sorts routes using a basic bubble sort algorithm, which is not efficient for large data sets. They require a more efficient sorting method to improve overall perf...
def merge_sort_routes(routes): """ Sort a list of routes based on distance using the merge sort algorithm. :param routes: List of tuples, where each tuple contains a route name and a distance. :return: List of tuples sorted by the distance in ascending order. """ if len(routes) <= 1: ...
from solution import merge_sort_routes def test_merge_sort_empty_list(): assert merge_sort_routes([]) == [] def test_merge_sort_single_element(): assert merge_sort_routes([("Route X", 45.0)]) == [("Route X", 45.0)] def test_merge_sort_multiple_elements(): routes = [("Route A", 120.5), ("Route B", 85.2), ...
[ { "docstring": "Sort a list of routes based on distance using the merge sort algorithm.\n\n:param routes: List of tuples, where each tuple contains a route name and a distance.\n:return: List of tuples sorted by the distance in ascending order.", "function_declaration": "def merge_sort_routes(routes):", ...
[ 1, 1, 1, 1, 0, 1, 1, 1, 0, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort_routes(routes):\n \"\"\"\n Sorts a list of routes based on distance using merge sort algorithm.\n Each route is represented as a tuple co...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000019542", "row_id": 19542, "seed_ids": "[3045]" }
0.554819
Algorithm_19542
I
[ "merge_sort_routes", "merge" ]
2
[ [ "merge_sort_routes", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a2dc4a35a3356e1aa07f1d1829d4f564500e1d7
b26f1ddf1dfaf7aadc757a4a3424562452b59116
v1.0
instruct
Algorithm
Algorithm_19714_I
### String Permutation Checker #### Context Permutation checking is a common problem in computer science, where you need to determine if one string is a rearrangement of another string. This problem has applications in areas such as anagram detection, cryptography, and data processing. You are required to implement f...
def normalize_string(s): """ Converts the input string to lowercase and removes all whitespace. Args: s (str): The input string to be normalized. Returns: str: The normalized string. """ return ''.join(s.split()).lower() def are_permutations(s1, s2): """ Checks if two ...
def test_normalize_string(): assert normalize_string(" LisTen ") == "listen" assert normalize_string("Tri Angle ") == "triangle" assert normalize_string("Wh!te Sp@ce") == "wh!tesp@ce" assert normalize_string(" ") == "" assert normalize_string("ABC123!@#") == "abc123!@#" def test_are_permutations...
[ { "docstring": "Converts the input string to lowercase and removes all whitespace.\n\nArgs:\ns (str): The input string to be normalized.\n\nReturns:\nstr: The normalized string.", "function_declaration": "def normalize_string(s):", "function_name": "normalize_string", "parameter_list": "(s)" }, ...
[ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def normalize_string(s):\n \"\"\"\n Normalizes the string by removing all whitespace and converting to lowercase.\n \"\"\"\n return ''.join(s.split()...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019714", "row_id": 19714, "seed_ids": "[1136]" }
0.708065
Algorithm_19714
I
[ "normalize_string", "are_permutations" ]
2
[ [ "are_permutations", "normalize_string" ] ]
1
[]
false
[]
false
pytest
false
[]
true
f45a4248fd73fe37f0a2125eeffa65b970476a65
7feccd20c60283e2de09ab541f3bb9bd34971564
v1.0
instruct
Algorithm
Algorithm_19808_I
### Coding Challenge: Substring Palindrome Count #### Problem Statement Given a text file containing a list of strings, your task is to compute the total number of palindromic substrings present in each string. A palindromic substring is one that reads the same forward and backward. You need to write a function `count...
def count_palindromic_substrings(s: str) -> int: n = len(s) count = 0 # A 2D array to store the palindromic status of substrings dp = [[False] * n for _ in range(n)] for i in range(n): dp[i][i] = True count += 1 for length in range(2, n+1): for i in range(n...
import pytest from solution import count_palindromic_substrings, compute_palindromic_substrings def test_count_palindromic_substrings(): assert count_palindromic_substrings("abba") == 6 assert count_palindromic_substrings("racecar") == 10 assert count_palindromic_substrings("abc") == 3 assert count_pal...
[ { "docstring": null, "function_declaration": "def count_palindromic_substrings(s):", "function_name": "count_palindromic_substrings", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def compute_palindromic_substrings(filename):", "function_name": "compute_pal...
[ 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": "def count_palindromic_substrings(s: str) -> int:\n \"\"\"\n Returns the total number of palindromic substrings in the given string.\n \"\"\"\n n = s....
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019808", "row_id": 19808, "seed_ids": "[2805]" }
0.765512
Algorithm_19808
I
[ "count_palindromic_substrings", "compute_palindromic_substrings" ]
2
[ [ "compute_palindromic_substrings", "count_palindromic_substrings" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fc51d1b90251f9e91929060634e990cacf8548cd
d4794ef006d92fc42105d115f4a8b0b09fc59245
v1.0
instruct
Algorithm
Algorithm_19890_I
### Subset Sum Problem using Dynamic Programming **Context**: You are asked to solve an instance of the Subset Sum Problem using Dynamic Programming. The Subset Sum Problem is a classic problem in computer science where the objective is to determine whether there is a subset of the given set with a sum equal to a give...
def initialize_dp_table(n, target): """ Initializes the DP table for subset sum problem. Parameters: - n: Number of items in the nums array - target: The target sum Returns: - DP table as a list of lists (2D table), where dp[i][j] is True if a subset with sum j can be achieve...
from solution import initialize_dp_table, fill_dp_table, subset_reconstruction, subset_sum def test_initialize_dp_table(): dp = initialize_dp_table(3, 5) assert len(dp) == 4 # Should have 4 rows (0 to 3) assert len(dp[0]) == 6 # Should have 6 columns (0 to 5) assert all(dp[i][0] for i in range(4)) #...
[ { "docstring": "Initializes the DP table for subset sum problem.\n\nParameters:\n- n: Number of items in the nums array\n- target: The target sum\n\nReturns:\n- DP table as a list of lists (2D table), where dp[i][j] is True if a subset\n with sum j can be achieved using the first i items.", "function_decla...
[ 1, 0, 0, 1, 1, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def initialize_dp_table(n: int, target: int) -> list[list[bool]]:\n \"\"\"\n Initializes a 2D DP table with dimensions (n+1) x (target+1)\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000019890", "row_id": 19890, "seed_ids": "[5321]" }
0.594289
Algorithm_19890
I
[ "initialize_dp_table", "fill_dp_table", "subset_reconstruction", "subset_sum" ]
4
[ [ "subset_sum", "fill_dp_table" ], [ "subset_sum", "initialize_dp_table" ], [ "subset_sum", "subset_reconstruction" ] ]
3
[]
false
[]
false
pytest
true
[]
true
c36169466c2565025eda64ee8d4a22b5069773c8
b614ea83ae40214a5c7627d606cf8ee175d6ea72
v1.0
instruct
Algorithm
Algorithm_19951_I
### Question Style - Carefully examine the format and presentation of the given questions. - Maintain a consistent tone and language used in the original set. ### Question Length - Ensure your new question is of comparable length to the existing ones. - If the original questions vary in length, aim for the average len...
from PIL import Image, ImageDraw import math def draw_branch(draw, x1, y1, angle, length, depth, branch_angle): """ Recursive function to draw branches of the fractal tree. """ if depth == 0: return # Calculate the end point of the branch x2 = x1 + int(math.cos(math.radians(angle)) * le...
from solution import generate_fractal_tree from PIL import Image def test_generate_fractal_tree_basic(): img = generate_fractal_tree(800, 600, 100, 30, 10) assert isinstance(img, Image.Image) assert img.size == (800, 600) def test_generate_fractal_tree_depth_0(): img = generate_fractal_tree(800, 600, ...
[ { "docstring": "Recursive function to draw branches of the fractal tree.", "function_declaration": "def draw_branch(draw, x1, y1, angle, length, depth, branch_angle):", "function_name": "draw_branch", "parameter_list": "(draw, x1, y1, angle, length, depth, branch_angle)" }, { "docstring": "G...
[ 0, 1, 0, 1, 1, 1, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from PIL import Image, ImageDraw\nimport math\n\ndef draw_branch(draw, x, y, length, angle, depth, branch_angle):\n if depth == 0:\n return\n\n # Ca...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000019951", "row_id": 19951, "seed_ids": "[4342]" }
0.397145
Algorithm_19951
I
[ "draw_branch", "generate_fractal_tree" ]
2
[ [ "generate_fractal_tree", "draw_branch" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
1af912cb8b116e284630be18910eefb835cf22de
0868117f4607b5f76e25cf756d5d110eeee52f07
v1.0
instruct
Algorithm
Algorithm_20012_I
### Coding Challenge: Implementing a Sorting Algorithm You have been provided a partially implemented function to sort a list of integers using the Merge Sort algorithm. Your task is to complete the implementation to ensure the function sorts the list correctly. ### Task **Function to Implement:** ```python def merg...
def merge_sort(arr): """ Given a list of integers `arr`, returns a new list that contains all the elements, sorted in non-decreasing order. Parameters: arr (list): The list of integers to be sorted. Returns: list: A new list containing all the elements from `arr` in sorted order. """ ...
from solution import merge_sort def test_merge_sort_with_unsorted_list(): assert merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] def test_merge_sort_with_unsorted_list_two(): assert merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13] def test_merge_sort_with_empty_li...
[ { "docstring": "Given a list of integers `arr`, returns a new list that contains all the elements,\nsorted in non-decreasing order.\n\nParameters:\narr (list): The list of integers to be sorted.\n\nReturns:\nlist: A new list containing all the elements from `arr` in sorted order.", "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 merge_sort(arr):\n \"\"\"\n Given a list of integers `arr`, returns a new list that contains all the elements,\n sorted in non-decreasing order.\n\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020012", "row_id": 20012, "seed_ids": "[1579]" }
0.625826
Algorithm_20012
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1b1901f2f02bec2187f97e3280a687db187d3f23
f372f708fb539a2e9993a3048b51d7c627b2cbf0
v1.0
instruct
Algorithm
Algorithm_20025_I
### Problem: Count Unique Substrings Given a string \( s \), implement a function to calculate the number of unique substrings of \( s \). Use a suffix array and a longest common prefix (LCP) array for an efficient solution. **Input Format** - A single input line containing the string \( s \) (1 ≤ |s| ≤ 10^5), consis...
def suffix_array_construction(s): n = len(s) suffixes = sorted((s[i:], i) for i in range(n)) suffix_arr = [suffix[1] for suffix in suffixes] return suffix_arr def lcp_array(s, suffix_arr): n = len(s) rank = [0] * n lcp = [0] * n for i, suffix in enumerate(suffix_arr): rank[...
from solution import count_unique_substrings def test_count_unique_substrings_example(): assert count_unique_substrings("abcab") == 12 def test_count_unique_substrings_single_char(): assert count_unique_substrings("a") == 1 def test_count_unique_substrings_all_unique(): assert count_unique_substrings("ab...
[ { "docstring": null, "function_declaration": "def suffix_array_construction(s):", "function_name": "suffix_array_construction", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def lcp_array(s, suffix_arr):", "function_name": "lcp_array", "parameter_list":...
[ 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": "def suffix_array_construction(s):\n n = len(s)\n suffixes = sorted((s[i:], i) for i in range(n))\n suffix_array = [suffix[1] for suffix in suffixes]\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000020025", "row_id": 20025, "seed_ids": "[3267]" }
0.74144
Algorithm_20025
I
[ "suffix_array_construction", "lcp_array", "count_unique_substrings" ]
3
[ [ "count_unique_substrings", "lcp_array" ], [ "count_unique_substrings", "suffix_array_construction" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bbbf3a154cd150d3520f7b63ffe83a49cba56810
5a08837bc49952b34abeab2d9d9ac1e538862689
v1.0
instruct
Algorithm
Algorithm_20032_I
### Problem Description: You need to implement a function `sum_of_squares_of_primes` which takes a list of integers as an input. The function should filter out prime numbers from the list, compute the square of each prime, and then return the sum of these squares. ### Input/Output: - **Input**: - A list of integers...
from math import isqrt def is_prime(number): """ Checks if a number is prime. :param number: int :return: bool """ if number <= 1: return False if number == 2: return True if number % 2 == 0: return False for i in range(3, isqrt(number) + 1, 2): ...
import pytest from solution import sum_of_squares_of_primes, is_prime def test_is_prime(): assert not is_prime(1) assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(17) def test_empty_list(): assert sum_of_squares_of_p...
[ { "docstring": "Checks if a number is prime.\n\n:param number: int\n:return: bool", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Takes a list of integers and returns the sum of squares of prime numbers in the li...
[ 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \n :param n: int - The number to check.\n :return: bool - True if n is a prime ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000020032", "row_id": 20032, "seed_ids": "[3754]" }
0.712963
Algorithm_20032
I
[ "is_prime", "sum_of_squares_of_primes" ]
2
[ [ "sum_of_squares_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ffc34d021e2db8c53c33ce327eeb20b36f4c2524
2eb2ae7cdebe0b6e65501e47f6e9a9e7b4c1f0ae
v1.0
instruct
Algorithm
Algorithm_20045_I
### K-Means Clustering on Customer Spending Data **Context**: Given a dataset containing customer spending data in a mall, your task is to implement the K-Means clustering algorithm to identify patterns in customer spending behavior. The dataset contains several features such as Customer ID, Age, Annual Income, and Sp...
import numpy as np import matplotlib.pyplot as plt import requests import pandas as pd from io import StringIO def collect_dataset(url): response = requests.get(url, timeout=10) df = pd.read_csv(StringIO(response.text)) dataset = df.values return dataset def normalize_features(dataset): """Normali...
import numpy as np from solution import * def test_normalize_features(): dataset = np.array([ [1, 19, 15, 39], [2, 21, 15, 81], [3, 20, 16, 6], [4, 23, 16, 77], [5, 31, 17, 40] ]) normalized_data = normalize_features(dataset) expected_mean = 15.8 expected_std...
[ { "docstring": null, "function_declaration": "def collect_dataset(url):", "function_name": "collect_dataset", "parameter_list": "(url)" }, { "docstring": "Normalize features of the dataset.", "function_declaration": "def normalize_features(dataset):", "function_name": "normalize_feat...
[ 0, 0, 1, 0, 1, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport requests\n\ndef collect_dataset(url):\n \"\"\"Download dataset from a URL and convert it into a Nu...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000020045", "row_id": 20045, "seed_ids": "[786]" }
0.768701
Algorithm_20045
I
[ "collect_dataset", "normalize_features", "initialize_centroids", "compute_distances", "assign_clusters", "update_centroids", "kmeans_clustering", "visualize_clusters", "main" ]
9
[ [ "kmeans_clustering", "assign_clusters" ], [ "kmeans_clustering", "compute_distances" ], [ "kmeans_clustering", "initialize_centroids" ], [ "kmeans_clustering", "update_centroids" ] ]
4
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "requests" ]
false
8f7ed54ca0ff724417663a8a12dabc083c58604a
5810f1cac26d08f0cf5868647c2e55569ed0aca3
v1.0
instruct
Algorithm
Algorithm_20061_I
### Problem: Implement a Merge Sort Algorithm You need to implement the Merge Sort algorithm, a widely used algorithm with `O(n log n)` time complexity for sorting an array. #### Function Signature ```python def merge_sort(arr: List[int]) -> List[int]: pass ``` ### Description Given: - `arr`: A list of integers ...
from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left: List[int], right: List[int]) -> List[int]: so...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_list(): assert...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n def merge(left: List[int], right: List[...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020061", "row_id": 20061, "seed_ids": "[3709]" }
0.633441
Algorithm_20061
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
56762c57f813e62552d324f3d624b43f89fdf32f
4ecaade1c2631324dfaa3fda0043b147fcbee9cb
v1.0
instruct
Algorithm
Algorithm_20125_I
### Problem Statement Write a function `analyze_github_contributors` that evaluates and summarizes the contributions of users to a specific GitHub repository. The function will accept the repository name, the owner of the repository, and other optional parameters to customize the analysis. The function should: 1. Fetc...
import requests from cachetools import TTLCache, cached from typing import List, Dict, Any # Cache to store results to avoid redundant API calls cache = TTLCache(maxsize=100, ttl=600) @cached(cache) def fetch_contributors(repo_owner: str, repo_name: str, page: int = 1) -> List[Dict[str, Any]]: """ Fetch contr...
import pytest import requests from unittest.mock import patch from solution import analyze_github_contributors, fetch_contributors # Mock data for testing mock_contributors = [ {"login": "user1", "contributions": 20}, {"login": "user2", "contributions": 15}, {"login": "user3", "contributions": 5} ] def mo...
[ { "docstring": "Fetch contributors from GitHub API for a given page.\n\nParameters:\n - repo_owner (str): The owner of the repository.\n - repo_name (str): The name of the repository.\n - page (int): Pagination page number.\n\nReturns:\n - List of contributor dictionaries.", "function_declaration": "def...
[ 0, 1, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nimport time\nfrom requests.exceptions import HTTPError\n\nCACHE = {}\n\ndef fetch_contributors(repo_owner, repo_name, page=1, per_page=100):\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000020125", "row_id": 20125, "seed_ids": "[2347]" }
0.667564
Algorithm_20125
I
[ "fetch_contributors", "analyze_github_contributors" ]
2
[ [ "analyze_github_contributors", "fetch_contributors" ] ]
1
[]
false
[]
false
pytest
true
[ "cachetools", "requests" ]
false
4e86d4803457070357fb303593c681a3ba9d3af0
139b3c0fa923f540cbb4d17b76142c78805212ab
v1.0
instruct
Algorithm
Algorithm_20137_I
### K-Means Clustering Implementation #### Context You are working as a data analyst for a retail company. Your task is to segment customers into distinct groups based on their purchasing behavior. You decide to use K-Means Clustering to identify clusters of customers with similar behavior. #### Objective Implement a...
import numpy as np import matplotlib.pyplot as plt def initialize_centroids(X, k): """ Randomly initialize the centroids by selecting k unique points from X. """ m = X.shape[0] indices = np.random.choice(m, k, replace=False) centroids = X[indices] return centroids def compute_distances(X, ...
import numpy as np import pytest from solution import k_means_clustering def test_k_means_clustering_basic(): X = np.array([[1, 2], [3, 4], [1, 0], [5, 2], [6, 4], [4, 1], [7, 3], [8, 0]]) k = 2 max_iterations = 100 plot = False labels = k_means_clustering(X, k, max_iterations, plot) asser...
[ { "docstring": "Randomly initialize the centroids by selecting k unique points from X.", "function_declaration": "def initialize_centroids(X, k):", "function_name": "initialize_centroids", "parameter_list": "(X, k)" }, { "docstring": "Compute the distance of each point in X to each centroid....
[ 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef k_means_clustering(X: np.ndarray, k: int, max_iterations: int, plot: bool) -> np.ndarray:\n m, n = ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020137", "row_id": 20137, "seed_ids": "[503]" }
0.765156
Algorithm_20137
I
[ "initialize_centroids", "compute_distances", "assign_clusters", "compute_centroids", "k_means_clustering" ]
5
[ [ "k_means_clustering", "assign_clusters" ], [ "k_means_clustering", "compute_centroids" ], [ "k_means_clustering", "compute_distances" ], [ "k_means_clustering", "initialize_centroids" ] ]
4
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
c25c02819056f91aeddb12b117508ca632389306
a019871a7dcf591b9e24a7579c577a5ecbc376fe
v1.0
instruct
Algorithm
Algorithm_20160_I
### Heap Sort Implementation Challenge **Scenario**: You have been recruited as a software engineer by a tech company that requires efficient data organization solutions. One of your first tasks is to develop a reliable sorting algorithm for their system. Given the need for efficiency and scalability, you decide to im...
def heapify(arr, n, i): """ Helper function to maintain the heap property of a subtree rooted at index i. n is the size of the heap. """ largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists...
from solution import heap_sort def test_heap_sort_with_positive_numbers(): assert heap_sort([5, 3, 8, 4, 2]) == [2, 3, 4, 5, 8] def test_heap_sort_with_negative_numbers(): assert heap_sort([-1, -3, -2, -5, -4]) == [-5, -4, -3, -2, -1] def test_heap_sort_with_mixed_numbers(): assert heap_sort([3, -1, 0, -...
[ { "docstring": "Helper function to maintain the heap property of a subtree rooted at index i.\nn is the size of the heap.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Sorts a collection of integers in asce...
[ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def heap_sort(collection: list[int]) -> list[int]:\n \"\"\"\n Sorts a list of integers in ascending order using the Heap Sort algorithm.\n \"\"\"\n \...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000020160", "row_id": 20160, "seed_ids": "[979]" }
0.692454
Algorithm_20160
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
875ae2b9f7780dfac3abb50e9e47d14914332a97
e8b9b55bf30fc26ce67f130c31b30801ffce7d2f
v1.0
instruct
Algorithm
Algorithm_20165_I
### **Meeting Scheduler** ### Problem Statement: You are required to build a meeting scheduler that checks if a proposed meeting time conflicts with any existing meetings. Your application will receive a list of existing meetings and a proposed new meeting time. Each meeting is defined by a start and end time, and no ...
from typing import List, Tuple def check_meeting_conflict(existing_meetings: List[Tuple[int, int]], new_meeting: Tuple[int, int]) -> bool: """ Checks if a new meeting conflicts with any existing meetings. :param existing_meetings: List of tuples where each tuple represents an existing meeting's start ...
from solution import check_meeting_conflict, add_meeting def test_check_meeting_conflict_no_conflict(): existing_meetings = [(900, 1030), (1300, 1430), (1600, 1730)] new_meeting = (1100, 1200) assert check_meeting_conflict(existing_meetings, new_meeting) == False def test_check_meeting_conflict_with_confl...
[ { "docstring": "Checks if a new meeting conflicts with any existing meetings.\n\n:param existing_meetings: List of tuples where each tuple represents an existing meeting's start and end time.\n:param new_meeting: A tuple representing the new meeting's start and end time.\n:return: Boolean value indicating wheth...
[ 1, 1, 1, 0, 0, 0, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef check_meeting_conflict(existing_meetings: List[Tuple[int, int]], new_meeting: Tuple[int, int]) -> bool:\n new_start, new...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020165", "row_id": 20165, "seed_ids": "[1915]" }
0.662824
Algorithm_20165
I
[ "check_meeting_conflict", "add_meeting" ]
2
[ [ "add_meeting", "check_meeting_conflict" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7403618ae8c6cf8f1566808073ef6c334f9ad43e
f0a7cc44991712cc4a201678703faa6fa0fc9754
v1.0
instruct
Algorithm
Algorithm_20166_I
### Description: You are provided with a function `filter_even_numbers` and `filter_odd_numbers` which filter out even and odd numbers from a list, respectively, returning a new list containing only the filtered numbers. Your task is to implement a combined method that utilizes both filters based on a specified filter ...
def filter_even_numbers(nums: list[int]) -> list[int]: return [num for num in nums if num % 2 == 0] def filter_odd_numbers(nums: list[int]) -> list[int]: return [num for num in nums if num % 2 != 0] def filter_numbers(nums: list[int], filter_type: str) -> list[int]: if filter_type == "even": retur...
from solution import filter_even_numbers, filter_odd_numbers, filter_numbers def test_filter_even_numbers(): assert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6] assert filter_even_numbers([1, 3, 5]) == [] assert filter_even_numbers([2, 4, 6]) == [2, 4, 6] assert filter_even_numbers([]) == [] d...
[ { "docstring": null, "function_declaration": "def filter_even_numbers(nums):", "function_name": "filter_even_numbers", "parameter_list": "(nums)" }, { "docstring": null, "function_declaration": "def filter_odd_numbers(nums):", "function_name": "filter_odd_numbers", "parameter_lis...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def filter_even_numbers(nums: list[int]) -> list[int]:\n return [num for num in nums if num % 2 == 0]\n\ndef filter_odd_numbers(nums: list[int]) -> list[int]:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020166", "row_id": 20166, "seed_ids": "[3164]" }
0.75121
Algorithm_20166
I
[ "filter_even_numbers", "filter_odd_numbers", "filter_numbers" ]
3
[ [ "filter_numbers", "filter_even_numbers" ], [ "filter_numbers", "filter_odd_numbers" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7ea6e003dd156cecc211e72b890f697349df801b
a62286e5f0d0ffd149f3f618c21c803bd44b2bad
v1.0
instruct
Algorithm
Algorithm_20212_I
### Scenario A logistics company is developing a system to help its customers track the location of delivery trucks in real-time. Each truck reports its location using GPS coordinates (latitude and longitude), and customers can query the system to find the nearest truck to a specific location. The goal is to implement ...
from typing import List, Tuple, Optional import math def euclidean_distance(coord1: Tuple[float, float], coord2: Tuple[float, float]) -> float: """ Calculate the Euclidean distance between two GPS coordinates. """ return math.sqrt((coord1[0] - coord2[0]) ** 2 + (coord1[1] - coord2[1]) ** 2) def find_n...
from solution import find_nearest_truck def test_find_nearest_truck_with_multiple_trucks(): trucks = [(34.052235, -118.243683), (36.778259, -119.417931), (37.774929, -122.419416)] location = (34.052235, -118.243683) assert find_nearest_truck(trucks, location) == (34.052235, -118.243683) def test_find_near...
[ { "docstring": "Calculate the Euclidean distance between two GPS coordinates.", "function_declaration": "def euclidean_distance(coord1, coord2):", "function_name": "euclidean_distance", "parameter_list": "(coord1, coord2)" }, { "docstring": "Find the nearest truck to the given location.", ...
[ 1, 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple, Optional\nimport math\n\ndef calculate_distance(loc1: Tuple[float, float], loc2: Tuple[float, float]) -> float:\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020212", "row_id": 20212, "seed_ids": "[1161]" }
0.645753
Algorithm_20212
I
[ "euclidean_distance", "find_nearest_truck" ]
2
[ [ "find_nearest_truck", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
70ddc2a9e0b67d4b151b386aeaff3b0ab2f4262e
f668274bb11e31e5efa66640fb5f9eafcf458636
v1.0
instruct
Algorithm
Algorithm_20232_I
### Question: Implement an Efficient Version of QuickSelect The QuickSelect algorithm is used to find the k-th smallest element in an unordered list. Although effective, its performance can be improved by optimizing the partitioning step and mitigating poor pivot choices. #### Requirements: 1. **Input**: - A list...
import random def partition(arr, low, high): pivot_index = random.randint(low, high) pivot = arr[pivot_index] arr[pivot_index], arr[high] = arr[high], arr[pivot_index] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] ...
from solution import efficient_quickselect def test_quickselect_example_cases(): assert efficient_quickselect([3, 1, 5, 2, 4], 3) == 3 assert efficient_quickselect([10, 4, 5, 8, 6, 11, 26], 5) == 10 assert efficient_quickselect([2, 6, 10, 15], 1) == 2 assert efficient_quickselect([2, 6, 10, 15], 5) == ...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quickselect(arr, low, high, k):", "function_name": "quickselect", "parameter_list...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def efficient_quickselect(arr: list, k: int) -> int:\n \"\"\"\n Efficient QuickSelect implementation.\n\n :param arr: Unordered input list\n :param k...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020232", "row_id": 20232, "seed_ids": "[912]" }
0.510026
Algorithm_20232
I
[ "partition", "quickselect", "efficient_quickselect" ]
3
[ [ "efficient_quickselect", "quickselect" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1415a4bcb8214fd8c2012a75bc5e4f7b1f3ec750
4c7ff0d42e91c82ec665da515c884f2ac8284ad3
v1.0
instruct
Algorithm
Algorithm_20289_I
### Coding Assessment Question **Scenario**: Algorithms often rely on certain mathematical properties or operations to solve problems efficiently. One such commonly used operation is determining the greatest common divisor (GCD) of two numbers, which finds the largest number that divides both numbers without leaving a...
from typing import List from functools import reduce import math def gcd(a: int, b: int) -> int: """ Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm. """ while b: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """ Returns the least commo...
from solution import gcd, lcm, gcd_of_list, lcm_of_list def test_gcd(): assert gcd(48, 18) == 6 assert gcd(0, 18) == 18 assert gcd(48, 0) == 48 assert gcd(0, 0) == 0 assert gcd(7, 1) == 1 assert gcd(20, 5) == 5 def test_lcm(): assert lcm(4, 5) == 20 assert lcm(0, 5) == 0 assert lcm...
[ { "docstring": "Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of a and b using the relationship betw...
[ 1, 1, 0, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nfrom functools import reduce\nimport math\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000020289", "row_id": 20289, "seed_ids": "[5319]" }
0.707263
Algorithm_20289
I
[ "gcd", "lcm", "gcd_of_list", "lcm_of_list" ]
4
[ [ "gcd_of_list", "gcd" ], [ "lcm", "gcd" ], [ "lcm_of_list", "lcm" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d99a4542869271fc110dc75d7fcd8dbbbe02b2f9
0a6643d500522a1ab24fdf10fe723baf577a6920
v1.0
instruct
Algorithm
Algorithm_20394_I
### Basic Statistical Functions Package You are tasked with implementing a small package that provides basic statistical functions. Your package should include functions for computing the mean, median, and standard deviation of a list of numbers. Ensure your implementations are efficient and handle edge cases appropri...
def mean(values): """ Computes the mean (average) of a list of numbers. :param values: List of numerical values :return: Mean of the values or None for an empty list """ if not values: return None return sum(values) / len(values) def median(values): """ Computes the med...
from solution import mean, median, std_dev def test_mean(): assert mean([2, 5, 1, 3, 4]) == 3.0 assert mean([]) == None assert mean([5]) == 5.0 assert mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5 def test_median(): assert median([2, 5, 1, 3, 4]) == 3.0 assert median([]) == None assert medi...
[ { "docstring": "Computes the mean (average) of a list of numbers.\n\n:param values: List of numerical values\n:return: Mean of the values or None for an empty list", "function_declaration": "def mean(values):", "function_name": "mean", "parameter_list": "(values)" }, { "docstring": "Computes...
[ 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef mean(values):\n \"\"\"\n Computes the average of the provided list of numbers.\n Returns None if the list is empty.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000020394", "row_id": 20394, "seed_ids": "[451]" }
0.74107
Algorithm_20394
I
[ "mean", "median", "std_dev" ]
3
[ [ "std_dev", "mean" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f67f608d4688a5d610f424ae87c4135cbf061a6e
e4192bdb1677583dacbec72e851c2bbef259d6df
v1.0
instruct
Algorithm
Algorithm_20439_I
### Question: Image Processing - Grayscale Filter As an engineer working on an image editing application, your task is to create a set of functions to apply a grayscale filter to a given color image. The objective is to convert the color image into its grayscale representation by properly averaging the color intensity...
def average_grayscale(red, green, blue): """ Calculate the average grayscale value of a pixel given its red, green, and blue intensity values. Args: red (int): Red intensity value (0-255). green (int): Green intensity value (0-255). blue (int): Blue intensity value (0-255). Returns...
import pytest from solution import average_grayscale, apply_grayscale_filter def test_average_grayscale_valid_values(): assert average_grayscale(100, 150, 200) == 150 assert average_grayscale(255, 0, 0) == 85 assert average_grayscale(0, 255, 0) == 85 assert average_grayscale(0, 0, 255) == 85 assert...
[ { "docstring": "Calculate the average grayscale value of a pixel given its red, green, and blue intensity values.\n\nArgs:\nred (int): Red intensity value (0-255).\ngreen (int): Green intensity value (0-255).\nblue (int): Blue intensity value (0-255).\n\nReturns:\nint: The grayscale value.\n\nRaises:\nValueErro...
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def average_grayscale(red, green, blue):\n \"\"\"\n Calculate the grayscale value by averaging the red, green, and blue values.\n \"\"\"\n if not (0 ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020439", "row_id": 20439, "seed_ids": "[2337]" }
0.621708
Algorithm_20439
I
[ "average_grayscale", "apply_grayscale_filter" ]
2
[ [ "apply_grayscale_filter", "average_grayscale" ] ]
1
[]
false
[]
false
pytest
true
[]
true
469ff8350bbe356db6ba75b20525f89e4067e3f5
ecea000dbb8d429e61d5a68e68b976f09fd7b3b5
v1.0
instruct
Algorithm
Algorithm_20464_I
### Memory Management: Simulate Garbage Collection in a Simple Language You are designing a basic simulator for a toy programming language that includes a fundamental garbage collection mechanism based on reference counting. Your task is to implement the core components of this simulator. #### Scenario: In this toy l...
def assign_reference(objects: dict, references: dict, var_name: str, obj_id: int) -> None: """ Assign a new reference to a variable. Parameters: objects (dict): Dictionary of object IDs to objects. references (dict): Dictionary of variable names to object IDs. var_name (str): Variable name ...
from solution import assign_reference, release_reference, garbage_collect def test_assign_reference(): objects = {1: {"data": "data1"}, 2: {"data": "data2"}} references = {} assign_reference(objects, references, 'a', 1) assert references == {'a': 1} assert objects[1]['__refcount__'] == 1 def test_...
[ { "docstring": "Assign a new reference to a variable.\n\nParameters:\nobjects (dict): Dictionary of object IDs to objects.\nreferences (dict): Dictionary of variable names to object IDs.\nvar_name (str): Variable name to assign a new reference.\nobj_id (int): Object ID to be referenced.\n\nReturns:\nNone", ...
[ 1, 1, 0, 0, 1, 1, 1, 0, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def assign_reference(objects: dict, references: dict, var_name: str, obj_id: int) -> None:\n # If var_name already has an assigned object, decrease the refere...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000020464", "row_id": 20464, "seed_ids": "[2282]" }
0.371538
Algorithm_20464
I
[ "assign_reference", "release_reference", "garbage_collect" ]
3
[ [ "assign_reference", "release_reference" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7d9b8b9d1fd08abc3fbfa18ac2ac08b5d6010dc7
e15115ec357d86447a1aef2d9627744541b209e9
v1.0
instruct
Algorithm
Algorithm_20582_I
### Coding Assessment Question #### Context Having efficient algorithms is crucial in computer science. One of the most common tasks is sorting an array. Now, it's time to implement one of the famous sorting algorithms - the Merge Sort. Your goal is to practice implementing the algorithm and ensure its correctness. #...
from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left: List[int], right: List[int]) -> List[int]: ...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_already_sorted(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted(): assert m...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020582", "row_id": 20582, "seed_ids": "[3225]" }
0.683717
Algorithm_20582
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4425f5b464d08f7031317259da1963b0c94e533c
f91ce4a1469d33c6b24ed5a644bc0fafdbe452e2
v1.0
instruct
Algorithm
Algorithm_20651_I
### Coding Question A balanced binary search tree (BST) is a type of binary tree where the left subtree contains only nodes with keys less than the node's key, and the right subtree contains only nodes with keys greater than the node's key. Additionally, the tree is balanced to minimize the height difference between s...
class TreeNode: def __init__(self, key: int): self.key = key self.left = None self.right = None self.height = 1 # New TreeNode is at height 1 (leaf) def get_height(node): return node.height if node else 0 def update_height(node): if node: node.height = 1 + max(get_...
from solution import TreeNode, insert_into_bst, calculate_tree_height, trace_heights_after_inserts def test_insert_into_bst(): root = None root = insert_into_bst(root, 10) assert root.key == 10 root = insert_into_bst(root, 20) assert root.right.key == 20 root = insert_into_bst(root, 5) asse...
[]
[ 1, 1, 0, 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": "class TreeNode:\n def __init__(self, key: int):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1 # Heigh...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000020651", "row_id": 20651, "seed_ids": "[4049]" }
0.643298
Algorithm_20651
I
[ "get_height", "update_height", "get_balance", "left_rotate", "right_rotate", "insert_into_bst", "calculate_tree_height", "trace_heights_after_inserts" ]
8
[ [ "get_balance", "get_height" ], [ "insert_into_bst", "get_balance" ], [ "insert_into_bst", "left_rotate" ], [ "insert_into_bst", "right_rotate" ], [ "insert_into_bst", "update_height" ], [ "left_rotate", "update_height" ], [ "right_rotate"...
10
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
a3378f08696616de64c5f674fa839937f40fe1c6
a72f0e5faf3fa5f2805c209ff28feab003ba874b
v1.0
instruct
Algorithm
Algorithm_20718_I
### Problem Statement You are tasked with implementing a function that sorts a list of integers using the Merge Sort algorithm. Merge Sort is a divide-and-conquer algorithm that divides the input list into two halves, recursively sorts them, and then merges the sorted halves to produce the final sorted list. ### Func...
from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left: List[int], right: List[int]) -> List[int]...
def test_merge_sort(): # Test with both positive and negative integers assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] assert merge_sort([-1, -5, 3, 0, 2, 1]) == [-5, -1, 0, 1, 2, 3] # Test with an empty list ...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 0, 0, 1, 0, 0, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n \"\"\"\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000020718", "row_id": 20718, "seed_ids": "[4361]" }
0.606764
Algorithm_20718
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
false
[]
true
424e866366da5cdad65fb0ff04e09510cc79651c
860d5aadd306c23008bf3a4b1c9c417d57ce03ec