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_28079_I
### Prime Gap Finder **Context**: A prime gap is the difference between two successive prime numbers. The problem of finding large prime gaps has applications in number theory and cryptography. In this exercise, you will implement a function to find the first pair of consecutive primes within a specified range `[start...
def sieve_of_eratosthenes(start: int, end: int) -> list: sieve = [True] * end sieve[0] = sieve[1] = False for i in range(2, int(end**0.5) + 1): if sieve[i]: for j in range(i * i, end, i): sieve[j] = False primes = [i for i in range(start, end) if...
def test_sieve_basic(): assert sieve_of_eratosthenes(2, 10) == [2, 3, 5, 7] def test_sieve_no_primes(): assert sieve_of_eratosthenes(14, 16) == [] def test_largest_gap_in_small_range(): assert find_largest_gap_prime_pair(10, 30) == (23, 29) def test_no_prime_pair(): assert find_largest_gap_prime_pair...
[ { "docstring": null, "function_declaration": "def sieve_of_eratosthenes(start, end):", "function_name": "sieve_of_eratosthenes", "parameter_list": "(start, end)" }, { "docstring": null, "function_declaration": "def find_largest_gap_prime_pair(start, end):", "function_name": "find_lar...
[ 0, 0, 0, 0, 0, 0, 0, 1, 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 sieve_of_eratosthenes(start: int, end: int) -> list:\n if start >= end:\n return []\n \n sieve = [True] * end\n sieve[0] = sieve[1] = Fals...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028079", "row_id": 28079, "seed_ids": "[3866]" }
0.629457
Algorithm_28079
I
[ "sieve_of_eratosthenes", "find_largest_gap_prime_pair" ]
2
[ [ "find_largest_gap_prime_pair", "sieve_of_eratosthenes" ] ]
1
[]
false
[]
false
pytest
false
[]
true
81dab000cd10adc75fb57e9c6f3fa262294ac385
585725f063d2d3c3cf7f4965a6c632bdfd2bbab4
v1.0
instruct
Algorithm
Algorithm_28114_I
### Coding Challenge: Simulate a Simple Blockchain Transaction **Context**: Blockchain technology employs a decentralized ledger to record transactions. One of the key aspects of blockchain is the immutability and consistency it provides. In this task, you are required to simulate a simple blockchain transaction syste...
import hashlib from typing import List, Tuple, Dict def hash_block(block: Dict) -> str: block_string = f"{block['sender']}{block['receiver']}{block['amount']}{block['previous_hash']}" return hashlib.sha256(block_string.encode()).hexdigest() def add_to_blockchain(transactions: List[Tuple[str, str, int]]) -> Li...
from solution import add_to_blockchain, hash_block def test_hash_block(): block = { "sender": "Alice", "receiver": "Bob", "amount": 50, "previous_hash": "0" } assert hash_block(block) == hashlib.sha256("AliceBob500".encode()).hexdigest() def test_add_to_blockchain_empty(): ...
[ { "docstring": null, "function_declaration": "def hash_block(block):", "function_name": "hash_block", "parameter_list": "(block)" }, { "docstring": null, "function_declaration": "def add_to_blockchain(transactions):", "function_name": "add_to_blockchain", "parameter_list": "(tran...
[ 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": "import hashlib\n\ndef hash_block(block: dict) -> str:\n block_string = f\"{block['sender']}{block['receiver']}{block['amount']}{block['previous_hash']}\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028114", "row_id": 28114, "seed_ids": "[2260]" }
0.49749
Algorithm_28114
I
[ "hash_block", "add_to_blockchain" ]
2
[ [ "add_to_blockchain", "hash_block" ] ]
1
[]
false
[]
false
pytest
true
[]
true
205aa3e458e3722f9a372cb6c55a0ee2bbec19b7
db65f15276f995ec87eb25e8520c2171189dfc56
v1.0
instruct
Algorithm
Algorithm_28139_I
### Coding Assessment Question You are provided with a basic implementation of a sorting algorithm. Your task is to extend this by implementing a hybrid sorting algorithm that combines the strengths of both Merge Sort and Insertion Sort for improved performance, particularly on nearly sorted datasets. ### Requirement...
from typing import List def insertion_sort(arr: List[int], left: int, right: int) -> None: """ Perform insertion sort on the subarray arr[left:right+1] """ for i in range(left + 1, right + 1): key = arr[i] j = i - 1 while j >= left and arr[j] > key: arr[j + 1] = arr[...
def test_hybrid_sort_case_1(): assert hybrid_sort([38, 27, 43, 3, 9, 82, 10], 5) == [3, 9, 10, 27, 38, 43, 82] def test_hybrid_sort_case_2(): assert hybrid_sort([1, 2, 3, 5, 4, 7, 6], 3) == [1, 2, 3, 4, 5, 6, 7] def test_hybrid_sort_single_element(): assert hybrid_sort([1], 2) == [1] def test_hybrid_sort...
[ { "docstring": "Perform insertion sort on the subarray arr[left:right+1]", "function_declaration": "def insertion_sort(arr, left, right):", "function_name": "insertion_sort", "parameter_list": "(arr, left, right)" }, { "docstring": "Merge two sorted subarrays arr[left:mid+1] and arr[mid+1:ri...
[ 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\n\ndef insertion_sort(arr: List[int], left: int, right: int) -> None:\n for i in range(left + 1, right + 1):\n key = arr[i]\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028139", "row_id": 28139, "seed_ids": "[4394]" }
0.588438
Algorithm_28139
I
[ "insertion_sort", "merge", "hybrid_sort_recursive", "hybrid_sort" ]
4
[ [ "hybrid_sort", "hybrid_sort_recursive" ], [ "hybrid_sort_recursive", "insertion_sort" ], [ "hybrid_sort_recursive", "merge" ] ]
3
[]
false
[]
false
pytest
false
[]
true
55f3faad2d878f031a110d04fc5d0305191167e8
a54b90f2dcad76ca7477f0106b4d9f14c5edfe97
v1.0
instruct
Algorithm
Algorithm_28156_I
### Scenario: You are developing a logistics tracking system for a delivery company. The company needs to determine the optimal sequence of stops for a delivery route in order to minimize travel time. The input consists of a list of delivery locations specified by their coordinates. You need to compute the shortest pos...
import itertools import math def calculate_distance(point1, point2): """ Helper function to calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def find_shortest_route(coords): """ Find the shortest route that visit...
from solution import find_shortest_route def test_no_coords(): assert find_shortest_route([]) == 0.0 def test_single_coord(): assert find_shortest_route([(0, 0)]) == 0.0 def test_two_coords(): assert find_shortest_route([(0, 0), (1, 1)]) == 2 * math.sqrt(2) def test_square_coords(): assert find_shor...
[ { "docstring": "Helper function to calculate the Euclidean distance between two points.", "function_declaration": "def calculate_distance(point1, point2):", "function_name": "calculate_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Find the shortest route that visits each...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import itertools\nimport math\n\ndef calculate_distance(p1, p2):\n \"\"\"\n Calculates the Euclidean distance between two points p1 and p2.\n \"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000028156", "row_id": 28156, "seed_ids": "[4919]" }
0.62405
Algorithm_28156
I
[ "calculate_distance", "find_shortest_route" ]
2
[ [ "find_shortest_route", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a28426a28971a2654b6cfff1cfd1417d6fafff8
16eb7fa6905fcbb2edadd51b6bf2906b925a3886
v1.0
instruct
Algorithm
Algorithm_28183_I
## Questions for Coding Assessment ### Context In the realm of quantum computing, the Quantum Fourier Transform (QFT) is a pivotal algorithm similar to the classical discrete Fourier Transform (DFT). It is extensively employed in quantum algorithms, including Shor's algorithm for integer factorization, and quantum p...
import math def miller_rabin_test(d, n): """ Perform the Miller-Rabin test on the number n. :param d: The odd part of n-1 (i.e., n-1 = 2^r * d). :param n: The number to be tested for primality. :return: False if n is composite, True otherwise. """ import random a = 2 + (random.rand...
from solution import is_prime def test_simple_primes(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(5) == True assert is_prime(7) == True def test_composite_numbers(): assert is_prime(4) == False assert is_prime(6) == False assert is_prime(8) == False assert i...
[ { "docstring": "Perform the Miller-Rabin test on the number n.\n:param d: The odd part of n-1 (i.e., n-1 = 2^r * d).\n:param n: The number to be tested for primality.\n:return: False if n is composite, True otherwise.", "function_declaration": "def miller_rabin_test(d, n):", "function_name": "miller_rab...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom qiskit import Aer, QuantumCircuit, execute\n\ndef quantum_fourier_transform(number_of_qubits: int) -> dict:\n \"\"\"\n Constructs ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000028183", "row_id": 28183, "seed_ids": "[3725]" }
0.460766
Algorithm_28183
I
[ "miller_rabin_test", "is_prime" ]
2
[ [ "is_prime", "miller_rabin_test" ] ]
1
[]
false
[]
false
pytest
true
[]
true
239bbac7069ba59df5f198e3a24ccee563f19504
c148b136f677eb51c6e31bc339596347e152bd5b
v1.0
instruct
Algorithm
Algorithm_28201_I
### File Compression and Decompression Implementation Develop a basic compression and decompression tool using the Run-Length Encoding (RLE) algorithm in Python. The tool will include functions to compress and decompress text, and handle file operations for reading and writing. ### Requirements: 1. **Compression Fun...
def compress(text: str) -> str: """ Compresses a given string using Run-Length Encoding (RLE). """ if not text: return "" compressed_text = [] current_char = text[0] count = 0 for char in text: if char == current_char: count += 1 else: ...
from solution import compress, decompress, compress_file, decompress_file import os def test_compress(): assert compress("aaaabbbcc") == "a4b3c2" assert compress("aabbcc") == "a2b2c2" assert compress("") == "" assert compress("abcd") == "a1b1c1d1" assert compress("aaaa") == "a4" def test_decompres...
[ { "docstring": "Compresses a given string using Run-Length Encoding (RLE).", "function_declaration": "def compress(text):", "function_name": "compress", "parameter_list": "(text)" }, { "docstring": "Decompresses a given RLE-compressed string back to its original form.", "function_declara...
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def compress(text: str) -> str:\n \"\"\"\n Compresses a given string using Run-Length Encoding (RLE).\n \"\"\"\n if not text:\n return \"\"\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000028201", "row_id": 28201, "seed_ids": "[308]" }
0.627584
Algorithm_28201
I
[ "compress", "decompress", "compress_file", "decompress_file" ]
4
[ [ "compress_file", "compress" ], [ "decompress_file", "decompress" ] ]
2
[]
false
[]
false
pytest
true
[]
true
43fa90f36bfc05bba38c7dea332d5536897ecd18
7fb6231fb285e611ef90af9a3430989f7162e545
v1.0
instruct
Algorithm
Algorithm_28222_I
### Question You have been tasked with developing a feature for a text-based game that involves traversing a grid. The player can move up, down, left, or right, and you need to validate and execute their moves. Implement a function `is_valid_move` to verify whether a move is valid given the current position and the gr...
def is_valid_move(grid, current_position, direction): """ Checks if the move is valid within the grid boundaries. Parameters: grid (list of lists): The game map. current_position (tuple): The current position of the player (row, col). direction (str): The move direction ("UP", "DOWN", "LEFT...
import pytest from solution import is_valid_move, move_player def test_is_valid_move(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] assert is_valid_move(grid, (1, 1), "UP") == True assert is_valid_move(grid, (0, 1), "UP") == False assert is_valid_move(grid, (2, 2), "DOWN...
[ { "docstring": "Checks if the move is valid within the grid boundaries.\n\nParameters:\ngrid (list of lists): The game map.\ncurrent_position (tuple): The current position of the player (row, col).\ndirection (str): The move direction (\"UP\", \"DOWN\", \"LEFT\", \"RIGHT\").\n\nReturns:\nbool: True if the move ...
[ 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_valid_move(grid, current_position, direction):\n \"\"\"\n Checks if the move is valid within the grid boundaries.\n \n Args:\n grid: list o...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000028222", "row_id": 28222, "seed_ids": "[341]" }
0.711806
Algorithm_28222
I
[ "is_valid_move", "move_player" ]
2
[ [ "move_player", "is_valid_move" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c40805a1be647073d720765c3624c52fcc9b7f46
5493243944d95bc1ec20c9852687cc7c1e3ceddf
v1.0
instruct
Algorithm
Algorithm_28245_I
### Sentiment Analysis Using Transformer-Based Models #### Context You are provided with a dataset containing text reviews and their corresponding sentiment labels. Your task is to use this data to train a transformer-based model (e.g., BERT) to classify the sentiments of the reviews. This problem will test your under...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, f1_score from transformers import BertTokenizer, BertForSequenceClassification, AdamW from torch.utils.data import DataLoader, Dataset import torch import torch.nn.functional as F cla...
from solution import transformer_sentiment_analysis import pandas as pd def test_transformer_sentiment_analysis(): # Create a sample CSV file sample_data = { 'text': ["Great product!", "Terrible service.", "Satisfied", "Not happy", "Awesome!", "Bad experience.", "I love it", "I hate it."], 'lab...
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, f1_score\nfrom transfo...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000028245", "row_id": 28245, "seed_ids": "[512]" }
0.651455
Algorithm_28245
I
[ "create_data_loader", "train_epoch", "eval_model", "get_predictions", "transformer_sentiment_analysis" ]
5
[ [ "transformer_sentiment_analysis", "create_data_loader" ], [ "transformer_sentiment_analysis", "get_predictions" ], [ "transformer_sentiment_analysis", "train_epoch" ] ]
3
[]
false
[ "ReviewsDataset" ]
true
pytest
true
[ "numpy", "pandas", "sklearn", "torch", "transformers" ]
false
892c36d99094e20b12a077bfa1d894caa9d2b96e
315936b93fe8db9cdb0ad156bbfdc0207a06f196
v1.0
instruct
Algorithm
Algorithm_28339_I
### Fibonacci Prime Detection ### Background The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. An interesting problem emerges when you try to identify which of these Fibonacci numbers are prime. ### Task You are required to implemen...
from typing import List def is_prime(num: int) -> bool: if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 retur...
from solution import prime_fibonacci def test_prime_fibonacci_up_to_50(): assert prime_fibonacci(50) == [2, 3, 5, 13] def test_prime_fibonacci_up_to_100(): assert prime_fibonacci(100) == [2, 3, 5, 13, 89] def test_prime_fibonacci_up_to_0(): assert prime_fibonacci(0) == [] def test_prime_fibonacci_up_to_...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def prime_fibonacci(limit):", "function_name": "prime_fibonacci", "parameter_list": "(limit)" } ]
[ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000028339", "row_id": 28339, "seed_ids": "[2496]" }
0.84102
Algorithm_28339
I
[ "is_prime", "prime_fibonacci" ]
2
[ [ "prime_fibonacci", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c2ed8d6c3abeaf1ff714f38a913349bcd6dd5d11
5edc712a7a8b6007ab3a3725baf00c40bd230f66
v1.0
instruct
Algorithm
Algorithm_28409_I
### QuickSort Algorithm Implementation Implement the QuickSort algorithm to sort a list of integers in ascending order. The QuickSort algorithm should use the last element as the pivot and follow these steps: 1. **Partitioning**: Rearrange the elements in the array such that all elements less than the pivot are posit...
from typing import List def partition(arr: List[int], low: int, high: int) -> int: """ This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot. ...
def test_quicksort_empty(): assert quicksort([]) == [] def test_quicksort_single_element(): assert quicksort([1]) == [1] def test_quicksort_sorted_list(): assert quicksort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_quicksort_reverse_sorted_list(): assert quicksort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5...
[ { "docstring": "This function takes last element as pivot, places the pivot element at its correct\nposition in sorted array, and places all smaller (smaller than pivot) to left of\npivot and all greater elements to right of pivot.", "function_declaration": "def partition(arr, low, high):", "function_na...
[ 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef partition(arr: List[int], low: int, high: int) -> int:\n \"\"\"\n This function takes the last element as pivot, places the ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000028409", "row_id": 28409, "seed_ids": "[5085]" }
0.667242
Algorithm_28409
I
[ "partition", "quicksort_helper", "quicksort" ]
3
[ [ "quicksort", "quicksort_helper" ], [ "quicksort_helper", "partition" ] ]
2
[]
false
[]
false
pytest
false
[]
true
1c5466f8bdeeeb0e501d80cd9a51c945c9c898c8
81a7534f510e0134cb6d19b89f8f045bbfb99f35
v1.0
instruct
Algorithm
Algorithm_28420_I
## Problem Statement You are given two non-negative integers `x` and `y`. Your task is to implement a function that calculates the greatest common divisor (GCD) of these two numbers using the Euclidean algorithm. Additionally, implement a function that calculates the least common multiple (LCM) of the two numbers using...
def gcd(x: int, y: int) -> int: """ Calculate the Greatest Common Divisor (GCD) of two non-negative integers using the Euclidean algorithm. """ while y: x, y = y, x % y return x def lcm(x: int, y: int) -> int: """ Calculate the Least Common Multiple (LCM) of two non-negative integer...
from solution import gcd, lcm def test_gcd(): assert gcd(8, 12) == 4 assert gcd(54, 24) == 6 assert gcd(101, 10) == 1 assert gcd(0, 5) == 5 assert gcd(10, 0) == 10 assert gcd(0, 0) == 0 assert gcd(9, 9) == 9 def test_lcm(): assert lcm(8, 12) == 24 assert lcm(54, 24) == 216 asse...
[ { "docstring": "Calculate the Greatest Common Divisor (GCD) of two non-negative integers using the Euclidean algorithm.", "function_declaration": "def gcd(x, y):", "function_name": "gcd", "parameter_list": "(x, y)" }, { "docstring": "Calculate the Least Common Multiple (LCM) of two non-negat...
[ 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 gcd(x: int, y: int) -> int:\n \"\"\"\n Calculate the Greatest Common Divisor (GCD) of two non-negative integers using the Euclidean algorithm.\n \"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028420", "row_id": 28420, "seed_ids": "[3596]" }
0.773635
Algorithm_28420
I
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
610d70089f53255cd94c11a7c41a77e3065b086c
793424c1d1b971828736f47cb44b530dd2d7f7ed
v1.0
instruct
Algorithm
Algorithm_28467_I
### Coding Assessment Question You are given a list of student records, where each record contains the student ID and a list of their scores across multiple subjects. Your task is to calculate the average score for each student and then rank the students based on their average scores, with ties broken by their student...
def calculate_average(scores): return sum(scores) / len(scores) def rank_students_by_average(student_records): # Calculate average scores student_averages = [ (student_id, round(calculate_average(scores), 2)) for student_id, scores in student_records ] # Sort by average score d...
from solution import rank_students_by_average def test_rank_students_basic(): student_records = [ (101, [75, 80, 85]), (102, [90, 85, 80]), (103, [80, 70, 80]), (104, [65, 70, 60]) ] assert rank_students_by_average(student_records) == ([(102, 85.0), (101, 80.0), (103, 76.67)...
[ { "docstring": null, "function_declaration": "def calculate_average(scores):", "function_name": "calculate_average", "parameter_list": "(scores)" }, { "docstring": null, "function_declaration": "def rank_students_by_average(student_records):", "function_name": "rank_students_by_avera...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rank_students_by_average(student_records):\n \"\"\"\n This function ranks students based on their average scores.\n\n Parameters:\n student_r...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000028467", "row_id": 28467, "seed_ids": "[4034]" }
0.649248
Algorithm_28467
I
[ "calculate_average", "rank_students_by_average" ]
2
[ [ "rank_students_by_average", "calculate_average" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2353ed90d4ff4c0b9aa8843361dc46acbc1c6e60
ca3d9d9b7f8b4da90aff52c526704d068a437625
v1.0
instruct
Algorithm
Algorithm_28470_I
### Problem Statement You are given a string containing lowercase characters and a dictionary of words. Your task is to implement the function `form_words(string: str, word_dict: List[str]) -> List[str]` that identifies all the words from the given dictionary that can be formed using the characters in the input string...
from collections import Counter from typing import List def can_form_word(string_counter, word): word_counter = Counter(word) for char, count in word_counter.items(): if string_counter[char] < count: return False return True def form_words(string: str, word_dict: List[str]) -> List[str...
from solution import form_words def test_form_words_example1(): string = "abppplee" word_dict = ["apple", "pear", "plea", "banana"] assert sorted(form_words(string, word_dict)) == sorted(["apple", "plea"]) def test_form_words_example2(): string = "eerekc" word_dict = ["tree", "treehouse", "reek", ...
[ { "docstring": null, "function_declaration": "def can_form_word(string_counter, word):", "function_name": "can_form_word", "parameter_list": "(string_counter, word)" }, { "docstring": null, "function_declaration": "def form_words(string, word_dict):", "function_name": "form_words", ...
[ 0, 1, 1, 0, 0, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import Counter\nfrom typing import List\n\ndef form_words(string: str, word_dict: List[str]) -> List[str]:\n \"\"\"\n Identifies all words...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000028470", "row_id": 28470, "seed_ids": "[4432]" }
0.740297
Algorithm_28470
I
[ "can_form_word", "form_words" ]
2
[ [ "form_words", "can_form_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dfe78a252fc2a4594d8a8eb0f182bbdceb865a94
c77be332ff668a303fb064fdd6e48cae88f54027
v1.0
instruct
Algorithm
Algorithm_28481_I
### Coding Assessment Question #### Context: Bob is a big fan of number series and loves to find out interesting properties about them. He came across a special type of series called a "cumulative prime sum series". In this series, each element is the sum of all prime numbers up to and including that position. Your ta...
from typing import List def is_prime(num: int) -> bool: if num <= 1: return False if num == 2: return True if num % 2 == 0: return False p = 3 while p * p <= num: if num % p == 0: return False p += 2 return True def generate_primes(limit: int...
from solution import cumulative_prime_sum def test_cumulative_prime_sum_1(): assert cumulative_prime_sum(1) == [2] def test_cumulative_prime_sum_3(): assert cumulative_prime_sum(3) == [2, 5, 10] def test_cumulative_prime_sum_5(): assert cumulative_prime_sum(5) == [2, 5, 10, 17, 28] def test_cumulative_p...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def generate_primes(limit):", "function_name": "generate_primes", "parameter_list": "(limit)" }, { "d...
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num < 2:\n return False\n f...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000028481", "row_id": 28481, "seed_ids": "[1067]" }
0.702055
Algorithm_28481
I
[ "is_prime", "generate_primes", "cumulative_prime_sum" ]
3
[ [ "cumulative_prime_sum", "generate_primes" ], [ "generate_primes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f297c66892cd3236fc8d7dd8b72a21d513716367
0c5935435e54c7685c33bc118178d844279bedc2
v1.0
instruct
Algorithm
Algorithm_28485_I
### Heap Sort Implementation Write a function `heap_sort(arr: List[int]) -> List[int]` that sorts an array of integers using the Heap Sort algorithm. The function should modify the input list in place and return it sorted in ascending order. #### Function Signature: ```python def heap_sort(arr: List[int]) -> List[int...
from typing import List def heapify(arr: List[int], n: int, i: int): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[i] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i], arr[largest] = a...
from solution import heap_sort def test_heap_sort_basic(): assert heap_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_heap_sort_sorted(): assert heap_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_heap_sort_reversed(): assert heap_sort([5, 4, 3, 2, 1]) == [1, 2, ...
[ { "docstring": null, "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": null, "function_declaration": "def heap_sort(arr):", "function_name": "heap_sort", "parameter_list": "(arr)" } ]
[ 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 heap_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Performs heap sort on the given list in place and returns it sorted in as...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028485", "row_id": 28485, "seed_ids": "[288]" }
0.690219
Algorithm_28485
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e0ed7ad43d4b016b3737853892adcf15a593d8a7
ceab8b942633a3d2538efd9889cfb63001de0378
v1.0
instruct
Algorithm
Algorithm_28525_I
### Maximum Subarray Sum using Divide and Conquer You are required to find the maximum sum of any contiguous subarray within a given list of integers using the Divide and Conquer approach. This problem is a classic example that can be solved efficiently by dividing the array into smaller subarrays and then combining t...
def max_crossing_sum(arr, left, mid, right): """ Helper function to find the maximum possible sum in arr[] such that the sum includes elements on the left of mid and elements on the right of mid """ # Include elements on left of mid sm = 0 left_sum = float('-inf') for i in range(mid, lef...
from solution import max_subarray_sum def test_single_element(): assert max_subarray_sum([1]) == 1 assert max_subarray_sum([-1]) == -1 def test_all_negative(): assert max_subarray_sum([-2, -3, -4, -1, -2, -1, -5, -3]) == -1 def test_mixed_elements(): assert max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) =...
[ { "docstring": "Helper function to find the maximum possible sum in arr[] such that\nthe sum includes elements on the left of mid and elements on the right of mid", "function_declaration": "def max_crossing_sum(arr, left, mid, right):", "function_name": "max_crossing_sum", "parameter_list": "(arr, l...
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def max_crossing_sum(arr, left, mid, right):\n # Include elements on left of mid.\n sm = 0\n left_sum = float('-inf')\n for i in range(mid, left - 1,...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028525", "row_id": 28525, "seed_ids": "[1132]" }
0.71244
Algorithm_28525
I
[ "max_crossing_sum", "max_subarray_sum_util", "max_subarray_sum" ]
3
[ [ "max_subarray_sum", "max_subarray_sum_util" ], [ "max_subarray_sum_util", "max_crossing_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1852cda2049e84735491f083589a29625ff2980a
2f5d76d6bbaa67206954fd5bce387eb578f77655
v1.0
instruct
Algorithm
Algorithm_28564_I
### Question: K-Nearest Neighbors Implementation In this task, you will implement a K-Nearest Neighbors (KNN) classifier from scratch. The KNN algorithm is a simple, yet powerful, classification method used in various applications, such as pattern recognition and data mining. #### Objectives: 1. Implement the follow...
import numpy as np from collections import Counter def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float: """ Calculates the Euclidean distance between two points in n-dimensional space. """ if point1.shape != point2.shape: raise ValueError("Both points must have the same dime...
import pytest import numpy as np from solution import euclidean_distance, k_neighbors, predict def test_euclidean_distance(): point1 = np.array([1, 2]) point2 = np.array([4, 6]) assert np.isclose(euclidean_distance(point1, point2), 5.0) point1 = np.array([1, 2, 3]) point2 = np.array([4, 5, 6])...
[ { "docstring": "Calculates the Euclidean distance between two points in n-dimensional space.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Finds the k-nearest neighbors for a...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float:\n \"\"\"\n Calculates the E...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000028564", "row_id": 28564, "seed_ids": "[498]" }
0.682418
Algorithm_28564
I
[ "euclidean_distance", "k_neighbors", "predict" ]
3
[ [ "k_neighbors", "euclidean_distance" ], [ "predict", "k_neighbors" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
d8b08ed423b6f87596570ad80bffdc9ddf26ee59
cd6f36669b10998d768b75b795f81eaecb072a17
v1.0
instruct
Algorithm
Algorithm_28593_I
### Huffman Encoding Huffman coding is a method of lossless data compression based on the frequency of occurrence of each data item. Your task is to implement the Huffman encoding algorithm to compress a given text file. #### Input Format: 1. A path to the input text file containing the text to be compressed. 2. A pa...
import heapq import os import pickle class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_frequency_table(text): frequency = {} f...
import os import pickle from solution import compress, HuffmanNode def read_compressed_file(path): with open(path, 'rb') as file: return pickle.load(file) def test_huffman_encoding(tmp_path): test_input = "this is an example for huffman encoding" input_file = tmp_path / "input.txt" output_file...
[]
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict, Counter\nimport struct\nimport os\n\nclass Node:\n def __init__(self, char=None, freq=None):\n self....
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000028593", "row_id": 28593, "seed_ids": "[4348]" }
0.582296
Algorithm_28593
I
[ "build_frequency_table", "build_huffman_tree", "build_huffman_codes", "compress" ]
4
[ [ "compress", "build_frequency_table" ], [ "compress", "build_huffman_codes" ], [ "compress", "build_huffman_tree" ] ]
3
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
3b4256994bec76d4919fa333b0352e3d50683eab
86c6d4bd02e527f2eeb0c63d3539d7656717a11e
v1.0
instruct
Algorithm
Algorithm_28609_I
### Merge Sort with Custom Comparator #### Objective: Implement a merge sort function that allows for a custom comparator function to be passed in, enabling the sort order to be specified (e.g., ascending, descending). #### Problem Statement: Write a function `merge_sort_custom(collection: list, comparator: Callable[...
from typing import Callable, Any, List def merge_sort_custom(collection: List[Any], comparator: Callable[[Any, Any], bool]) -> List[Any]: if len(collection) <= 1: return collection mid = len(collection) // 2 left = merge_sort_custom(collection[:mid], comparator) right = merge_sort_custom(colle...
from solution import merge_sort_custom def ascending(a, b): return a < b def descending(a, b): return a > b def test_merge_sort_custom_empty(): assert merge_sort_custom([], ascending) == [] def test_merge_sort_custom_single_element(): assert merge_sort_custom([1], ascending) == [1] def test_merge_s...
[ { "docstring": null, "function_declaration": "def merge_sort_custom(collection, comparator):", "function_name": "merge_sort_custom", "parameter_list": "(collection, comparator)" }, { "docstring": null, "function_declaration": "def merge(left, right, comparator):", "function_name": "m...
[ 1, 0, 1, 1, 1, 0, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import Callable, Any\n\ndef merge_sort_custom(collection: list, comparator: Callable[[Any, Any], bool]) -> list:\n if len(collection) <= 1:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028609", "row_id": 28609, "seed_ids": "[1381]" }
0.566248
Algorithm_28609
I
[ "merge_sort_custom", "merge" ]
2
[ [ "merge_sort_custom", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
815db77a7caa4d97b165197101f6a799e964c33b
4ad10901752c1642f326827fa07bb4358ffb9350
v1.0
instruct
Algorithm
Algorithm_28682_I
### Coding Assessment Question #### Problem Statement: Write a Python function that takes a list of integers and returns a new list that contains only the prime numbers from the original list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. #### Functional Requ...
from typing import List def is_prime(n: int) -> bool: """Returns True if n is a prime number, else False.""" if n <= 1: return False if n == 2: return True if n % 2 == 0: return False max_divisor = int(n**0.5) + 1 for d in range(3, max_divisor, 2): if n % d == 0:...
from solution import filter_primes def test_filter_primes_basic_examples(): assert filter_primes([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7] assert filter_primes([11, 13, 17, 19, 23, 29]) == [11, 13, 17, 19, 23, 29] assert filter_primes([15, 21, 22, 24, 25]) == [] assert filter_primes([1, 0, -1, -10,...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers from the input list.", "function_declaration": "def filter_primes(numbers...
[ 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\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n ret...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028682", "row_id": 28682, "seed_ids": "[4106]" }
0.687264
Algorithm_28682
I
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
168d0ee816a0f5f33d26a616aec9bc6ff54678ed
f917685feefb52d9be2883f9854848bc316c903b
v1.0
instruct
Algorithm
Algorithm_28691_I
### Scenario: You are building a chatbot for a customer service application. One of the duties of the chatbot is to detect and correct common spelling mistakes in user messages before processing them further. To achieve this, you need to implement a function that takes a string containing the user message and returns t...
from typing import Set def levenshtein_distance(a, b): if len(a) > len(b): a, b = b, a distances = range(len(a) + 1) for i2, c2 in enumerate(b): distances_ = [i2 + 1] for i1, c1 in enumerate(a): if c1 == c2: distances_.append(distances[i1]) el...
from solution import correct_spelling def test_basic_example(): assert correct_spelling("hallo wrold", {"hello", "world"}) == 'hello world' def test_spelling_errors_example(): assert correct_spelling("speling errrs in somthing", {"spelling", "errors", "something", "in"}) == 'spelling errors in something' def...
[ { "docstring": null, "function_declaration": "def levenshtein_distance(a, b):", "function_name": "levenshtein_distance", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def correct_spelling(message, correct_words):", "function_name": "correct_spelling", ...
[ 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": "def levenshtein_distance(word1, word2):\n \"\"\"\n Computes the Levenshtein distance between two words.\n \"\"\"\n m, n = len(word1), len(word2)\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028691", "row_id": 28691, "seed_ids": "[5037]" }
0.596018
Algorithm_28691
I
[ "levenshtein_distance", "correct_spelling" ]
2
[ [ "correct_spelling", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
547461f7b788732b570675d41882477fbe5330c6
a42455facff39011a59834bdcc34c2ca775e676c
v1.0
instruct
Algorithm
Algorithm_28696_I
### Problem: Convert Array to Heap You are given an array of integers. The objective is to convert this array into a min-heap, which is a complete binary tree where each node is smaller than its children. #### Instructions: 1. **Implement Heapify Function**: Complete the function `heapify` which takes the array and ...
def heapify(arr, n, i): """ Ensures the subtree rooted at index `i` follows the min-heap property. Parameters: arr (list): The array representation of the heap. n (int): The size of the heap. i (int): The index of the root of the subtree to be heapified. """ smallest = i left = ...
def test_heapify(): arr = [4, 10, 3, 5, 1] heapify(arr, len(arr), 1) assert arr == [4, 1, 3, 5, 10] # After heapifying index 1 def test_build_min_heap_case1(): arr = [4, 10, 3, 5, 1] assert build_min_heap(arr) == [1, 4, 3, 5, 10] def test_build_min_heap_case2(): arr = [9, 7, 8, 3, 2, 5, 6] ...
[ { "docstring": "Ensures the subtree rooted at index `i` follows the min-heap property.\n\nParameters:\narr (list): The array representation of the heap.\nn (int): The size of the heap.\ni (int): The index of the root of the subtree to be heapified.", "function_declaration": "def heapify(arr, n, i):", "f...
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def heapify(arr, n, i):\n \"\"\"\n Ensures the subtree rooted at index i satisfies the min-heap property.\n \"\"\"\n smallest = i\n left = 2 * i +...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028696", "row_id": 28696, "seed_ids": "[5247]" }
0.617987
Algorithm_28696
I
[ "heapify", "build_min_heap" ]
2
[ [ "build_min_heap", "heapify" ] ]
1
[]
false
[]
false
pytest
false
[]
true
4b6fdc5c42b1e7241ab6a6096ad8368b4f55a338
89e3d3bb5f7d763deeeb41d12b6671a57e903a27
v1.0
instruct
Algorithm
Algorithm_28699_I
**Problem Statement** You are given a list of integers and a positive integer `k`. Your task is to find the `k`th smallest pair distance. The distance of a pair `(a, b)` is defined as the absolute difference between `a` and `b`, i.e., `|a - b|`. **Your task** is to implement the function `find_kth_smallest_pair_dista...
from typing import List def count_pairs_with_distance_less_than(mid, nums): count = 0 j = 0 for i in range(len(nums)): while j < len(nums) and nums[j] - nums[i] <= mid: j += 1 count += j - i - 1 return count def find_kth_smallest_pair_distance(numbers: List[int], k: int) ->...
def test_find_kth_smallest_pair_distance_1(): assert find_kth_smallest_pair_distance([1, 3, 1], 1) == 0 def test_find_kth_smallest_pair_distance_2(): assert find_kth_smallest_pair_distance([1, 6, 1], 3) == 5 def test_find_kth_smallest_pair_distance_large(): assert find_kth_smallest_pair_distance([1, 2, 3,...
[ { "docstring": null, "function_declaration": "def count_pairs_with_distance_less_than(mid, nums):", "function_name": "count_pairs_with_distance_less_than", "parameter_list": "(mid, nums)" }, { "docstring": null, "function_declaration": "def find_kth_smallest_pair_distance(numbers, k):", ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport bisect\n\ndef count_pairs_with_distance_less_than_or_equal(numbers: List[int], max_distance: int) -> int:\n count = 0\n for...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028699", "row_id": 28699, "seed_ids": "[2649]" }
0.704435
Algorithm_28699
I
[ "count_pairs_with_distance_less_than", "find_kth_smallest_pair_distance" ]
2
[ [ "find_kth_smallest_pair_distance", "count_pairs_with_distance_less_than" ] ]
1
[]
false
[]
false
pytest
false
[]
true
dd20a4c368cb97034cb51aff1558bea58a17be7f
775a5e8b7dc485d9b7bf52ef89d31b1c452249a0
v1.0
instruct
Algorithm
Algorithm_28735_I
**Scenario**: You are developing a text editor with a specific feature that allows users to find and highlight all occurrences of a certain word. To enhance performance, you want to implement search functionality using the Knuth-Morris-Pratt (KMP) algorithm, which efficiently locates substrings within a string. **Cha...
from typing import List def compute_lps(pattern: str) -> List[int]: """ Computes the Longest Prefix which is also Suffix (LPS) array. The LPS array is used to skip characters while matching. """ lps = [0] * len(pattern) length = 0 i = 1 while i < len(pattern): if pattern[i]...
from solution import find_all_occurrences def test_find_all_occurrences_basic(): assert find_all_occurrences("abracadabra", "abra") == [0, 7] def test_find_all_occurrences_repeated_pattern(): assert find_all_occurrences("aaaaaa", "aa") == [0, 1, 2, 3, 4] def test_find_all_occurrences_no_match(): assert f...
[ { "docstring": "Computes the Longest Prefix which is also Suffix (LPS) array.\nThe LPS array is used to skip characters while matching.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "Finds all occurrence...
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Computes the Longest Prefix which is also Suffix (LPS) array.\n The LP...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000028735", "row_id": 28735, "seed_ids": "[429]" }
0.540283
Algorithm_28735
I
[ "compute_lps", "find_all_occurrences" ]
2
[ [ "find_all_occurrences", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4fa5071bca45c2304a5fd62b8e67739e22255793
e2abbbcae9b38b4c737844bfd8182a4c14d5cfdc
v1.0
instruct
Algorithm
Algorithm_28779_I
### Coding Question #### Context You are developing a custom logging system for a web application to keep track of user activities. The current implementation logs all activities into a single file without any distinction between different types of activities or severity levels. #### Task Write a function `log_activi...
import logging from logging.handlers import RotatingFileHandler import os def setup_logger(name, log_file, level=logging.INFO): """Function to setup a logger""" logger = logging.getLogger(name) logger.setLevel(level) handler = RotatingFileHandler(log_file, maxBytes=5 * 1024 * 1024, backupCount=1) h...
import os from solution import log_activity def setup_function(function): """ Setup for tests: Create 'logs' directory if not exist, and clear any existing log files """ os.makedirs('logs', exist_ok=True) for f in os.listdir('logs'): os.remove(os.path.join('logs', f)) def teardown_function(functio...
[ { "docstring": "Function to setup a logger", "function_declaration": "def setup_logger(name, log_file, level=logging.INFO):", "function_name": "setup_logger", "parameter_list": "(name, log_file, level=logging.INFO)" }, { "docstring": null, "function_declaration": "def log_activity(activi...
[ 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": "import logging\nimport os\nfrom logging.handlers import RotatingFileHandler\n\ndef get_logger(name, logfile, level=logging.INFO):\n logger = logging.getLogger...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000028779", "row_id": 28779, "seed_ids": "[3948]" }
0.638021
Algorithm_28779
I
[ "setup_logger", "log_activity" ]
2
[ [ "log_activity", "setup_logger" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ee859b52697af6ffaeabd248a9c911e4ae495c8f
d2abaffe25473d9787d32bd5348986d697a58a0c
v1.0
instruct
Algorithm
Algorithm_28818_I
### Maze Solver Using Depth-First Search **Objective**: Implement a maze-solving algorithm using depth-first search (DFS) to reinforce understanding of graph traversal, recursion, and stack utilization. #### Scenario You are working on a pathfinding application that solves mazes. Your task is to implement a depth-fir...
from typing import List, Tuple def is_valid_move(maze: List[List[int]], visited: List[List[bool]], row: int, col: int) -> bool: """ Check if the current cell (row, col) is a valid move. """ n, m = len(maze), len(maze[0]) return 0 <= row < n and 0 <= col < m and not visited[row][col] and maze[row][c...
from solution import is_valid_move, dfs, find_path def test_is_valid_move(): maze = [[0, 1], [1, 0]] visited = [[False, False], [False, False]] assert is_valid_move(maze, visited, 0, 0) == True assert is_valid_move(maze, visited, 0, 1) == False assert is_valid_move(maze, visited, 1, 0) == False ...
[ { "docstring": "Check if the current cell (row, col) is a valid move.", "function_declaration": "def is_valid_move(maze, visited, row, col):", "function_name": "is_valid_move", "parameter_list": "(maze, visited, row, col)" }, { "docstring": "Perform DFS to find a path from the start to the e...
[ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef is_valid_move(maze: List[List[int]], visited: List[List[bool]], row: int, col: int) -> bool:\n \"\"\"\n Check if movi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000028818", "row_id": 28818, "seed_ids": "[1861]" }
0.603711
Algorithm_28818
I
[ "is_valid_move", "dfs", "find_path" ]
3
[ [ "dfs", "is_valid_move" ], [ "find_path", "dfs" ] ]
2
[]
false
[]
false
pytest
true
[]
true
115de9d79dcd3688be765433fa37a9f86ff84433
308a79267878635c8a29bf3eeec82d3afe7b1c0a
v1.0
instruct
Algorithm
Algorithm_28836_I
### Coding Question: Implement and Test a User Authentication System **Scenario:** You are tasked with implementing a simple user authentication system. The system should allow users to create accounts and then authenticate using their username and password. For security reasons, the passwords should be stored securel...
import hashlib # In-Memory user db user_db = {} def hash_password(password: str) -> str: return hashlib.sha256(password.encode()).hexdigest() def register_user(username: str, password: str) -> bool: if username in user_db: return False hashed_password = hash_password(password) user_db[usernam...
from solution import register_user, authenticate_user, user_db def test_register_user_success(): user_db.clear() assert register_user("test_user", "securePass123") == True def test_register_user_duplicate(): user_db.clear() register_user("test_user", "securePass123") assert register_user("test_use...
[ { "docstring": null, "function_declaration": "def hash_password(password):", "function_name": "hash_password", "parameter_list": "(password)" }, { "docstring": null, "function_declaration": "def register_user(username, password):", "function_name": "register_user", "parameter_lis...
[ 0, 0, 1, 0, 0, 1, 1, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import hashlib\n\nuser_db = {}\n\ndef hash_password(password: str) -> str:\n return hashlib.sha256(password.encode()).hexdigest()\n\ndef register_user(usernam...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028836", "row_id": 28836, "seed_ids": "[3964]" }
0.572313
Algorithm_28836
I
[ "hash_password", "register_user", "authenticate_user" ]
3
[ [ "authenticate_user", "hash_password" ], [ "register_user", "hash_password" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8c5f9d68df70ba458983b278ac3e3c7d9fe37155
89ac8241afdb50dc1c3dd17af12ad2326e20997c
v1.0
instruct
Algorithm
Algorithm_28855_I
## Problem Description You are assigned the task of enhancing a simple text compressor. The compressor will use a rudimentary form of Run-Length Encoding (RLE) to compress strings. Your task is to improve its functionality by including support for decoding, validating input, and handling special cases for extended cha...
def enhanced_compress(word): """ Compresses a string using Run-Length Encoding (RLE). Parameters: word (str): The string to compress. Returns: str: The compressed string. """ if not word: return "" compressed = [] count = 1 for i in range(1, len(word)): ...
from solution import enhanced_compress, enhanced_decompress, bulk_compress, bulk_decompress def test_enhanced_compress(): assert enhanced_compress("aaabbc") == "a3b2c1" assert enhanced_compress("hellooo") == "h1e1l2o3" assert enhanced_compress("a") == "a1" assert enhanced_compress("") == "" assert ...
[ { "docstring": "Compresses a string using Run-Length Encoding (RLE).\n\nParameters:\nword (str): The string to compress.\n\nReturns:\nstr: The compressed string.", "function_declaration": "def enhanced_compress(word):", "function_name": "enhanced_compress", "parameter_list": "(word)" }, { "d...
[ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def enhanced_compress(word):\n \"\"\"\n Compress the given string using Run-Length Encoding (RLE).\n \"\"\"\n compressed = []\n i = 0\n while i...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028855", "row_id": 28855, "seed_ids": "[345]" }
0.798454
Algorithm_28855
I
[ "enhanced_compress", "enhanced_decompress", "bulk_compress", "bulk_decompress" ]
4
[ [ "bulk_compress", "enhanced_compress" ], [ "bulk_decompress", "enhanced_decompress" ] ]
2
[]
false
[]
false
pytest
true
[]
true
616b3d76fa7741e54f18276b432d8bfe5f1c3e3f
3c0ac095099bd2978d1c146309f0f0452edc134e
v1.0
instruct
Algorithm
Algorithm_28903_I
### Median of Medians Algorithm for Quickselect in Finding the k-th Smallest Element You are tasked with implementing an efficient algorithm to find the k-th smallest element in an unsorted array. Utilize the "Median of Medians" algorithm to achieve a guaranteed worst-case time complexity. Your task is to implement t...
from typing import List def median_of_medians(arr: List[int], left: int, right: int) -> int: """ Selects the pivot element using the Median of Medians method within the given subarray. """ n = right - left + 1 if n <= 5: return sorted(arr[left:right + 1])[n // 2] medians = [] for i...
from solution import quickselect def test_quickselect_example(): array = [12, 3, 5, 7, 4, 19, 26] k = 3 assert quickselect(array, 0, len(array) - 1, k) == 5 def test_quickselect_duplicate_elements(): array = [12, 3, 5, 7, 5, 19, 12, 26] k = 4 assert quickselect(array, 0, len(array) - 1, k) == ...
[ { "docstring": "Selects the pivot element using the Median of Medians method within the given subarray.", "function_declaration": "def median_of_medians(arr, left, right):", "function_name": "median_of_medians", "parameter_list": "(arr, left, right)" }, { "docstring": "Partitions the array a...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def median_of_medians(arr, left, right):\n \"\"\"\n Selects the pivot element using the Median of Medians method within the given subarray.\n \n :par...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000028903", "row_id": 28903, "seed_ids": "[1745]" }
0.695723
Algorithm_28903
I
[ "median_of_medians", "partition", "quickselect" ]
3
[ [ "quickselect", "median_of_medians" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9cc0dd0aaf34e87fba4c20b40da9eb516b667385
040522f3352e4f3b33aec3d734a6045d58be658f
v1.0
instruct
Algorithm
Algorithm_28921_I
### Problem Statement: You have been tasked with implementing an algorithm that generates the first `N` prime numbers. A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. ### Detailed Requirements 1. **Input**: - An integer `N` which denotes the num...
def is_prime(x: int) -> bool: """ Check if a number is prime. :param x: The number to check. :return: True if x is prime, False otherwise. """ if x <= 1: return False for i in range(2, int(x**0.5) + 1): if x % i == 0: return False return True def generat...
from solution import is_prime, generate_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(1) == False def test_generate_primes(): assert generate_primes(1) == [2] assert generate_primes(2...
[ { "docstring": "Check if a number is prime.\n\n:param x: The number to check.\n:return: True if x is prime, False otherwise.", "function_declaration": "def is_prime(x):", "function_name": "is_prime", "parameter_list": "(x)" }, { "docstring": "Generate the first N prime numbers.\n\n:param N: ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(x: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \n :param x: The number to check.\n :return: True if x is prime, False othe...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028921", "row_id": 28921, "seed_ids": "[3979]" }
0.729755
Algorithm_28921
I
[ "is_prime", "generate_primes" ]
2
[ [ "generate_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b61e6cccd3f4c5fb757872a0445e342caa5e79dd
ee96106a0da021239feaf167dadfe4efaa3f03d6
v1.0
instruct
Algorithm
Algorithm_28936_I
### Factorial Prime Factors **Context**: The prime factorization of factorials is a crucial concept in number theory and can be used to solve various problems in mathematics and computer science, such as algorithm optimization, cryptographic applications, and numerical analyses. ### Problem Statement Write a functio...
from collections import defaultdict import math def sieve_of_eratosthenes(limit): """ Generate a list of primes up to the limit using the Sieve of Eratosthenes algorithm. """ is_prime = [True] * (limit + 1) is_prime[0] = is_prime[1] = False # 0 and 1 are not primes for start in range(2, in...
def test_factorial_prime_factors(): assert factorial_prime_factors(10) == {2: 8, 3: 4, 5: 2, 7: 1} assert factorial_prime_factors(5) == {2: 3, 3: 1, 5: 1} assert factorial_prime_factors(1) == {} assert factorial_prime_factors(0) == {} assert factorial_prime_factors(20) == {2: 18, 3: 8, 5: 4, 7: 2, 1...
[ { "docstring": "Generate a list of primes up to the limit using the Sieve of Eratosthenes algorithm.", "function_declaration": "def sieve_of_eratosthenes(limit):", "function_name": "sieve_of_eratosthenes", "parameter_list": "(limit)" }, { "docstring": "Calculate the prime factors and their p...
[ 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 prime_factors(n):\n \"\"\" \n A function to return the list of prime numbers up to n.\n \"\"\"\n sieve = [True] * (n + 1)\n p = 2\n while p...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000028936", "row_id": 28936, "seed_ids": "[2834]" }
0.737391
Algorithm_28936
I
[ "sieve_of_eratosthenes", "prime_factors_in_factorial", "factorial_prime_factors" ]
3
[ [ "factorial_prime_factors", "prime_factors_in_factorial" ], [ "factorial_prime_factors", "sieve_of_eratosthenes" ] ]
2
[]
false
[]
false
pytest
false
[]
true
f554c4b9478bf5bc7fdc82fa7251759d78854edf
a84ae2a263eba5172553e3f5d35a81fa869bb233
v1.0
instruct
Algorithm
Algorithm_28986_I
### Coding Assessment Question You are developing a new feature for a financial analysis tool that involves statistical calculations on stock data. Your task is to implement a utility function that computes various financial metrics based on a given stock's historical prices. You need to create a function `compute_fi...
import numpy as np def compute_financial_metrics(metric_type: str, prices: np.ndarray, **kwargs) -> np.ndarray: if not isinstance(prices, np.ndarray): raise ValueError("Input 'prices' must be a numpy array.") if metric_type == "simple_moving_average": return simple_moving_average(prices, **kwa...
import numpy as np from solution import compute_financial_metrics, simple_moving_average, relative_strength_index def test_simple_moving_average(): prices = np.array([100, 102, 101, 105, 107, 110, 108, 111]) result = compute_financial_metrics("simple_moving_average", prices, window=3) expected = np.array([...
[ { "docstring": null, "function_declaration": "def compute_financial_metrics(metric_type, prices, **kwargs):", "function_name": "compute_financial_metrics", "parameter_list": "(metric_type, prices, **kwargs)" }, { "docstring": null, "function_declaration": "def simple_moving_average(price...
[ 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": "import numpy as np\n\ndef compute_financial_metrics(metric_type: str, prices: np.ndarray, **kwargs) -> np.ndarray:\n if not isinstance(prices, np.ndarray):\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000028986", "row_id": 28986, "seed_ids": "[696]" }
0.654304
Algorithm_28986
I
[ "compute_financial_metrics", "simple_moving_average", "exponential_moving_average", "bollinger_bands", "relative_strength_index", "moving_average_convergence_divergence", "average_true_range", "rate_of_change", "stochastic_oscillator", "momentum" ]
10
[ [ "bollinger_bands", "simple_moving_average" ], [ "compute_financial_metrics", "average_true_range" ], [ "compute_financial_metrics", "bollinger_bands" ], [ "compute_financial_metrics", "exponential_moving_average" ], [ "compute_financial_metrics", "momentum" ...
12
[]
false
[]
false
pytest
true
[ "numpy" ]
false
8b3668e9a149577dc690d7e211424a37bcb60512
c8161016faeaff8734f51869094242c6e08ec913
v1.0
instruct
Algorithm
Algorithm_29104_I
### Given Context You have been asked to improve the functionality of a Python script that processes and analyzes log files from various servers. The current implementation efficiently reads and processes a single file, but the requirement is to extend it to handle multiple files concurrently, due to the growing volume...
import concurrent.futures import os def process_log_file(file_path: str) -> dict: """ Processes a single log file and extracts relevant information. """ result = {} try: with open(file_path, 'r') as file: # Simulated log processing logic for line in file: ...
from solution import process_log_files, process_log_file def test_process_single_log_file(tmpdir): log_content = "line1\nline2\nline3\n" file_path = tmpdir.join("logfile.txt") file_path.write(log_content) result = process_log_file(str(file_path)) expected_result = { "line1\n": "line1",...
[ { "docstring": "Processes a single log file and extracts relevant information.", "function_declaration": "def process_log_file(file_path):", "function_name": "process_log_file", "parameter_list": "(file_path)" }, { "docstring": "Processes multiple log files concurrently and returns their res...
[ 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import concurrent.futures\n\ndef process_log_file(file_path: str) -> dict:\n \"\"\"\n Processes a single log file and extracts relevant information.\n \...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000029104", "row_id": 29104, "seed_ids": "[4914]" }
0.62048
Algorithm_29104
I
[ "process_log_file", "process_log_files" ]
2
[ [ "process_log_files", "process_log_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
00ab0cf3d0eb8eb8b2a2a1b5c82e289556f7d431
b7d47357fdcfb53e53ae041553495c9981dce820
v1.0
instruct
Algorithm
Algorithm_29119_I
### Problem Statement Implement a feature to validate and correct common date formats in textual data. You need to write two functions: 1. `is_valid_date(date_str: str) -> bool` 2. `correct_date_format(date_str: str) -> str` ### Function Specifications #### 1. is_valid_date(date_str: str) -> bool * Checks if the ...
import re from datetime import datetime def is_valid_date(date_str): """ Checks if the provided string is a valid date in the formats YYYY-MM-DD, DD-MM-YYYY, or MM/DD/YYYY. Args: date_str (str): A string representing a date. Returns: bool: A boolean indicating whether the date string ...
from solution import is_valid_date, correct_date_format def test_is_valid_date(): assert is_valid_date('2023-10-15') == True assert is_valid_date('15-10-2023') == True assert is_valid_date('10/15/2023') == True assert is_valid_date('2023/10/15') == False assert is_valid_date('2023-13-01') == False ...
[ { "docstring": "Checks if the provided string is a valid date in the formats YYYY-MM-DD, DD-MM-YYYY, or MM/DD/YYYY.\n\nArgs:\ndate_str (str): A string representing a date.\n\nReturns:\nbool: A boolean indicating whether the date string is valid.", "function_declaration": "def is_valid_date(date_str):", ...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from datetime import datetime\n\ndef is_valid_date(date_str):\n \"\"\"\n Checks if the provided string is a valid date in the formats YYYY-MM-DD, DD-MM-YYY...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000029119", "row_id": 29119, "seed_ids": "[3338]" }
0.78981
Algorithm_29119
I
[ "is_valid_date", "correct_date_format" ]
2
[ [ "correct_date_format", "is_valid_date" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95b8028e5f69d2661b68b03489f2b12a2d5b3351
584bb83cf3d3a514121c3fdc60c3eb82a872d572
v1.0
instruct
Algorithm
Algorithm_29146_I
### Coding Task: Multi-rule Roman Numeral Converter **Objective**: Create an advanced Roman numeral converter that can convert integer numbers to Roman numeral strings, validate Roman numeral strings, and calculate the sum of two Roman numeral strings. #### Functions to Implement: 1. **`int_to_roman(n: int) -> str`**...
def int_to_roman(n: int) -> str: """ Converts an integer to a Roman numeral string. Args: - n (int): The integer to convert (must be between 1 and 3999). Returns: - str: The Roman numeral representation of the integer. Raises: - ValueError: If n is not within the range 1-3999. ...
import pytest from solution import int_to_roman, is_valid_roman, sum_romans, roman_to_int def test_int_to_roman(): assert int_to_roman(1) == "I" assert int_to_roman(4) == "IV" assert int_to_roman(9) == "IX" assert int_to_roman(58) == "LVIII" assert int_to_roman(1994) == "MCMXCIV" assert int_to_...
[ { "docstring": "Converts an integer to a Roman numeral string.\nArgs:\n- n (int): The integer to convert (must be between 1 and 3999).\n\nReturns:\n- str: The Roman numeral representation of the integer.\n\nRaises:\n- ValueError: If n is not within the range 1-3999.\n- TypeError: If n is not an integer.", "...
[ 0, 0, 0, 1, 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 int_to_roman(n):\n \"\"\"\n Convert an integer to a Roman numeral string.\n \n Parameters:\n n (int): The integer to convert, must be in the r...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029146", "row_id": 29146, "seed_ids": "[3559]" }
0.618062
Algorithm_29146
I
[ "int_to_roman", "is_valid_roman", "roman_to_int", "sum_romans" ]
4
[ [ "sum_romans", "int_to_roman" ], [ "sum_romans", "is_valid_roman" ], [ "sum_romans", "roman_to_int" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6663641bb8c0383a6027e2356b9b5f72cc75adbd
8914f42130f7079bb59a59a8456a461c1a885fa0
v1.0
instruct
Algorithm
Algorithm_29187_I
### Context You are working with a dataset of user activity logs from a website, where each row represents a user's session with various features including the length of the session in seconds and the number of actions performed. Your task is to implement a k-means clustering algorithm to segment users based on their a...
import numpy as np def initialize_centroids(data, k): """ Randomly initialize the cluster centroids by selecting k unique data points. :param data: np.ndarray, matrix of input features. :param k: int, number of clusters. :return: np.ndarray, matrix containing the initialized centroids. ...
import numpy as np from solution import kmeans_clustering def test_kmeans_single_cluster(): data = np.array([[1, 2], [1, 2], [1, 2]]) k = 1 iterations = 10 centroids = kmeans_clustering(data, k, iterations) assert centroids.shape == (1, 2) assert np.allclose(centroids, [[1, 2]]) def test_kmean...
[ { "docstring": "Randomly initialize the cluster centroids by selecting k unique data points.\n\n:param data: np.ndarray, matrix of input features.\n:param k: int, number of clusters.\n\n:return: np.ndarray, matrix containing the initialized centroids.", "function_declaration": "def initialize_centroids(data...
[ 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": "import numpy as np\n\ndef initialize_centroids(data, k):\n random_indices = np.random.choice(data.shape[0], k, replace=False)\n return data[random_indices]...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029187", "row_id": 29187, "seed_ids": "[476]" }
0.814852
Algorithm_29187
I
[ "initialize_centroids", "assign_clusters", "update_centroids", "kmeans_clustering" ]
4
[ [ "kmeans_clustering", "assign_clusters" ], [ "kmeans_clustering", "initialize_centroids" ], [ "kmeans_clustering", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
8846fb43a8841e21978bd2c9723ef765d8efa758
497280e3afb8b05d4fbb53a06eb58cf2457b0b3d
v1.0
instruct
Algorithm
Algorithm_29193_I
### Intersection of Two Sorted Arrays You are given two functions that deal with finding common elements in two sorted arrays: 1. `find_intersection(arr1: list, arr2: list) -> list`: This function finds the intersection of two sorted arrays and returns it as a list. 2. `merge_sort(arr: list) -> list`: This function s...
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_array = [] i = j = 0 while i < len(left) and j < len(right): if l...
from solution import sorted_intersection def test_example1(): assert sorted_intersection([1, 3, 4, 5, 7], [2, 3, 5, 6]) == [3, 5] def test_example2(): assert sorted_intersection([10, 20, 30], [30, 40, 50]) == [30] def test_example3(): assert sorted_intersection([1, 2, 2, 3], [2, 2, 4]) == [2, 2] def tes...
[ { "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)" }, { "docst...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array using merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029193", "row_id": 29193, "seed_ids": "[4108]" }
0.658941
Algorithm_29193
I
[ "merge_sort", "merge", "find_intersection", "sorted_intersection" ]
4
[ [ "merge_sort", "merge" ], [ "sorted_intersection", "find_intersection" ], [ "sorted_intersection", "merge_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
daf0a594d2c81b3f08b640216a4344d948c9495a
ea7a7433d60e062fde8e344349e5e85792506f22
v1.0
instruct
Algorithm
Algorithm_29196_I
### Problem Statement You are required to solve a problem related to temperature data analysis from various monitoring stations. Each station records the temperature in Celsius throughout the day and reports the readings. ### Your Task 1. **Compute Average Daily Temperature**: Implement a function that calculates...
def average_temperature(temperatures): """ Calculates the average temperature of the given list of temperature readings. Parameters: temperatures (List[float]): List of temperature readings in Celsius. Returns: float: The average temperature. """ if not temperatures: ra...
from solution import average_temperature, detect_anomaly def test_average_temperature_single_reading(): assert average_temperature([25.0]) == 25.0 def test_average_temperature_multiple_readings(): assert average_temperature([20.0, 22.0, 24.0, 26.0]) == 23.0 assert average_temperature([10.0, 10.0, 10.0, 10...
[ { "docstring": "Calculates the average temperature of the given list of temperature readings.\n\nParameters:\ntemperatures (List[float]): List of temperature readings in Celsius.\n\nReturns:\nfloat: The average temperature.", "function_declaration": "def average_temperature(temperatures):", "function_na...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef average_temperature(temperatures: List[float]) -> float:\n \"\"\"\n Computes the average temperature of the given list of te...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029196", "row_id": 29196, "seed_ids": "[782]" }
0.592054
Algorithm_29196
I
[ "average_temperature", "detect_anomaly" ]
2
[ [ "detect_anomaly", "average_temperature" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e844fc370d00d9dda4e40a58ece50c6ab4c169d2
6c4c9af6d3731c09ce5793e1f559eabbfa76f5de
v1.0
instruct
Algorithm
Algorithm_29209_I
### Coding Assessment Question You are tasked with writing a function `next_prime(n: int) -> int` which takes an integer `n` and returns the smallest prime number greater than `n`. **Function Signature**: ```python def next_prime(n: int) -> int: pass ``` ### Input - An integer `n` where `1 <= n <= 10^6`. ### Ou...
import math def is_prime(num): """ Efficient check if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: retu...
from solution import next_prime def test_next_prime_small_numbers(): assert next_prime(1) == 2 assert next_prime(2) == 3 assert next_prime(3) == 5 assert next_prime(4) == 5 def test_next_prime_reasonable_numbers(): assert next_prime(11) == 13 assert next_prime(17) == 19 assert next_prime(2...
[ { "docstring": "Efficient check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns the smallest prime number greater than n.", "function_declaration": "def next_prime(n):", "function_...
[ 0, 1, 0, 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": "import math\n\ndef is_prime(number):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if number <= 1:\n return False\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "0000029209", "row_id": 29209, "seed_ids": "[4005]" }
0.773038
Algorithm_29209
I
[ "is_prime", "next_prime" ]
2
[ [ "next_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de1dbdfac38be1bfe4e8c508e876f11266c35550
5532a4c675bc85db36205d2cd407724d3f288689
v1.0
instruct
Algorithm
Algorithm_29293_I
### Coding Assessment Question: Maximal Rectangle in a Binary Matrix **Scenario**: You are working on a geographical information system that involves analyzing two-dimensional grids of data. One common operation is identifying the largest rectangular region in a binary grid that is filled entirely with `1`s, which can...
def maximal_rectangle(matrix): if not matrix: return 0 max_area = 0 n_cols = len(matrix[0]) heights = [0] * n_cols for row in matrix: for i in range(n_cols): if row[i] == 0: heights[i] = 0 else: heights[i] += 1 max_are...
def test_maximal_rectangle(): matrix = [ [1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0] ] assert maximal_rectangle(matrix) == 6 def test_maximal_rectangle_empty_matrix(): matrix = [] assert maximal_rectangle(matrix) == 0 def test_maximal_rectangl...
[ { "docstring": null, "function_declaration": "def maximal_rectangle(matrix):", "function_name": "maximal_rectangle", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def max_histogram_area(heights):", "function_name": "max_histogram_area", "parameter_...
[ 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": "def maximal_rectangle(matrix):\n if not matrix:\n return 0\n\n max_area = 0\n rows = len(matrix)\n cols = len(matrix[0])\n heights = [0] * ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000029293", "row_id": 29293, "seed_ids": "[5115]" }
0.727307
Algorithm_29293
I
[ "maximal_rectangle", "max_histogram_area" ]
2
[ [ "maximal_rectangle", "max_histogram_area" ] ]
1
[]
false
[]
false
pytest
false
[]
true
02348c8f95860474a20a5f359120ef96073e27a4
7799c6bdc2856ee25902297fc8aaadb32b28a4c8
v1.0
instruct
Algorithm
Algorithm_29304_I
### Advanced Coding Challenge: Implementing K-Means Clustering with Optimizations #### Background K-Means clustering is a widely-used algorithm for partitioning a dataset into K clusters, where each data point belongs to the cluster with the nearest mean. The algorithm works iteratively, alternating between assigning ...
import numpy as np def k_means_plus_plus(data, K): n_samples, n_features = data.shape centroids = np.empty((K, n_features)) # Choose the first centroid randomly from the data points centroids[0] = data[np.random.choice(n_samples)] for k in range(1, K): # Compute the distance from ...
import numpy as np from solution import k_means, k_means_plus_plus def test_k_means_plus_plus_initialization(): data = np.array([ [1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0] ]) K = 2 centroids = k_means_plus_plus(data, K) a...
[ { "docstring": null, "function_declaration": "def k_means_plus_plus(data, K):", "function_name": "k_means_plus_plus", "parameter_list": "(data, K)" }, { "docstring": null, "function_declaration": "def k_means(data, K, max_iters=300, tol=0.0001):", "function_name": "k_means", "par...
[ 0, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.spatial.distance import cdist, euclidean\n\ndef k_means_plus_plus(data, K):\n \"\"\" Initialize centroids using the K-Means++ a...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029304", "row_id": 29304, "seed_ids": "[513]" }
0.652396
Algorithm_29304
I
[ "k_means_plus_plus", "k_means" ]
2
[ [ "k_means", "k_means_plus_plus" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
7d02d65e5f7d09ffdb21383df898f473997f7d7c
b0452e75f8c0c1be860552d6d80f3dd802e60954
v1.0
instruct
Algorithm
Algorithm_29374_I
### Question: Sum of Unique Elements You are tasked with implementing functions to identify and sum unique elements present in a list. Unique elements are defined as those that appear exactly once in the input list. #### Implement the Following Functions: **1. Function `find_unique_elements(values: list) -> list`:**...
from collections import Counter def find_unique_elements(values): if not isinstance(values, list) or any(not isinstance(x, int) for x in values): raise ValueError("Input must be a list of integers.") if not values: raise ValueError("Input list must not be empty.") counter = Counter(val...
import pytest from solution import find_unique_elements, sum_of_unique_elements def test_find_unique_elements(): assert find_unique_elements([1, 2, 2, 3, 4, 4, 5]) == [1, 3, 5] assert find_unique_elements([7, 8, 9]) == [7, 8, 9] assert find_unique_elements([6, 6, 6]) == [] assert find_unique_elements([...
[ { "docstring": null, "function_declaration": "def find_unique_elements(values):", "function_name": "find_unique_elements", "parameter_list": "(values)" }, { "docstring": null, "function_declaration": "def sum_of_unique_elements(values):", "function_name": "sum_of_unique_elements", ...
[ 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 find_unique_elements(values):\n \"\"\"\n Returns a list of integers that appear exactly once in the input list.\n \n :param values: A list of int...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029374", "row_id": 29374, "seed_ids": "[4188]" }
0.680999
Algorithm_29374
I
[ "find_unique_elements", "sum_of_unique_elements" ]
2
[ [ "sum_of_unique_elements", "find_unique_elements" ] ]
1
[]
false
[]
false
pytest
true
[]
true
583a029f818c969850d98040874efa35c6548574
bf38df15b66b46d9123f9fcf89d84e80d00aedad
v1.0
instruct
Algorithm
Algorithm_29427_I
### Introduction You are developing a 2D simulation of diffusion processes in a rectangular grid. The goal is to model the spread of a substance from an initial point over time. At every time step, the substance spreads evenly to its neighboring cells based on a given diffusion factor. Your task involves implementing f...
from typing import List, Tuple def initialize_grid( width: int, height: int, initial_point: Tuple[int, int], initial_concentration: float ) -> List[List[float]]: if width <= 0 or height <= 0: raise ValueError("Width and height must be positive integers") if initial_concentration < 0: raise ...
import pytest from solution import initialize_grid, diffuse_step, concentration_at_point def test_initialize_grid_valid_input(): grid = initialize_grid(5, 5, (2, 2), 100.0) expected_grid = [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 100.0, 0.0, 0....
[ { "docstring": null, "function_declaration": "def initialize_grid(width, height, initial_point, initial_concentration):", "function_name": "initialize_grid", "parameter_list": "(width, height, initial_point, initial_concentration)" }, { "docstring": null, "function_declaration": "def dif...
[ 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef initialize_grid(\n width: int, height: int, initial_point: Tuple[int, int], initial_concentration: float\n) -> List[List...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000029427", "row_id": 29427, "seed_ids": "[575]" }
0.479042
Algorithm_29427
I
[ "initialize_grid", "diffuse_step", "concentration_at_point" ]
3
[ [ "concentration_at_point", "diffuse_step" ], [ "concentration_at_point", "initialize_grid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d2f30a859abfcd854148a256256b848ef883bd28
0271a14740b7278b6b78a6865575bfd498159a59
v1.0
instruct
Algorithm
Algorithm_29492_I
### Question #### Description You are given a list of strings and a list of queries. For each query, you need to determine if the query is a substring of any string in the list. Implement a function to perform this task efficiently using a Trie data structure. #### Function Signature ```python def substring_search(st...
class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: node.ch...
from solution import substring_search def test_example_case(): strings = ["abracadabra", "alligator", "brazilian"] queries = ["cad", "gat", "br"] assert substring_search(strings, queries) == [True, True, True] def test_no_match_case(): strings = ["hello", "world"] queries = ["xyz", "abc"] asse...
[]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.end_of_word = False\n\nclass Trie:\n def __init__(self):\n self.root...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000029492", "row_id": 29492, "seed_ids": "[5000]" }
0.689632
Algorithm_29492
I
[ "build_suffix_trie", "substring_search" ]
2
[ [ "substring_search", "build_suffix_trie" ] ]
1
[]
false
[ "TrieNode", "Trie" ]
true
pytest
true
[]
true
1693177647c78c96c3fe54b90b45e29575a461c2
86d1aefe55f771dec5333b87c974e8b13f1fe1c2
v1.0
instruct
Algorithm
Algorithm_29552_I
### Scenario You are developing a navigation system for a marine vessel that needs to determine the optimal path through a set of waypoints. The goal is to visit each waypoint exactly once and return to the starting point, minimizing the total traveled distance. This is a classic Traveling Salesperson Problem (TSP) in ...
from itertools import permutations from typing import List, Tuple def calculate_total_distance(path: List[Tuple[int, int]]) -> float: """ Calculate the total distance of a given path. """ def euclidean_distance(p1, p2): return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 total_...
from solution import find_optimal_path def test_single_path(): assert find_optimal_path([(0, 0), (1, 1)]) == [(0, 0), (1, 1), (0, 0)] def test_triangle_path(): points = [(0, 0), (0, 2), (2, 0)] path = find_optimal_path(points) assert path[-1] == path[0] assert set(path[:-1]) == set(points) def te...
[ { "docstring": "Calculate the total distance of a given path.", "function_declaration": "def calculate_total_distance(path):", "function_name": "calculate_total_distance", "parameter_list": "(path)" }, { "docstring": "Determines the optimal path to visit each point exactly once and return to...
[ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from itertools import permutations\nfrom typing import List, Tuple\n\ndef calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000029552", "row_id": 29552, "seed_ids": "[5050]" }
0.644353
Algorithm_29552
I
[ "calculate_total_distance", "find_optimal_path" ]
2
[ [ "find_optimal_path", "calculate_total_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5b8fb5fec58459ae1d19c026c3143de71fbc25cc
7fbf76417bc04210b48c003093617fa09912ddb8
v1.0
instruct
Algorithm
Algorithm_29575_I
### Fibonacci Sequence with Matrix Exponentiation You are required to implement an efficient algorithm to find the Nth number in the Fibonacci sequence using matrix exponentiation. ### Task 1. Implement the `matrix_multiply` function to multiply two 2x2 matrices. 2. Implement the `matrix_exponentiate` function to ra...
def matrix_multiply(A: list[list[int]], B: list[list[int]]) -> list[list[int]]: """ Multiplies two 2x2 matrices A and B. """ return [ [ A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1] ], [ A[1][0] * B[0][0] + A[1][1...
from solution import matrix_multiply, matrix_exponentiate, fib def test_matrix_multiply(): A = [[1, 1], [1, 0]] B = [[1, 1], [1, 0]] expected = [[2, 1], [1, 1]] assert matrix_multiply(A, B) == expected def test_matrix_exponentiate(): matrix = [[1, 1], [1, 0]] power = 2 expected = [[2, 1], ...
[ { "docstring": "Multiplies two 2x2 matrices A and B.", "function_declaration": "def matrix_multiply(A, B):", "function_name": "matrix_multiply", "parameter_list": "(A, B)" }, { "docstring": "Calculates matrix raised to a power using exponentiation by squaring.", "function_declaration": "...
[ 1, 0, 0, 1, 0, 1, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def matrix_multiply(A, B):\n return [\n [A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[0][1]*B[1][1]],\n [A[1][0]*B[0][0] + A[1][1]*B[1...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029575", "row_id": 29575, "seed_ids": "[34]" }
0.725158
Algorithm_29575
I
[ "matrix_multiply", "matrix_exponentiate", "fib" ]
3
[ [ "fib", "matrix_exponentiate" ], [ "matrix_exponentiate", "matrix_multiply" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c4a22a6064c761b4555f9d32c343212a14e36e7e
15f294ec71f93f7be637d74547eadec8a3ee5287
v1.0
instruct
Algorithm
Algorithm_29684_I
### Prime Path Check Write a function to determine whether there exists a "prime path" between two given prime numbers. A prime path is a sequence of prime numbers where each consecutive pair of primes in the sequence differs by exactly 2 (i.e., twin primes). #### Implementation Requirements 1. **Function to Impleme...
def is_prime(n: int) -> bool: """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: retu...
from solution import prime_path_exists, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(20) == False assert is_prime(23) == True def test_generate_primes_in_range(): assert generate_p...
[ { "docstring": "Returns True if n is a prime number, otherwise False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generates a list of prime numbers in the inclusive range from start to end.", "function_declaration"...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Returns True if n is a prime number, else returns False.\n \"\"\"\n if n <= 1:\n return False\n if...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000029684", "row_id": 29684, "seed_ids": "[4065]" }
0.669783
Algorithm_29684
I
[ "is_prime", "generate_primes_in_range", "prime_path_exists" ]
3
[ [ "generate_primes_in_range", "is_prime" ], [ "prime_path_exists", "generate_primes_in_range" ], [ "prime_path_exists", "is_prime" ] ]
3
[]
false
[]
false
pytest
true
[]
true
48f6ec70a016c2552ccb95e384c5db18eec8f9df
168049d9cd90df378ad69e580e160c14293df173
v1.0
instruct
Algorithm
Algorithm_29746_I
### Coding Question: Matrix Exponentiation through Fast Exponentiation #### Background In computer science, matrix exponentiation can be a powerful technique to calculate powers of matrices efficiently. This technique uses the fast exponentiation method, similar to binary exponentiation used for scalar values, but ada...
from typing import List def matrix_multiply(A: List[List[int]], B: List[List[int]], size: int) -> List[List[int]]: """Helper function to multiply two matrices A and B.""" C = [[0] * size for _ in range(size)] for i in range(size): for j in range(size): for k in range(size): ...
from solution import matrix_exponentiation def test_matrix_exponentiation_example_1(): matrix = [[1, 2], [3, 4]] exponent = 2 expected = [[7, 10], [15, 22]] assert matrix_exponentiation(matrix, exponent) == expected def test_matrix_exponentiation_example_2(): matrix = [[2, 0], [0, 2]] exponent...
[ { "docstring": "Helper function to multiply two matrices A and B.", "function_declaration": "def matrix_multiply(A, B, size):", "function_name": "matrix_multiply", "parameter_list": "(A, B, size)" }, { "docstring": "Performs matrix exponentiation using fast exponentiation method.", "func...
[ 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n n = len(A)\n result = [[0] * n for _ in range(...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000029746", "row_id": 29746, "seed_ids": "[846]" }
0.589515
Algorithm_29746
I
[ "matrix_multiply", "matrix_exponentiation" ]
2
[ [ "matrix_exponentiation", "matrix_multiply" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0e7eca1f0d6aba69889813b93fa0acbbdf44d48c
1268203ec1dc49625a1033ccd3b5fd4df3cb41c4
v1.0
instruct
Algorithm
Algorithm_29766_I
### Question: Counting Valid Sudoku Boards **Context**: A Sudoku board is a 9x9 grid where each cell can either be a number from 1 to 9 or empty (represented by 0). For a Sudoku board to be valid, each row, column, and 3x3 sub-grid must contain no duplicate numbers from 1 to 9. **Task**: Write a function `count_vali...
from typing import List def is_valid_sudoku(board: List[List[int]]) -> bool: def is_valid_group(group: List[int]) -> bool: numbers = [num for num in group if num != 0] return len(numbers) == len(set(numbers)) def get_subgrid(board: List[List[int]], start_row: int, start_col: int) -> List[i...
from solution import count_valid_sudoku_boards def test_count_valid_sudoku_boards_all_valid(): boards = [ [ [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,...
[ { "docstring": null, "function_declaration": "def is_valid_sudoku(board):", "function_name": "is_valid_sudoku", "parameter_list": "(board)" }, { "docstring": null, "function_declaration": "def count_valid_sudoku_boards(boards):", "function_name": "count_valid_sudoku_boards", "par...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_valid_sudoku(board):\n def is_valid_unit(unit):\n unit = [i for i in unit if i != 0]\n return len(unit) == len(set(unit))\n\n def is_v...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000029766", "row_id": 29766, "seed_ids": "[2395]" }
0.64216
Algorithm_29766
I
[ "is_valid_sudoku", "count_valid_sudoku_boards" ]
2
[ [ "count_valid_sudoku_boards", "is_valid_sudoku" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4be9d28bec0340ee1ed3248bb88e79ac75d28d96
d94a1020a159b98d909e90fad82e4264e4527fe3
v1.0
instruct
Algorithm
Algorithm_29782_I
### Scenario: As a software engineer, you are tasked with designing a service that processes large sets of log data to identify and report unique IP addresses that have accessed the system. The objective is to examine access patterns and detect potential security issues or unauthorized access attempts. ### Task: Imple...
import re def find_unique_ips(logfile_path): """ Reads a log file, extracts unique IP addresses, and writes them to an output file. :param logfile_path: The path to the log file. """ ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b') unique_ips = set() # Reading the log file ...
from solution import find_unique_ips, is_valid_ip import os def test_valid_ip(): assert is_valid_ip('192.168.1.1') == True assert is_valid_ip('0.0.0.0') == True assert is_valid_ip('255.255.255.255') == True assert is_valid_ip('256.100.100.100') == False assert is_valid_ip('192.168.1.256') == False ...
[ { "docstring": "Reads a log file, extracts unique IP addresses, and writes them to an output file.\n\n:param logfile_path: The path to the log file.", "function_declaration": "def find_unique_ips(logfile_path):", "function_name": "find_unique_ips", "parameter_list": "(logfile_path)" }, { "do...
[ 1, 1, 0, 0, 1, 0, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef find_unique_ips(logfile_path):\n \"\"\"\n Reads through a log file, extracts all unique IP addresses, and writes them to an output file.\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000029782", "row_id": 29782, "seed_ids": "[4169]" }
0.66167
Algorithm_29782
I
[ "find_unique_ips", "is_valid_ip" ]
2
[ [ "find_unique_ips", "is_valid_ip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb35ae2e2c31bb431e1dea8944b91cb18a72572f
1acf561dd83cbf47fe9b15f67b3eed308982bd0d
v1.0
instruct
Algorithm
Algorithm_29791_I
### Coding Assessment Question You have been appointed as a software developer to enhance a service that monitors and processes cryptocurrency prices in real-time. Your task is to refactor and expand the current solution to support better error handling, data processing, and feature extension. **Your tasks are:** 1....
import requests from datetime import datetime, timedelta def fetch_crypto_prices(api_url, retries=3): """ Fetches cryptocurrency prices from an alternative API with retry mechanism. Args: - api_url (str): The URL of the API to fetch data from. - retries (int): The number of retries for failed requ...
import pytest from unittest.mock import patch from solution import fetch_crypto_prices, calculate_average_price, display_prices def test_fetch_crypto_prices_success(): with patch('requests.get') as mock_get: mock_response = mock_get.return_value mock_response.status_code = 200 mock_response...
[ { "docstring": "Fetches cryptocurrency prices from an alternative API with retry mechanism.\n\nArgs:\n- api_url (str): The URL of the API to fetch data from.\n- retries (int): The number of retries for failed requests.\n\nReturns:\n- dict: A dictionary containing the cryptocurrency prices and historical data.",...
[ 1, 0, 0, 1, 0, 0, 0, 0, 1 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nfrom datetime import datetime, timedelta\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\ndef fetch_crypto_prices(api_url, retry_li...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000029791", "row_id": 29791, "seed_ids": "[2421]" }
0.405784
Algorithm_29791
I
[ "fetch_crypto_prices", "calculate_average_price", "display_prices" ]
3
[ [ "display_prices", "calculate_average_price" ], [ "display_prices", "fetch_crypto_prices" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
c88ed525d29b456e73bc07417bb759101fdef627
52077445c2fd30a5eff8966995803937a8ffd6dd
v1.0
instruct
Algorithm
Algorithm_29882_I
### Decision Tree Classifier Implementation with Pruning #### Context As a data scientist at a financial institution, you are tasked with predicting whether a loan application will be approved (1) or rejected (0) based on applicant data. You choose to implement a Decision Tree classifier from scratch to perform this b...
import numpy as np class TreeNode: def __init__(self, gini, num_samples, num_samples_per_class, predicted_class): self.gini = gini self.num_samples = num_samples self.num_samples_per_class = num_samples_per_class self.predicted_class = predicted_class self.feature_index = 0 ...
import numpy as np from solution import decision_tree_classifier def test_simple_decision_tree(): X = np.array([[1, 2], [1, 3], [2, 3], [3, 2], [3, 3], [2, 2], [7, 8], [8, 7], [7, 7], [8, 8]]) y = np.array([0, 0, 1, 1, 1, 0, 1, 1, 1, 0]) X_val = np.array([[3, 3], [2, 3], [8, 8], [1, 2], [7, 7]]) y_val ...
[]
[ 0, 0, 1, 0, 1, 0, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\nclass TreeNode:\n def __init__(self, gini=None, samples=None, value=None, feature_index=None, threshold=None, left=None, right=None):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000029882", "row_id": 29882, "seed_ids": "[503]" }
0.569596
Algorithm_29882
I
[ "gini_impurity", "grow_tree", "best_split", "prune_tree", "predict_tree", "single_predict", "accuracy_score", "decision_tree_classifier" ]
8
[ [ "decision_tree_classifier", "accuracy_score" ], [ "decision_tree_classifier", "grow_tree" ], [ "decision_tree_classifier", "predict_tree" ], [ "decision_tree_classifier", "prune_tree" ], [ "grow_tree", "best_split" ], [ "grow_tree", "gini_impurit...
9
[]
false
[ "TreeNode" ]
true
pytest
true
[ "numpy" ]
false
5346d207e261ce9ffcfeb1fa9f9f85e92a563d0e
8d7c8e733309d2966f4f5529b18b67c7607e181d
v1.0
instruct
Algorithm
Algorithm_29893_I
File Content Hashing You are required to implement functions that calculate the MD5 hash of a file and compare the hashes of multiple files to find duplicates. Your implementation should include the following methods: 1. **calculate_md5_hash()**: Computes the MD5 hash for a single file. 2. **find_duplicate_files()**:...
import hashlib from typing import List, Dict def calculate_md5_hash(file_path: str) -> str: """ Compute the MD5 hash for a given file. Parameters: file_path (str): The path to the file. Returns: str: The MD5 hash of the file content as a hexadecimal string. """ md5_hash = hash...
from solution import calculate_md5_hash, find_duplicate_files import tempfile import os def create_temp_files(file_contents): """ Helper function to create temporary files with given contents. Parameters: file_contents (List[str]): List of strings for file contents. Returns: List[...
[ { "docstring": "Compute the MD5 hash for a given file.\n\nParameters:\n file_path (str): The path to the file.\n\nReturns:\n str: The MD5 hash of the file content as a hexadecimal string.", "function_declaration": "def calculate_md5_hash(file_path):", "function_name": "calculate_md5_hash", "pa...
[ 1, 0, 1, 1, 1, 1, 0, 1, 0 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import hashlib\nfrom typing import List\n\ndef calculate_md5_hash(file_path: str) -> str:\n \"\"\"\n Computes the MD5 hash for a single file.\n \"\"\"\n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000029893", "row_id": 29893, "seed_ids": "[1172]" }
0.848373
Algorithm_29893
I
[ "calculate_md5_hash", "find_duplicate_files" ]
2
[ [ "find_duplicate_files", "calculate_md5_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
299b2451052c6ddf3ad061c9f325dbef89852389
00d6166daed79c2bbd8ca54f3d6e1566211ddf02
v1.0
instruct
Algorithm
Algorithm_29895_I
**Data Analysis on Student Records** As part of a student information management system, you are tasked to develop a set of data analysis functions to handle student records. Each student record includes details such as student ID, name, scores across multiple subjects, and their attendance percentage. **Objective:**...
from typing import List, Dict, Any def calculate_average_scores(records: List[Dict[str, Any]]) -> Dict[str, float]: """ Calculates the average score for each student across all subjects. Args: records: List of student records, where each record is a dictionary. Returns: A ...
def test_calculate_average_scores(): records = [ {"student_id": "S1", "scores": {"math": 90, "science": 80, "english": 85}}, {"student_id": "S2", "scores": {"math": 70, "science": 75, "english": 65}}, ] expected = {"S1": 85.00, "S2": 70.00} assert calculate_average_scores(records) == exp...
[ { "docstring": "Calculates the average score for each student across all subjects.\n\nArgs:\n records: List of student records, where each record is a dictionary.\n \nReturns:\n A dictionary mapping student IDs to their average scores.", "function_declaration": "def calculate_average_scores(records...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Tuple\n\ndef calculate_average_scores(records: List[Dict[str, any]]) -> Dict[str, float]:\n average_scores = {}\n for record...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000029895", "row_id": 29895, "seed_ids": "[4303]" }
0.661455
Algorithm_29895
I
[ "calculate_average_scores", "classify_attendance", "top_performers", "failed_subjects", "calculate_grade" ]
5
[ [ "calculate_grade", "calculate_average_scores" ], [ "top_performers", "calculate_average_scores" ] ]
2
[]
false
[]
false
pytest
false
[]
true
514d5a8d38036708fab62755fe310cc3d9d75171
90ad6504b6413eb725ddee9b84071e872eaee19f
v1.0
instruct
Algorithm
Algorithm_29987_I
### Question: #### Context: You are tasked with creating a feature for a text editor that helps users find and correct common misspellings. Specifically, you need to correct words based on a given dictionary of correct words. #### Task: Implement a function `correct_misspellings(text: str, dictionary: List[str]) -> s...
from typing import List import difflib def find_most_similar(word: str, dictionary: List[str]) -> str: # Use difflib.get_close_matches to find the closest match from the dictionary matches = difflib.get_close_matches(word, dictionary, n=1, cutoff=0.0) if matches: return matches[0] else: ...
from solution import correct_misspellings def test_correct_misspellings_basic(): assert correct_misspellings("Ths is a smple txt", ["This", "is", "a", "simple", "text"]) == "This is a simple text" def test_correct_misspellings_hello_world(): assert correct_misspellings("Helo wrld", ["Hello", "world"]) == "Hel...
[ { "docstring": null, "function_declaration": "def find_most_similar(word, dictionary):", "function_name": "find_most_similar", "parameter_list": "(word, dictionary)" }, { "docstring": null, "function_declaration": "def correct_misspellings(text, dictionary):", "function_name": "corre...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport difflib\n\ndef find_most_similar(word: str, dictionary: List[str]) -> str:\n \"\"\"\n Find the most similar word in the dic...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000029987", "row_id": 29987, "seed_ids": "[3690]" }
0.681367
Algorithm_29987
I
[ "find_most_similar", "correct_misspellings" ]
2
[ [ "correct_misspellings", "find_most_similar" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aec0af81af505512a6f185edf710d2a2c5fc60b1
c383a7344acbf2a1c984d494e8ca3e341358947c
v1.0
instruct
Algorithm
Algorithm_29992_I
### Question You are given two functions, `merge_sorted_iterative` and `merge_sorted_recursive`, which merge two sorted lists of numbers into a single sorted list using iterative and recursive methods respectively. However, to handle more complex real-world scenarios, another useful function is merging multiple sorted ...
def merge_two_sorted_lists(l1, l2): result = [] i, j = 0, 0 while i < len(l1) and j < len(l2): if l1[i] < l2[j]: result.append(l1[i]) i += 1 else: result.append(l2[j]) j += 1 result.extend(l1[i:]) result.extend(l2[j:]) return result...
def test_merge_k_sorted(): assert merge_k_sorted([[1, 4, 5], [1, 3, 4], [2, 6]]) == [1, 1, 2, 3, 4, 4, 5, 6] assert merge_k_sorted([[], [1], [2, 5, 8]]) == [1, 2, 5, 8] assert merge_k_sorted([[10, 15, 30], [5, 6, 6], [1, 2, 3]]) == [1, 2, 3, 5, 6, 6, 10, 15, 30] assert merge_k_sorted([[]]) == [] ass...
[ { "docstring": null, "function_declaration": "def merge_two_sorted_lists(l1, l2):", "function_name": "merge_two_sorted_lists", "parameter_list": "(l1, l2)" }, { "docstring": null, "function_declaration": "def merge_k_sorted(lists):", "function_name": "merge_k_sorted", "parameter_...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_two_lists(l1, l2):\n \"\"\"Helper function to merge two sorted lists\"\"\"\n merged = []\n i, j = 0, 0\n while i < len(l1) and j < len(l2):...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000029992", "row_id": 29992, "seed_ids": "[3543]" }
0.562304
Algorithm_29992
I
[ "merge_two_sorted_lists", "merge_k_sorted" ]
2
[ [ "merge_k_sorted", "merge_two_sorted_lists" ] ]
1
[]
false
[]
false
pytest
false
[]
true
a1aa51bc43e1ca2bc53e4136e779683750eb738f
429f4c45053f0b1fe21f181d4c386d1f8df7df55
v1.0
instruct
Algorithm
Algorithm_30018_I
### Date Formatting and Validation **Context**: In software development, handling dates is a common requirement. Ensuring that dates are correctly formatted and valid is crucial to avoid errors in applications. The European date format typically used is `DD/MM/YYYY`. **Task**: Write a function `validate_date_format...
def validate_date_format(date_str): if not isinstance(date_str, str) or len(date_str) != 10: return False if date_str[2] != '/' or date_str[5] != '/': return False try: day, month, year = map(int, date_str.split('/')) except ValueError: return False if not ...
def test_validate_date_format(): # Test valid leap year dates assert validate_date_format("29/02/2020") == True # Leap year assert validate_date_format("28/02/2021") == True # Not a leap year # Test invalid February dates assert validate_date_format("30/02/2021") == False # February never has 30 ...
[ { "docstring": null, "function_declaration": "def validate_date_format(date_str):", "function_name": "validate_date_format", "parameter_list": "(date_str)" }, { "docstring": null, "function_declaration": "def is_leap_year(year):", "function_name": "is_leap_year", "parameter_list"...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def validate_date_format(date_str: str) -> bool:\n \"\"\"\n Validates if the provided date string is in DD/MM/YYYY format and represents a real date.\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000030018", "row_id": 30018, "seed_ids": "[2720]" }
0.849209
Algorithm_30018
I
[ "validate_date_format", "is_leap_year" ]
2
[ [ "validate_date_format", "is_leap_year" ] ]
1
[]
false
[]
false
pytest
false
[]
true
c33ab252b2aac465536cf32ada7b51ec44c54c10
1da521d44912d04eabd3a48bb56146a240617aa7
v1.0
instruct
Algorithm
Algorithm_30137_I
### Problem Statement You are a software developer for a travel application, and you need to implement a function that determines the optimal order to visit a series of attractions in a single day while minimizing travel time. The app provides distances between pairs of attractions. ### Function Specification **Funct...
from itertools import permutations def get_distance(start, end, distances): """ Get the distance between start and end points from the distances dictionary. It assumes that the distances are symmetric. """ if (start, end) in distances: return distances[(start, end)] else: return...
from solution import optimal_attraction_order def test_optimal_order_example(): start = "Home" attractions = ["Museum", "Park", "Zoo"] distances = { ("Home", "Museum"): 10, ("Home", "Park"): 20, ("Home", "Zoo"): 15, ("Museum", "Park"): 25, ("Museum", "Zoo"): 10, ...
[ { "docstring": "Get the distance between start and end points from the distances dictionary.\nIt assumes that the distances are symmetric.", "function_declaration": "def get_distance(start, end, distances):", "function_name": "get_distance", "parameter_list": "(start, end, distances)" }, { "...
[ 0, 1, 0, 0, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef optimal_attraction_order(start, attractions, distances):\n \"\"\"\n Determines the optimal order to visit the att...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000030137", "row_id": 30137, "seed_ids": "[330]" }
0.654622
Algorithm_30137
I
[ "get_distance", "optimal_attraction_order" ]
2
[ [ "optimal_attraction_order", "get_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
68853b21af3c32846c613fb93a70e7e23580c230
4890277c3392bc9a02445a9c72eaf63302a724e6
v1.0
instruct
Algorithm
Algorithm_30144_I
### String Matching with Knuth-Morris-Pratt Algorithm In various text processing and data analysis applications, efficiently finding occurrences of a pattern in a given text is crucial. One effective way to achieve this is by utilizing the Knuth-Morris-Pratt (KMP) algorithm. Your task is to implement a function that ...
from typing import List def compute_lps(pattern: str) -> List[int]: """ Computes the Longest Prefix Suffix (LPS) array for the given pattern. LPS array is used to avoid matching the characters that we know will anyway match. """ lps = [0] * len(pattern) length = 0 # Length of the previous long...
from solution import find_pattern def test_find_pattern_example(): text = "ababcabcabababd" pattern = "ababd" assert find_pattern(text, pattern) == [10] def test_find_pattern_no_occurrence(): text = "abcdefgh" pattern = "xyz" assert find_pattern(text, pattern) == [] def test_find_pattern_mult...
[ { "docstring": "Computes the Longest Prefix Suffix (LPS) array for the given pattern.\nLPS array is used to avoid matching the characters that we know will anyway match.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { ...
[ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_pattern(text: str, pattern: str) -> List[int]:\n \"\"\"\n Implements the Knuth-Morris-Pratt (KMP) algorithm to find all...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000030144", "row_id": 30144, "seed_ids": "[3614]" }
0.601913
Algorithm_30144
I
[ "compute_lps", "find_pattern" ]
2
[ [ "find_pattern", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
661e2f30457011f27772414c029cca3778b24235
607b84d0681d7100ae28956a8f9b6fade46716a1
v1.0
instruct
Algorithm
Algorithm_30168_I
### Coding Challenge In computational geometry, calculating the intersection of two line segments is a common task. You are provided with a function template to determine if two line segments in a 2D plane intersect. #### Objective Your task is to implement a function `do_segments_intersect` that takes the coordinate...
from typing import Tuple def orientation(p: Tuple[float, float], q: Tuple[float, float], r: Tuple[float, float]) -> int: val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) if val == 0: return 0 # collinear return 1 if val > 0 else 2 # clock or counterclock wise def on_segment(p...
def test_do_segments_intersect(): # Segments intersect assert do_segments_intersect(((1.0, 1.0), (4.0, 4.0)), ((1.0, 4.0), (4.0, 1.0))) == True # Segments do not intersect assert do_segments_intersect(((1.0, 1.0), (2.0, 2.0)), ((1.0, 2.0), (2.0, 3.0))) == False # Segments touch at endpoint...
[ { "docstring": null, "function_declaration": "def orientation(p, q, r):", "function_name": "orientation", "parameter_list": "(p, q, r)" }, { "docstring": null, "function_declaration": "def on_segment(p, q, r):", "function_name": "on_segment", "parameter_list": "(p, q, r)" }, ...
[ 1, 0, 1, 1, 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": "from typing import Tuple\n\ndef orientation(p: Tuple[float, float], q: Tuple[float, float], r: Tuple[float, float]) -> int:\n val = (q[1] - p[1]) * (r[0] - q[...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000030168", "row_id": 30168, "seed_ids": "[3759]" }
0.585292
Algorithm_30168
I
[ "orientation", "on_segment", "do_segments_intersect" ]
3
[ [ "do_segments_intersect", "on_segment" ], [ "do_segments_intersect", "orientation" ] ]
2
[]
false
[]
false
pytest
false
[]
true
a054e0d1cb0d28b6fe0b9c524b948d25ffd9dc8a
a1bbab1421cfba7a6e83bac10ddee90b48d64e02
v1.0
instruct
Algorithm
Algorithm_30272_I
### Question Title: Vehicle Path Prediction Based on GPS Coordinates ### Question Description In this task, you are required to write a program that predicts the future trajectory of a vehicle based on its past GPS coordinates. You will receive sequences of GPS points with timestamps and will need to extrapolate futu...
import numpy as np def linear_regression_fit(timestamps, coordinates): slope, intercept = np.polyfit(timestamps, coordinates, 1) return slope, intercept def predict_future_path(past_points, future_timesteps): if len(past_points) < 2: raise ValueError("At least two past points are required for line...
from solution import predict_future_path def test_predict_future_path_case1(): past_points = [ (37.7749, -122.4194, 1609459200), (37.7750, -122.4195, 1609459260) ] future_timesteps = [1609459320, 1609459380] predicted_path = predict_future_path(past_points, future_timesteps) as...
[ { "docstring": null, "function_declaration": "def linear_regression_fit(timestamps, coordinates):", "function_name": "linear_regression_fit", "parameter_list": "(timestamps, coordinates)" }, { "docstring": null, "function_declaration": "def predict_future_path(past_points, future_timeste...
[ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\ndef predict_future_path(\n past_points: List[Tuple[fl...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000030272", "row_id": 30272, "seed_ids": "[5043]" }
0.558732
Algorithm_30272
I
[ "linear_regression_fit", "predict_future_path" ]
2
[ [ "predict_future_path", "linear_regression_fit" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
8d23ed635541bec4776d4e06f0dcef45ad711c36
372d59ec16b89b416541b00ace4ca24247874084
v1.0
instruct
Algorithm
Algorithm_30339_I
### CODING ASSESSMENT QUESTION #### Introduction You are a software developer working on a productivity tool that calculates the average reading time of articles based on their word count. The average reading speed of a person is approximately 200 words per minute. You need to implement two functions to compute the re...
def calculate_reading_time(word_count: int) -> float: if not isinstance(word_count, int) or word_count <= 0: raise ValueError("Word count must be a positive integer") return word_count / 200 def format_reading_time(word_count: int) -> str: if not isinstance(word_count, int) or word_count <= 0: ...
from solution import calculate_reading_time, format_reading_time import pytest def test_calculate_reading_time_valid_input(): assert calculate_reading_time(1000) == 5.0 assert calculate_reading_time(450) == 2.25 assert calculate_reading_time(200) == 1.0 def test_calculate_reading_time_invalid_input(): ...
[ { "docstring": null, "function_declaration": "def calculate_reading_time(word_count):", "function_name": "calculate_reading_time", "parameter_list": "(word_count)" }, { "docstring": null, "function_declaration": "def format_reading_time(word_count):", "function_name": "format_reading...
[ 1, 1, 0, 1, 1, 1, 0, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def calculate_reading_time(word_count: int) -> float:\n \"\"\"\n Returns the estimated reading time in minutes based on the word count.\n \n Args:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000030339", "row_id": 30339, "seed_ids": "[1100]" }
0.52211
Algorithm_30339
I
[ "calculate_reading_time", "format_reading_time" ]
2
[ [ "format_reading_time", "calculate_reading_time" ] ]
1
[]
false
[]
false
pytest
true
[]
true
80962941f8b9e9889b68fc35cb8a74f09bd81bfc
286d346315d55e9869428d76c1025269149e46e1
v1.0
instruct
Algorithm
Algorithm_30358_I
### Coding Challenge: Digit Sum and Query #### Context: You have been tasked with implementing a set of functions that deal with digit sums and their properties. These operations are useful in digital root calculations, checksum algorithms, and other numeric applications. Implement these functions efficiently to handl...
def digit_sum(n: int) -> int: """ Returns the sum of the digits of the given number n. """ return sum(int(digit) for digit in str(n)) def range_digit_sum(start: int, end: int) -> int: """ Returns the sum of digit sums for all numbers in the range [start, end]. """ total_sum = 0 for ...
def test_digit_sum_single_digit(): assert digit_sum(5) == 5 def test_digit_sum_multiple_digits(): assert digit_sum(12345) == 15 def test_digit_sum_large_number(): assert digit_sum(9876543210) == 45 def test_range_digit_sum_small_range(): assert range_digit_sum(10, 12) == 6 # digit_sum(10) + digit_su...
[ { "docstring": "Returns the sum of the digits of the given number n.", "function_declaration": "def digit_sum(n):", "function_name": "digit_sum", "parameter_list": "(n)" }, { "docstring": "Returns the sum of digit sums for all numbers in the range [start, end].", "function_declaration": ...
[ 1, 0, 1, 1, 1, 1, 0, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def digit_sum(n: int) -> int:\n \"\"\"\n Returns the sum of the digits of the given number n.\n \"\"\"\n return sum(int(digit) for digit in str(n))\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000030358", "row_id": 30358, "seed_ids": "[4272]" }
0.686671
Algorithm_30358
I
[ "digit_sum", "range_digit_sum" ]
2
[ [ "range_digit_sum", "digit_sum" ] ]
1
[]
false
[]
false
pytest
false
[]
true
625e811624ed67a1617a1b82fac4e271865a147c
f4727db1619b68fb0a95c512df0bfe0bb89f2682
v1.0
instruct
Algorithm
Algorithm_30424_I
### Implementing the K-Nearest Neighbors (KNN) Algorithm for Classification **Context**: You are provided with a dataset that includes different species of flowers characterized by features such as petal length, petal width, sepal length, and sepal width. Your task is to implement the K-Nearest Neighbors algorithm fro...
import numpy as np import pandas as pd from collections import Counter from sklearn.metrics import confusion_matrix def load_and_split_dataset(url, test_size): """ Load dataset from the given URL and split into training and testing set. Parameters: url (str): URL of the CSV dataset test_size (floa...
import pandas as pd import numpy as np from solution import load_and_split_dataset, euclidean_distance, predict_classification, knn, calculate_accuracy # Create a mock dataset for testing data = { 'sepal_length': [5.1, 4.9, 4.7, 4.6, 5.0], 'sepal_width': [3.5, 3.0, 3.2, 3.1, 3.6], 'petal_length': [1.4, 1.4...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\nfrom collections import Counter\nfrom sklearn.metrics import confusion_matrix\n\ndef load_and_split_dataset(url, test_si...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000030424", "row_id": 30424, "seed_ids": "[786]" }
0.605592
Algorithm_30424
I
[ "load_and_split_dataset", "euclidean_distance", "predict_classification", "knn", "calculate_accuracy", "main" ]
6
[ [ "knn", "predict_classification" ], [ "predict_classification", "euclidean_distance" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
993cf0bf3636c02be487f42541cd55db42cab39d
569bab3a6308369bcd2a6bcf3ba3844015b57815
v1.0
instruct
Algorithm
Algorithm_30462_I
### Stock Price Analyzer You have been provided with a function that fetches historical stock prices for the company of your choice from a mock API. The task is to enhance the functionality to compute various stock metrics. ## Requirements 1. **Function Implementation**: - Implement a function `stock_analysis(api...
import requests import statistics from datetime import datetime def fetch_stock_data(api_url: str, ticker_symbol: str, start_date: str, end_date: str) -> list: """ Fetch stock data from the mock API. """ params = { 'ticker': ticker_symbol, 'start': start_date, 'end': end_date ...
import pytest from unittest.mock import patch from solution import fetch_stock_data, stock_analysis fake_api_url = "https://api.mockstockdata.com/historical" fake_ticker = "AAPL" fake_start_date = "2021-01-01" fake_end_date = "2021-12-31" fake_data = [ {"date": "2021-01-01", "open": 130.0, "close": 132.0, "high"...
[ { "docstring": "Fetch stock data from the mock API.", "function_declaration": "def fetch_stock_data(api_url, ticker_symbol, start_date, end_date):", "function_name": "fetch_stock_data", "parameter_list": "(api_url, ticker_symbol, start_date, end_date)" }, { "docstring": "Fetches stock prices...
[ 0, 1, 0, 1, 1, 0, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nimport statistics\nfrom datetime import datetime\n\ndef fetch_stock_data(api_url: str, ticker_symbol: str, start_date: str, end_date: str) -> di...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000030462", "row_id": 30462, "seed_ids": "[2420]" }
0.610472
Algorithm_30462
I
[ "fetch_stock_data", "stock_analysis" ]
2
[ [ "stock_analysis", "fetch_stock_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
96fee251538806352fafe91b8bcdf4184095a61f
31f4f44ad9e6795fbac27d24d3d052834b27c60b
v1.0
instruct
Algorithm
Algorithm_30482_I
**Problem Statement**: You are required to implement a simple spell checker for an English language file using the Damerau-Levenshtein distance algorithm. This algorithm calculates the minimum number of operations (insertions, deletions, substitutions, and transpositions) needed to transform one string into another. W...
import numpy as np def damerau_levenshtein_distance(s1, s2): """ Calculate the Damerau-Levenshtein distance between two strings s1 and s2. """ d = np.zeros((len(s1) + 1, len(s2) + 1), dtype=int) d[0] = np.arange(len(s2) + 1) d[:, 0] = np.arange(len(s1) + 1) for i in range(1, len(s...
def test_damerau_levenshtein_distance(): assert damerau_levenshtein_distance("helo", "hello") == 1 assert damerau_levenshtein_distance("helo", "world") == 4 assert damerau_levenshtein_distance("helo", "helo") == 0 assert damerau_levenshtein_distance("abcd", "acbd") == 1 def test_spell_check(tmp_path): ...
[ { "docstring": "Calculate the Damerau-Levenshtein distance between two strings s1 and s2.", "function_declaration": "def damerau_levenshtein_distance(s1, s2):", "function_name": "damerau_levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": "Checks and corrects the spelling o...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import os\nfrom collections import defaultdict\nfrom Levenshtein import damerau_levenshtein_distance as dld\n\ndef spell_check(file_path, dictionary_path):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "0000030482", "row_id": 30482, "seed_ids": "[4289]" }
0.603334
Algorithm_30482
I
[ "damerau_levenshtein_distance", "spell_check" ]
2
[ [ "spell_check", "damerau_levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
false
[ "numpy" ]
false
dd4ca2ab4822de48397cc90b675de52deb1bd0d2
0b002da2ebd4fc52d7b8a098a12a7e94d5e0d65b
v1.0
instruct
Algorithm
Algorithm_30519_I
### Problem Statement Given a string `s` containing only lowercase English letters, you are required to implement a function that generates all possible distinct palindromic substrings of `s`. A palindromic substring is defined as a substring that reads the same forwards and backwards. ### Function Signature ```pytho...
def is_palindrome(sub: str) -> bool: return sub == sub[::-1] def find_palindromic_substrings(s: str): palindromes = set() n = len(s) for i in range(n): for j in range(i, n): sub = s[i:j+1] if is_palindrome(sub): palindromes.add(sub) return s...
from solution import find_palindromic_substrings def test_empty_string(): assert find_palindromic_substrings("") == [] def test_single_character(): assert find_palindromic_substrings("a") == ["a"] def test_distinct_characters(): assert find_palindromic_substrings("abc") == ["a", "b", "c"] def test_repea...
[ { "docstring": null, "function_declaration": "def is_palindrome(sub):", "function_name": "is_palindrome", "parameter_list": "(sub)" }, { "docstring": null, "function_declaration": "def find_palindromic_substrings(s):", "function_name": "find_palindromic_substrings", "parameter_li...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_palindromic_substrings(s: str) -> List[str]:\n def is_palindrome(sub: str) -> bool:\n return sub == sub[::-1]\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000030519", "row_id": 30519, "seed_ids": "[4205]" }
0.760722
Algorithm_30519
I
[ "is_palindrome", "find_palindromic_substrings" ]
2
[ [ "find_palindromic_substrings", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0085ffe1c71ace538bbbd96c9c78fad7e4b2881
b066ebc5ea965d53d01d135ba2dd9ff8640a2853
v1.0
instruct
Algorithm
Algorithm_30535_I
### Matrix Rotation by Specified Angle #### Context: Rotating a matrix is a common operations in many applications including graphics and image processing. The task involves rotating a 2D matrix by a given angle which can be 90, 180, or 270 degrees clockwise. #### Task: Implement a `rotate_matrix` function that rotat...
def rotate_matrix_90(matrix): n = len(matrix) return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)] def rotate_matrix_180(matrix): n = len(matrix) return [[matrix[n - i - 1][n - j - 1] for j in range(n)] for i in range(n)] def rotate_matrix_270(matrix): n = len(matrix) return [[m...
from solution import rotate_matrix def test_rotate_matrix_90(): assert rotate_matrix([[1, 2], [3, 4]], 90) == [[3, 1], [4, 2]] assert rotate_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 90) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]] def test_rotate_matrix_180(): assert rotate_matrix([[1, 2], [3, 4]], 180) == [[4, ...
[ { "docstring": null, "function_declaration": "def rotate_matrix_90(matrix):", "function_name": "rotate_matrix_90", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def rotate_matrix_180(matrix):", "function_name": "rotate_matrix_180", "parameter_list"...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rotate_matrix_90(matrix):\n \"\"\"\n Rotates the given NxN matrix by 90 degrees clockwise.\n \"\"\"\n return [list(row) for row in zip(*matrix[::...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000030535", "row_id": 30535, "seed_ids": "[1112]" }
0.577133
Algorithm_30535
I
[ "rotate_matrix_90", "rotate_matrix_180", "rotate_matrix_270", "rotate_matrix" ]
4
[ [ "rotate_matrix", "rotate_matrix_180" ], [ "rotate_matrix", "rotate_matrix_270" ], [ "rotate_matrix", "rotate_matrix_90" ] ]
3
[]
false
[]
false
pytest
true
[]
true
49ab869bfa0be64e87443483ad86a91de7af067c
ea11854515469946af0ea4cd93f23412028ac193
v1.0
instruct
Algorithm
Algorithm_30551_I
### Problem Statement You are working on data validation functions for a contact management system. The following tasks require your attention: 1. **Validate Email Addresses**: Write a function named `is_valid_email` that takes a string as input and returns a boolean indicating whether the email address is valid....
import re def is_valid_email(email: str) -> bool: """ Validates if the input string is a valid email address. Args: email (str): email address to validate. Returns: bool: True if the email is valid, False otherwise. Raises: ValueError: If the input is not a string or is a...
import pytest from solution import is_valid_email, extract_domain def test_is_valid_email_valid_cases(): assert is_valid_email("test@example.com") == True assert is_valid_email("user@domain.co") == True assert is_valid_email("user.name@sub.domain.co") == True def test_is_valid_email_invalid_cases(): a...
[ { "docstring": "Validates if the input string is a valid email address.\n\nArgs:\nemail (str): email address to validate.\n\nReturns:\nbool: True if the email is valid, False otherwise.\n\nRaises:\nValueError: If the input is not a string or is an empty string.", "function_declaration": "def is_valid_email(...
[ 1, 0, 1, 1, 0, 1, 0, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef is_valid_email(email: str) -> bool:\n \"\"\"\n Validates an email address based on the given criteria.\n \n Args:\n email: A stri...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000030551", "row_id": 30551, "seed_ids": "[3575]" }
0.596242
Algorithm_30551
I
[ "is_valid_email", "extract_domain" ]
2
[ [ "extract_domain", "is_valid_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c6ad2a73f7472a24b8f69f205d6fedc68fa6dc55
70b1731d7e36dd3e0f389b6051c6bc74ea6f24db
v1.0
instruct
Algorithm
Algorithm_30586_I
### Problem: Implement a Function to Compute the Carmichael Function Given a positive integer `n`, write a function `carmichael_lambda(n: int) -> int` that computes the Carmichael function (also known as the reduced totient function). The function should return the smallest positive integer `m` such that `a^m ≡ 1 (mod...
from math import gcd from functools import reduce def lcm(a, b): return abs(a * b) // gcd(a, b) def prime_factors(n): factors = {} d = 2 while d * d <= n: while (n % d) == 0: if d in factors: factors[d] += 1 else: factors[d] = 1 ...
import pytest from solution import carmichael_lambda def test_carmichael_lambda(): # Base cases assert carmichael_lambda(1) == 1 # Small primes assert carmichael_lambda(7) == 6 assert carmichael_lambda(3) == 2 # Powers of two assert carmichael_lambda(4) == 2 assert carmichael_...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": null, ...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import gcd\nfrom functools import reduce\n\ndef lcm(a, b):\n \"\"\"Compute the least common multiple of a and b.\"\"\"\n return abs(a * b) // gcd...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000030586", "row_id": 30586, "seed_ids": "[3228]" }
0.59865
Algorithm_30586
I
[ "lcm", "prime_factors", "carmichael_lambda" ]
3
[ [ "carmichael_lambda", "lcm" ], [ "carmichael_lambda", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3ee0f391bfb637fbc6315fd5b675dfe4af202795
af10c91373e926bd2b159fd938836d0a889e690b
v1.0
instruct
Algorithm
Algorithm_30692_I
### Problem Statement Write a function that parses a given log file containing multiple lines of log entries and extracts the IP addresses that accessed the system. The function should return a list of unique IP addresses in the order they first appeared in the log file. Consider all entries that contain an IP address ...
import re def extract_unique_ips(log: str) -> list[str]: """ Extracts unique IP addresses from the log and returns them in the order they first appeared. """ ip_pattern = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') unique_ips = [] seen_ips = set() for line in log.splitlines(): ...
from solution import extract_unique_ips def test_extract_unique_ips_basic(): log_data = """ 2023-03-15 10:15:42 INFO - Connection from 192.168.1.1 2023-03-15 10:15:43 WARNING - Failed login attempt from 10.0.0.1 2023-03-15 10:15:44 INFO - Connection from 192.168.1.1 2023-03-15 10:16:00 ERROR - Conn...
[ { "docstring": "Extracts unique IP addresses from the log and returns them in the order they first appeared.", "function_declaration": "def extract_unique_ips(log):", "function_name": "extract_unique_ips", "parameter_list": "(log)" }, { "docstring": "Validates if a given IP address is a vali...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef extract_unique_ips(log: str) -> list[str]:\n \"\"\"\n Parses a given log file string and extracts unique IP addresses in the order \n t...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000030692", "row_id": 30692, "seed_ids": "[3879]" }
0.683813
Algorithm_30692
I
[ "extract_unique_ips", "valid_ip" ]
2
[ [ "extract_unique_ips", "valid_ip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3bde592c4dab6ae7fff7bf1a392ad59b47df5da2
d6887086f84e3002f9e915f2f63428829d1cf046
v1.0
instruct
Algorithm
Algorithm_30712_I
### Problem Statement You are tasked with implementing a simple text-based card game where a player tries to guess whether the next card in a deck will be higher or lower than the current card. ### Requirements 1. **Deck Initialization**: Initialize a standard 52-card deck. 2. **Card Display**: Display the current ca...
import random # Initialize rank and suits RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] def initialize_deck(): """Initialize and return a shuffled 52-card deck.""" deck = [{'rank': rank, 'suit': suit} for suit in SUITS ...
import pytest from solution import initialize_deck, card_value, display_card def test_initialize_deck(): deck = initialize_deck() assert len(deck) == 52 # Test if all cards are unique all_cards = {(card['rank'], card['suit']) for card in deck} assert len(all_cards) == 52 def test_card_value(): ...
[ { "docstring": "Initialize and return a shuffled 52-card deck.", "function_declaration": "def initialize_deck():", "function_name": "initialize_deck", "parameter_list": "()" }, { "docstring": "Return the value of a card for comparison.", "function_declaration": "def card_value(card):", ...
[ 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
7
easy
0.778
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\n\ndef initialize_deck():\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']\n suits = ['Hearts', 'Diam...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "0000030712", "row_id": 30712, "seed_ids": "[3951]" }
0.609442
Algorithm_30712
I
[ "initialize_deck", "card_value", "display_card", "play_high_low_game" ]
4
[ [ "play_high_low_game", "card_value" ], [ "play_high_low_game", "display_card" ], [ "play_high_low_game", "initialize_deck" ] ]
3
[]
false
[]
false
pytest
true
[]
true
be2df1abfceb708485cbc4313ac6adba5728bbf5
a396ad32eb1f09f8366ee3928645f11588d4d13a
v1.0
instruct
Algorithm
Algorithm_30746_I
### Coding Assessment Question As a backend developer, you are tasked with improving the data processing flow of a weather forecasting application. This application fetches recent weather data from an external API and processes it to provide valuable insights to end-users. The main issues to address include handling v...
import time # Function to fetch weather data from an API def fetch_weather_data(location: str) -> dict[str, float | str]: """ Fetch weather data for a given location. This function simulates an API call to fetch weather data for the provided location. """ # This should be replaced with actual ...
import pytest from solution import fetch_weather_data, process_weather_data, get_cached_weather_data def test_fetch_weather_data(): expected = {"temperature": 15.4, "humidity": 70, "description": "Cloudy"} result = fetch_weather_data("New York") assert result == expected def test_process_weather_data(): ...
[ { "docstring": "Fetch weather data for a given location.\n\nThis function simulates an API call to fetch weather data for the provided location.", "function_declaration": "def fetch_weather_data(location):", "function_name": "fetch_weather_data", "parameter_list": "(location)" }, { "docstrin...
[ 0, 1, 1, 0, 0, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import requests\nfrom datetime import datetime, timedelta\n\n# Cache with expiry of 30 minutes\nCACHE_EXPIRY = timedelta(minutes=30)\ncache = {}\n\ndef fetch_wea...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000030746", "row_id": 30746, "seed_ids": "[2342]" }
0.510485
Algorithm_30746
I
[ "fetch_weather_data", "process_weather_data", "get_cached_weather_data" ]
3
[ [ "get_cached_weather_data", "fetch_weather_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3cfdb00a78a5d244839099f0ad21339420c26928
77a5b45f32b35d2b7415aca97acc28197c58bbe9
v1.0
instruct
Algorithm
Algorithm_30811_I
### Question: Log Analyzer for Web Server #### Objective: As a part of maintaining a web server, you are tasked with implementing a log analyzer. This analyzer should parse a given log file, extract specific information, and compute statistical information. The log file is in a standardized format (Common Log Format)....
import re def parse_log_entry(log_entry: str) -> dict: """ Parse a single log entry. Parameters: log_entry (str): A single line log entry in Common Log Format. Returns: dict: A dictionary with keys 'ip', 'timestamp', 'request_type', 'url', and 'status_code' containing extra...
from solution import parse_log_entry, parse_log_file, most_frequent_ip, error_rate def test_parse_log_entry(): log_entry = '127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326' result = parse_log_entry(log_entry) expected = { 'ip': '127.0.0.1', 'timestamp': '10...
[ { "docstring": "Parse a single log entry.\n\nParameters:\nlog_entry (str): A single line log entry in Common Log Format.\n\nReturns:\ndict: A dictionary with keys 'ip', 'timestamp', 'request_type', 'url', \n and 'status_code' containing extracted data.", "function_declaration": "def parse_log_entry(log...
[ 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef parse_log_entry(log_entry: str) -> dict:\n \"\"\"\n Parse a single log entry.\n \n Parameters:\n log_entry (str): A single line l...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "0000030811", "row_id": 30811, "seed_ids": "[5046]" }
0.681194
Algorithm_30811
I
[ "parse_log_entry", "parse_log_file", "most_frequent_ip", "error_rate" ]
4
[ [ "parse_log_file", "parse_log_entry" ] ]
1
[]
false
[]
false
pytest
true
[]
true
70aec5532cd826404658108c7ba71a679512d976
aa616b383e24f3fb989909026209a35f33e6a3e5
v1.0
instruct
Algorithm
Algorithm_30825_I
## Problem Statement You are given a list of cities and the distances between some pairs of these cities in a text file. Each line in the file represents a distance between two cities in the format `CityA,CityB,Distance`, where `CityA` and `CityB` are distinct city names, and `Distance` is a positive integer represent...
import itertools import math def parse_distances(filepath: str): distances = {} with open(filepath, 'r') as file: for line in file: cityA, cityB, dist = line.strip().split(',') dist = int(dist) if cityA not in distances: distances[cityA] = {} ...
def test_parse_distances(): from solution import parse_distances filepath = 'test_cities.txt' with open(filepath, 'w') as f: f.write("A,B,10\n") f.write("A,C,15\n") f.write("B,C,20\n") distances = parse_distances(filepath) assert distances == { 'A': {'B': 10, 'C': 15}...
[ { "docstring": null, "function_declaration": "def parse_distances(filepath):", "function_name": "parse_distances", "parameter_list": "(filepath)" }, { "docstring": null, "function_declaration": "def tsp(distances, start_city):", "function_name": "tsp", "parameter_list": "(distanc...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import itertools\nimport json\n\ndef parse_distances(filepath):\n distances = {}\n with open(filepath, 'r') as file:\n for line in file:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000030825", "row_id": 30825, "seed_ids": "[2026]" }
0.713045
Algorithm_30825
I
[ "parse_distances", "tsp", "shortest_route" ]
3
[ [ "shortest_route", "parse_distances" ], [ "shortest_route", "tsp" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ab00ecf70e7ea3677618561d55e69fd03073dc18
1123b32db5318919373dcee48cee5cbd75561138
v1.0
instruct
Algorithm
Algorithm_30881_I
### Matrix Column Mean You are given a matrix represented as a list of lists, where each sublist is a row of the matrix. Your task is to perform the following operations: 1. `column_means(matrix: List[List[float]]) -> List[float]`: This function computes the mean of each column in the matrix. 2. `scale_columns(matrix...
from typing import List, Tuple def column_means(matrix: List[List[float]]) -> List[float]: num_rows = len(matrix) num_cols = len(matrix[0]) means = [sum(matrix[row][col] for row in range(num_rows)) / num_rows for col in range(num_cols)] return means def scale_columns(matrix: List[List[float]], factors...
def test_column_means(): matrix = [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0] ] assert column_means(matrix) == [4.0, 5.0, 6.0] def test_scale_columns(): matrix = [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0] ] factors = [4.0, 5.0, 6....
[ { "docstring": null, "function_declaration": "def column_means(matrix):", "function_name": "column_means", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def scale_columns(matrix, factors):", "function_name": "scale_columns", "parameter_list": "(mat...
[ 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\n\ndef column_means(matrix: List[List[float]]) -> List[float]:\n \"\"\"\n Returns the mean of each column in the matrix.\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000030881", "row_id": 30881, "seed_ids": "[4108]" }
0.670468
Algorithm_30881
I
[ "column_means", "scale_columns", "compute_and_scale" ]
3
[ [ "compute_and_scale", "column_means" ], [ "compute_and_scale", "scale_columns" ] ]
2
[]
false
[]
false
pytest
false
[]
true
bac98f7edd9cf161559f70124da7a9bec6e3bc0e
2f0cd0cc3579b3687e88f8ee3744f9272d6d855f
v1.0
instruct
Algorithm
Algorithm_30947_I
### JSON Data Validator & Cleaner You are required to write a Python script that reads a JSON file containing product data, validates its structure, applies cleaning rules, and outputs a cleaned JSON file. Your task focuses on implementing functions for data validation, data cleaning, and file operations. #### Task R...
import json def load_json(file_path: str) -> list[dict]: with open(file_path, 'r') as file: return json.load(file) def validate_data(data: list[dict]) -> bool: required_fields = {"product_id", "name", "price", "quantity"} for entry in data: if not all(field in entry and entry[field] for fi...
import pytest from solution import load_json, validate_data, clean_data, save_json def test_validate_data(): valid_data = [ {"product_id": "12345", "name": "Product A", "price": "19.99", "quantity": "100"}, {"product_id": "67890", "name": "Product B", "price": "29.99", "quantity": "200"} ] ...
[ { "docstring": null, "function_declaration": "def load_json(file_path):", "function_name": "load_json", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def validate_data(data):", "function_name": "validate_data", "parameter_list": "(data)" }, ...
[ 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": "import json\n\ndef load_json(file_path: str) -> list[dict]:\n with open(file_path, 'r') as file:\n return json.load(file)\n\ndef validate_data(data: li...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "0000030947", "row_id": 30947, "seed_ids": "[4379]" }
0.611076
Algorithm_30947
I
[ "load_json", "validate_data", "is_float", "is_int", "clean_data", "save_json" ]
6
[ [ "validate_data", "is_float" ], [ "validate_data", "is_int" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bf4d428c1db415a4a6c32cdde8d7f2c303ab81f4
c2f17c21161e0ae0ab1d34c45a0ce268684ae4e3
v1.0
instruct
Algorithm
Algorithm_30978_I
### Question You are given an integer array `nums` of length `n`, which consists of positive integers, and an integer target `k`. Your task is to determine if there is a subarray within `nums` whose length is exactly `k` and the sum of its elements is a prime number. If such a subarray exists, return `True`, otherwise...
import math from typing import List def is_prime(number: int) -> bool: """ Checks if a number is a prime. """ 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 numb...
from solution import subarray_sum_is_prime def test_subarray_sum_is_prime_example(): assert subarray_sum_is_prime([2, 3, 5, 1, 6, 4, 7], 3) == True def test_subarray_sum_is_prime_no_prime_sum(): assert subarray_sum_is_prime([4, 6, 8, 10, 12], 2) == False def test_subarray_sum_is_prime_single_element_prime():...
[ { "docstring": "Checks if a number is a prime.", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Determines if there is a subarray of length k with a prime sum.", "function_declaration": "def subarray_sum_is_pr...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport math\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Determine if a number is prime.\n \"\"\"\n if n <= 1:\n retur...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000030978", "row_id": 30978, "seed_ids": "[5051]" }
0.644504
Algorithm_30978
I
[ "is_prime", "subarray_sum_is_prime" ]
2
[ [ "subarray_sum_is_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7f21d3354a83e2ca7f18ff43bf7d17453b1345e
e03aca8b1e3e8d8618a362923ff8d9b2b73717bb
v1.0
instruct
Algorithm
Algorithm_30993_I
### Description: You are given a sentence composed exclusively of words and spaces. Your task is to find and return the longest palindrome (a word that reads the same backward as forward) within the sentence. In case of ties (multiple words of the same maximum length), return the one which appears first in the sentence...
def is_palindrome(word: str) -> bool: """ Helper function to check if a given word is a palindrome. """ return word == word[::-1] def find_longest_palindromic_word(sentence: str) -> str: """ Returns the longest palindromic word in the given sentence. If no palindromic word is found, returns...
def test_is_palindrome(): assert is_palindrome("racecar") == True assert is_palindrome("level") == True assert is_palindrome("python") == False assert is_palindrome("a") == True assert is_palindrome("aa") == True def test_find_longest_palindromic_word(): assert find_longest_palindromic_word("ra...
[ { "docstring": "Helper function to check if a given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Returns the longest palindromic word in the given sentence.\nIf no palindromic word ...
[ 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 is_palindrome(word: str) -> bool:\n \"\"\"\n Helper function to check if a word is a palindrome.\n \"\"\"\n return word == word[::-1]\n\ndef find...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000030993", "row_id": 30993, "seed_ids": "[2779]" }
0.754213
Algorithm_30993
I
[ "is_palindrome", "find_longest_palindromic_word" ]
2
[ [ "find_longest_palindromic_word", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
false
[]
true
8f5a89ff200e0d79ed24fe98687c0121b61fbd72
5a84bad12fd9af0c3aad8b003541f43e34506721
v1.0
instruct
Algorithm
Algorithm_31181_I
## Coding Assessment Question You are tasked with designing a function that monitors the state of a web service and sends an alert through email when the service becomes unavailable. You will build a function based on the provided code snippet. ### Function Signature ```python def monitor_service(url: str, email: str...
import time import requests import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email_alert(to_email, subject, body): from_email = "alert@example.com" password = "password" # Placeholder: this should be securely managed msg = MIMEMultipart() msg...
import pytest from unittest.mock import patch, call from solution import monitor_service, send_email_alert @patch('solution.requests.get') @patch('solution.send_email_alert') def test_service_available(mock_send_email_alert, mock_requests_get): mock_requests_get.return_value.status_code = 200 with patch('time....
[ { "docstring": null, "function_declaration": "def send_email_alert(to_email, subject, body):", "function_name": "send_email_alert", "parameter_list": "(to_email, subject, body)" }, { "docstring": null, "function_declaration": "def monitor_service(url, email, check_interval):", "funct...
[ 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 requests\nimport smtplib\nimport time\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef monitor_service(url: st...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000031181", "row_id": 31181, "seed_ids": "[1904]" }
0.636414
Algorithm_31181
I
[ "send_email_alert", "monitor_service" ]
2
[ [ "monitor_service", "send_email_alert" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
70546d38e2eb4dd4cc255fb67f5c8f11685797d9
e9e40336cb0d5e38359703f17581ec407d269eb4
v1.0
instruct
Algorithm
Algorithm_31252_I
### Question: You are to implement a function that calculates a modified version of the atbash cipher algorithm with additional features and constraints. **Objective:** Write two functions, `custom_atbash_encode` and `custom_atbash_decode`. 1. `custom_atbash_encode(plain: str) -> str`: - Converts a given string u...
def custom_atbash_encode(plain: str) -> str: def atbash(char): if 'a' <= char <= 'z': return chr(ord('z') - (ord(char) - ord('a'))) return char return ''.join(atbash(char) for char in plain) def custom_atbash_decode(encoded: str) -> str: return custom_atbash_encode(encoded)
def test_custom_atbash_encode(): assert custom_atbash_encode("hello world!") == "svool dliow!" assert custom_atbash_encode("abc xyz") == "zyx cba" assert custom_atbash_encode("123-456-789") == "123-456-789" assert custom_atbash_encode("the quick brown-fox jumps over the lazy-dog.") == "gsv jfrxp yildm-u...
[ { "docstring": null, "function_declaration": "def custom_atbash_encode(plain):", "function_name": "custom_atbash_encode", "parameter_list": "(plain)" }, { "docstring": null, "function_declaration": "def custom_atbash_decode(encoded):", "function_name": "custom_atbash_decode", "pa...
[ 1, 0, 1, 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 custom_atbash_encode(plain: str) -> str:\n def atbash_char(c):\n if 'a' <= c <= 'z':\n return chr(219 - ord(c)) # 219 = ord('a') + ord(...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000031252", "row_id": 31252, "seed_ids": "[435]" }
0.656839
Algorithm_31252
I
[ "custom_atbash_encode", "custom_atbash_decode" ]
2
[ [ "custom_atbash_decode", "custom_atbash_encode" ] ]
1
[]
false
[]
false
pytest
false
[]
true
070d5f79cfdb2b9afdcb2fb4ccc19ff8f2387c98
82b37def6a4e96ea05791312ebab516e57814117
v1.0
instruct
Algorithm
Algorithm_31340_I
### Coding Assessment Question: Genetic Sequence Similarity #### Context: In bioinformatics, one common task is to compare genetic sequences to identify similarities and differences. This process is essential for tasks such as identifying evolutionary relationships, diagnosing genetic disorders, and more. #### Proble...
def hamming_distance(seq1, seq2): """ Calculates the Hamming distance between two sequences. Sequences must be of equal length. Parameters: seq1 (str): First genetic sequence. seq2 (str): Second genetic sequence. Returns: int: Hamming distance between seq1 and s...
from solution import hamming_distance, longest_common_subsequence, similarity_percentage, complement_sequence def test_hamming_distance(): assert hamming_distance("AGCT", "TCGA") == 4 assert hamming_distance("AAAA", "AAAA") == 0 assert hamming_distance("GATTACA", "GACTATA") == 2 try: hamming_di...
[ { "docstring": "Calculates the Hamming distance between two sequences.\nSequences must be of equal length.\n\nParameters:\n seq1 (str): First genetic sequence.\n seq2 (str): Second genetic sequence.\n \nReturns:\n int: Hamming distance between seq1 and seq2.\n \nRaises:\n ValueError: If the se...
[ 1, 1, 0, 0, 0, 1, 0, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def hamming_distance(seq1, seq2):\n \"\"\"\n Calculate the Hamming distance between two sequences.\n\n :param seq1: First genetic sequence (string).\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031340", "row_id": 31340, "seed_ids": "[4028]" }
0.670274
Algorithm_31340
I
[ "hamming_distance", "longest_common_subsequence", "similarity_percentage", "complement_sequence" ]
4
[ [ "similarity_percentage", "hamming_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2685d37fce1abaa767e83582a5ee4e143ea766f5
5421a1a5dc2d7d0f3e23aca765a696257ae7a16c
v1.0
instruct
Algorithm
Algorithm_31344_I
### Coding Task: Design a function that solves a Sudoku puzzle using a backtracking algorithm. The function should accept a 2D list representing the Sudoku board and fill in the missing digits. The empty cells are represented by zeros. ### Function Specification - **Function Name**: `solve_sudoku` - **Input**: A 9x9 2...
def is_valid(board, row, col, num): # Check if the number is not repeated in the current row, column, or 3x3 grid for i in range(9): if board[row][i] == num or board[i][col] == num: return False start_row, start_col = (row // 3) * 3, (col // 3) * 3 for i in range(3): for j in...
from solution import solve_sudoku def test_solve_sudoku(): 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], [0, 6, 0, 0, 0, ...
[ { "docstring": null, "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": null, "function_declaration": "def solve_sudoku(board):", "function_name": "solve_sudoku", "parameter_list...
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def solve_sudoku(board):\n \"\"\"\n Solves the Sudoku puzzle using backtracking.\n Modifies the board in place to fill in the missing digits.\n \"\"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031344", "row_id": 31344, "seed_ids": "[252]" }
0.532431
Algorithm_31344
I
[ "is_valid", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
727f567617c1c013519d3260cd94c9d1ce5ebf60
65ddb741c291b02ef19dba39d972426a1851e0a0
v1.0
instruct
Algorithm
Algorithm_31346_I
### String Compression **Context**: String compression algorithms are commonly used to save space in data storage and transmission. One simple scheme for compressing a string is to abbreviate sequences of repeated characters to the first character followed by a count of repetitions. In this exercise, you will implemen...
def compress_string(s: str) -> str: if not s: return "" compressed = [] count = 1 for i in range(1, len(s)): if s[i] == s[i - 1]: count += 1 else: compressed.append(s[i - 1] + (str(count) if count > 1 else "")) count = 1 compressed.append...
from solution import compress_string, decompress_string, compare_compression def test_compress_empty_string(): assert compress_string("") == "" def test_compress_single_char(): assert compress_string("a") == "a" def test_compress_no_repeats(): assert compress_string("abc") == "abc" def test_comp...
[ { "docstring": null, "function_declaration": "def compress_string(s):", "function_name": "compress_string", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def decompress_string(s):", "function_name": "decompress_string", "parameter_list": "(s)" }, { ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def compress_string(s: str) -> str:\n if not s:\n return \"\"\n compressed = []\n count = 1\n\n for i in range(1, len(s)):\n if s[i] ==...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031346", "row_id": 31346, "seed_ids": "[3866]" }
0.748322
Algorithm_31346
I
[ "compress_string", "decompress_string", "compare_compression" ]
3
[ [ "compare_compression", "compress_string" ], [ "compare_compression", "decompress_string" ] ]
2
[]
false
[]
false
pytest
true
[]
true
80772a1838517fc65b7ea128cfe61b6ca985873a
1d3f1403b643c5d0d74861704c33fd40502de280
v1.0
instruct
Algorithm
Algorithm_31361_I
### Persistent Palindrome Checker You are tasked with creating a function that checks whether a number is a "persistent palindrome." A number is considered a persistent palindrome if it becomes a palindrome through repeated reversal and addition. The function should return the number of iterations required to reach a ...
def is_palindrome(num: int) -> bool: """ Helper function to determine if a number is a palindrome. """ return str(num) == str(num)[::-1] def persistent_palindrome(num: int) -> int: """ Returns the number of iterations required for a number to become a palindrome through repeated reversal an...
from solution import persistent_palindrome def test_persistent_palindrome_example1(): assert persistent_palindrome(26) == 1 def test_persistent_palindrome_example2(): assert persistent_palindrome(89) == 24 def test_persistent_palindrome_example3(): assert persistent_palindrome(196) == -1 def test_persis...
[ { "docstring": "Helper function to determine if a number is a palindrome.", "function_declaration": "def is_palindrome(num):", "function_name": "is_palindrome", "parameter_list": "(num)" }, { "docstring": "Returns the number of iterations required for a number to become\na palindrome through...
[ 1, 0, 1, 1, 0, 1, 0, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def persistent_palindrome(num: int) -> int:\n \"\"\"\n Checks if the provided number becomes a palindrome through repeated reversal\n and addition withi...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031361", "row_id": 31361, "seed_ids": "[1518]" }
0.668598
Algorithm_31361
I
[ "is_palindrome", "persistent_palindrome" ]
2
[ [ "persistent_palindrome", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6a0f94e77cf49c5d76b1dcdd960ce5f9ba1024a6
ecde064b2898d1bbe0b5ba367e1bb46d443917e5
v1.0
instruct
Algorithm
Algorithm_31406_I
### Question: Matrix Transpose and Dot Product Calculation In data analysis, matrix operations are essential. You are tasked with implementing two functions to calculate the transpose of a matrix and the dot product of two matrices. #### Function 1: `matrix_transpose` ```python def matrix_transpose(matrix: List[List...
from typing import List def matrix_transpose(matrix: List[List[int]]) -> List[List[int]]: """ Calculate the transpose of a given matrix. Args: matrix (List[List[int]]): A 2D list (list of lists) where each list represents a row in the matrix. Returns: List[List[int]]: The transpose of...
from solution import matrix_transpose, matrix_dot_product def test_matrix_transpose(): assert matrix_transpose([[1, 2], [3, 4], [5, 6]]) == [[1, 3, 5], [2, 4, 6]] assert matrix_transpose([[1]]) == [[1]] assert matrix_transpose([[1, 2, 3]]) == [[1], [2], [3]] assert matrix_transpose([[1], [2], [3]]) == ...
[ { "docstring": "Calculate the transpose of a given matrix.\n\nArgs:\nmatrix (List[List[int]]): A 2D list (list of lists) where each list represents a row in the matrix.\n\nReturns:\nList[List[int]]: The transpose of the input matrix.", "function_declaration": "def matrix_transpose(matrix):", "function_n...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef matrix_transpose(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Calculate the transpose of a given matrix.\n\n P...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031406", "row_id": 31406, "seed_ids": "[1001]" }
0.589311
Algorithm_31406
I
[ "matrix_transpose", "matrix_dot_product" ]
2
[ [ "matrix_dot_product", "matrix_transpose" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0c6b6b4bc5532bbf9efbc32d90ee368dbabcc8c
b5c42aa381adee56df3e12f83e2d43474cde3ad8
v1.0
instruct
Algorithm
Algorithm_31457_I
### Scenario A library management system is being developed to manage book inventories, user information, and book borrowings. The system needs to consistently track the status of books and users and report on overdue books. ### Task 1. **Function Requirement: `add_new_user`** - **Purpose**: Create a functio...
import datetime # Data storage users_db = {} books_db = {} class LibraryError(Exception): """Custom exception for library-related errors.""" pass def validate_user_data(user_data): if not isinstance(user_data, dict): raise LibraryError("Invalid user data format") required_keys = {'user_id', '...
import pytest from datetime import datetime, timedelta # Assuming the code above is in `solution.py` from solution import add_new_user, borrow_book, LibraryError @pytest.fixture(autouse=True) def reset_data(): global users_db, books_db users_db.clear() books_db.clear() def test_add_new_user(): user_d...
[]
[ 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 datetime\n\n# Dictionary to store user information\nusers = {}\n\n# Dictionary to store book status\nbooks = {}\n\nclass UserExistsError(Exception):\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000031457", "row_id": 31457, "seed_ids": "[2296]" }
0.499534
Algorithm_31457
I
[ "validate_user_data", "add_new_user", "validate_date", "borrow_book" ]
4
[ [ "add_new_user", "validate_user_data" ], [ "borrow_book", "validate_date" ] ]
2
[]
false
[ "LibraryError" ]
true
pytest
true
[]
true
399dfb612db33cfa60ec5ce6a209d45c030d537d
ac860e876d2f4ba9bc65cd37d29fe12097fc9a58
v1.0
instruct
Algorithm
Algorithm_31530_I
**Context**: Data compression is a critical aspect in various computer science applications, including file storage, data transmission, and real-time streaming. Huffman coding is an efficient method for lossless data compression, which constructs an optimal binary tree-based encoding for symbols based on their frequenc...
import heapq from typing import List, Tuple, Dict class Node: def __init__(self, freq, char=None, left=None, right=None): self.freq = freq self.char = char self.left = left self.right = right def __lt__(self, other): return self.freq < other.freq def build_huffman_tree...
from solution import huffman_encoding def test_basic_example(): char_freq = [('a', 5), ('b', 9), ('c', 12), ('d', 13), ('e', 16), ('f', 45)] result = huffman_encoding(char_freq) assert set(result.keys()) == {'a', 'b', 'c', 'd', 'e', 'f'} assert all(result[char].startswith('0') for char in ['f']) as...
[]
[ 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple, Dict\nimport heapq\n\nclass HuffmanNode:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000031530", "row_id": 31530, "seed_ids": "[4068]" }
0.585621
Algorithm_31530
I
[ "build_huffman_tree", "generate_huffman_codes", "huffman_encoding" ]
3
[ [ "huffman_encoding", "build_huffman_tree" ], [ "huffman_encoding", "generate_huffman_codes" ] ]
2
[]
false
[ "Node" ]
true
pytest
true
[]
true
f2d32df50e00447536b383fd52bd49754291439b
3bc951fc94907f0c8ab7b05568faa0f75e81df0b
v1.0
instruct
Algorithm
Algorithm_31552_I
### Problem Statement You are tasked with developing a function that calculates the least common multiple (LCM) of an array of integers. Your function should be capable of handling both positive and negative integers. ### Function Signature ```python def array_lcm(numbers: list[int]) -> int: pass ``` ### Input ...
def gcd(a, b): """ Helper function to compute the greatest common divisor of a and b. """ while b: a, b = b, a % b return a def lcm(a, b): """ Helper function to compute the least common multiple of a and b. """ return abs(a * b) // gcd(a, b) def array_lcm(numbers: list[int...
from solution import array_lcm def test_pair_of_numbers(): assert array_lcm([4, 6]) == 12 def test_triple_numbers(): assert array_lcm([15, 20, 30]) == 60 def test_with_negatives(): assert array_lcm([-3, 9, 12]) == 36 def test_with_complementary_negatives(): assert array_lcm([5, -5]) == 5 def test_w...
[ { "docstring": "Helper function to compute the greatest common divisor of a and b.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Helper function to compute the least common multiple of a and b.", "function_declaration": ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from math import gcd\nfrom functools import reduce\n\ndef array_lcm(numbers: list[int]) -> int:\n \"\"\"\n Calculate the least common multiple (LCM) of an ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031552", "row_id": 31552, "seed_ids": "[3305]" }
0.674857
Algorithm_31552
I
[ "gcd", "lcm", "array_lcm" ]
3
[ [ "array_lcm", "lcm" ], [ "lcm", "gcd" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9d75722ff4047a381c4e086e078f59f805a36caa
dcb541f9285be2b10c1f822b27ebefa095cb835c
v1.0
instruct
Algorithm
Algorithm_31557_I
### Coding Assessment Question #### Context In the following task, you are required to implement a solution to encode and decode strings using a simple Caesar Cipher. A Caesar Cipher is one of the simplest known encryption techniques whereby each letter in the plaintext is shifted by a fixed number of positions down t...
def caesar_encode(text, shift): def shift_char(c, shift): if 'a' <= c <= 'z': return chr((ord(c) - ord('a') + shift) % 26 + ord('a')) elif 'A' <= c <= 'Z': return chr((ord(c) - ord('A') + shift) % 26 + ord('A')) else: return c return ''.join(shift_cha...
from solution import caesar_encode, caesar_decode def test_encode_basic(): assert caesar_encode('Hello, World!', 3) == 'Khoor, Zruog!' assert caesar_encode('abcXYZ', 2) == 'cdeZAB' assert caesar_encode('Python 3.9', 1) == 'Qzuipo 3.9' def test_decode_basic(): assert caesar_decode('Khoor, Zruog!', ...
[ { "docstring": null, "function_declaration": "def caesar_encode(text, shift):", "function_name": "caesar_encode", "parameter_list": "(text, shift)" }, { "docstring": null, "function_declaration": "def caesar_decode(text, shift):", "function_name": "caesar_decode", "parameter_list...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def caesar_encode(text, shift):\n \"\"\"\n Encodes the given text using the Caesar Cipher with the specified shift.\n \n :param text: The plaintext s...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031557", "row_id": 31557, "seed_ids": "[326]" }
0.677268
Algorithm_31557
I
[ "caesar_encode", "caesar_decode" ]
2
[ [ "caesar_decode", "caesar_encode" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5941523103885e8d1754e39b42f539dcb6b83257
b4c95803e62a1b9c9dbcf03d9866228f44c26897
v1.0
instruct
Algorithm
Algorithm_31586_I
### Problem Statement You are tasked with writing a function that checks for prime numbers in a given range and returns them in descending order. A number is considered prime if it has exactly two distinct positive divisors: 1 and itself. #### Function Signature ```python def primes_in_range(lower_bound: int, upper_bo...
def is_prime(n: int) -> bool: """ Determines if a number n is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i ...
from solution import is_prime, primes_in_range def test_is_prime(): assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(11) def test_primes_in_range_case_1(): assert primes_in_range(10, 50) == [47, 43, 41, 37, 31, 29, 23, 1...
[ { "docstring": "Determines if a number n is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns all prime numbers within the specified range in descending order.", "function_declaration": "def primes_in_rang...
[ 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 is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031586", "row_id": 31586, "seed_ids": "[3607]" }
0.689086
Algorithm_31586
I
[ "is_prime", "primes_in_range" ]
2
[ [ "primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89d101052760900eceec9aa03a95f73984c590b5
51aae49cac2649b085d2baa01efe4c675018cce9
v1.0
instruct
Algorithm
Algorithm_31640_I
### Coding Assessment Question #### Context Sorting algorithms are fundamental to computer science, forming the backbone for various optimizations and efficiency improvements in coding tasks. Understanding and implementing these algorithms is essential for any developer. #### Task Implement a function `find_kth_lar...
from typing import List import random def partition(nums, left, right, pivot_index): pivot_value = nums[pivot_index] # Move pivot to end nums[pivot_index], nums[right] = nums[right], nums[pivot_index] store_index = left # Move all larger elements to the left for i in range(left, right): ...
def test_find_kth_largest(): assert find_kth_largest([3, 2, 1, 5, 6, 4], 2) == 5 assert find_kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4 assert find_kth_largest([1], 1) == 1 assert find_kth_largest([1, 2], 1) == 2 assert find_kth_largest([1, 2], 2) == 1 assert find_kth_largest([-1, -1], 2) ...
[ { "docstring": null, "function_declaration": "def partition(nums, left, right, pivot_index):", "function_name": "partition", "parameter_list": "(nums, left, right, pivot_index)" }, { "docstring": "Returns the k-th largest element of list within left..right", "function_declaration": "def ...
[ 0, 1, 1, 0, 0, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nimport random\n\ndef partition(nums, left, right, pivot_index):\n pivot_value = nums[pivot_index]\n nums[pivot_index], nums[right]...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "0000031640", "row_id": 31640, "seed_ids": "[2816]" }
0.757209
Algorithm_31640
I
[ "partition", "quickselect", "find_kth_largest" ]
3
[ [ "find_kth_largest", "quickselect" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
false
[]
true
859e92ecf8157c99033a212627ddc602812158ec
958c6e17b1862b70328763de3d635972f62f5279
v1.0
instruct
Algorithm
Algorithm_31654_I
### Scenario You are tasked with developing a simple recommendation system for an online bookstore. Your system will suggest books to users based on their past purchases using a collaborative filtering approach. The idea is to recommend books that other users with similar tastes have bought. ### Task Implement a funct...
from collections import Counter from typing import List, Dict import numpy as np def jaccard_similarity(user_books1: List[str], user_books2: List[str]) -> float: set1, set2 = set(user_books1), set(user_books2) intersection = set1.intersection(set2) union = set1.union(set2) if not union: return ...
from solution import recommend_books def test_recommend_books_with_similar_users(): purchase_data = { "Alice": ["Book1", "Book2", "Book3"], "Bob": ["Book2", "Book4"], "Charlie": ["Book1", "Book4", "Book5"], "Diana": ["Book1", "Book2", "Book4"] } result = recommend_books(purc...
[ { "docstring": null, "function_declaration": "def jaccard_similarity(user_books1, user_books2):", "function_name": "jaccard_similarity", "parameter_list": "(user_books1, user_books2)" }, { "docstring": null, "function_declaration": "def recommend_books(purchase_data, target_user, num_rec...
[ 0, 0, 1, 0, 1, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from collections import Counter\nfrom typing import List, Dict\n\ndef jaccard_similarity(set1: set, set2: set) -> float:\n \"\"\"\n Compute the Jaccard sim...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000031654", "row_id": 31654, "seed_ids": "[4386]" }
0.579079
Algorithm_31654
I
[ "jaccard_similarity", "recommend_books" ]
2
[ [ "recommend_books", "jaccard_similarity" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
7f08eecd9dcf75afce9c6e67675ecac3fb875d71
deab248d6d58bb286a4d90229218379a39714d3f
v1.0
instruct
Algorithm
Algorithm_31672_I
### Task: Implement a Binary Search Tree Deletion Function #### Scenario You are given a basic implementation of a Binary Search Tree (BST) that supports insertion and in-order traversal. However, the tree lacks a function to delete a node. Your task is to extend this implementation by adding a delete function that co...
class TreeNode: def __init__(self, key): self.left = None self.right = None self.val = key def delete_node(root, key): if root is None: return root if key < root.val: root.left = delete_node(root.left, key) elif key > root.val: root.right = delete_node(r...
from solution import TreeNode, delete_node, inorder_traversal def test_delete_leaf_node(): root = TreeNode(50) root.left = TreeNode(30) root.right = TreeNode(70) root.left.left = TreeNode(20) root.left.right = TreeNode(40) root.right.left = TreeNode(60) root.right.right = TreeNode(80) ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef delete_node(root, key):\n if...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "0000031672", "row_id": 31672, "seed_ids": "[3800]" }
0.627322
Algorithm_31672
I
[ "delete_node", "min_value_node", "inorder_traversal" ]
3
[ [ "delete_node", "min_value_node" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
fa07656345e3b6abf02aeba09c1ab4646d9a139f
5b1773828efbfbf780895a53bd4746c51f435c52
v1.0
instruct
Algorithm
Algorithm_31701_I
### Question You are given three different methods for determining if a number is a prime number: - An iterative approach using a basic loop (`is_prime_iterative`). - A more optimized approach using the square root technique (`is_prime_sqrt`). - A compact approach using generator expressions (`is_prime_compact`). You...
def is_prime_iterative(n: int) -> bool: """Return True if n is a prime number using iterative approach.""" if n < 2: return False for i in range(2, n): if n % i == 0: return False return True def is_prime_sqrt(n: int) -> bool: """Return True if n is a prime number using ...
def test_is_prime_iterative(): assert not is_prime_iterative(0) assert not is_prime_iterative(1) assert is_prime_iterative(2) assert is_prime_iterative(3) assert not is_prime_iterative(4) assert is_prime_iterative(17) assert not is_prime_iterative(20) def test_is_prime_sqrt(): assert no...
[ { "docstring": "Return True if n is a prime number using iterative approach.", "function_declaration": "def is_prime_iterative(n):", "function_name": "is_prime_iterative", "parameter_list": "(n)" }, { "docstring": "Return True if n is a prime number using square root optimization.", "fun...
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime_iterative(n: int) -> bool:\n if n <= 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n retu...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000031701", "row_id": 31701, "seed_ids": "[3592]" }
0.739316
Algorithm_31701
I
[ "is_prime_iterative", "is_prime_sqrt", "is_prime_compact", "prime_check_factory" ]
4
[ [ "prime_check_factory", "is_prime_compact" ], [ "prime_check_factory", "is_prime_iterative" ], [ "prime_check_factory", "is_prime_sqrt" ] ]
3
[]
false
[]
false
pytest
false
[]
true
15d554a1d6f39b9849b2289ef8c0adf0d7686c21
bc206bed7e55467312c3a39ccc7bc647372e447c
v1.0
instruct
Algorithm
Algorithm_31716_I
### Question: Custom Merge Sort for Even and Odd Separation The classic Merge Sort algorithm is a comparison-based sorting algorithm known for its efficiency and stability. However, sometimes sorting requirements can be peculiar. Let's customize Merge Sort to first separate even and odd numbers, and then within each g...
def custom_merge_sort(array: list[int]) -> list[int]: """ Sorts the list such that even numbers in descending order come before odd numbers in descending order. :param array: List of integers to be sorted :return: List of integers sorted based on the criteria """ if len(array) <= ...
from solution import custom_merge_sort def test_example_cases(): assert custom_merge_sort([9, 4, 2, 5, 3]) == [4, 2, 9, 5, 3] assert custom_merge_sort([7, 3, 5, 1]) == [7, 5, 3, 1] assert custom_merge_sort([8, -6, 12, 0, 7]) == [12, 8, 0, -6, 7] assert custom_merge_sort([]) == [] def test_all_even_num...
[ { "docstring": "Sorts the list such that even numbers in descending order come before odd \nnumbers in descending order.\n\n:param array: List of integers to be sorted\n:return: List of integers sorted based on the criteria", "function_declaration": "def custom_merge_sort(array):", "function_name": "cus...
[ 0, 0, 1, 0, 1, 1, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def custom_merge_sort(array):\n \"\"\"\n Sorts the input list such that all even numbers sorted in descending order come before odd numbers in descending o...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031716", "row_id": 31716, "seed_ids": "[982]" }
0.670737
Algorithm_31716
I
[ "custom_merge_sort", "merge" ]
2
[ [ "custom_merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5d3f5dc4a68c84989fa216562afe89c62dc7d2fe
3c08b69c2e2331ae807d4340912a6aa5fec84d8b
v1.0
instruct
Algorithm
Algorithm_31872_I
### Merge Sort Implementation and Adaptation ### Objective Your task is to implement the Merge Sort algorithm for sorting a list of integers, as well as adapt the algorithm to sort a list of dictionaries based on a specified key. ### Problem Description #### Part 1: Merge Sort for Integers Implement the `merge_sort...
from typing import List, Dict, Union def merge_sort(collection: List[int]) -> List[int]: if len(collection) <= 1: return collection middle = len(collection) // 2 left_half = merge_sort(collection[:middle]) right_half = merge_sort(collection[middle:]) return merge(left_half, right_half) d...
def test_merge_sort(): assert merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13] assert merge_sort([-3, 10, 0, -19, 2]) == [-19, -3, 0, 2, 10] assert merge_sort([1, 2, 3, 2, 1]) == [1, 1, 2, 2, 3] assert merge_sort([]) == [] assert merge_sort([1]) == [1] def test_merge_sort_dict(): asse...
[ { "docstring": null, "function_declaration": "def merge_sort(collection):", "function_name": "merge_sort", "parameter_list": "(collection)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, ...
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Union\n\ndef merge_sort(collection: List[int]) -> List[int]:\n if len(collection) <= 1:\n return collection\n \n d...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "0000031872", "row_id": 31872, "seed_ids": "[923]" }
0.579789
Algorithm_31872
I
[ "merge_sort", "merge", "merge_sort_dict", "merge_dict" ]
4
[ [ "merge_sort", "merge" ], [ "merge_sort_dict", "merge_dict" ] ]
2
[]
false
[]
false
pytest
false
[]
true
4c819644f60493b0b41a30779d9c2df2361dae53
ec51455dc90b09c256ec9bdecb288165b60cbbaa
v1.0
instruct
Algorithm
Algorithm_31915_I
### Divisible Triangular Numbers A triangular number or triangle number is a number that can be represented in the form of a triangle with dots. The \( n \)th triangular number \( T_n \) is the sum of the first \( n \) natural numbers, i.e., \( T_n = \frac{n(n+1)}{2} \). You are tasked with writing a function that fi...
def count_divisors(n): """ Helper function to count the divisors of a given number n. """ count = 0 sqrt_n = int(n**0.5) for i in range(1, sqrt_n + 1): if n % i == 0: if i * i == n: count += 1 else: count += 2 return count def ...
def test_find_triangle_number_with_5_divisors(): assert find_triangle_number_with_divisors(5) == 28 def test_find_triangle_number_with_100_divisors(): assert find_triangle_number_with_divisors(100) == 73920 def test_find_triangle_number_with_500_divisors(): assert find_triangle_number_with_divisors(500) =...
[ { "docstring": "Helper function to count the divisors of a given number n.", "function_declaration": "def count_divisors(n):", "function_name": "count_divisors", "parameter_list": "(n)" }, { "docstring": "Finds the smallest triangular number with more than D divisors.", "function_declara...
[ 1, 1, 1, 1, 1, 0, 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 count_divisors(n):\n \"\"\"\n Helper function to count the number of divisors of a number n.\n \"\"\"\n divisors = 0\n sqrt_n = int(n ** 0.5)\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000031915", "row_id": 31915, "seed_ids": "[2551]" }
0.549222
Algorithm_31915
I
[ "count_divisors", "find_triangle_number_with_divisors" ]
2
[ [ "find_triangle_number_with_divisors", "count_divisors" ] ]
1
[]
false
[]
false
pytest
false
[]
true
974cffad66fcd5c79bc4b264ed43e7dd6300d629
830468aafc1d358ffdc52ead00659fce3d6d60b9
v1.0
instruct
Algorithm
Algorithm_31991_I
### K-Nearest Neighbors Classification You are tasked with implementing a K-Nearest Neighbors (KNN) classification model from scratch. Your task is to: 1. Download and process a given dataset. 2. Implement the KNN algorithm to classify new data points based on the majority class of their k-nearest neighbors. 3. Evalua...
import csv import math import requests from typing import List, Tuple from collections import Counter def collect_dataset() -> List[Tuple[float, float, int]]: url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/iris.csv" response = requests.get(url) response.raise_for_status() data = []...
from solution import collect_dataset, knn_classify, calculate_accuracy, run_knn_classification def test_collect_dataset(): data = collect_dataset() assert len(data) > 0 assert all(len(row) == 3 for row in data) def test_knn_classify(): train_data = [ (1.0, 2.0, 0), (2.0, 3.0, 0), ...
[ { "docstring": null, "function_declaration": "def collect_dataset():", "function_name": "collect_dataset", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import csv\nimport math\nimport requests\nfrom collections import Counter\nfrom typing import List, Tuple\n\ndef collect_dataset() -> List[Tuple[float, float, in...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "0000031991", "row_id": 31991, "seed_ids": "[681]" }
0.607195
Algorithm_31991
I
[ "collect_dataset", "euclidean_distance", "knn_classify", "calculate_accuracy", "run_knn_classification" ]
5
[ [ "knn_classify", "euclidean_distance" ], [ "run_knn_classification", "calculate_accuracy" ], [ "run_knn_classification", "knn_classify" ] ]
3
[]
false
[]
false
pytest
true
[ "requests" ]
false
8b7cc309c7c34895c6ad119bb09bad9e12d462cb
7b18f9b26013dfe05d4bd0d4e44c82a8b8691bc5
v1.0
instruct
Algorithm
Algorithm_32042_I
### Coding Question: Median and Geometric Progression Analysis #### Objective: You need to enhance your mathematical analysis skills by working with median calculations and geometric progression checks. Your task is to write a new function that utilizes both to solve a given problem. #### Problem Statement: Write a f...
def is_geometric_series(series): if len(series) <= 1: return True ratio = series[1] / series[0] for i in range(1, len(series)): if series[i] / series[i - 1] != ratio: return False return True def median(lst): sorted_lst = sorted(lst) n = len(sorted_lst) mid = n /...
def test_is_geometric_series_single_element(): assert is_geometric_series([5]) == True def test_is_geometric_series_true(): assert is_geometric_series([3, 9, 27]) == True assert is_geometric_series([2, 8, 32, 128]) == True def test_is_geometric_series_false(): assert is_geometric_series([3, 9, 28]) ==...
[ { "docstring": null, "function_declaration": "def is_geometric_series(series):", "function_name": "is_geometric_series", "parameter_list": "(series)" }, { "docstring": null, "function_declaration": "def median(lst):", "function_name": "median", "parameter_list": "(lst)" }, { ...
[ 0, 1, 1, 1, 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": "def is_geometric_series(series):\n if len(series) <= 1:\n return True\n ratio = series[1] / series[0]\n for i in range(1, len(series)):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "0000032042", "row_id": 32042, "seed_ids": "[4064]" }
0.579332
Algorithm_32042
I
[ "is_geometric_series", "median", "analyze_geometric_series" ]
3
[ [ "analyze_geometric_series", "is_geometric_series" ], [ "analyze_geometric_series", "median" ] ]
2
[]
false
[]
false
pytest
false
[]
true
afa8d0a389ace86545caf588f395d2bd99549403
bae81c472fd07b76c55b5f9da5ccd2902574c192