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
complete
Evol
Evol_6297_C
import asyncio import aiohttp API_ENDPOINTS = [ 'https://api.example.com/data/source1', 'https://api.example.com/data/source2', # Add more API endpoints as needed ] def clean_data(data): """ Cleans received data. Implement specific data cleaning logic here. """ # Example data cleaning logi...
import requests import asyncio import aiohttp import concurrent.futures from datetime import datetime import logging logging.basicConfig(level=logging.INFO) API_ENDPOINTS = [ 'https://api.example.com/data/source1', 'https://api.example.com/data/source2', # Add more API endpoints as needed ] def clean_dat...
import pytest import asyncio from unittest.mock import patch, AsyncMock from solution import clean_data, aggregate_data, generate_insights, fetch_data, gather_data, process_data def test_clean_data(): raw_data = {'a': 1, 'b': None, 'c': 2} cleaned_data = clean_data(raw_data) assert cleaned_data == {'a': 1,...
[ { "docstring": "Cleans received data. Implement specific data cleaning logic here.", "function_declaration": "def clean_data(data):", "function_name": "clean_data", "parameter_list": "(data)" }, { "docstring": "Aggregates data from multiple sources.", "function_declaration": "def aggrega...
[ 0, 1, 1, 1, 0, 0, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport json\nfrom datetime import datetime, timedelta\n\nclass DataProcessor:\n def __init__(self, api_urls):\n self.api_...
trial_gpt4o_2
{ "original_instruction": "Create an advanced Python script capable of interfacing with a RESTful API to gather and process real-time data streams from multiple sources. The script should efficiently handle the streaming data by employing multithreading or asynchronous programming techniques to manage varying data ar...
0.554942
Evol_6297
C
[ "clean_data", "aggregate_data", "generate_insights", "fetch_data", "gather_data", "process_data" ]
6
[ [ "fetch_data", "clean_data" ], [ "gather_data", "fetch_data" ], [ "process_data", "aggregate_data" ], [ "process_data", "gather_data" ], [ "process_data", "generate_insights" ] ]
5
[ "process_data" ]
false
[]
false
pytest
true
[ "aiohttp", "requests" ]
false
46f665b43125d4690bd705df323ea1c3cb7dffc9
a61780b2dee716a1e9320c6b9dfd2d85e280a231
v1.0
complete
Evol
Evol_7180_C
def get_prime_subset(nums: List[int]) -> List[int]: """ Returns a subset of the input list consisting of prime elements in descending order. >>> get_prime_subset([10, 3, 7, 4, 11, 20]) [11, 7, 3] >>> get_prime_subset([2, 3, 5, 7, 11]) [11, 7, 5, 3, 2] >>> get_prime_subset([4, 6, 8, 10, 12]) [] """
def is_prime(n): """ Helper function to check if a number is prime. """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def get_prime_subset(nums): """ Returns a subset of the input list consisting of prime ...
from solution import get_prime_subset def test_get_prime_subset_mixed_numbers(): assert get_prime_subset([10, 3, 7, 4, 11, 20]) == [11, 7, 3] def test_get_prime_subset_all_primes(): assert get_prime_subset([2, 3, 5, 7, 11]) == [11, 7, 5, 3, 2] def test_get_prime_subset_no_primes(): assert get_prime_subse...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a subset of the input list consisting of prime elements in descending order.", "function_declaratio...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Helper function to check if a number is a prime number\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True...
trial_gpt4o_9
{ "original_instruction": "Write a function that takes a list of integers as input and returns a subset of the list consisting of elements that are prime numbers. Additionally, the subset should be in descending order. For example, given the input list [10, 3, 7, 4, 11, 20], the output should be [11, 7, 3].", "prom...
0.630312
Evol_7180
C
[ "is_prime", "get_prime_subset" ]
2
[ [ "get_prime_subset", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
216990aff3a4d9aa54740e1493fd46f5c1d19c7e
884936b2d6c89bdda0dd4cfb122477c543d4f2f9
v1.0
complete
Evol
Evol_6403_C
def is_prime(number: int) -> bool: """ Returns True if the number is a prime, else False. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(17) True >>> is_prime(18) False """ pass def filter_primes(nu...
def is_prime(number: int) -> bool: """ Returns True if the number is a prime, else False. """ if number <= 1: return False if number == 2: return True if number % 2 == 0: return False for i in range(3, int(number**0.5) + 1, 2): if number % i == 0: ...
from solution import filter_primes, is_prime def test_is_prime(): assert is_prime(0) == False assert is_prime(1) == False assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(19) == Tru...
[ { "docstring": "Returns True if the number is a prime, else False.", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Filters the list of integers, returning only the prime numbers.", "function_declaration": "de...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(number: int) -> bool:\n \"\"\"\n Returns True if the number is a prime, else False.\n A prime number is greater th...
trial_gpt4o_9
{ "original_instruction": "**Write a function in Python that takes a list of integers and returns a new list containing only the prime numbers from the original list.**\n\nFunction Signature:\n```python\ndef filter_primes(numbers: list[int]) -> list[int]:\n pass\n```\n\n## Example\n```python\nnumbers = [2, 3, 4, 5...
0.783554
Evol_6403
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
03072447475145988828e11a06ca71ec84bcaa81
56d82fd0d0440272405043f3aa647e7fd0918076
v1.0
complete
Evol
Evol_7131_C
from typing import List def is_prime(n: int) -> bool: """Check if a number is prime.""" # Write your implementation here def filter_primes(lst: List[int]) -> List[int]: """ Returns a list containing only the prime numbers from the input list. :param lst: List of integers :return: List of ...
def is_prime(n): """Check if a number is prime""" if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def filter_primes(lst): """ Returns a l...
from solution import filter_primes def test_filter_primes_all_primes(): assert filter_primes([2, 3, 5, 7, 11]) == [2, 3, 5, 7, 11] def test_filter_primes_mixed_numbers(): assert filter_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == [2, 3, 5, 7, 11] def test_filter_primes_no_primes(): assert filter_primes...
[ { "docstring": "Check if a number is prime", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list containing only the prime numbers from the input list.\n\n:param lst: List of integers\n:return: List of prime integ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % ...
trial_gpt4o_8
{ "original_instruction": "Create a function that accepts a list of integers and returns a new list containing only the elements that are prime numbers. For this purpose, a prime number is defined as an integer greater than 1 that has no positive divisors other than 1 and itself.", "prompt_id": "00007131", "row_i...
0.747087
Evol_7131
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9fee81bbe87f12695d1081bc614bcda3ddf279e9
1f99a3045effe4593f0c9d457cdc7af8229fbffb
v1.0
complete
Evol
Evol_7560_C
def is_palindrome(s: str) -> bool: """Checks if the given string is a palindrome, ignoring spaces, punctuation, and case.""" pass def filter_palindromes(strings: List[str]) -> List[str]: """Returns a list of strings that are palindromes. >>> filter_palindromes(["racecar", "hello", "madam"]) ["racecar",...
import re def is_palindrome(s): """ Checks if the given string is a palindrome, ignoring spaces, punctuation, and case. """ # Using regex to remove non-alphanumeric characters and convert to lowercase cleaned = re.sub(r'[^A-Za-z0-9]', '', s).lower() return cleaned == cleaned[::-1] def filt...
from solution import filter_palindromes def test_filter_palindromes_single_word(): assert filter_palindromes(["racecar", "hello", "madam"]) == ["racecar", "madam"] def test_filter_palindromes_with_spaces_and_punctuation(): assert filter_palindromes(["A man, a plan, a canal, Panama", "No lemon, no melon", "Was...
[ { "docstring": "Checks if the given string is a palindrome, ignoring spaces,\npunctuation, and case.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Returns a list of strings that are palindromes.", "function...
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef is_palindrome(s):\n \"\"\"\n Checks if the given string is a palindrome, ignoring spaces, punctuation, and case.\n \"\"\"\n # Remove s...
trial_gpt4o_9
{ "original_instruction": "Write a function that receives a list of strings and returns a new list containing only those strings that are palindromes. A palindrome is a word that reads the same backward as forward, ignoring spaces, punctuation, and case. The function should be insensitive to capitalization and spaces...
0.85705
Evol_7560
C
[ "is_palindrome", "filter_palindromes" ]
2
[ [ "filter_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
60c5de185a189c83f3725c5ffde27e839e742029
c828a24eae49476d7325ee3b3dba3a8c6fa3e24f
v1.0
complete
Evol
Evol_7303_C
def merge_and_sort(list1: List[int], list2: List[int]) -> List[int]: """ Merges two lists of integers and returns the merged list sorted in ascending order. >>> merge_and_sort([3, 1, 4], [2, 6, 5]) [1, 2, 3, 4, 5, 6] >>> merge_and_sort([], []) [] >>> merge_and_sort([3, 1, 4], []) [1, 3,...
def merge_and_sort(list1, list2): """ Merges two lists and sorts them using merge sort algorithm. Returns the sorted merged list. """ merged_list = list1 + list2 return merge_sort(merged_list) def merge_sort(lst): if len(lst) <= 1: return lst mid = len(lst) // 2 left_ha...
from solution import merge_and_sort def test_merge_and_sort_simple_case(): assert merge_and_sort([3, 1, 4], [2, 6, 5]) == [1, 2, 3, 4, 5, 6] def test_merge_and_sort_with_empty_lists(): assert merge_and_sort([], []) == [] assert merge_and_sort([3, 1, 4], []) == [1, 3, 4] assert merge_and_sort([], [2, 6...
[ { "docstring": "Merges two lists and sorts them using merge sort algorithm.\nReturns the sorted merged list.", "function_declaration": "def merge_and_sort(list1, list2):", "function_name": "merge_and_sort", "parameter_list": "(list1, list2)" }, { "docstring": null, "function_declaration"...
[ 1, 1, 1, 0, 0, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_and_sort(list1, list2):\n \"\"\"\n Merges two lists and returns a new list sorted in ascending order.\n \"\"\"\n merged_list = list1 + list2\...
trial_gpt4o_9
{ "original_instruction": "Write a function named `merge_and_sort` that takes two lists of integers as input, merges them into a single list, and returns the merged list sorted in ascending order. You are not allowed to use any built-in sorting functions. Ensure efficiency by leveraging a sorting algorithm such as me...
0.602924
Evol_7303
C
[ "merge_and_sort", "merge_sort", "merge" ]
3
[ [ "merge_and_sort", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
21a99fba629f48479c1e0f8faa17f85dc0ac3059
aba7abb379ff6fb66fad773b6df589ff04088acc
v1.0
complete
Evol
Evol_6713_C
def infix_to_postfix(expression: str) -> str: """Converts an infix mathematical expression to postfix notation. >>> infix_to_postfix("3+4") "34+" >>> infix_to_postfix("2*(5+1)") "251+*" >>> infix_to_postfix("(1+2)*(3+4)") "12+34+*" """ pass def evaluate_postfix(postfix_expr: str) -> int: ""...
def infix_to_postfix(expression): precedence = {'+': 1, '-': 1, '*': 2, '/': 2} stack = [] postfix = [] for char in expression: if char.isdigit(): postfix.append(char) elif char == '(': stack.append(char) elif char == ')': while stack and ...
from solution import infix_to_postfix, evaluate_postfix, process_expressions def test_infix_to_postfix(): assert infix_to_postfix("3+4") == "34+" assert infix_to_postfix("2*(5+1)") == "251+*" assert infix_to_postfix("(1+2)*(3+4)") == "12+34+*" def test_evaluate_postfix(): assert evaluate_postfix("34+"...
[ { "docstring": null, "function_declaration": "def infix_to_postfix(expression):", "function_name": "infix_to_postfix", "parameter_list": "(expression)" }, { "docstring": null, "function_declaration": "def evaluate_postfix(postfix_expr):", "function_name": "evaluate_postfix", "par...
[ 0, 0, 1, 1, 1, 1, 1, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def infix_to_postfix(expression):\n \"\"\"\n Convert infix expression to postfix expression.\n \"\"\"\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '...
trial_gpt4o_5
{ "original_instruction": "Given a list of strings representing mathematical expressions in infix notation, write a function that converts each expression into its equivalent postfix notation and evaluates the result. The input list can contain any valid arithmetic expressions involving the operators +, -, *, /, and ...
0.537098
Evol_6713
C
[ "infix_to_postfix", "evaluate_postfix", "process_expressions" ]
3
[ [ "process_expressions", "evaluate_postfix" ], [ "process_expressions", "infix_to_postfix" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b1dcc102117345a2622e66e607737930cc8b53a1
37dcfa29203b80ad5620511ca4d5185790a59309
v1.0
complete
Evol
Evol_7655_C
from typing import List def is_prime(n: int) -> bool: """ Determines if a number n is prime. >>> is_prime(2) True >>> is_prime(4) False >>> is_prime(13) True """ pass def filter_primes(numbers: List[int]) -> List[int]: """ Returns a list of prime numbers from the input...
def is_prime(n): """ 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 += 6 retu...
from solution import filter_primes, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(13) == True assert is_prime(25) == False assert is_prime(29) == True assert is_prime(1) == False def test_filter_primes_empty_...
[ { "docstring": "Determines if a number n is prime.", "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):", "func...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Checks if n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n %...
trial_gpt4o_9
{ "original_instruction": "Write a function in Python that takes a list of integers as input and returns a new list containing only the prime numbers from the original list. To determine if a number is prime, you should implement a helper function `is_prime()`. Optimize your code for efficiency with respect to both t...
0.771244
Evol_7655
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0367eaba772959f64bbfe59506ffd7c37f89ca08
40ed0e4abf9974fc01134282016cbd0ed2cdc71c
v1.0
complete
Evol
Evol_7599_C
def is_prime(n: int) -> bool: """Returns True if the number n is a prime number, otherwise False.""" pass def filter_primes(nums: List[int]) -> List[int]: """ Returns a list of prime numbers from the given list of integers. >>> filter_primes([]) [] >>> filter_primes([4, 6, 8, 9, 10, 12]) []...
from math import isqrt def is_prime(n): """ Returns True if the number 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 ...
from solution import filter_primes def test_filter_primes_empty_list(): assert filter_primes([]) == [] def test_filter_primes_no_primes(): assert filter_primes([4, 6, 8, 9, 10, 12]) == [] def test_filter_primes_all_primes(): assert filter_primes([2, 3, 5, 7, 11, 13]) == [2, 3, 5, 7, 11, 13] def test_fil...
[ { "docstring": "Returns True if the number n is a prime number, otherwise False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers from the given list of integers.", "function_declaration"...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, int(n ...
trial_gpt4o_3
{ "original_instruction": "Design a Python function that takes a list of integers and returns a new list that contains only the prime numbers from the original list. Ensure the solution is efficient by implementing an optimal primality test. \n\nNext, write a unit test for this function using the unittest framework i...
0.787611
Evol_7599
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
63a9eafd2bfb972ee90d6a04dd4e4ba4a97d40a5
fd41c58d5bc1ad3b37a5a01fb2632d9bfc4aabc2
v1.0
complete
Evol
Evol_7978_C
from typing import List def filter_primes(numbers: List[int]) -> List[int]: """ Create a function that takes a list of integers and returns a new list containing only the prime numbers from the original list. A prime number is a number greater than 1 that has no positive divisors other than 1 and...
from typing import List def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return Fa...
from solution import filter_primes def test_filter_primes_mixed_numbers(): assert filter_primes([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7] def test_filter_primes_no_primes(): assert filter_primes([4, 6, 8, 10, 15, 22]) == [] def test_filter_primes_all_primes(): assert filter_primes([2, 3, 5, 7, 11, 13...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers from the given list of integers.", "function_declaration": "def filter_prim...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n re...
trial_gpt4o_8
{ "original_instruction": "Create a function that takes a list of integers and returns a new list containing only the prime numbers from the original list. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. Write a function `filter_primes(numbers: List[int]) -> List[int]`...
0.716026
Evol_7978
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2d1c88625501c6e076259a8136174f42af25e041
2652809d8f8da88fd8937770295840a2df87a838
v1.0
complete
Evol
Evol_8411_C
def is_prime(num: int) -> bool: """ Helper function to check if a number is prime. >>> is_prime(2) True >>> is_prime(4) False """ def filter_primes(numbers: List[int]) -> List[int]: """ Returns a list of prime numbers from the given list of integers. >>> filter_primes([2, 3, 5, 7, 1...
def is_prime(num): """ Helper function to check if a number is prime. """ if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def filter_primes(numbers): """ Returns a list of prime numbers from the given...
import pytest from solution import is_prime, filter_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False def test_filter_primes_with_primes(): assert filter_primes([2, 3, 5, 7, 11]...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns a list of prime numbers from the given list of integers.\n\nParameters:\nnumbers (list): A list of ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n ret...
trial_gpt4o_7
{ "original_instruction": "Write a Python function that takes a list of integers as input and returns a new list containing only the elements that are prime numbers. Ensure your solution effectively identifies prime numbers and handles edge cases such as empty lists or lists containing non-integer values.", "prompt...
0.686793
Evol_8411
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95e8faf7b154ef4055df0b4467eeedc04c0bb2c3
3609ea337becf4ba5aa2c08fd74d5b41a85f0cf2
v1.0
complete
Evol
Evol_7768_C
from datetime import datetime from typing import List, Tuple def compute_overlap_minutes(appointments: List[Tuple[str, str]]) -> int: """ Returns the total time in minutes when all appointments overlap. :param appointments: List of tuples where each tuple is (start_time, end_time) ...
from datetime import datetime def compute_overlap_minutes(appointments): """ Returns the total time in minutes when all appointments overlap. :param appointments: List of tuples where each tuple is (start_time, end_time) with time in "HH:MM" 24-hour format. :return: Total ...
from solution import compute_overlap_minutes def test_no_overlap(): appointments = [('09:00', '10:00'), ('11:00', '12:00'), ('13:00', '14:00')] assert compute_overlap_minutes(appointments) == 0 def test_full_overlap(): appointments = [('09:00', '12:00'), ('10:00', '11:00')] assert compute_overlap_minu...
[ { "docstring": "Returns the total time in minutes when all appointments overlap.\n\n:param appointments: List of tuples where each tuple is (start_time, end_time)\n with time in \"HH:MM\" 24-hour format.\n:return: Total overlapping time in minutes.", "function_declaration": "def compute_...
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def calculate_overlap_minutes(appointments):\n \"\"\"\n Returns the total time in minutes when all appointments overlap.\n \"\"\"\n from datetime impor...
trial_gpt4o_8
{ "original_instruction": "Write a function that takes a list of timestamps representing the start and end times of various appointments in a 24-hour format \"HH:MM\". The function should return the total time in minutes when all appointments overlap.\n\nExample:\nappointments = [('09:00', '12:30'), ('11:15', '14:00'...
0.599766
Evol_7768
C
[ "compute_overlap_minutes", "convert_to_minutes" ]
2
[ [ "compute_overlap_minutes", "convert_to_minutes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
21863da8c6c73a89e7156365c5f7eaa383da1b82
a124ac78907d890582d865f06d101e48911cedd5
v1.0
complete
Evol
Evol_8426_C
from typing import List def is_prime(n: int) -> bool: """ Checks if a number is prime. >>> is_prime(2) == True >>> is_prime(3) == True >>> is_prime(4) == False >>> is_prime(17) == True >>> is_prime(18) == False >>> is_prime(1) == False >>> is_prime(0) == False >>> is_prime(-1) == Fa...
def is_prime(n): """ Checks if a number is prime. :param n: An integer to check for primality. :return: True if n is prime, False otherwise. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: ...
from solution import is_prime, filter_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-1) == Fal...
[ { "docstring": "Checks if a number is prime.\n\n:param n: An integer to check for primality.\n:return: True if n is prime, False otherwise.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Filters the prime numbers from a l...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n %...
trial_gpt4o_9
{ "original_instruction": "Write a function that takes a list of integers and returns a new list containing only the prime numbers from the original list. You should write a helper function `is_prime()` to check if a number is prime, and use this helper function within a list comprehension to filter the prime numbers...
0.810895
Evol_8426
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c81fe2987e156a8a1cb12c37aa8ec73674deedcf
9b4f0fb443dd62d56e81da02bc86db40967c4890
v1.0
complete
Evol
Evol_9405_C
def count_vowels(s: str) -> int: """ Returns the number of vowels (a, e, i, o, u) in the given string. >>> count_vowels("hello") == 2 >>> count_vowels("world") == 1 >>> count_vowels("AEIOU") == 5 """ def count_vowels_in_list(strings: List[str]) -> List[int]: """ Returns a list of counts of ...
def count_vowels(s): """ Returns the number of vowels (a, e, i, o, u) in the given string. """ vowels = set('aeiou') return sum(1 for char in s.lower() if char in vowels) def count_vowels_in_list(strings): """ Returns a list of counts of vowels in each string of the input list. """ ...
from solution import count_vowels, count_vowels_in_list def test_count_vowels(): assert count_vowels("hello") == 2 assert count_vowels("world") == 1 assert count_vowels("AEIOU") == 5 assert count_vowels("bcdfghjklmnpqrstvwxyz") == 0 assert count_vowels("Beautiful Day") == 6 def test_count_vowels_i...
[ { "docstring": "Returns the number of vowels (a, e, i, o, u) in the given string.", "function_declaration": "def count_vowels(s):", "function_name": "count_vowels", "parameter_list": "(s)" }, { "docstring": "Returns a list of counts of vowels in each string of the input list.", "function...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def count_vowels(s):\n \"\"\"\n Returns the number of vowels (a, e, i, o, u) in the string s.\n \"\"\"\n vowels = 'aeiouAEIOU'\n return sum(1 for ch...
trial_gpt4o_9
{ "original_instruction": "Design a Python function that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string. Expand your function to handle a list of strings and return a list of counts corresponding to each string.", "prompt_id": "00009405", "row_id": 9405, "seed_ids": "[258...
0.865241
Evol_9405
C
[ "count_vowels", "count_vowels_in_list" ]
2
[ [ "count_vowels_in_list", "count_vowels" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cede00ddb0b8c3bf4e39b852577bf79a43bb8d5e
816945471fe90f2a92a94cd315623f82ac033341
v1.0
complete
Evol
Evol_8599_C
import re class InvalidRomanNumeralException(Exception): pass def validate_roman_numeral(s: str) -> bool: """ Validates whether a given string is a valid Roman numeral. >>> validate_roman_numeral("IX") == True >>> validate_roman_numeral("IIII") == False """ def roman_to_int(s: str) -> int: ...
import re class InvalidRomanNumeralException(Exception): pass def validate_roman_numeral(s): """ Validates whether a given string is a valid Roman numeral. """ pattern = re.compile( "^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" ) return pattern.match(s) is not None de...
import pytest from solution import roman_to_int, validate_roman_numeral, InvalidRomanNumeralException def test_validate_roman_numeral(): assert validate_roman_numeral("IX") == True assert validate_roman_numeral("MCMXCIV") == True assert validate_roman_numeral("IIII") == False assert validate_roman_nume...
[]
[ 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\nclass InvalidRomanNumeralError(Exception):\n pass\n\ndef roman_to_int(s):\n \"\"\"\n Convert a roman numeral to an integer.\n\n :param s: ...
trial_gpt4o_9
{ "original_instruction": "Write a Python function that takes in a string containing a Roman numeral and converts it to its integer value. The function should handle Roman numerals up to 3999 and should account for subtractive combinations (e.g., IV for 4). Additionally, provide a method to validate whether a given s...
0.60921
Evol_8599
C
[ "validate_roman_numeral", "roman_to_int" ]
2
[ [ "roman_to_int", "validate_roman_numeral" ] ]
1
[]
false
[ "InvalidRomanNumeralException" ]
true
pytest
true
[]
true
5f1db9c3dff9cb3abea908bccc76abc7eb0787dc
d27a3f2813796dc95e731d4cc3ab4866839f0c4d
v1.0
complete
Evol
Evol_9431_C
def is_prime(n: int) -> bool: """ Helper function to check if a number is prime. """ pass def filter_primes(numbers: List[int]) -> List[int]: """ Returns a list of prime numbers from the input list of integers. Parameters: numbers (list): A list of integers Returns: li...
def is_prime(n): """ Helper function to check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i +...
from solution import filter_primes def test_empty_list(): assert filter_primes([]) == [] def test_no_primes(): assert filter_primes([4, 6, 8, 10]) == [] def test_only_primes(): assert filter_primes([2, 3, 5, 7, 11, 13, 17]) == [2, 3, 5, 7, 11, 13, 17] def test_mixed_numbers(): assert filter_primes([...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers from the input list of integers.\n\nParameters:\nnumbers (list): A list of inte...
[ 0, 1, 1, 1, 0, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2 or n == 3:\n return True\n ...
trial_gpt4o_7
{ "original_instruction": "Implement a function that takes a list of integers and returns a new list containing only the prime numbers from the original list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your implementation should have a time complexity that...
0.783977
Evol_9431
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
df8533f180b58846bece1e83d0c1c6971fb2dcbd
818759d11ec81d7524d047a6c44a49b8d11a8a68
v1.0
complete
Evol
Evol_7155_C
import pandas as pd import matplotlib.pyplot as plt def load_weather_data(file_path): """ Load weather data from a CSV file. """ pass def preprocess_data(data): """ Preprocess data by parsing dates and handling missing/incomplete data. """ pass def calculate_monthly_statistics(data): ...
import pandas as pd import matplotlib.pyplot as plt def load_weather_data(file_path): """ Load weather data from a CSV file. """ return pd.read_csv(file_path) def preprocess_data(data): """ Preprocess data by parsing dates and handling missing/incomplete data. """ data['date'] = pd.to_...
import pandas as pd from io import StringIO from solution import load_weather_data, preprocess_data, calculate_monthly_statistics, identify_extreme_cities, analyze_weather_data def test_load_weather_data(): data = "date,city,temperature\n2023-01-01,CityA,30\n2023-01-02,CityA,25" df = load_weather_data(StringIO...
[ { "docstring": "Load weather data from a CSV file.", "function_declaration": "def load_weather_data(file_path):", "function_name": "load_weather_data", "parameter_list": "(file_path)" }, { "docstring": "Preprocess data by parsing dates and handling missing/incomplete data.", "function_de...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndef load_dataset(file_path):\n \"\"\"\n Loads the weather dataset from a specified file path into a p...
trial_gpt4o_9
{ "original_instruction": "You are given a dataset of historical weather data with various attributes such as temperature, humidity, wind speed, and date taken for different cities. Your task is to write a Python script that achieves the following objectives:\n\n1. Parse the dataset and load it into an appropriate da...
0.777493
Evol_7155
C
[ "load_weather_data", "preprocess_data", "calculate_monthly_statistics", "identify_extreme_cities", "plot_temperature_comparison", "analyze_weather_data" ]
6
[ [ "analyze_weather_data", "calculate_monthly_statistics" ], [ "analyze_weather_data", "identify_extreme_cities" ], [ "analyze_weather_data", "load_weather_data" ], [ "analyze_weather_data", "plot_temperature_comparison" ], [ "analyze_weather_data", "preprocess...
5
[]
false
[]
false
pytest
true
[ "matplotlib", "pandas" ]
false
3cca00b4930d0e32c4480302c461ebeedee905fb
7f1b851bcc12a0390429c79cb95e2852a2f95f72
v1.0
complete
Evol
Evol_9401_C
from typing import List def is_prime(n: int) -> bool: """ Determines if n is a prime number. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(11) True >>> is_prime(21) False >>> is_prime(1) False >>> is_prime(0) False >>> is_prime(-5) False """ ...
def is_prime(n): """ Determines if n is a prime number. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def filter_primes(numbers): ...
from solution import is_prime, filter_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(11) == True assert is_prime(21) == False assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-5) == Fal...
[ { "docstring": "Determines if n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers from the given list of integers.", "function_declaration": "def filter_primes(numbers):...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_9
{ "original_instruction": "Write a function that takes a list of integers as input and returns a new list containing only the prime numbers from the input list. To determine if a number is prime, check if it is greater than 1 and has no divisors other than 1 and itself.\n\nExample input: [2, 3, 4, 5, 6, 7, 8, 9, 10, ...
0.807422
Evol_9401
C
[ "is_prime", "filter_primes" ]
2
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0264bce0263c206fc3da1df0736ca9815d8716ad
203449eff1415de7332e122854ea9125c132dd2f
v1.0
complete
Evol
Evol_9000_C
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score def load_and_preprocess_data(file_path): """ Load and preprocess the weather data from a CSV f...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score def load_and_preprocess_data(file_path): """ Load and preprocess the weather data from a CSV f...
import pandas as pd import numpy as np from sklearn.datasets import make_classification from solution import load_and_preprocess_data, train_predictive_model, forecast_precipitation # Create a temporary sample dataset def create_temp_csv(): X, y = make_classification(n_samples=100, n_features=5, n_classes=2, rando...
[ { "docstring": "Load and preprocess the weather data from a CSV file.\n\nParameters:\nfile_path (str): The path to the CSV file containing the weather data.\n\nReturns:\nX_train, X_test, y_train, y_test: Split and scaled training and testing data.", "function_declaration": "def load_and_preprocess_data(file...
[ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomFor...
trial_gpt4o_9
{ "original_instruction": "You are given a dataset containing historical weather data for a city, including features such as temperature, humidity, and wind speed along with a label indicating whether precipitation was observed on that day. Using this dataset, build a predictive model to forecast precipitation for fu...
0.777692
Evol_9000
C
[ "load_and_preprocess_data", "train_predictive_model", "forecast_precipitation" ]
3
[ [ "forecast_precipitation", "load_and_preprocess_data" ], [ "forecast_precipitation", "train_predictive_model" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
d1edf751e45ee36cf694bc1f8be6a6a8f146501d
4231afd37cfc7e45ac68a69f7b0240b833a81f53
v1.0
complete
Evol
Evol_8540_C
def find_armstrong_numbers(low, high): """ Determine all the Armstrong numbers within a specified range. An Armstrong number (also known as a narcissistic number) for a given number of digits is a number that is equal to the sum of its own digits each raised to the power of the number of digits. ...
def is_armstrong(number): """ Checks if a number is an Armstrong number. """ digits = [int(d) for d in str(number)] power = len(digits) return number == sum(d ** power for d in digits) def find_armstrong_numbers(low, high): """ Returns a list of all Armstrong numbers between low and hig...
from solution import find_armstrong_numbers import pytest def test_same_low_high_value(): assert find_armstrong_numbers(153, 153) == [153] def test_standard_range_with_multiple_armstrongs(): assert set(find_armstrong_numbers(100, 500)) == {153, 370, 371, 407} def test_range_with_no_armstrongs(): assert ...
[ { "docstring": "Checks if a number is an Armstrong number.", "function_declaration": "def is_armstrong(number):", "function_name": "is_armstrong", "parameter_list": "(number)" }, { "docstring": "Returns a list of all Armstrong numbers between low and high (inclusive).\nBoth low and high shou...
[ 1, 0, 0, 1, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_armstrong(number):\n \"\"\"\n Check if the number is an Armstrong number.\n \"\"\"\n digits = list(map(int, str(number)))\n power = len(digit...
trial_gpt4o_9
{ "original_instruction": "Create a function to determine all the Armstrong numbers within a specified range. An Armstrong number (also known as a narcissistic number) for a given number of digits is a number that is equal to the sum of its own digits each raised to the power of the number of digits.\n\nThe function ...
0.528444
Evol_8540
C
[ "is_armstrong", "find_armstrong_numbers" ]
2
[ [ "find_armstrong_numbers", "is_armstrong" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8b3d4163adf01392643a4424474728f144c5d1c9
a619d48439b31e6d92664188b7ead0ac16a638ce
v1.0
complete
Evol
Evol_9509_C
def is_prime(num: int) -> bool: """ Returns True if num is a prime number, else False. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(5) True >>> is_prime(1) False >>> is_prime(0) False >>> is_prime(-3) False >>> is_prime(19) True >>> is_prime(20...
def is_prime(num): """ Returns True if num is a prime number, else False. """ if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def extract_primes(nums): """ Returns a list containing only the prime num...
from solution import extract_primes, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-3) == False assert is_prime(19) == Tru...
[ { "docstring": "Returns True if num is a prime number, else False.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns a list containing only the prime numbers from the original list 'nums'.", "function_declara...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Checks if a number is a prime.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\...
trial_gpt4o_9
{ "original_instruction": "Write a function that takes a list of integers and returns a new list containing only the prime numbers from the original list. The function should preserve the order of elements as in the original list.\nFor example:\n>>> extract_primes([2, 3, 4, 5, 6, 7, 8, 9, 10])\n[2, 3, 5, 7]\n>>> extr...
0.778159
Evol_9509
C
[ "is_prime", "extract_primes" ]
2
[ [ "extract_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8bb8416c8dddf47919d0b24d498703abcdbe4c5a
c03ab4dcb0638d73a8113fc99941caf362239f13
v1.0
complete
Evol
Evol_4471_C
from typing import List def is_fibonacci_number(n: int) -> bool: """ Check if a number is a Fibonacci number by checking if one of (5*n*n + 4) or (5*n*n - 4) is a perfect square. >>> is_fibonacci_number(0) == True >>> is_fibonacci_number(1) == True >>> is_fibonacci_number(4) == False >>> is_fibonac...
def is_fibonacci_number(n): """ Check if a number is a Fibonacci number by checking if one of (5*n*n + 4) or (5*n*n - 4) is a perfect square. """ if n < 0: return False def is_perfect_square(x): s = int(x ** 0.5) return s * s == x return is_perfect_square(5 * n * n...
from solution import filter_fibonacci_numbers, is_fibonacci_number def test_is_fibonacci_number(): assert is_fibonacci_number(0) == True assert is_fibonacci_number(1) == True assert is_fibonacci_number(2) == True assert is_fibonacci_number(3) == True assert is_fibonacci_number(4) == False asser...
[ { "docstring": "Check if a number is a Fibonacci number by checking if one of \n(5*n*n + 4) or (5*n*n - 4) is a perfect square.", "function_declaration": "def is_fibonacci_number(n):", "function_name": "is_fibonacci_number", "parameter_list": "(n)" }, { "docstring": "Returns a list of elemen...
[ 1, 0, 1, 1, 0, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef is_fibonacci(n):\n \"\"\"\n Returns True if n is a Fibonacci number, else False.\n \"\"\"\n if n < 0:\n return False\n # A...
trial_gpt4o_9
{ "original_instruction": "Develop a Python function that takes a list of integers and returns a new list containing only the elements that are Fibonacci numbers from the original list. Utilize an efficient algorithm to determine if a number is a Fibonacci number.", "prompt_id": "00004471", "row_id": 4471, "see...
0.74626
Evol_4471
C
[ "is_fibonacci_number", "filter_fibonacci_numbers" ]
2
[ [ "filter_fibonacci_numbers", "is_fibonacci_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7c9a4b5a42663814447bf6b4c2ff9653f7075688
dba9b3e99aa2e91afd8350a05fc3ac0c23d38703
v1.0
complete
Evol
Evol_9305_C
import os import logging logging.basicConfig(level=logging.ERROR) def count_lines_in_file(file_path: str, exclude_blank_lines: bool) -> int: """ Counts the number of lines in a given file. Parameters: file_path (str): The path to the file. exclude_blank_lines (bool): Whether to exclude blank ...
import os import logging logging.basicConfig(level=logging.ERROR) def count_lines_in_file(file_path, exclude_blank_lines): """ Counts the number of lines in a given file. Parameters: file_path (str): The path to the file. exclude_blank_lines (bool): Whether to exclude blank lines from the cou...
from solution import count_lines_in_file, total_lines def test_count_lines_in_file(): with open('test_file.txt', 'w') as f: f.write("Line 1\n\nLine 3\n") assert count_lines_in_file('test_file.txt', exclude_blank_lines=False) == 3 assert count_lines_in_file('test_file.txt', exclude_blank_lines=...
[ { "docstring": "Counts the number of lines in a given file.\n\nParameters:\nfile_path (str): The path to the file.\nexclude_blank_lines (bool): Whether to exclude blank lines from the count.\n\nReturns:\nint: The number of lines in the file, or 0 if the file cannot be read.", "function_declaration": "def co...
[ 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import os\n\ndef count_lines_in_file(file_path, exclude_blank_lines=False):\n \"\"\"\n Count the number of lines in a given file.\n \n Parameters:\n ...
trial_gpt4o_6
{ "original_instruction": "Create a command-line application that accepts a list of file paths as input and returns the total number of lines across all the files. If a file path is invalid or the file cannot be read, the application should gracefully handle this scenario by logging an appropriate error message and c...
0.582026
Evol_9305
C
[ "count_lines_in_file", "total_lines" ]
2
[ [ "total_lines", "count_lines_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
99683a4be7a9d44019f465f74c55b0c4b5fbed46
324952e5de960582e58f09d62917fbb33f68a026
v1.0
complete
Evol
Evol_9342_C
def is_prime(n: int) -> bool: """ Check if a number is prime. """ ... def reorganize_list(numbers: List[int]) -> List[int]: """ Reorganize a given list of integers such that all prime numbers appear first in ascending order, followed by non-prime numbers in descending order without di...
def is_prime(n): """ Check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def reorganize_list(numbers): ...
import pytest from solution import reorganize_list def test_reorganize_list_example(): assert reorganize_list([11, 17, 8, 4, 7, 2, 15, 22]) == [2, 7, 11, 17, 22, 15, 8, 4] def test_reorganize_list_all_primes(): assert reorganize_list([2, 3, 5, 7, 11]) == [2, 3, 5, 7, 11] def test_reorganize_list_all_non_prim...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Reorganizes the list of integers such that all prime numbers appear first \nin ascending order, followed by non-prime numbers in d...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n ...
trial_gpt4o_8
{ "original_instruction": "Reorganize a given list of integers such that all prime numbers appear first in ascending order, followed by non-prime numbers in descending order without disturbing their relative order from the original list. Return the reorganized list.\nnumbers = [11, 17, 8, 4, 7, 2, 15, 22]", "prompt...
0.619116
Evol_9342
C
[ "is_prime", "reorganize_list" ]
2
[ [ "reorganize_list", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d52cc5b720a45404f22616be3189b173138e9c69
989db5c410f6dc06a9e12216b7e3dabf1e51d455
v1.0
complete
Evol
Evol_8264_C
import sqlite3 from contextlib import contextmanager from typing import List, Tuple, Optional @contextmanager def open_connection(db_name: str): """ Context manager for opening and closing the SQLite database connection. """ conn = sqlite3.connect(db_name) try: yield conn finally: conn....
import sqlite3 from contextlib import contextmanager @contextmanager def open_connection(db_name): conn = sqlite3.connect(db_name) try: yield conn finally: conn.close() def create_books_table(db_name): with open_connection(db_name) as conn: cursor = conn.cursor() cursor...
import os import pytest from solution import ( create_books_table, add_book, get_book, update_book, delete_book, search_books_by_title_author, list_books_by_date_range ) DB_NAME = 'test_library.db' @pytest.fixture(scope='module', autouse=True) def setup_db(): # Create a temporary datab...
[ { "docstring": null, "function_declaration": "def open_connection(db_name):", "function_name": "open_connection", "parameter_list": "(db_name)" }, { "docstring": null, "function_declaration": "def create_books_table(db_name):", "function_name": "create_books_table", "parameter_li...
[ 0, 0, 1, 1, 0, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_evol-i2i_10000_1735980704_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import sqlite3\nfrom contextlib import closing\n\nDB_NAME = \"library.db\"\n\ndef create_connection():\n return sqlite3.connect(DB_NAME)\n\ndef initialize_db():...
trial_gpt4o_7
{ "original_instruction": "Create a Python script that interacts with a SQLite database to manage a collection of books in a library. The script should allow users to perform CRUD operations on the books, where each book has a title, author, publication date, and genre. Implement search functionality to query the dat...
0.600347
Evol_8264
C
[ "open_connection", "create_books_table", "add_book", "get_book", "update_book", "delete_book", "search_books_by_title_author", "list_books_by_date_range" ]
8
[ [ "add_book", "open_connection" ], [ "create_books_table", "open_connection" ], [ "delete_book", "open_connection" ], [ "get_book", "open_connection" ], [ "list_books_by_date_range", "open_connection" ], [ "search_books_by_title_author", "open_conn...
7
[]
false
[]
false
pytest
true
[]
true
96cc3bcd797f444dc36fc6e6d32db1712203026b
6953237552f307bb26915fc75a5ada3d7074c212
v1.0
complete
Algorithm
Algorithm_20289_C
from typing import List def gcd(a: int, b: int) -> int: """ Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm. >>> gcd(48, 18) ->int 6 >>> gcd(0, 18) ->int 18 >>> gcd(48, 0) ->int 48 >>> gcd(0, 0) ->int 0 >>> gcd(7, 1) ->int 1 >>> gcd(20, 5) ->int 5 """ ...
from typing import List from functools import reduce import math def gcd(a: int, b: int) -> int: """ Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm. """ while b: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """ Returns the least commo...
from solution import gcd, lcm, gcd_of_list, lcm_of_list def test_gcd(): assert gcd(48, 18) == 6 assert gcd(0, 18) == 18 assert gcd(48, 0) == 48 assert gcd(0, 0) == 0 assert gcd(7, 1) == 1 assert gcd(20, 5) == 5 def test_lcm(): assert lcm(4, 5) == 20 assert lcm(0, 5) == 0 assert lcm...
[ { "docstring": "Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of a and b using the relationship betw...
[ 1, 1, 0, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\nfrom functools import reduce\nimport math\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment Question\n\n**Scenario**: Algorithms often rely on certain mathematical properties or operations to solve problems efficiently. One such commonly used operation is determining the greatest common divisor (GCD) of two numbers, which finds the largest number that divides...
0.801125
Algorithm_20289
C
[ "gcd", "lcm", "gcd_of_list", "lcm_of_list" ]
4
[ [ "gcd_of_list", "gcd" ], [ "lcm", "gcd" ], [ "lcm_of_list", "lcm" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4970dc756f6ead56cfa9954fe522d21e7dea7946
0a6643d500522a1ab24fdf10fe723baf577a6920
v1.0
complete
Algorithm
Algorithm_16033_C
from typing import List def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Rotates a given NxN matrix 90 degrees clockwise. >>> rotate_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[7, 4, 1], [8, 5, 2], [9, 6, 3]] >>> rotate_matrix([[1, 2], [3, 4]]) [[3, 1], [4, 2]] """ pas...
from typing import List def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Rotates a given NxN matrix 90 degrees clockwise. """ n = len(matrix) new_matrix = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): new_matrix[j][n-i-1] = matrix[i][...
from solution import rotate_matrix, are_matrices_identical_after_rotation def test_rotate_matrix_3x3(): matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] expected = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] assert rotate_matrix(matrix) == expected ...
[ { "docstring": "Rotates a given NxN matrix 90 degrees clockwise.", "function_declaration": "def rotate_matrix(matrix):", "function_name": "rotate_matrix", "parameter_list": "(matrix)" }, { "docstring": "Checks if the original matrix is identical to the rotated matrix after a 90 degrees rotat...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates an N x N matrix by 90 degrees clockwise.\n ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Objective:\nImplement a function that rotates a square matrix 90 degrees clockwise. Then, create another function that verifies if two matrices are identical after rotation.\n\n#### Problem Statement:\nYou need to create a function `rotate_matrix(matri...
0.530156
Algorithm_16033
C
[ "rotate_matrix", "are_matrices_identical_after_rotation" ]
2
[ [ "are_matrices_identical_after_rotation", "rotate_matrix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a2bd81c4ee15c163ee1d6c4ed5c5ae3a4ec64140
ad780279d82d91fc13c7f18d3cb6ad1e7cb4b100
v1.0
complete
Algorithm
Algorithm_205_C
def a_star_pathfinding(maze, start, goal): """ Implements the A* pathfinding algorithm to find the shortest path from start to goal in a grid maze. The maze is represented as a 2D list where `0` represents an open cell and `1` represents an obstacle. The agent can move horizontally or vertically but no...
import heapq def heuristic(a, b): """ Calculate the Manhattan distance between point a and point b. """ return abs(a[0] - b[0]) + abs(a[1] - b[1]) def a_star_pathfinding(maze, start, goal): """ Implements the A* pathfinding algorithm to find the shortest path from start to goal in a grid maze....
from solution import a_star_pathfinding def test_simple_path(): maze = [ [0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1], [1, 1, 0, 0] ] start = (0, 0) goal = (2, 2) expected_path = [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)] assert a_star_pathfinding(maze, start, goal) ==...
[ { "docstring": "Calculate the Manhattan distance between point a and point b.", "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": "Implements the A* pathfinding algorithm to find the shortest path from start to goal in ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\n\ndef a_star_pathfinding(maze, start, goal):\n def heuristic(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n \n rows, cols = ...
trial_gpt4o_6
{ "original_instruction": "### Pathfinding in a Grid Maze\n\n#### Context\nPathfinding algorithms are essential in robotics and AI, used for navigating agents through environments. One popular algorithm is A* (A-star), which combines features of uniform-cost search and pure heuristic search to efficiently find the sh...
0.582165
Algorithm_205
C
[ "heuristic", "a_star_pathfinding" ]
2
[ [ "a_star_pathfinding", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6be7ce93f04d5db742ab9cfcfbdf07f42417a65a
ecc8dfc90920957356191947f50604fa08887f47
v1.0
complete
Algorithm
Algorithm_25613_C
def merge_sort(array: list[int]) -> list[int]: """Sort a list of integers using the merge sort algorithm and return the sorted list. Args: array (list[int]): A list of integers to sort. Returns: list[int]: A new list containing the elements of the input list in non-decreasing order...
def merge_sort(array): # Base case: arrays with fewer than 2 elements are already sorted if len(array) < 2: return array # Split array into two halves mid = len(array) // 2 left_half = merge_sort(array[:mid]) right_half = merge_sort(array[mid:]) # Merge sorted halves re...
from solution import merge_sort def test_merge_sort_random(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_with_duplicates(): assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] ...
[ { "docstring": null, "function_declaration": "def merge_sort(array):", "function_name": "merge_sort", "parameter_list": "(array)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(array: list[int]) -> list[int]:\n \"\"\"\n Perform merge sort on a list of integers and return the sorted list.\n \"\"\"\n if len(arra...
trial_gpt4o_9
{ "original_instruction": "### Sorting a List Using Merge Sort\n\nYou are required to implement the merge sort algorithm to sort a list of integers in non-decreasing order. Your function will recursively divide the list into two halves, sort each half, and then merge the sorted halves into a single sorted list.\n\n##...
0.658091
Algorithm_25613
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7720e79c79169d60f9c21c2f8c96a9d31148063d
ccbf098c079ecbde11b5bec358f2940ecbf55b4d
v1.0
complete
Algorithm
Algorithm_27833_C
def is_circular_prime(n: int) -> bool: """ Check if a number is a circular prime. A circular prime is a prime number that remains prime when its digits are cyclically rotated in any order. >>> is_circular_prime(197) True >>> is_circular_prime(101) False >>> is_circular_prime(71) ...
def is_prime(num): """Helper function to check if a number is prime.""" if num < 2: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True def rotations(n): """Generate all cyclic rotations of an integer n.""" s = str(n) retu...
from solution import is_circular_prime def test_single_digit_primes(): assert is_circular_prime(2) == True assert is_circular_prime(3) == True assert is_circular_prime(5) == True assert is_circular_prime(7) == True def test_non_circular_primes(): assert is_circular_prime(23) == False # 23 -> 32 ...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Generate all cyclic rotations of an integer n.", "function_declaration": "def rotations(n):", "func...
[ 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + ...
trial_gpt4o_0
{ "original_instruction": "### Problem Statement\n\nIn this task, you will write a function that checks if a number is a circular prime. A circular prime is a prime number that remains prime when its digits are cyclically rotated in any order.\n\n### Guidelines\n\n- Implement a function `is_circular_prime(n: int) -> ...
0.755669
Algorithm_27833
C
[ "is_prime", "rotations", "is_circular_prime" ]
3
[ [ "is_circular_prime", "is_prime" ], [ "is_circular_prime", "rotations" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cf3ec888a103969785b8c4ebe7886aa91dfe9d82
0e0401485e67c044a911f2bf761b9c26cea4bb07
v1.0
complete
Algorithm
Algorithm_36214_C
### Completion Task Implement the following: import requests from datetime import datetime, timedelta def get_historical_price(api_key: str, symbol: str, date: str) -> float: url = f"https://api.coingecko.com/api/v3/coins/{symbol}/history" params = {'date': date.replace('-', ''), 'localization': 'false'} ...
import requests from datetime import datetime, timedelta def get_historical_price(api_key: str, symbol: str, date: str) -> float: url = f"https://api.coingecko.com/api/v3/coins/{symbol}/history" params = {'date': date.replace('-', ''), 'localization': 'false'} try: response = requests.get(url, para...
from solution import get_historical_price, get_portfolio_value_by_date_range, get_current_portfolio_value import requests def test_get_historical_price(monkeypatch): class MockResponse: @staticmethod def json(): return { "market_data": { "current_pric...
[ { "docstring": null, "function_declaration": "def get_historical_price(api_key, symbol, date):", "function_name": "get_historical_price", "parameter_list": "(api_key, symbol, date)" }, { "docstring": null, "function_declaration": "def get_portfolio_value_by_date_range(api_key, portfolio,...
[ 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 requests\nfrom datetime import datetime, timedelta\n\ndef get_historical_price(api_key: str, symbol: str, date: str) -> float:\n url = f\"https://api.c...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment Question\n\nYou are required to extend the functionality of a program that monitors a cryptocurrency portfolio using a public API. The existing implementation calculates the current value of the portfolio based on real-time prices. Now, extend the functionality to incl...
0.562023
Algorithm_36214
C
[ "get_historical_price", "get_portfolio_value_by_date_range", "get_current_portfolio_value" ]
3
[ [ "get_portfolio_value_by_date_range", "get_historical_price" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
a8dfc0171391fdb705d770e562d46394ad5fdba4
23c4d71093233766fb45233a150a7bb364157234
v1.0
complete
Algorithm
Algorithm_34302_C
def is_leap_year(year: int) -> bool: """ Check if a year is a leap year. >>> is_leap_year(2020) True >>> is_leap_year(2019) False >>> is_leap_year(2000) True >>> is_leap_year(1900) False """ pass def days_in_month(month: int, year: int) -> int: """ Return the num...
def is_leap_year(year): """Check if a year is a leap year.""" if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False return True return False def days_in_month(month, year): """Return the number of...
def test_is_leap_year(): assert is_leap_year(2020) == True assert is_leap_year(2019) == False assert is_leap_year(2000) == True assert is_leap_year(1900) == False def test_days_in_month(): assert days_in_month(1, 2020) == 31 assert days_in_month(2, 2020) == 29 assert days_in_month(2, 2021) ...
[ { "docstring": "Check if a year is a leap year.", "function_declaration": "def is_leap_year(year):", "function_name": "is_leap_year", "parameter_list": "(year)" }, { "docstring": "Return the number of days in a given month of a particular year.", "function_declaration": "def days_in_mont...
[ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_leap_year(year):\n \"\"\"\n Returns True if the given year is a leap year, otherwise False.\n \"\"\"\n if year % 4 == 0:\n if year % 10...
trial_gpt4o_9
{ "original_instruction": "### Scenario\nYou are developing a module for a financial application that must handle and process dates efficiently. You need a function that calculates the difference between two given dates and returns the result in days. Given your understanding of date manipulation, implement this func...
0.608211
Algorithm_34302
C
[ "is_leap_year", "days_in_month", "days_in_year_to_date", "days_between_years", "days_difference" ]
5
[ [ "days_between_years", "is_leap_year" ], [ "days_difference", "days_between_years" ], [ "days_difference", "days_in_year_to_date" ], [ "days_difference", "is_leap_year" ], [ "days_in_month", "is_leap_year" ], [ "days_in_year_to_date", "days_in_mon...
6
[]
false
[]
false
pytest
false
[]
true
ec430e55194970856490b09f44386f9280c07107
b4f144da3844a09f5a73ba4c223902a1deb7bf2e
v1.0
complete
Algorithm
Algorithm_45487_C
def merge_sort(arr: list) -> list: """Implement the merge sort algorithm, a classic divide-and-conquer sorting technique. >>> merge_sort([]) == [] True >>> merge_sort([3]) == [3] True >>> merge_sort([3, 1, 2]) == [1, 2, 3] True >>> merge_sort([5, 2, 9, 1]) == [1, 2, 5, 9] True ...
def merge_sort(arr: list) -> list: if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left: list, right: list) -> list: sorted_arr = [] left_idx, right_idx = 0,...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([3]) == [3] def test_merge_sort_sorted(): assert merge_sort([1, 2, 3]) == [1, 2, 3] def test_merge_sort_unsorted(): assert merge_sort([3, 1, 2]) == [1...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr: list) -> list:\n \"\"\"\n Sorts the given list of integers using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n### Implementing a Merge Sort Algorithm\n\nYou are required to implement the merge sort algorithm, a classic divide-and-conquer sorting technique. Merge sort is known for its efficiency and consistency in performance.\n\n### Objective\nImplement a function `m...
0.556717
Algorithm_45487
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f4c399da1b6806a12f9d1a27a162dcbc71d12f03
81d2c876c5e7cd5a3cf954d742fa7a18f5d27c05
v1.0
complete
Algorithm
Algorithm_44121_C
from typing import List def get_active_ips(logs: List[str]) -> List[str]: """Returns a sorted list of unique IP addresses that have a status of 'ACTIVE'. >>> get_active_ips(["192.168.0.1 - ACTIVE", "192.168.0.2 - INACTIVE", "192.168.0.1 - ACTIVE"]) ['192.168.0.1'] >>> get_active_ips(["10.0.0.1 - ACTIV...
from typing import List import re def validate_ip(ip: str) -> bool: """ Validate an IP address to ensure it follows a valid IPv4 format. """ pattern = re.compile( r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' ) return pattern.match(...
import pytest from solution import get_active_ips def test_single_active_ip(): logs = ["192.168.0.1 - ACTIVE", "192.168.0.2 - INACTIVE", "192.168.0.1 - ACTIVE"] assert get_active_ips(logs) == ["192.168.0.1"] def test_multiple_active_ips(): logs = ["10.0.0.1 - ACTIVE", "192.168.1.1 - ACTIVE", ...
[ { "docstring": "Validate an IP address to ensure it follows a valid IPv4 format.", "function_declaration": "def validate_ip(ip):", "function_name": "validate_ip", "parameter_list": "(ip)" }, { "docstring": "Returns a sorted list of unique IP addresses that have a status of \"ACTIVE\".", ...
[ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef get_active_ips(logs: List[str]) -> List[str]:\n \"\"\"\n Extracts unique active IP addresses from the log entries and return...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n#### Scenario:\nYour task is to develop a utility function for monitoring a network by checking the IP addresses that are currently active. For simplicity, we'll use IPv4 addresses, and you need to identify and return the active IP addresses in a sorted ord...
0.669327
Algorithm_44121
C
[ "validate_ip", "get_active_ips" ]
2
[ [ "get_active_ips", "validate_ip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8399515d546c663667efeb0323c0d5a52c81869d
a77cab97cddf8ec2512162abe10cca696ff41f0c
v1.0
complete
Algorithm
Algorithm_36327_C
def is_magic_square(square: List[List[int]]) -> bool: """ Check if a given 3x3 square is a magic square. :param square: List of lists representing the 3x3 square. :return: Boolean indicating if the square is a magic square. """ def count_magic_squares() -> int: """ Find and count all p...
from itertools import permutations def is_magic_square(square): """ Check if a given 3x3 square is a magic square. :param square: List of lists representing the 3x3 square. :return: Boolean indicating if the square is a magic square. """ # Calculate the sums of rows, columns, and diagonals...
from solution import is_magic_square, count_magic_squares def test_is_magic_square(): assert is_magic_square([[2, 7, 6], [9, 5, 1], [4, 3, 8]]) is True assert is_magic_square([[8, 1, 6], [3, 5, 7], [4, 9, 2]]) is True assert is_magic_square([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) is False def test_count_magic_...
[ { "docstring": "Check if a given 3x3 square is a magic square.\n\n:param square: List of lists representing the 3x3 square.\n:return: Boolean indicating if the square is a magic square.", "function_declaration": "def is_magic_square(square):", "function_name": "is_magic_square", "parameter_list": "(...
[ 1, 1, 0, 1, 1, 0, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef is_magic_square(square):\n # Check rows\n for i in range(0, 9, 3):\n if sum(square[i:i+3]) != 15:\n ...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\nA valid magic square is a grid of numbers where the sum of every row, column, and diagonal is the same. You are required to generate all possible 3x3 magic squares and count how many unique ones exist when arranging the numbers from 1 to 9 without repetition.\n\n**Fun...
0.659859
Algorithm_36327
C
[ "is_magic_square", "count_magic_squares" ]
2
[ [ "count_magic_squares", "is_magic_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a1f60fafe72619700ba472c0a0351346dad54dc
e9da906dd0773bdb6e116463969ac8cb4af6ea5b
v1.0
complete
Algorithm
Algorithm_44945_C
from typing import List def rotate_90(matrix: List[List[int]]) -> List[List[int]]: """Returns the matrix rotated by 90 degrees clockwise.""" return [list(row) for row in zip(*matrix[::-1])] def is_rotation(A: List[List[int]], B: List[List[int]]) -> bool: """ Check if matrix B is a rotation of matrix A by ...
from typing import List def rotate_90(matrix: List[List[int]]) -> List[List[int]]: """Returns the matrix rotated by 90 degrees clockwise.""" return [list(row) for row in zip(*matrix[::-1])] def is_rotation(A: List[List[int]], B: List[List[int]]) -> bool: """Check if matrix B is a rotation of matrix A by 9...
def test_is_rotation(): A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] B_90 = [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] B_180 = [ [9, 8, 7], [6, 5, 4], [3, 2, 1] ] B_270 = [ [3, 6, 9], [2, 5, 8], [1, 4, 7] ...
[ { "docstring": "Returns the matrix rotated by 90 degrees clockwise.", "function_declaration": "def rotate_90(matrix):", "function_name": "rotate_90", "parameter_list": "(matrix)" }, { "docstring": "Check if matrix B is a rotation of matrix A by 90, 180, or 270 degrees.", "function_declar...
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef rotate_90(matrix: List[List[int]]) -> List[List[int]]:\n n = len(matrix)\n rotated = [[0] * n for _ in range(n)]\n for i ...
trial_gpt4o_5
{ "original_instruction": "### Matrix Rotation Check: Is It a Rotation?\n\n#### Problem Statement\n\nYou are given two `n x n` matrices, `A` and `B`, where `n` is a positive integer. The goal is to determine if matrix `B` can be obtained by rotating matrix `A` (by 90, 180, or 270 degrees).\n\nWrite a function `is_rot...
0.543784
Algorithm_44945
C
[ "rotate_90", "is_rotation" ]
2
[ [ "is_rotation", "rotate_90" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b339a197cbedad6e42e7ba31a2ac143dbb856120
882a578ba85203c27a7f269e80b0cfbf9e2b8fa3
v1.0
complete
Algorithm
Algorithm_43482_C
def sum_of_primes(a: int, b: int) -> int: """ Calculate the sum of all prime numbers within the specified range [a, b]. >>> sum_of_primes(10, 20) 60 >>> sum_of_primes(1, 5) 10 >>> sum_of_primes(13, 13) 13 >>> sum_of_primes(14, 16) 0 >>> sum_of_primes(1, 1000) 76127 >...
def is_prime(n): """ Helper function to check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def sum_of_pr...
from solution import sum_of_primes def test_sum_of_primes_range_10_20(): assert sum_of_primes(10, 20) == 60 def test_sum_of_primes_range_1_5(): assert sum_of_primes(1, 5) == 10 def test_sum_of_primes_single_prime(): assert sum_of_primes(13, 13) == 13 def test_sum_of_primes_no_primes(): assert sum_of...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the sum of all prime numbers in the range [a, b].", "function_declaration": "def sum_of_primes(a, b...
[ 0, 1, 0, 1, 1, 0, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ...
trial_gpt4o_9
{ "original_instruction": "### Sum of Primes in a Range\n\n#### Context\nIn many applications, it's crucial to identify and work with prime numbers efficiently. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. For instance, the primes between 1 and 10 are 2, 3, 5...
0.713156
Algorithm_43482
C
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4b0d9b1cde197a277ff1c3265b21ae5d855bb5e8
b2996ddd2b28be8c1465aeecb2bd517f75c73874
v1.0
complete
Algorithm
Algorithm_17469_C
def merge_intervals(intervals): """ Merges overlapping intervals. """ if not intervals: return [] intervals.sort(key=lambda x: x[0]) merged = [intervals[0]] for current in intervals[1:]: last = merged[-1] if current[0] <= last[1]: # Overlap mer...
def merge_intervals(intervals): """ Merges overlapping intervals. """ if not intervals: return [] intervals.sort(key=lambda x: x[0]) merged = [intervals[0]] for current in intervals[1:]: last = merged[-1] if current[0] <= last[1]: # Overlap mer...
from solution import schedule_resources def test_no_tasks(): maintenance = (6, 10) tasks = [] assert schedule_resources(tasks, maintenance) == [(0, 6), (10, float('inf'))] def test_no_overlap(): tasks = [(1, 5), (8, 10)] maintenance = (12, 15) assert schedule_resources(tasks, maintenance) == [...
[ { "docstring": "Merges overlapping intervals.", "function_declaration": "def merge_intervals(intervals):", "function_name": "merge_intervals", "parameter_list": "(intervals)" }, { "docstring": "Subtract one interval from a list of intervals.", "function_declaration": "def subtract_interv...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_intervals(intervals):\n \"\"\" Merges overlapping intervals and returns a new list of the merged intervals. \"\"\"\n if not intervals:\n r...
trial_gpt4o_8
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\nYou have been given a utility function `merge_intervals` that merges a list of overlapping intervals and returns a new list of the merged intervals. Your task is to use this function effectively to create new functionality for scheduling resou...
0.539771
Algorithm_17469
C
[ "merge_intervals", "subtract_intervals", "schedule_resources" ]
3
[ [ "schedule_resources", "merge_intervals" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8311096f115900b12b0a8413d9bdb0699a3aa246
5ab47b49665463c7cd1926251a8b239f84d72b21
v1.0
complete
Algorithm
Algorithm_39720_C
def kmp_search(s: str, p: str) -> int: """Find the starting index of the first occurrence of the pattern `p` in the string `s` using the Knuth-Morris-Pratt (KMP) algorithm. If the pattern is not found, return -1. >>> kmp_search("ababcababcabc", "abc") == 2 >>> kmp_search("hello", "ll") == 2 ...
def build_kmp_table(p): """ Build the KMP table for the given pattern. """ m = len(p) kmp_table = [0] * m j = 0 for i in range(1, m): while j > 0 and p[i] != p[j]: j = kmp_table[j - 1] if p[i] == p[j]: j += 1 kmp_table[i] = j ...
def test_kmp_search(): assert kmp_search("ababcababcabc", "abc") == 2 assert kmp_search("hello", "ll") == 2 assert kmp_search("aaaaaaa", "bba") == -1 assert kmp_search("mississippi", "issi") == 1 assert kmp_search("a", "a") == 0 assert kmp_search("abcdef", "def") == 3 assert kmp_search("abcd...
[ { "docstring": "Build the KMP table for the given pattern.", "function_declaration": "def build_kmp_table(p):", "function_name": "build_kmp_table", "parameter_list": "(p)" }, { "docstring": "Returns the starting index of the first occurrence of the pattern `p` in the string `s`.\nIf the patt...
[ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def kmp_search(s: str, p: str) -> int:\n \"\"\"\n KMP algorithm to find the first occurrence of the pattern `p` in the string `s`.\n Returns the startin...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nYou are given a string `s` and a pattern `p`. Your task is to implement a function that finds the starting index of the first occurrence of the pattern `p` in the string `s` using the Knuth-Morris-Pratt (KMP) algorithm. If the pattern is not found, return -1.\n\n###...
0.527945
Algorithm_39720
C
[ "build_kmp_table", "kmp_search" ]
2
[ [ "kmp_search", "build_kmp_table" ] ]
1
[]
false
[]
false
pytest
false
[]
true
9d47d092cd80eb470a85db37de2da035357e1bc4
8e6ec77df3cfb310519ecd01986fdb3a447aaa6e
v1.0
complete
Algorithm
Algorithm_7739_C
def celsius_to_fahrenheit(celsius: float) -> float: """ Converts a temperature from Celsius to Fahrenheit. >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(100) 212.0 >>> celsius_to_fahrenheit(-40) -40.0 >>> celsius_to_fahrenheit(37) 98.6 """ def fahrenheit_to_celsius(fahrenheit...
def celsius_to_fahrenheit(celsius: float) -> float: """ Converts a temperature from Celsius to Fahrenheit. """ return (celsius * 9/5) + 32 def fahrenheit_to_celsius(fahrenheit: float) -> float: """ Converts a temperature from Fahrenheit to Celsius. """ return (fahrenheit - 32) * 5/9 de...
from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, temperature_converter def test_celsius_to_fahrenheit(): assert celsius_to_fahrenheit(0) == 32.0 assert celsius_to_fahrenheit(100) == 212.0 assert celsius_to_fahrenheit(-40) == -40.0 assert celsius_to_fahrenheit(37) == 98.6 def test_fah...
[ { "docstring": "Converts a temperature from Celsius to Fahrenheit.", "function_declaration": "def celsius_to_fahrenheit(celsius):", "function_name": "celsius_to_fahrenheit", "parameter_list": "(celsius)" }, { "docstring": "Converts a temperature from Fahrenheit to Celsius.", "function_de...
[ 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 celsius_to_fahrenheit(celsius: float) -> float:\n \"\"\"\n Converts a temperature from Celsius to Fahrenheit.\n \n Parameters:\n celsius (floa...
trial_gpt4o_8
{ "original_instruction": "### Objective\n\nImplement and validate the provided temperature and unit conversion functions with a focus on ensuring both correctness in conversions and handling edge cases effectively.\n\n### Question\n\nYou are tasked to implement three functions: `celsius_to_fahrenheit`, `fahrenheit_t...
0.547967
Algorithm_7739
C
[ "celsius_to_fahrenheit", "fahrenheit_to_celsius", "temperature_converter" ]
3
[ [ "temperature_converter", "celsius_to_fahrenheit" ], [ "temperature_converter", "fahrenheit_to_celsius" ] ]
2
[]
false
[]
false
pytest
true
[]
true
38ab0c7fd9310b24cffedb82e1b855a471e1ea80
f2da662a1d667f406a9790bbf8bfcf87f9a91c7a
v1.0
complete
Algorithm
Algorithm_23082_C
import math from functools import reduce def find_lcm(arr: list) -> int: """ Find the smallest positive integer that is a multiple of all numbers in the given array. >>> find_lcm([1, 2, 3, 4, 5]) == 60 >>> find_lcm([2, 7, 3, 9, 4]) == 252 >>> find_lcm([5, 10, 20]) == 20 """
import math from functools import reduce def lcm(a, b): """ Helper function to find the Least Common Multiple (LCM) of two numbers. """ return abs(a * b) // math.gcd(a, b) def find_lcm(arr): """ Returns the Least Common Multiple (LCM) of all the numbers in the array. """ return reduce(...
from solution import find_lcm def test_lcm_of_array_elements(): assert find_lcm([1, 2, 3, 4, 5]) == 60 assert find_lcm([2, 7, 3, 9, 4]) == 252 assert find_lcm([5, 10, 20]) == 20 assert find_lcm([12, 15, 25]) == 300 assert find_lcm([2]) == 2 assert find_lcm([100, 200, 300]) == 600 assert fin...
[ { "docstring": "Helper function to find the Least Common Multiple (LCM) of two numbers.", "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": "Returns the Least Common Multiple (LCM) of all the numbers in the array.", "function_d...
[ 1, 1, 1, 0, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom functools import reduce\n\ndef find_lcm(arr):\n \"\"\"\n Returns the least common multiple (LCM) of all the positive integers in the arra...
trial_gpt4o_9
{ "original_instruction": "### Problem Description\n\nYou are given an array `arr` of positive integers. Your task is to find the smallest positive integer that is a multiple of all the numbers in the array.\n\nWrite a function `find_lcm` that:\n\n- Takes `arr` as an input list of positive integers.\n- Returns the sm...
0.685089
Algorithm_23082
C
[ "lcm", "find_lcm" ]
2
[ [ "find_lcm", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e9727a6a17e6bf4eefe62086e71d713ab29b216b
12d2d3464bceaa502c61d708c0c05195c5d5ce27
v1.0
complete
Algorithm
Algorithm_28470_C
from typing import List def form_words(string: str, word_dict: List[str]) -> List[str]: """ Identifies all the words from the given dictionary that can be formed using the characters in the input string. >>> form_words("abppplee", ["apple", "pear", "plea", "banana"]) ['apple', 'plea'] >>> for...
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": "### Problem Statement\n\nYou 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...
0.671062
Algorithm_28470
C
[ "can_form_word", "form_words" ]
2
[ [ "form_words", "can_form_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
25aed2cd101d7e3d64dd24529ff8e14761ceaa81
c77be332ff668a303fb064fdd6e48cae88f54027
v1.0
complete
Algorithm
Algorithm_23380_C
from typing import List def rearrange_primes(numbers: List[int]) -> List[int]: """ Rearranges primes in a list in descending order while keeping non-primes in the same positions. Parameters: - numbers (List[int]): A list of integers containing both prime and non-prime numbers. Returns: - ...
from typing import List def is_prime(n: int) -> bool: """Helper function to check if a number is prime.""" if n <= 1: return False if n == 2: return True # 2 is the only even prime number if n % 2 == 0: return False # No other even number can be a prime for i in range(3, i...
def test_no_primes(): assert rearrange_primes([1, 4, 6, 8, 10]) == [1, 4, 6, 8, 10] def test_all_primes(): assert rearrange_primes([2, 3, 5, 7, 11]) == [11, 7, 5, 3, 2] def test_mixed_numbers(): assert rearrange_primes([10, 7, 2, 11, 4, 5, 8, 13]) == [10, 13, 11, 7, 4, 5, 8, 2] def test_single_prime(): ...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Rearranges primes in a list in descending order while keeping non-primes in the same positions.", "function...
[ 1, 1, 0, 0, 0, 1, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Helper function to determine if an integer is a prime number.\n \"\"\"\n if n <= ...
trial_gpt4o_6
{ "original_instruction": "### Prime Number Rearrangement\n\n**Objective**:\nAssess the student's ability to work with number theory concepts and practice their sorting and list manipulation skills within a programming context.\n\n**Task**:\nWrite a Python function `rearrange_primes` that takes a list of integers, id...
0.601492
Algorithm_23380
C
[ "is_prime", "rearrange_primes" ]
2
[ [ "rearrange_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
false
[]
true
4440a2ce12eea1135c7f9522342cc62af81ebc2b
7eae099c1cb7cb366d4da021944e755d52ca752a
v1.0
complete
Algorithm
Algorithm_17957_C
import random import math import matplotlib.pyplot as plt from typing import List, Tuple class Route: def __init__(self, points: List[Tuple[int, int]]): self.points = points[:] def total_distance(self) -> float: """ Returns the total distance of the route. >>> Route([(0, 0), (3, 4...
import random import math import matplotlib.pyplot as plt from itertools import combinations class Route: def __init__(self, points: list): self.points = points random.shuffle(self.points) def total_distance(self) -> float: distance = 0.0 for i in range(len(self.points)): ...
from solution import Route, genetic_algorithm def test_total_distance(): points = [(0, 0), (3, 4), (3, 0)] route = Route(points) assert math.isclose(route.total_distance(), 12.0, rel_tol=1e-5) def test_mutate(): points = [(0, 0), (3, 4), (3, 0)] route = Route(points) route.mutate(1.0) asse...
[]
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\nimport math\nfrom typing import List, Tuple\n\nclass Route:\n def __init__(self, points: List[Tuple[int, int]]):\n self.points = points\...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\nA logistics company needs to ensure that its delivery trucks operate efficiently by optimizing the routes they take from a warehouse to multiple delivery points. They decide to use the Genetic Algorithm (GA) approach to solve this problem. Your task is to implement a ...
0.606025
Algorithm_17957
C
[ "crossover", "genetic_algorithm" ]
2
[ [ "genetic_algorithm", "crossover" ] ]
1
[]
false
[ "Route" ]
true
pytest
true
[ "matplotlib" ]
false
6faf4a1bf75849ccf6cc554591a11409ee444065
96c1bb5c40a39055a34b66238a059bd1f3c3eb56
v1.0
complete
Algorithm
Algorithm_35793_C
def find_kth_smallest(arr: list, k: int) -> int: """ Find the k-th smallest element in an unsorted array. The function should aim for an average-case time complexity of O(n). Args: arr (list): A list of integers. k (int): The 1-based index of the k-th smallest element to find. Returns:...
def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quickselect(arr, low, high, k): if low < high: ...
from solution import find_kth_smallest def test_find_kth_smallest(): assert find_kth_smallest([3, 2, 1, 5, 4], 3) == 3 assert find_kth_smallest([9, -1, 3, 5, 2], 2) == 2 assert find_kth_smallest([1], 1) == 1 assert find_kth_smallest([5, 5, 5, 5, 5], 3) == 5 assert find_kth_smallest([x for x in rang...
[ { "docstring": null, "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quickselect(arr, low, high, k):", "function_name": "quickselect", "parameter_list...
[ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\n\ndef partition(arr, low, high):\n pivot = arr[high]\n i = low - 1\n for j in range(low, high):\n if arr[j] <= pivot:\n ...
trial_gpt4o_7
{ "original_instruction": "## Problem Statement\nYou are tasked with writing a function that finds the k-th smallest element in an unsorted array. Your implementation should aim for an average-case time complexity of O(n).\n\n### Requirements:\n1. **Function Signature**:\n ```python\n def find_kth_smallest(arr: l...
0.710793
Algorithm_35793
C
[ "partition", "quickselect", "find_kth_smallest" ]
3
[ [ "find_kth_smallest", "quickselect" ], [ "quickselect", "partition" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d68732c68d0d8856d498a01c1b92075aa5a1bbb0
49f09f0d25c9109f8c56d10c33723d8c1c144291
v1.0
complete
Algorithm
Algorithm_23272_C
import asyncio import signal import random import logging # Setup logging logging.basicConfig(level=logging.INFO) async def fetch_stock_price(stock_symbol): """ Simulates fetching the stock price for a given symbol. Randomly raises ConnectionError to simulate network issues. """ pass async def mo...
import asyncio import signal import random import logging # Setup logging logging.basicConfig(level=logging.INFO) # Simulated stock price data provider async def fetch_stock_price(stock_symbol): """ Simulates fetching the stock price for a given symbol. Randomly raises ConnectionError to simulate network ...
from solution import monitor_stock_price, fetch_stock_price import asyncio import pytest # Test the mocked fetch_stock_price function def test_fetch_stock_price(): stock_symbol = "AAPL" prices = [] for _ in range(100): try: price = asyncio.run(fetch_stock_price(stock_symbol)) ...
[ { "docstring": null, "function_declaration": "def signal_handler():", "function_name": "signal_handler", "parameter_list": "()" } ]
[ 1, 1, 1, 0, 0, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\nimport random\nimport logging\n\n# Setup logging\nlogging.basicConfig(level=logging.INFO)\n\n# Simulated stock price data provider...
trial_gpt4o_0
{ "original_instruction": "### Real-Time Stock Price Monitoring App\n\nYou are tasked with creating a real-time stock price monitoring application that connects to a stock price data provider and periodically fetches and displays the latest price of a given stock. The application must also handle network errors grace...
0.513241
Algorithm_23272
C
[ "fetch_stock_price", "monitor_stock_price" ]
2
[ [ "monitor_stock_price", "fetch_stock_price" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1c79e04a27247a4e4e60ba34f6fbf615903f5e13
65f653c13151cb12b769b09d61245875b27bb366
v1.0
complete
Algorithm
Algorithm_12869_C
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def balance_factor(root: TreeNode) -> int: """ Determine the balance factor of a binary tree. >>> balance_factor(TreeNode(1, TreeNode(2, TreeNode(3)))) 2 >>> ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def height(node): if node is None: return 0 return 1 + max(height(node.left), height(node.right)) def balance_factor(root: TreeNode) -> int: if root is N...
from solution import TreeNode, balance_factor def test_empty_tree(): assert balance_factor(None) == 0 def test_single_node(): assert balance_factor(TreeNode(1)) == 0 def test_left_heavy_tree(): root = TreeNode(1, TreeNode(2, TreeNode(3))) assert balance_factor(root) == 2 def test_right_heavy_tree():...
[]
[ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef heigh...
trial_gpt4o_9
{ "original_instruction": "### Question: Determine the Balance Factor of a Binary Tree\n\nIn this task, you need to write a Python function that takes the root of a binary tree and returns the balance factor of the tree. The balance factor of a binary tree is defined as the difference between the height of its left s...
0.622334
Algorithm_12869
C
[ "height", "balance_factor" ]
2
[ [ "balance_factor", "height" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
2a75342a11b6eeef735c07b098181222f0318f46
2381ec5ee8984b4c4033255f729471fd73e13d58
v1.0
complete
Algorithm
Algorithm_7288_C
def merge_sort(arr: list[int]) -> list[int]: """ Sorts a list of integers using the Merge Sort algorithm. >>> merge_sort([12, 11, 13, 5, 6, 7]) [5, 6, 7, 11, 12, 13] >>> merge_sort([]) [] >>> merge_sort([1]) [1] >>> merge_sort([3, 2, 1]) [1, 2, 3] >>> merge_sort([10, -1, 2, 5, 0]) [-1, 0, 2, 5, ...
def merge_sort(arr: list[int]) -> list[int]: """ Sorts a list of integers using the Merge Sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(lef...
from solution import merge_sort def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_list(): assert merge_...
[ { "docstring": "Sorts a list of integers using the Merge Sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted lists into one sorted list.", "function_declaration": "def merge(left, ...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort(arr: list[int]) -> list[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n rig...
trial_gpt4o_9
{ "original_instruction": "### Coding Question\n\n#### Context\nSorting arrays is a fundamental task in computer science. One of the commonly used algorithms for sorting is the Merge Sort algorithm, which follows a divide-and-conquer approach to sort elements efficiently.\n\nMerge Sort works by:\n1. Dividing the unso...
0.635854
Algorithm_7288
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6f185909bfef8e3e936229ed06013103869e25d3
c77e338f5ce0fc6e930a9bbec1c3013199e3d9c8
v1.0
complete
Algorithm
Algorithm_45447_C
from typing import List def is_prime(n: int) -> bool: """ Returns True if n is a prime number, otherwise False. """ pass def sort_primes(arr: List[int]) -> List[int]: """ Sorts the prime numbers in an array in ascending order while keeping the non-prime numbers in their original positions...
from typing import List def is_prime(n: int) -> bool: """ Returns True if n is a prime number, otherwise 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 i in range(3, max_divisor, 2): ...
from solution import sort_primes def test_sort_primes_with_mixed_numbers(): assert sort_primes([29, 15, -3, 4, 17, 5, 2]) == [2, 15, -3, 4, 5, 17, 29] def test_sort_primes_with_some_primes(): assert sort_primes([7, 10, 23, 12, 19]) == [7, 10, 19, 12, 23] def test_sort_primes_with_primes_at_end(): assert ...
[ { "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": "Sorts the prime numbers in an array in ascending order while keeping \nthe non-prime numbers in their or...
[ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n for ...
trial_gpt4o_9
{ "original_instruction": "### Question\nYou need to develop a function that processes an array of integers and sorts all prime numbers in ascending order while leaving the positions of the non-prime numbers unchanged.\n\n**Function Signature:**\n```python\ndef sort_primes(arr: List[int]) -> List[int]:\n \"\"\"\n ...
0.687772
Algorithm_45447
C
[ "is_prime", "sort_primes" ]
2
[ [ "sort_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
536d111be2c74d6219394660326b5ae9a2a3227d
4d22abf42f64c065ba70de171c994aabaff977ae
v1.0
complete
Algorithm
Algorithm_27410_C
def fibonacci(n: int) -> int: """Returns the n-th Fibonacci number. >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(-1) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer. """ d...
def fibonacci(n): """ Returns the n-th Fibonacci number. """ if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer.") if n == 0: return 0 elif n == 1: return 1 a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a...
from solution import fibonacci, fibonacci_mod_m def test_fibonacci(): assert fibonacci(0) == 0 assert fibonacci(1) == 1 assert fibonacci(5) == 5 assert fibonacci(10) == 55 def test_fibonacci_invalid_input(): import pytest with pytest.raises(ValueError): fibonacci(-1) with pytest.ra...
[ { "docstring": "Returns the n-th Fibonacci number.", "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": "Returns the n-th Fibonacci number modulo m.", "function_declaration": "def fibonacci_mod_m(n, m):", "function_nam...
[ 0, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def fibonacci(n: int) -> int:\n \"\"\"\n Returns the n-th Fibonacci number.\n \"\"\"\n if n < 0:\n raise ValueError(\"Input must be a non-nega...
trial_gpt4o_9
{ "original_instruction": "### Fibonacci Sequence and Modular Arithmetic\n\n#### Context:\nThe Fibonacci sequence is often encountered in programming challenges. For this task, you are required to efficiently calculate the Fibonacci numbers and apply modular arithmetic to keep the values manageable.\n\n#### Requireme...
0.786919
Algorithm_27410
C
[ "fibonacci", "fibonacci_mod_m" ]
2
[ [ "fibonacci_mod_m", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4e90bfb702df51e628f159a13b2a8cb003e3ebc5
27db3b665c13fd6f162bd08724ff4dea1627a28b
v1.0
complete
Algorithm
Algorithm_4792_C
import heapq def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_neighbors(point, maze): x, y = point neighbors = [] for nx, ny in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if 0 <= nx < len(maze) and 0 <= ny < len(maze[0]) and maze[nx][ny] == 0: neighbor...
import heapq def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_neighbors(point, maze): x, y = point neighbors = [] for nx, ny in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if 0 <= nx < len(maze) and 0 <= ny < len(maze[0]) and maze[nx][ny] == 0: neighbor...
from solution import a_star_pacman def test_basic_case(): maze = [ [0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0], [1, 0, 1, 0] ] start = (0, 0) end = (3, 3) assert a_star_pacman(maze, start, end) == [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (3, 3)] def test_single...
[ { "docstring": null, "function_declaration": "def heuristic(a, b):", "function_name": "heuristic", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def get_neighbors(point, maze):", "function_name": "get_neighbors", "parameter_list": "(point, maze)" }...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\n\ndef heuristic(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\ndef a_star_pacman(maze, start, end):\n rows, cols = len(maze), len(maz...
trial_gpt4o_5
{ "original_instruction": "### Task\n\nImplement the A* algorithm to solve the Pac-Man shortest path problem on a grid with passable and impassable cells. Pac-Man starts at a given start cell and needs to reach an end cell, navigating through passable cells while avoiding impassable cells.\n\n### Function Signature\n...
0.612651
Algorithm_4792
C
[ "heuristic", "get_neighbors", "a_star_pacman" ]
3
[ [ "a_star_pacman", "get_neighbors" ], [ "a_star_pacman", "heuristic" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c9f3faf67bf9e08604be8dabe20cc6fc893d721e
1cd5659152ef09b837243edf6c587720436fdf12
v1.0
complete
Algorithm
Algorithm_46282_C
import os from typing import List def hash_file(filepath: str) -> str: """Generate MD5 hash for the content of the file.""" import hashlib hash_md5 = hashlib.md5() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md...
import os import hashlib def hash_file(filepath): """Generate MD5 hash for the content of the file.""" hash_md5 = hashlib.md5() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def find_duplicates(direc...
import os import tempfile import pytest from solution import find_duplicates, remove_duplicates def create_test_file(path, content): with open(path, 'w') as f: f.write(content) @pytest.fixture def setup_filesystem(): with tempfile.TemporaryDirectory() as tmpdir: # Create files create_t...
[ { "docstring": "Generate MD5 hash for the content of the file.", "function_declaration": "def hash_file(filepath):", "function_name": "hash_file", "parameter_list": "(filepath)" }, { "docstring": "Find duplicates in a specified directory.", "function_declaration": "def find_duplicates(di...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import os\nimport hashlib\n\ndef hash_file(filepath):\n \"\"\"Generate a hash for the given file.\"\"\"\n hasher = hashlib.sha256()\n with open(filepath...
trial_gpt4o_3
{ "original_instruction": "### Problem Statement: File Deduplicator\n\nYou work for a data storage company that frequently deals with large amounts of data. A significant challenge is ensuring that redundant files are not stored multiple times, saving both space and costs. You've been tasked with creating a solution ...
0.748822
Algorithm_46282
C
[ "hash_file", "find_duplicates", "remove_duplicates" ]
3
[ [ "find_duplicates", "hash_file" ], [ "remove_duplicates", "find_duplicates" ] ]
2
[]
false
[]
false
pytest
true
[]
true
870eb94e080ba518215892744d905e16184ae37a
bb17292f698e4178d28e7b1e8709b8dbe5e66d9c
v1.0
complete
Algorithm
Algorithm_19193_C
import math def factorial_digit_sum(n: int) -> int: """ Returns the sum of the digits of the factorial of n. :param n: Non-negative integer :return: Sum of digits of factorial of n :raises ValueError: If n is negative :raises TypeError: If n is not an integer >>> factorial_digit_s...
import math def factorial_digit_sum(n: int) -> int: """ Returns the sum of the digits of the factorial of n. :param n: Non-negative integer :return: Sum of digits of factorial of n :raises ValueError: If n is negative :raises TypeError: If n is not an integer """ if not isinstance(...
from solution import factorial_digit_sum, is_sum_of_factorial_digits def test_factorial_digit_sum_positive(): assert factorial_digit_sum(5) == 3 # 5! = 120 and 1 + 2 + 0 = 3 def test_factorial_digit_sum_large(): assert factorial_digit_sum(10) == 27 # 10! = 3628800 and 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 def tes...
[ { "docstring": "Returns the sum of the digits of the factorial of n.\n\n:param n: Non-negative integer\n:return: Sum of digits of factorial of n\n:raises ValueError: If n is negative\n:raises TypeError: If n is not an integer", "function_declaration": "def factorial_digit_sum(n):", "function_name": "fac...
[ 1, 0, 1, 0, 0, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef factorial_digit_sum(n: int) -> int:\n \"\"\"\n Returns the sum of the digits of the factorial of n.\n \n :param n: Integer, the nu...
trial_gpt4o_8
{ "original_instruction": "### Coding Task: Factorial Digit Sum Calculation\n\n**Objective**: Implement an algorithm to compute the sum of digits of the factorial of a given number `n`. Additionally, implement a method to check if a given number is equal to the sum of the digits of any factorial of a given `m`.\n\n##...
0.661461
Algorithm_19193
C
[ "factorial_digit_sum", "is_sum_of_factorial_digits" ]
2
[ [ "is_sum_of_factorial_digits", "factorial_digit_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fc93fec1b3399b6f9f277fea84644e9a9cb17ca7
71e5ae3333d5f930bb6a8d6cba4db400b9c764d2
v1.0
complete
Algorithm
Algorithm_5304_C
from typing import List def find_pattern_indices(text: str, pattern: str) -> List[int]: """ Returns a list of all starting indices where the pattern is found in the text. Parameters: text (str): The text string to search within. pattern (str): The pattern string to search for. Returns: Li...
from typing import List def compute_prefix_function(pattern: str) -> List[int]: """ Preprocesses the pattern string and returns the prefix table used in the KMP algorithm. """ m = len(pattern) prefix_table = [0] * m j = 0 for i in range(1, m): while j > 0 and pattern[i] != patt...
from solution import find_pattern_indices def test_pattern_at_start_and_middle(): assert find_pattern_indices("abracadabra", "abra") == [0, 7] def test_pattern_overlapping(): assert find_pattern_indices("banana", "ana") == [1, 3] def test_single_occurrence(): assert find_pattern_indices("hello world", "w...
[ { "docstring": "Preprocesses the pattern string and returns the prefix table used in the KMP algorithm.", "function_declaration": "def compute_prefix_function(pattern):", "function_name": "compute_prefix_function", "parameter_list": "(pattern)" }, { "docstring": "Returns a list of all starti...
[ 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 find_pattern_indices(text: str, pattern: str) -> List[int]:\n \"\"\"\n Returns a list of all starting indices where the patt...
trial_gpt4o_4
{ "original_instruction": "### Question\nYou are tasked with developing a function that identifies all the starting indices where a given pattern string appears in another given text string using a sliding window approach.\n\n### Function Signature\n```python\ndef find_pattern_indices(text: str, pattern: str) -> List...
0.604638
Algorithm_5304
C
[ "compute_prefix_function", "find_pattern_indices" ]
2
[ [ "find_pattern_indices", "compute_prefix_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e5ccf1387141a88a260659726563cae0d2b98d52
403903959d245672155cbf3ef16a1b6bf65a3851
v1.0
complete
Algorithm
Algorithm_16105_C
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ This function implements the Merge Sort algorithm to sort a list of integers. Arguments: arr -- list of integers to be sorted Returns: sorted list of integers Example: >>> merge_sort([38, 27, 43, 3, ...
from typing import List def merge_sort(arr: List[int]) -> List[int]: """ This function implements the Merge Sort algorithm to sort a list of integers. """ if len(arr) <= 1: return arr # Divide the array into two halves middle = len(arr) // 2 left_half = merge_sort(arr[:middle]) ...
from solution import merge_sort def test_merge_sort_with_positive_numbers(): assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] def test_merge_sort_with_mixed_numbers(): assert merge_sort([5, 1, 4, 2, -8]) == [-8, 1, 2, 4, 5] def test_merge_sort_with_duplicates(): assert merge_so...
[ { "docstring": "This function implements the Merge Sort algorithm to sort a list of integers.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "This helper function merges two sorted lists into a single sorted list."...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question\n\n**Background**:\n\nSorting algorithms are fundamental in computer science, often serving as building blocks for more complex algorithms. One such algorithm is the \"Merge Sort\", a divide-and-conquer algorithm that splits the array into halves, sorts them r...
0.627379
Algorithm_16105
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
67adf258977049c1162b59bc11cd0719a499e589
019f4ffe011c526be1ea869d1b6a05460df2e76b
v1.0
complete
Algorithm
Algorithm_21871_C
def rotate_90_clockwise(mat: List[List[int]]) -> List[List[int]]: """ Rotate the given matrix 90 degrees clockwise. >>> rotate_90_clockwise([[1, 2], [3, 4]]) [[3, 1], [4, 2]] >>> rotate_90_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[7, 4, 1], [8, 5, 2], [9, 6, 3]] """ def can_rotate_to_match...
def rotate_90_clockwise(mat): """ Rotate the given matrix 90 degrees clockwise. """ n = len(mat) return [[mat[n - j - 1][i] for j in range(n)] for i in range(n)] def can_rotate_to_match(mat1, mat2): """ Returns whether mat1 can be rotated to match mat2. """ if len(mat1) != len(mat2)...
from solution import can_rotate_to_match def test_match_after_0_degrees(): mat1 = [[1, 2], [3, 4]] mat2 = [[1, 2], [3, 4]] assert can_rotate_to_match(mat1, mat2) == True def test_match_after_90_degrees(): mat1 = [[1, 2], [3, 4]] mat2 = [[3, 1], [4, 2]] assert can_rotate_to_match(mat1, mat2) ==...
[ { "docstring": "Rotate the given matrix 90 degrees clockwise.", "function_declaration": "def rotate_90_clockwise(mat):", "function_name": "rotate_90_clockwise", "parameter_list": "(mat)" }, { "docstring": "Returns whether mat1 can be rotated to match mat2.", "function_declaration": "def ...
[ 1, 0, 0, 1, 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\n\ndef rotate_90_clockwise(mat: List[List[int]]) -> List[List[int]]:\n \"\"\"Returns the matrix rotated 90 degrees clockwise.\"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "### Matrix Rotation Checker\n\n**Problem Statement**:\nYou need to implement a function that determines if a given matrix can be rotated 90 degrees clockwise multiple times to become equal to another given matrix. Your task is to write a function `can_rotate_to_match` to check if the transf...
0.515438
Algorithm_21871
C
[ "rotate_90_clockwise", "can_rotate_to_match" ]
2
[ [ "can_rotate_to_match", "rotate_90_clockwise" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ee1827560ac5e7f98ef26b2b2c67206170b8a986
27eb8d221a2627176f00564ce7527109bf50b7c9
v1.0
complete
Algorithm
Algorithm_14302_C
import re def normalize_string(s: str) -> str: """ Normalize the string by converting to lowercase and removing non-alphanumeric characters. """ return re.sub(r'[^A-Za-z0-9]', '', s.lower()) def is_palindrome(s: str) -> bool: """ Check if a given string is a palindrome using simple comparison....
import re def normalize_string(s: str) -> str: """ Normalize the string by converting to lowercase and removing non-alphanumeric characters. """ return re.sub(r'[^A-Za-z0-9]', '', s.lower()) def is_palindrome(s: str) -> bool: """ Check if a given string is a palindrome using simple comparison....
from solution import is_palindrome, is_palindrome_recursion, is_palindrome_two_pointer def test_is_palindrome(): assert is_palindrome("A man, a plan, a canal, Panama") == True assert is_palindrome("racecar") == True assert is_palindrome("hello") == False assert is_palindrome("") == True assert is_p...
[ { "docstring": "Normalize the string by converting to lowercase and removing non-alphanumeric characters.", "function_declaration": "def normalize_string(s):", "function_name": "normalize_string", "parameter_list": "(s)" }, { "docstring": "Check if a given string is a palindrome using simple...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\n\ndef normalize_string(s: str) -> str:\n \"\"\"\n Normalize the string by converting to lowercase and removing non-alphanumeric characters.\n ...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nCreate a function that checks if a given string is a palindrome. A palindrome is a word, number, phrase, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Implement three different methods: \...
0.823852
Algorithm_14302
C
[ "normalize_string", "is_palindrome", "is_palindrome_recursion", "is_palindrome_two_pointer" ]
4
[ [ "is_palindrome", "normalize_string" ], [ "is_palindrome_recursion", "normalize_string" ], [ "is_palindrome_two_pointer", "normalize_string" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4b6344ca3337d8facf990cd4b089345979612da6
7626d9e39f37ef246a7b5d8196cd529cd99d2f9b
v1.0
complete
Algorithm
Algorithm_41134_C
import threading from concurrent.futures import ThreadPoolExecutor, as_completed import requests from typing import List, Dict def fetch_url(url: str) -> (str, int): try: response = requests.get(url, timeout=5) return url, response.status_code except requests.RequestException: return ur...
import threading from concurrent.futures import ThreadPoolExecutor, as_completed import requests def fetch_url(url): try: response = requests.get(url, timeout=5) return url, response.status_code except requests.RequestException as e: return url, None def multithreaded_web_crawler(urls,...
import pytest from solution import multithreaded_web_crawler def test_multithreaded_web_crawler(): urls = [ "http://httpbin.org/status/200", "http://httpbin.org/status/404", "http://httpbin.org/status/500" ] num_threads = 3 result = multithreaded_web_crawler(urls, num_threads) ...
[ { "docstring": null, "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def multithreaded_web_crawler(urls, num_threads):", "function_name": "multithreaded_web_crawler", "paramete...
[ 1, 1, 1, 1, 0, 1, 0, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import threading\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor\nfrom collections import defaultdict\nimport time\n\ndef fetch_url(url, resu...
trial_gpt4o_7
{ "original_instruction": "### Advanced Problem: Implementing a Multithreaded Web Crawler\n\n#### Scenario\nYou are to design a multithreaded web crawler that can crawl a list of URLs concurrently. The crawler should avoid crawling the same URL multiple times and should handle potential errors such as timeouts or HTT...
0.557445
Algorithm_41134
C
[ "fetch_url", "multithreaded_web_crawler" ]
2
[ [ "multithreaded_web_crawler", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
8e522f5bacf3c4e393a8096ab5b76a35a38e154a
1f5c90b7156e5cb59e7039f93237890d2ec1f55e
v1.0
complete
Algorithm
Algorithm_21327_C
import numpy as np def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float: """ Computes the Euclidean distance between two points. Parameters: - point1: np.ndarray - point2: np.ndarray Returns: - float: Euclidean distance. """ pass def k_nearest_neighbors(x_train...
import numpy as np from collections import Counter def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float: """ Computes the Euclidean distance between two points. Parameters: - point1: np.ndarray - point2: np.ndarray Returns: - float: Euclidean distance. """ ...
import numpy as np from solution import euclidean_distance, k_nearest_neighbors def test_euclidean_distance_same_point(): point1 = np.array([1.0, 2.0]) point2 = np.array([1.0, 2.0]) assert euclidean_distance(point1, point2) == 0.0 def test_euclidean_distance_different_points(): point1 = np.array([1.0,...
[ { "docstring": "Computes the Euclidean distance between two points.\n\nParameters:\n- point1: np.ndarray\n- point2: np.ndarray\n\nReturns:\n- float: Euclidean distance.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(poi...
[ 1, 0, 1, 1, 0, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float:\n \"\"\"\n Computes the Euc...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment Question: Implementing K-Nearest Neighbors (K-NN) from Scratch\n\n#### Objective\nImplement the K-Nearest Neighbors (K-NN) algorithm from scratch to classify data into categories. This problem will test your understanding of distance metrics, sorting, and the concept o...
0.662828
Algorithm_21327
C
[ "euclidean_distance", "k_nearest_neighbors" ]
2
[ [ "k_nearest_neighbors", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
1d2f23ceb35ee1ef6044a1f7f57e867039e89a70
2f8542dc5aa9f4e447ed925479c4edb13df9b052
v1.0
complete
Algorithm
Algorithm_6778_C
def is_prime(number: int) -> bool: """ Check if a number is a prime number. >>> is_prime(5) True >>> is_prime(4) False """ pass def compute_factorial(number: int) -> int: """ Compute the factorial of a number. >>> compute_factorial(5) 120 >>> compute_factorial(0) 1 """ pass def...
import math def is_prime(number): """ Check if a number is a prime number. """ if number < 2: return False for i in range(2, int(math.sqrt(number)) + 1): if number % i == 0: return False return True def compute_factorial(number): """ Compute the factorial of...
from solution import analyze_number def test_analyze_number_prime_and_factorial(): assert analyze_number(5) == (True, 120) assert analyze_number(7) == (True, 5040) def test_analyze_number_non_prime_and_factorial(): assert analyze_number(4) == (False, 24) assert analyze_number(8) == (False, 40320) def...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Compute the factorial of a number.", "function_declaration": "def compute_factorial(number):", "functio...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(number):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if number <= 1:\n return False\n if number == 2:\n return Tr...
trial_gpt4o_9
{ "original_instruction": "### Coding Question: Prime Number and Factorial Analysis\n\n#### Objective:\nYou are given two functions: one that checks if a number is prime, and another that computes the factorial of a number. Your task is to enhance these functions and write a new function that works with both to solve...
0.712605
Algorithm_6778
C
[ "is_prime", "compute_factorial", "analyze_number" ]
3
[ [ "analyze_number", "compute_factorial" ], [ "analyze_number", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9aeb0cd30c0c61c540b1d90071bf23bfb667d494
9c8551a75f1ae0426c118696902c05722bfa7380
v1.0
complete
Algorithm
Algorithm_48185_C
def find_substrings(main_sentence: str, words: list[str]) -> list[str]: """ Identify which words from the list appear as exact substrings in the main sentence, case-insensitively. >>> find_substrings("The quick brown fox jumps over the lazy dog", ["quick", "dog", "cat", "Fox"]) ["quick", "dog", "Fox"] ...
def find_substrings(main_sentence: str, words: list[str]) -> list[str]: """ Identify which words from the list appear as exact substrings in the main sentence, case-insensitively. """ main_sentence_lower = main_sentence.lower() return [word for word in words if word.lower() in main_sentence_lower] ...
from solution import find_substrings, substring_occurrence_count, substring_presence_score def test_find_substrings(): main_sentence = "The quick brown fox jumps over the lazy dog" words = ["quick", "dog", "cat", "Fox"] assert find_substrings(main_sentence, words) == ["quick", "dog", "Fox"] def test_find_...
[ { "docstring": "Identify which words from the list appear as exact substrings in the main sentence, case-insensitively.", "function_declaration": "def find_substrings(main_sentence, words):", "function_name": "find_substrings", "parameter_list": "(main_sentence, words)" }, { "docstring": "Co...
[ 1, 1, 1, 1, 0, 1, 1, 1, 0, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def find_substrings(main_sentence: str, words: list[str]) -> list[str]:\n \"\"\"\n Finds and returns the words from the list that appear as exact substring...
trial_gpt4o_7
{ "original_instruction": "### Sentence Substring Matching\n\nGiven a main sentence and a list of words, write functions to identify which words from the list appear as exact substrings in the main sentence, case-insensitively. Your task is to implement the following functions:\n\n1. **`find_substrings(main_sentence:...
0.748564
Algorithm_48185
C
[ "find_substrings", "substring_occurrence_count", "substring_presence_score" ]
3
[ [ "substring_presence_score", "find_substrings" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1918ddc5f2a14a35ec41b17dca80919cb064bfd1
0120044e04839888bfe00bc8aa17ca358802a25f
v1.0
complete
Algorithm
Algorithm_46474_C
import numpy as np def decision_tree_classifier(X: np.ndarray, y: np.ndarray, max_depth: int = 5) -> dict: """ Trains a decision tree model and returns a dictionary representing the tree structure. The function should: 1. Calculate the entropy of a dataset. 2. Compute the information gain of a pot...
import numpy as np def entropy(y): unique, counts = np.unique(y, return_counts=True) probabilities = counts / len(y) return -np.sum(probabilities * np.log2(probabilities)) def information_gain(y, y_left, y_right): weight_left = len(y_left) / len(y) weight_right = len(y_right) / len(y) return e...
import pytest import numpy as np from solution import decision_tree_classifier def test_single_node_tree(): X = np.array([[0], [0], [0], [0]]) y = np.array([1, 1, 1, 1]) tree = decision_tree_classifier(X, y, max_depth=1) assert tree == {'class': 1} def test_two_node_tree(): X = np.array([[0], [1],...
[ { "docstring": null, "function_declaration": "def entropy(y):", "function_name": "entropy", "parameter_list": "(y)" }, { "docstring": null, "function_declaration": "def information_gain(y, y_left, y_right):", "function_name": "information_gain", "parameter_list": "(y, y_left, y_r...
[ 0, 1, 1, 0, 0, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom collections import Counter\n\ndef entropy(y):\n counter = Counter(y)\n probabilities = [count / len(y) for count in counter.values...
trial_gpt4o_2
{ "original_instruction": "### Decision Tree Classifier Implementation Challenge\n\n#### Context\nYou are presented with a dataset of medical records where each record contains information about patient symptoms and a binary diagnosis: healthy (0) or diseased (1). Your task is to implement a decision tree classifier ...
0.51938
Algorithm_46474
C
[ "entropy", "information_gain", "split_dataset", "best_split", "build_tree", "decision_tree_classifier" ]
6
[ [ "best_split", "information_gain" ], [ "best_split", "split_dataset" ], [ "build_tree", "best_split" ], [ "build_tree", "split_dataset" ], [ "decision_tree_classifier", "build_tree" ], [ "information_gain", "entropy" ] ]
6
[]
false
[]
false
pytest
true
[ "numpy" ]
false
46606ff4b35f3a9b598b7694623a04dcc8e4498f
3bf613590f1999332f230180051dccd661d0cdff
v1.0
complete
Algorithm
Algorithm_4099_C
def nand_gate(input_1: int, input_2: int) -> int: """ This function implements a NAND gate. A NAND gate returns True (1) if at least one of the inputs is False (0). """ return int(not (input_1 and input_2)) def and_using_nand(input_1: int, input_2: int) -> int: """ Compute the AND operation...
def nand_gate(input_1: int, input_2: int) -> int: """ This function implements a NAND gate. A NAND gate returns True (1) if at least one of the inputs is False (0). """ return int(not (input_1 and input_2)) def and_using_nand(input_1: int, input_2: int) -> int: """ This function simulates a...
from solution import and_using_nand def test_and_using_nand(): # Test all combinations of input pairs assert and_using_nand(0, 0) == 0 assert and_using_nand(0, 1) == 0 assert and_using_nand(1, 0) == 0 assert and_using_nand(1, 1) == 1
[ { "docstring": "This function implements a NAND gate.\nA NAND gate returns True (1) if at least one of the inputs is False (0).", "function_declaration": "def nand_gate(input_1, input_2):", "function_name": "nand_gate", "parameter_list": "(input_1, input_2)" }, { "docstring": "This function ...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def nand_gate(input_1: int, input_2: int) -> int:\n return int(not (input_1 and input_2))\n\ndef and_using_nand(input_1: int, input_2: int) -> int:\n \"\"\...
trial_gpt4o_9
{ "original_instruction": "### Question:\n#### Problem Statement:\nYou are required to implement a basic digital circuit using NAND gates to simulate an AND gate. The AND gate outputs True (1) only when both inputs are True (1), and False (0) otherwise. Your task is to write a function that computes the AND operation...
0.512177
Algorithm_4099
C
[ "nand_gate", "and_using_nand" ]
2
[ [ "and_using_nand", "nand_gate" ] ]
1
[]
false
[]
false
pytest
true
[]
true
590b7efb9b63f78ca39cde9a214d88658287763a
4aae88e157fbe3c54432d04c2ac528a6b7954257
v1.0
complete
Algorithm
Algorithm_968_C
def nor_gate(input_1: int, input_2: int) -> int: return int(not (input_1 or input_2)) def and_using_nor(input_1: int, input_2: int) -> int: """ Compute the AND operation using only NOR gates. >>> and_using_nor(0, 0) 0 >>> and_using_nor(0, 1) 0 >>> and_using_nor(1, 0) 0 >>> ...
def nor_gate(input_1: int, input_2: int) -> int: return int(not (input_1 or input_2)) def and_using_nor(input_1: int, input_2: int) -> int: """ Compute the AND operation using only NOR gates :param input_1: First boolean input (0 or 1) :param input_2: Second boolean input (0 or 1) :return: Resu...
from solution import and_using_nor, nor_gate def test_nor_gate(): assert nor_gate(0, 0) == 1 assert nor_gate(0, 1) == 0 assert nor_gate(1, 0) == 0 assert nor_gate(1, 1) == 0 def test_and_using_nor(): assert and_using_nor(0, 0) == 0 assert and_using_nor(0, 1) == 0 assert and_using_nor(1, 0)...
[ { "docstring": null, "function_declaration": "def nor_gate(input_1, input_2):", "function_name": "nor_gate", "parameter_list": "(input_1, input_2)" }, { "docstring": "Compute the AND operation using only NOR gates\n:param input_1: First boolean input (0 or 1)\n:param input_2: Second boolean ...
[ 0, 1, 1, 1, 0, 0, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def nor_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Compute the NOR operation.\n :param input_1: First boolean input (0 or 1)\n :param input_...
trial_gpt4o_9
{ "original_instruction": "### Question:\n#### Problem Statement:\nYou are assigned to implement a digital circuit using only NOR gates to simulate the AND gate function. The AND gate outputs True (1) only when both inputs are True.\n\n#### Function Signature:\n```python\ndef and_using_nor(input_1: int, input_2: int)...
0.52972
Algorithm_968
C
[ "nor_gate", "and_using_nor" ]
2
[ [ "and_using_nor", "nor_gate" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f9683de624469c49729236d2bcadcbe3f87dbe73
cfc2d86a2c45d8297b4e0b0082c8803889966682
v1.0
complete
Algorithm
Algorithm_13532_C
def is_palindrome(number: int) -> bool: """ Check if a number is a palindrome. >>> is_palindrome(121) == True >>> is_palindrome(123) == False >>> is_palindrome(12321) == True >>> is_palindrome(123321) == True >>> is_palindrome(123421) == False """ pass def largest_palindromic_...
def is_palindrome(number): """ Check if a number is a palindrome. """ return str(number) == str(number)[::-1] def largest_palindromic_product(): """ Finds the largest palindromic number that is a product of two 3-digit numbers. """ max_palindrome = 0 # Iterate over all pairs of...
from solution import largest_palindromic_product, is_palindrome def test_is_palindrome(): assert is_palindrome(121) == True assert is_palindrome(123) == False assert is_palindrome(12321) == True assert is_palindrome(123321) == True assert is_palindrome(123421) == False def test_largest_palindromic...
[ { "docstring": "Check if a number is a palindrome.", "function_declaration": "def is_palindrome(number):", "function_name": "is_palindrome", "parameter_list": "(number)" }, { "docstring": "Finds the largest palindromic number that is a product of two 3-digit numbers.", "function_declarat...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_palindrome(n):\n \"\"\"\n Checks if the integer n is a palindrome.\n \"\"\"\n s = str(n)\n return s == s[::-1]\n\ndef largest_palindromic_p...
trial_gpt4o_9
{ "original_instruction": "### Palindromic Product of Two 3-Digit Numbers\n\nA palindromic number reads the same forward and backward (e.g., 121 or 989). Write a function to find the largest palindromic number that is a product of two 3-digit numbers.\n\n**Function Signature**:\n```python\ndef largest_palindromic_pro...
0.697558
Algorithm_13532
C
[ "is_palindrome", "largest_palindromic_product" ]
2
[ [ "largest_palindromic_product", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7c3ec0503f3cd92174ec046f43a2e15c72537ff0
13ce8d43d521cb48244e11da99f44560d5e3c60b
v1.0
complete
Algorithm
Algorithm_12778_C
def rotate_in_place(matrix: list[list[int]]) -> None: """ Rotates the NxN matrix 90 degrees clockwise in place. """ pass def extract_new_matrix(matrix: list[list[int]]) -> list[list[int]]: """ Creates a new NxN matrix representing the original matrix rotated 90 degrees clockwise. """ pa...
def rotate_in_place(matrix: list[list[int]]) -> None: """ Rotates the NxN matrix 90 degrees clockwise in place. """ n = len(matrix) for i in range(n // 2): for j in range(i, n - i - 1): temp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j -...
from solution import rotate, rotate_in_place, extract_new_matrix def test_rotate_in_place(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] rotate_in_place(matrix) assert matrix == [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] def test_extract_new_matrix(): ...
[ { "docstring": "Rotates the NxN matrix 90 degrees clockwise in place.", "function_declaration": "def rotate_in_place(matrix):", "function_name": "rotate_in_place", "parameter_list": "(matrix)" }, { "docstring": "Creates a new NxN matrix representing the original matrix rotated 90 degrees clo...
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def rotate_in_place(matrix):\n \"\"\"\n Rotates the NxN matrix 90 degrees clockwise in place.\n \"\"\"\n n = len(matrix)\n for x in range(n // 2):...
trial_gpt4o_9
{ "original_instruction": "### Matrix Rotation: 90-Degree Challenge\n\nMatrix rotation is a fundamental operation in computer graphics and image processing. In this challenge, you are tasked with rotating a given NxN matrix 90 degrees clockwise.\n\n#### Task:\n\nImplement the matrix rotation with two different approa...
0.572973
Algorithm_12778
C
[ "rotate_in_place", "extract_new_matrix", "rotate" ]
3
[ [ "rotate", "extract_new_matrix" ], [ "rotate", "rotate_in_place" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b99b9c3c678c3a6b320af71d7e22f588c6816faa
1270b72075ceec1132a624efbcde9e6f0d0d9f3d
v1.0
complete
Algorithm
Algorithm_971_C
def sort_primes(lst: list) -> list: """ Returns a new list with prime numbers at the beginning in their original relative order, followed by non-prime numbers in their original relative order. >>> sort_primes([3, 6, 2, 7, 8, 1]) [3, 2, 7, 6, 8, 1] >>> sort_primes([10, 11, 13, 14, 15]) [11, ...
def is_prime(n): """ Helper function to check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i +...
from solution import sort_primes def test_sort_primes_mixed(): assert sort_primes([3, 6, 2, 7, 8, 1]) == [3, 2, 7, 6, 8, 1] def test_sort_primes_no_primes(): assert sort_primes([4, 6, 8, 9, 10]) == [4, 6, 8, 9, 10] def test_sort_primes_all_primes(): assert sort_primes([11, 13, 17, 19, 2, 3, 7]) == [11, 1...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a new list with prime numbers at the beginning in their original relative order,\nfollowed by non-prime...
[ 1, 1, 1, 0, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement\nYou need to implement a function that takes a list of integers and returns a new list with the same integers sorted, but every prime number in the list should appear at the beginning in their original relative order, followed by the non-prime numbers in their original...
0.631923
Algorithm_971
C
[ "is_prime", "sort_primes" ]
2
[ [ "sort_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f9fdb51c34b1920a252305779d4b0c39a5e9501e
1d8a23435d34e0e672806b16237c03094ca4fa99
v1.0
complete
Algorithm
Algorithm_45537_C
import numpy as np import matplotlib.pyplot as plt import requests import csv from typing import Tuple def collect_dataset() -> np.matrix: """ Downloads and processes the customer behavior dataset. """ pass def initialize_centroids(data: np.matrix, k: int) -> np.matrix: """ Randomly initialize...
import numpy as np import matplotlib.pyplot as plt import requests import csv from typing import Tuple def collect_dataset() -> np.matrix: """ Downloads and processes the customer behavior dataset. """ url = 'https://example.com/customer_behavior.csv' # Example URL; replace with actual URL respons...
import numpy as np import pytest from solution import collect_dataset, initialize_centroids, assign_clusters, update_centroids, run_kmeans, visualize_clusters def test_collect_dataset(monkeypatch): def mock_get(url): from io import StringIO class MockResponse: def __init__(self...
[ { "docstring": "Downloads and processes the customer behavior dataset.", "function_declaration": "def collect_dataset():", "function_name": "collect_dataset", "parameter_list": "()" }, { "docstring": "Randomly initializes k centroids from the dataset.", "function_declaration": "def initi...
[ 0, 1, 1, 1, 1, 0, 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 numpy as np\nimport matplotlib.pyplot as plt\nimport requests\nimport csv\n\ndef collect_dataset() -> np.matrix:\n url = 'https://example.com/customer_...
trial_gpt4o_4
{ "original_instruction": "### K-Means Clustering for Customer Segmentation\n\nYou are tasked with implementing the K-Means clustering algorithm from scratch to perform customer segmentation based on purchasing behaviors. Your task involves:\n1. Downloading and processing a given dataset.\n2. Implementing the K-Means...
0.80961
Algorithm_45537
C
[ "collect_dataset", "initialize_centroids", "assign_clusters", "update_centroids", "run_kmeans", "visualize_clusters", "main" ]
7
[ [ "run_kmeans", "assign_clusters" ], [ "run_kmeans", "initialize_centroids" ], [ "run_kmeans", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "requests" ]
false
2889d461d6be99eefa628325006c14d1c97e4d13
a526e75b36a4b82ac623ab3d46db56d9b3bb6c46
v1.0
complete
Algorithm
Algorithm_33812_C
from typing import List def spell_check(word: str, dictionary: List[str]) -> str: """ Finds and returns the dictionary word with the smallest edit distance to the input word. Args: word (str): A string representing the misspelled word. dictionary (List[str]): A list of strings represe...
from typing import List def edit_distance(word1: str, word2: str) -> int: m, n = len(word1), len(word2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i...
from solution import spell_check def test_spell_check_basic(): assert spell_check("speling", ["spelling", "spelt", "spell"]) == "spelling" def test_spell_check_single_letter(): assert spell_check("a", ["a", "b", "c"]) == "a" def test_spell_check_empty_word(): assert spell_check("", ["a", ""]) == "" def ...
[ { "docstring": null, "function_declaration": "def edit_distance(word1, word2):", "function_name": "edit_distance", "parameter_list": "(word1, word2)" }, { "docstring": null, "function_declaration": "def spell_check(word, dictionary):", "function_name": "spell_check", "parameter_l...
[ 0, 1, 0, 0, 0, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef edit_distance(word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n...
trial_gpt4o_8
{ "original_instruction": "### Scenario:\nYou are developing a spell-checking feature for a word processor. The feature needs to suggest the closest correct spelling for a given word based on a dictionary of valid English words. The closeness is determined by the minimum number of single-character edits (insertions, ...
0.534101
Algorithm_33812
C
[ "edit_distance", "spell_check" ]
2
[ [ "spell_check", "edit_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
321977a1b2e301f5f0cc676d0bb5e3e29ecf81e1
6ab1a12f866bda3b277b31e8de38b362ad3b0f07
v1.0
complete
Algorithm
Algorithm_32519_C
import numpy as np def is_prime(n: int) -> bool: """ Check if a number is prime. """ if n <= 1: return False for i in range(2, int(np.sqrt(n)) + 1): if n % i == 0: return False return True def prime_index(n: int) -> int: """ Find number of primes less than or equal to n...
import numpy as np def is_prime(n: int) -> bool: """ Check if a number is prime. """ if n <= 1: return False for i in range(2, int(np.sqrt(n)) + 1): if n % i == 0: return False return True def prime_index(n: int) -> int: """ Find number of primes less than o...
import numpy as np from solution import replace_primes_with_indices def test_replace_primes_with_indices(): matrix = np.array([ [2, 3, 4], [5, 6, 7], [8, 9, 10] ]) expected_output = np.array([ [1, 2, 4], [3, 6, 4], [8, 9, 10] ]) assert np.array_equal(...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find number of primes less than or equal to n.", "function_declaration": "def prime_index(n):", "function_name": "prime_in...
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n for i in range(2, int(np.sqrt(n)) + 1):\n if n % i == 0:\n ...
trial_gpt4o_5
{ "original_instruction": "### [New Question] Prime Number and Matrix Manipulation\n\n#### Objective\nGiven a matrix of integers, your task is to write a function that identifies all prime numbers within this matrix and replaces each prime number with its corresponding prime index, where the prime index of a prime nu...
0.635366
Algorithm_32519
C
[ "is_prime", "prime_index", "replace_primes_with_indices" ]
3
[ [ "prime_index", "is_prime" ], [ "replace_primes_with_indices", "is_prime" ], [ "replace_primes_with_indices", "prime_index" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
0c3ff78606044347f3052a74b15173d4affc939a
b42150efa216736017b50d8cbbdce73a58f7359c
v1.0
complete
Algorithm
Algorithm_3448_C
import csv def average_grade(math: int, science: int, english: int) -> float: """ Calculate the average of the given grades for math, science, and English. >>> average_grade(90, 95, 85) 90.0 >>> average_grade(70, 80, 90) 80.0 >>> average_grade(100, 95, 100) 98.33 >>> average_grade(0, 0, 0) 0.0 ...
import csv def average_grade(math: int, science: int, english: int) -> float: """ Calculate the average of the given grades for math, science, and English. """ return round((math + science + english) / 3, 2) def process_student_data(filename: str = "students.csv") -> dict: """ Process the stud...
import pytest from solution import average_grade, process_student_data def test_average_grade(): assert average_grade(90, 95, 85) == 90.0 assert average_grade(70, 80, 90) == 80.0 assert average_grade(100, 95, 100) == 98.33 assert average_grade(0, 0, 0) == 0.0 def test_process_student_data(tmp_path): ...
[ { "docstring": "Calculate the average of the given grades for math, science, and English.", "function_declaration": "def average_grade(math, science, english):", "function_name": "average_grade", "parameter_list": "(math, science, english)" }, { "docstring": "Process the student data in the ...
[ 1, 1, 1, 0, 1, 1, 1, 1, 0, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def average_grade(math: int, science: int, english: int) -> float:\n \"\"\"\n Calculate the average of the given grades for math, science, and English.\n ...
trial_gpt4o_7
{ "original_instruction": "### CSV Data Aggregation\n\n**Objective**: In this task, you will implement a function that reads a CSV file containing student data, processes it to compute average grades, and outputs summary statistics.\n\n### Problem Statement:\nYou are given a CSV file with student records. Each row co...
0.729862
Algorithm_3448
C
[ "average_grade", "process_student_data" ]
2
[ [ "process_student_data", "average_grade" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0fc240f914d479752b89f049c8bf76b5b3dcad1b
5a3111377b8f0a431b948cea5468e2f55c8a929b
v1.0
complete
Algorithm
Algorithm_42287_C
def encode_message(message: str, shift: int) -> str: """ Encode a message using the Caesar Cipher technique. >>> encode_message("Hello, World!", 5) "Mjqqt, Btwqi!" >>> encode_message("abcXYZ", -3) "xyzUVW" >>> encode_message("123! abc! XYZ?@", 2) "123! cde! ZAB?@" >>> encode_message("Hel...
def encode_message(message: str, shift: int) -> str: def shift_char(c, shift): if c.isalpha(): base = ord('A') if c.isupper() else ord('a') return chr((ord(c) - base + shift) % 26 + base) return c return ''.join(shift_char(c, shift) for c in message) def decode_message(...
from solution import encode_message, decode_message def test_encode_message_positive_shift(): assert encode_message("Hello, World!", 5) == "Mjqqt, Btwqi!" def test_decode_message_positive_shift(): assert decode_message("Mjqqt, Btwqi!", 5) == "Hello, World!" def test_encode_message_negative_shift(): asser...
[ { "docstring": null, "function_declaration": "def encode_message(message, shift):", "function_name": "encode_message", "parameter_list": "(message, shift)" }, { "docstring": null, "function_declaration": "def decode_message(encoded_message, shift):", "function_name": "decode_message"...
[ 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def encode_message(message: str, shift: int) -> str:\n def shift_char(c, shift):\n if c.isalpha():\n base = ord('A') if c.isupper() else ord...
trial_gpt4o_7
{ "original_instruction": "### Scenario\n\nAs a software developer, you are working on a project related to data privacy and encryption. One of the tasks involves encoding and decoding messages using a simple substitution cipher where each letter in the alphabet is shifted by a fixed number of positions. The encoding...
0.703961
Algorithm_42287
C
[ "encode_message", "decode_message" ]
2
[ [ "decode_message", "encode_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a7619b467d7159dbe375ff290d77a35c1adef46
e570e177ebc3f7d78cea7e79721ac88cbae196c2
v1.0
complete
Algorithm
Algorithm_15918_C
def find_closest_pair(coordinates): """ Find the closest pair of coordinates among a given set of coordinates. >>> find_closest_pair([(34.0522, -118.2437), (40.7128, -74.0060), (37.7749, -122.4194), (34.0522, -118.2436)]) ((34.0522, -118.2437), (34.0522, -118.2436)) >>> find_closest_pair([(19.4326, -99.1332...
import math def euclidean_distance(coord1, coord2): return math.sqrt((coord1[0] - coord2[0])**2 + (coord1[1] - coord2[1])**2) def find_closest_pair(coordinates): if len(coordinates) < 2: raise ValueError("At least two coordinates are required") min_distance = float('inf') closest_pair = N...
from solution import find_closest_pair def test_find_closest_pair_basic(): coords = [(0, 0), (1, 1), (2, 2)] assert find_closest_pair(coords) == ((0, 0), (1, 1)) def test_find_closest_pair_identical_points(): coords = [(1, 1), (1, 1), (2, 2)] assert find_closest_pair(coords) == ((1, 1), (1, 1)) def t...
[ { "docstring": null, "function_declaration": "def euclidean_distance(coord1, coord2):", "function_name": "euclidean_distance", "parameter_list": "(coord1, coord2)" }, { "docstring": null, "function_declaration": "def find_closest_pair(coordinates):", "function_name": "find_closest_pa...
[ 1, 1, 0, 1, 0, 1, 1, 1, 1 ]
7
easy
0.778
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl", "solution_code": "def euclidean_distance(coord1, coord2):\n \"\"\"\n Computes the Euclidean distance between two coordinates.\n \"\"\"\n retur...
trial_gpt4o_9
{ "original_instruction": "### Scenario\n\nYou are developing software for a company that processes large sets of geographical data. One task is to find the closest pair of coordinates among a given set of coordinates.\n\n### Function Details\n\nImplement a function `find_closest_pair` that takes a list of tuples whe...
0.683756
Algorithm_15918
C
[ "euclidean_distance", "find_closest_pair" ]
2
[ [ "find_closest_pair", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7fd47645ca7b7385782689df08c9d0c600eea13
db9306127eeb6f6ebf4858d99affe91cc0beefc9
v1.0
complete
Algorithm
Algorithm_35446_C
import numpy as np def min_max_normalize(data: np.ndarray) -> np.ndarray: """Apply Min-Max normalization to the data. >>> data = np.array([[1, 2], [3, 4], [5, 6]]) >>> min_max_normalize(data) array([[0. , 0. ], [0.5, 0.5], [1. , 1. ]]) """ def z_score_standardize(data: np...
import numpy as np def min_max_normalize(data: np.ndarray) -> np.ndarray: """ Apply Min-Max normalization to the data. """ min_val = np.min(data, axis=0) max_val = np.max(data, axis=0) return (data - min_val) / (max_val - min_val) def z_score_standardize(data: np.ndarray) -> np.ndarray: ""...
import numpy as np from solution import min_max_normalize, z_score_standardize, PCA, preprocess_data def test_min_max_normalize(): data = np.array([[1, 2], [3, 4], [5, 6]]) normalized = min_max_normalize(data) assert np.allclose(normalized, np.array([[0. , 0. ], [0.5, 0.5], [1. , 1. ]])) def test_z_score_...
[]
[ 0, 1, 1, 0, 1, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef min_max_normalize(data: np.ndarray) -> np.ndarray:\n min_vals = np.min(data, axis=0)\n max_vals = np.max(data, axis=0)\n retur...
trial_gpt4o_7
{ "original_instruction": "### Data Normalization and Principal Component Analysis Implementation Assessment\n\n#### Context\nYou are tasked with implementing data normalization techniques and enhancing a machine learning pre-processing pipeline with Principal Component Analysis (PCA). This will help ensure comprehen...
0.743796
Algorithm_35446
C
[ "min_max_normalize", "z_score_standardize", "preprocess_data" ]
3
[ [ "preprocess_data", "min_max_normalize" ], [ "preprocess_data", "z_score_standardize" ] ]
2
[]
false
[ "PCA" ]
true
pytest
true
[ "numpy" ]
false
12606753c0958178456180addb17d0f5117fd957
b536e9e660933e2495574062f88454cb76963c54
v1.0
complete
Algorithm
Algorithm_3008_C
def find_kth_perfect_number(k: int) -> int: """ Implement a Python function `find_kth_perfect_number` that takes an integer `k` and returns the k-th perfect number. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding itself. Requirements: 1. The func...
def find_divisors(n): """ Returns a list of proper divisors of n (excluding the number itself). """ divisors = [] for i in range(1, n // 2 + 1): if n % i == 0: divisors.append(i) return divisors def is_perfect_number(n): """ Checks if the number n is a perfect number...
from solution import find_kth_perfect_number def test_find_first_perfect_number(): assert find_kth_perfect_number(1) == 6 def test_find_second_perfect_number(): assert find_kth_perfect_number(2) == 28 def test_find_third_perfect_number(): assert find_kth_perfect_number(3) == 496 def test_find_fourth_per...
[ { "docstring": "Returns a list of proper divisors of n (excluding the number itself).", "function_declaration": "def find_divisors(n):", "function_name": "find_divisors", "parameter_list": "(n)" }, { "docstring": "Checks if the number n is a perfect number.", "function_declaration": "def...
[ 0, 0, 0, 0, 1, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def find_kth_perfect_number(k: int) -> int:\n \"\"\"\n Returns the k-th perfect number.\n \"\"\"\n if k <= 0:\n return -1\n \n def is_pe...
trial_gpt4o_9
{ "original_instruction": "Implement a Python function `find_kth_perfect_number` that takes an integer `k` and returns the k-th perfect number. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding itself.\n\n### Requirements:\n1. The function should handle edge cases suc...
0.614843
Algorithm_3008
C
[ "find_divisors", "is_perfect_number", "find_kth_perfect_number" ]
3
[ [ "find_kth_perfect_number", "is_perfect_number" ], [ "is_perfect_number", "find_divisors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
61e795798ec9215bef22be5b2ae0b74a8dd0a6a2
a2ddbefe4fe3e278ae12778251147bb226b2c096
v1.0
complete
Algorithm
Algorithm_11150_C
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.metrics import silhouette_score from sklearn.preprocessing import StandardScaler def load_dataset(samples: int = 300, centers: int = 3, cluster_std: float = 0.60) -> np.ndarray: ...
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.metrics import silhouette_score from sklearn.preprocessing import StandardScaler def load_dataset(samples: int = 300, centers: int = 3, cluster_std: float = 0.60) -> np.ndarray: ...
import pytest from solution import load_dataset, preprocess_data, kmeans_clustering def test_load_dataset(): data = load_dataset(samples=100, centers=3, cluster_std=0.60) assert data.shape == (100, 2) def test_preprocess_data(): data = np.array([[1, 2], [3, 4], [5, 6]]) processed_data = preprocess_dat...
[ { "docstring": "Generate a synthetic dataset with the given parameters.", "function_declaration": "def load_dataset(samples=300, centers=3, cluster_std=0.6):", "function_name": "load_dataset", "parameter_list": "(samples=300, centers=3, cluster_std=0.6)" }, { "docstring": "Normalize the prov...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nfrom sklearn.metrics import sil...
trial_gpt4o_2
{ "original_instruction": "### Question\nWrite a Python program to implement a K-Means clustering algorithm for a given dataset. The goal is to cluster the instances in the dataset into k clusters and evaluate the clustering performance using a silhouette score.\n\n### Requirements:\n- Implement the K-Means clusterin...
0.754098
Algorithm_11150
C
[ "load_dataset", "preprocess_data", "kmeans_clustering", "main" ]
4
[ [ "kmeans_clustering", "preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
7dcd4fda1425fa6507d0c17e59ed5914c0985199
3e496fc8a64576ac790f53d0f676bb1ba3beff93
v1.0
complete
Algorithm
Algorithm_2123_C
import re from typing import List def generate_suggestions(dictionary: List[str], word: str) -> List[str]: """ Returns a list of words that are the closest match to the given misspelled word from the dictionary. """ pass def correct_text(segment: str, dictionary: List[str]) -> str: """ Correct...
import re from difflib import get_close_matches def generate_suggestions(dictionary: list[str], word: str) -> list[str]: """ Returns a list of words that are the closest match to the given misspelled word from the dictionary. """ # Using difflib.get_close_matches to find the closest matches closest...
from solution import generate_suggestions, correct_text def test_generate_suggestions(): dictionary = ["hello", "world", "welcome", "to", "the", "autocorrect", "system"] assert generate_suggestions(dictionary, "helo") == ["hello"] assert generate_suggestions(dictionary, "wrld") == ["world"] assert gene...
[ { "docstring": "Returns a list of words that are the closest match to the given misspelled word from the dictionary.", "function_declaration": "def generate_suggestions(dictionary, word):", "function_name": "generate_suggestions", "parameter_list": "(dictionary, word)" }, { "docstring": "Cor...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import re\nimport numpy as np\n\ndef levenshtein_distance(a, b):\n \"\"\"\n Calculate the Levenshtein distance between two strings.\n \"\"\"\n len_a ...
trial_gpt4o_1
{ "original_instruction": "In this exercise, you are tasked with implementing a basic text auto-correction system. The system should suggest the most probable correct word for each misspelled word in a given text segment. The suggestions will be based on a provided dictionary of correctly spelled words.\n\n### Functi...
0.681176
Algorithm_2123
C
[ "generate_suggestions", "correct_text" ]
2
[ [ "correct_text", "generate_suggestions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be0fa487e90ff7d8e5b4e9a6ae18484205818298
4ac3c7a8849fcbedfb4eb7891790b5377aa7d396
v1.0
complete
Algorithm
Algorithm_41619_C
def partition_array(arr: List[int], k: int) -> int: """ Partitions an array into `k` or fewer non-empty continuous subarrays to minimize the maximum subarray sum. Args: - arr (List[int]): A list of integers representing the array to be partitioned. - k (int): The maximum number of partitions allowe...
def partition_array(arr, k): """ Partitions an array into `k` or fewer non-empty continuous subarrays to minimize the maximum subarray sum. Args: - arr (List[int]): A list of integers representing the array to be partitioned. - k (int): The maximum number of partitions allowed. Returns...
import pytest from solution import partition_array, visualize_partitions def test_partition_array_example(): arr = [7, 2, 5, 10, 8] k = 2 assert partition_array(arr, k) == 18 def test_partition_array_single_element(): arr = [10] k = 1 assert partition_array(arr, k) == 10 def test_partition_ar...
[ { "docstring": "Partitions an array into `k` or fewer non-empty continuous subarrays to minimize the maximum subarray sum.\n\nArgs:\n- arr (List[int]): A list of integers representing the array to be partitioned.\n- k (int): The maximum number of partitions allowed.\n\nReturns:\n- int: The minimized maximum sum...
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef partition_array(arr: List[int], k: int) -> int:\n def can_partition(mid: int) -> bool:\n current_sum = 0\n count ...
trial_gpt4o_8
{ "original_instruction": "### Partitioning an Array to Minimize Maximum Subarray Sum\n\n#### Problem Description:\n\nYou are tasked with partitioning an array into `k` or fewer non-empty continuous subarrays such that the maximum sum among these subarrays is minimized. Write two functions: one to implement this part...
0.700601
Algorithm_41619
C
[ "partition_array", "visualize_partitions" ]
2
[ [ "visualize_partitions", "partition_array" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff7ace828deef836eb394c5c4db4c7cdbbc4e61e
a3d0a1d40d264daa2b35af3428c016977df41991
v1.0
complete
Algorithm
Algorithm_16449_C
def is_palindromic_prime(n: int) -> bool: """ Verifies whether a given positive integer `n` is a palindromic prime. >>> is_palindromic_prime(101) True >>> is_palindromic_prime(131) True >>> is_palindromic_prime(10) False """ pass def find_palindromic_primes(limit: int) -> List[int]:...
def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def is_palindromic_prime(n): if not isinst...
from solution import is_palindromic_prime, find_palindromic_primes def test_is_palindromic_prime(): assert is_palindromic_prime(101) == True assert is_palindromic_prime(131) == True assert is_palindromic_prime(10) == False assert is_palindromic_prime(11) == True assert is_palindromic_prime(2) == Tr...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_palindromic_prime(n):", "function_name": "is_palindromic_prime", "parameter_list": "(n)" }, { "doc...
[ 1, 1, 1, 0, 0, 1, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n ...
trial_gpt4o_0
{ "original_instruction": "### Coding Question: Find and Verify Palindromic Prime Numbers\n\n#### Context\nPalindromic primes are primes that remain the same when their digits are reversed. This exercise requires understanding of prime number algorithms and string manipulation to efficiently verify palindromic primes...
0.697038
Algorithm_16449
C
[ "is_prime", "is_palindromic_prime", "find_palindromic_primes" ]
3
[ [ "find_palindromic_primes", "is_palindromic_prime" ], [ "is_palindromic_prime", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f7628b1ea6fd076ef2d4007eae32c0444b0fc1c0
d42a36a0351f3fdca6b230d4dee05cbe72a7bcd9
v1.0
complete
Algorithm
Algorithm_42609_C
def is_valid_time(time_str: str) -> bool: """ Checks whether a given time string is in a valid "HH:MM" format. Args: time_str (str): The time string to validate. Returns: bool: True if the time string is valid, False otherwise. >>> is_valid_time("18:45") True >>> is_valid_time("25...
def is_valid_time(time_str: str) -> bool: """ Checks whether a given time string is in a valid "HH:MM" format. Args: time_str (str): The time string to validate. Returns: bool: True if the time string is valid, False otherwise. """ if len(time_str) != 5 or time_str[2] != ':': ...
import pytest from solution import is_valid_time, minutes_since_midnight, duration_between def test_is_valid_time(): assert is_valid_time("12:34") == True assert is_valid_time("23:59") == True assert is_valid_time("00:00") == True assert is_valid_time("25:00") == False assert is_valid_time("12:60")...
[ { "docstring": "Checks whether a given time string is in a valid \"HH:MM\" format.\n\nArgs:\ntime_str (str): The time string to validate.\n\nReturns:\nbool: True if the time string is valid, False otherwise.", "function_declaration": "def is_valid_time(time_str):", "function_name": "is_valid_time", ...
[ 0, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_valid_time(time_str: str) -> bool:\n \"\"\"\n Checks whether a given time string is in a valid \"HH:MM\" format.\n \n :param time_str: A strin...
trial_gpt4o_8
{ "original_instruction": "### Problem Statement\nYou are given a function called `duration_between` that calculates the duration between two times represented in a 24-hour format (\"HH:MM\"). Your task is to expand the implementation to account for more complex time scenarios and edge cases.\n\nYou need to implement...
0.568929
Algorithm_42609
C
[ "is_valid_time", "minutes_since_midnight", "duration_between" ]
3
[ [ "duration_between", "minutes_since_midnight" ] ]
1
[]
false
[]
false
pytest
true
[]
true
675c105411669a75666dc4bc52eebb7429c014f2
44631c3275122ff11d0d368d3836a545f794fabd
v1.0
complete
Algorithm
Algorithm_36429_C
import time from typing import Dict def factorial_recursive(n: int) -> int: """Computes the factorial of n recursively. >>> factorial_recursive(0) 1 >>> factorial_recursive(5) 120 """ pass def factorial_iterative(n: int) -> int: """Computes the factorial of n iteratively. >>> facto...
import time def factorial_recursive(n: int) -> int: """ Computes the factorial of n recursively. """ if n == 0: return 1 return n * factorial_recursive(n - 1) def factorial_iterative(n: int) -> int: """ Computes the factorial of n iteratively. """ result = 1 for i in ra...
from solution import factorial_recursive, factorial_iterative, compare_execution_time def test_factorial_recursive(): assert factorial_recursive(0) == 1 assert factorial_recursive(1) == 1 assert factorial_recursive(5) == 120 assert factorial_recursive(10) == 3628800 def test_factorial_iterative():...
[ { "docstring": "Computes the factorial of n recursively.", "function_declaration": "def factorial_recursive(n):", "function_name": "factorial_recursive", "parameter_list": "(n)" }, { "docstring": "Computes the factorial of n iteratively.", "function_declaration": "def factorial_iterative...
[ 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 time\n\ndef factorial_recursive(n: int) -> int:\n \"\"\"\n Returns the factorial of n using recursive approach.\n \"\"\"\n if n == 0:\n ...
trial_gpt4o_9
{ "original_instruction": "### Question\n\n**Problem Statement**:\n\nYou are given a function to calculate the factorial of a number. Your task is to extend this functionality by writing two new functions: one to compute the factorial recursively and another to compute it iteratively. Additionally, you should compare...
0.60098
Algorithm_36429
C
[ "factorial_recursive", "factorial_iterative", "compare_execution_time" ]
3
[ [ "compare_execution_time", "factorial_iterative" ], [ "compare_execution_time", "factorial_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
42d0bc6d9e975bf6644d9da54de4b606316c51cc
63fcb96ecaa7b0ef72839637bf14958b4a480994
v1.0
complete
Algorithm
Algorithm_311_C
from itertools import permutations import math def shortest_route(points: list[tuple[int, int]]) -> float: """ Determine the shortest possible route to deliver packages to a list of delivery points. Args: - points: a list of tuples representing the coordinates (x, y) of delivery points on a 2D plane. ...
import math from itertools import permutations def euclidean_distance(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def total_distance(route): distance = 0.0 for i in range(len(route) - 1): distance += euclidean_distance(route[i], route[i + 1]) # Adding the return trip...
from solution import shortest_route def test_single_point(): assert shortest_route([(0, 0)]) == 0.0 def test_two_points(): assert shortest_route([(0, 0), (1, 1)]) == round(2 * math.sqrt(2), 3) def test_three_points(): assert shortest_route([(0, 0), (1, 1), (2, 2)]) == round(2 * math.sqrt(2) + math.sqrt(8...
[ { "docstring": null, "function_declaration": "def euclidean_distance(p1, p2):", "function_name": "euclidean_distance", "parameter_list": "(p1, p2)" }, { "docstring": null, "function_declaration": "def total_distance(route):", "function_name": "total_distance", "parameter_list": "...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nimport itertools\n\ndef calculate_distance(p1, p2):\n \"\"\"Calculate the Euclidean distance between two points.\"\"\"\n return math.sqrt((p1[...
trial_gpt4o_9
{ "original_instruction": "### Coding Question: Determine Optimal Delivery Route\n\nYou are tasked with developing a function for a delivery company that needs to find the shortest possible route to deliver packages to a list of delivery points. The delivery point coordinates are given as (x, y) pairs on a 2D plane. ...
0.666133
Algorithm_311
C
[ "euclidean_distance", "total_distance", "shortest_route" ]
3
[ [ "shortest_route", "total_distance" ], [ "total_distance", "euclidean_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ce4b2e30734cc2286c841252d95750cd615ea7e7
381a54b98d0d8b6f46910726f4454057e1527446
v1.0
complete
Algorithm
Algorithm_47115_C
from typing import List def custom_radix_sort(arr: List[int]) -> List[int]: """ Sort an array of integers using the Radix Sort algorithm. >>> custom_radix_sort([-15, 3, 0, -23, 5, 7, -1]) [-23, -15, -1, 0, 3, 5, 7] >>> custom_radix_sort([3, 1, 4, 2]) [1, 2, 3, 4] >>> custom_radix_sort([-3, -1, ...
from typing import List from math import log10 def counting_sort_for_radix(arr, exp, base): n = len(arr) output = [0] * n count = [0] * base for i in range(n): index = abs(arr[i]) // exp count[index % base] += 1 for i in range(1, base): count[i] += count[i - 1] for i ...
from solution import custom_radix_sort def test_single_negative_element(): assert custom_radix_sort([-1]) == [-1] def test_single_non_negative_element(): assert custom_radix_sort([0]) == [0] assert custom_radix_sort([1]) == [1] def test_mixed_elements_simple(): assert custom_radix_sort([-15, 3, 0, -2...
[ { "docstring": null, "function_declaration": "def counting_sort_for_radix(arr, exp, base):", "function_name": "counting_sort_for_radix", "parameter_list": "(arr, exp, base)" }, { "docstring": null, "function_declaration": "def radix_sort(arr, base=10):", "function_name": "radix_sort"...
[ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef custom_radix_sort(arr: List[int]) -> List[int]:\n def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\...
trial_gpt4o_8
{ "original_instruction": "**Context:** Radix Sort is a non-comparative integer sorting algorithm that sorts numbers by processing individual digits. It works well with data that has a fixed length of integer representations and is often implemented for sorting large numbers efficiently. Your task will be to sort an ...
0.699907
Algorithm_47115
C
[ "counting_sort_for_radix", "radix_sort", "custom_radix_sort" ]
3
[ [ "custom_radix_sort", "radix_sort" ], [ "radix_sort", "counting_sort_for_radix" ] ]
2
[]
false
[]
false
pytest
true
[]
true
20be4b36fc6f50a026602d14c5317bc421da4b67
62a5d1a68c2eb01b0b07a45a401ff5cd75aebe84
v1.0
complete
Algorithm
Algorithm_23715_C
from typing import List def number_of_divisors(x: int) -> int: """ Helper function to return the number of divisors of x. """ pass def game_of_sequences(a1: int, n: int) -> List[int]: """ Generates a sequence of numbers based on the rule provided. :param a1: The initial element of the...
from typing import List def number_of_divisors(x: int) -> int: """ Helper function to return the number of divisors of x. """ count = 0 for i in range(1, int(x**0.5) + 1): if x % i == 0: count += 1 if i != x // i: # To account for both divisors when i is not the squ...
from solution import game_of_sequences, number_of_divisors def test_number_of_divisors(): assert number_of_divisors(1) == 1 assert number_of_divisors(2) == 2 assert number_of_divisors(3) == 2 assert number_of_divisors(4) == 3 assert number_of_divisors(6) == 4 assert number_of_divisors(12) == 6 ...
[ { "docstring": "Helper function to return the number of divisors of x.", "function_declaration": "def number_of_divisors(x):", "function_name": "number_of_divisors", "parameter_list": "(x)" }, { "docstring": "Generates a sequence of numbers based on the rule provided.\n\n:param a1: The initi...
[ 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 number_of_divisors(x: int) -> int:\n count = 0\n for i in range(1, x + 1):\n if x % i == 0:\n count += 1\n...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\n**Game of Sequences** is a game where players take turns constructing a sequence of numbers based on a specific rule. The rule is to add the number of divisors of each element to the sequence as its next element. Initially, the sequence starts with a given integer `...
0.657221
Algorithm_23715
C
[ "number_of_divisors", "game_of_sequences" ]
2
[ [ "game_of_sequences", "number_of_divisors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de71189b1531f05322a6918cf612ae3b7d3bf596
6e7e4cf99a31869a5632a6710fa9db95db409072
v1.0
complete
Algorithm
Algorithm_45612_C
def rearrange_string(s: str) -> str: """ Rearranges the input string such that all letters appear before any digits while maintaining their original order. >>> rearrange_string("a1b2c3") abc123 >>> rearrange_string("x9y8") xy98 >>> rearrange_string("1a2b3") ab123 """ def combine_rearra...
def rearrange_string(s): """ Rearranges the input string such that all letters appear before any digits while maintaining their original order. :param s: Input string containing a mix of alphanumeric characters :return: Rearranged string with letters first followed by digits """ letters = '...
from solution import rearrange_string, combine_rearranged_strings def test_rearrange_string(): assert rearrange_string("a1b2c3") == "abc123" assert rearrange_string("x9y8") == "xy98" assert rearrange_string("1a2b3") == "ab123" assert rearrange_string("abcd1234") == "abcd1234" assert rearrange_strin...
[ { "docstring": "Rearranges the input string such that all letters appear before any digits while maintaining their original order.\n\n:param s: Input string containing a mix of alphanumeric characters\n:return: Rearranged string with letters first followed by digits", "function_declaration": "def rearrange_...
[ 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 rearrange_string(s):\n \"\"\"\n Rearranges the characters in the given string such that all letters appear before any digits,\n maintaining their or...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement:**\n\nYou are provided with a list of strings where each string consists of a mix of letters and digits. Your goal is to rearrange the characters in each string such that:\n1. All letters appear before any digits.\n2. Both letters and digits within their own groups shoul...
0.620624
Algorithm_45612
C
[ "rearrange_string", "combine_rearranged_strings" ]
2
[ [ "combine_rearranged_strings", "rearrange_string" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e00f2b4c063a2566ea1eb48e2c00c9f3386f3056
1ae53b4e4f2ff9d18f76598db810b190056c2f40
v1.0
complete
Algorithm
Algorithm_19542_C
def merge_sort_routes(routes: list[tuple[str, float]]) -> list[tuple[str, float]]: """ Sort a list of routes based on distance using the merge sort algorithm. :param routes: List of tuples, where each tuple contains a route name and a distance. :return: List of tuples sorted by the distance in ascending...
def merge_sort_routes(routes): """ Sort a list of routes based on distance using the merge sort algorithm. :param routes: List of tuples, where each tuple contains a route name and a distance. :return: List of tuples sorted by the distance in ascending order. """ if len(routes) <= 1: ...
from solution import merge_sort_routes def test_merge_sort_empty_list(): assert merge_sort_routes([]) == [] def test_merge_sort_single_element(): assert merge_sort_routes([("Route X", 45.0)]) == [("Route X", 45.0)] def test_merge_sort_multiple_elements(): routes = [("Route A", 120.5), ("Route B", 85.2), ...
[ { "docstring": "Sort a list of routes based on distance using the merge sort algorithm.\n\n:param routes: List of tuples, where each tuple contains a route name and a distance.\n:return: List of tuples sorted by the distance in ascending order.", "function_declaration": "def merge_sort_routes(routes):", ...
[ 1, 1, 1, 1, 0, 1, 1, 1, 0, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def merge_sort_routes(routes):\n \"\"\"\n Sorts a list of routes based on distance using merge sort algorithm.\n Each route is represented as a tuple co...
trial_gpt4o_7
{ "original_instruction": "### Coding Assessment Question\n\n#### Context\nA logistics company wants to optimize the sorting of its delivery routes based on distance. Their current system sorts routes using a basic bubble sort algorithm, which is not efficient for large data sets. They require a more efficient sortin...
0.510535
Algorithm_19542
C
[ "merge_sort_routes", "merge" ]
2
[ [ "merge_sort_routes", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c2136da94578b90d8a21f4f305fc91b468095bd8
b26f1ddf1dfaf7aadc757a4a3424562452b59116
v1.0
complete
Algorithm
Algorithm_37874_C
def adjust_brightness(image: list[list[tuple[int, int, int]]], factor: float) -> list[list[tuple[int, int, int]]]: """ Adjust the brightness of a 2D list representing an image. Each pixel is represented by a tuple (red, green, blue), where 0 <= red, green, blue <= 255. The factor is a float where a value ...
def clamp(value, min_value, max_value): return max(min_value, min(value, max_value)) def adjust_brightness(image, factor): if not image: return [] adjusted_image = [] for row in image: adjusted_row = [] for (red, green, blue) in row: adjusted_red = clamp(int(red * f...
from solution import adjust_brightness def test_brightness_increase(): image = [[(100, 100, 100), (50, 50, 50)], [(200, 200, 200), (25, 25, 25)]] expected = [[(120, 120, 120), (60, 60, 60)], [(240, 240, 240), (30, 30, 30)]] assert adjust_brightness(image, 1.2) == expected def test_brightness_decrease(): ...
[ { "docstring": null, "function_declaration": "def clamp(value, min_value, max_value):", "function_name": "clamp", "parameter_list": "(value, min_value, max_value)" }, { "docstring": null, "function_declaration": "def adjust_brightness(image, factor):", "function_name": "adjust_bright...
[ 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 adjust_brightness(image: list[list[tuple[int, int, int]]], factor: float) -> list[list[tuple[int, int, int]]]:\n \"\"\"\n Adjust the brightness of a gi...
trial_gpt4o_9
{ "original_instruction": "### Context\nIn computer graphics, colors are often represented in the RGB color model. In this model, each color is described by three components - red, green, and blue - each ranging from 0 to 255. A common task in image processing is to adjust the brightness of an image, which can be don...
0.521825
Algorithm_37874
C
[ "clamp", "adjust_brightness" ]
2
[ [ "adjust_brightness", "clamp" ] ]
1
[]
false
[]
false
pytest
true
[]
true
303998e8e84176db1690965d79033d30b7b3674b
153c2586a9e8aa42d5ecdc2d1b93f225ca2dc956
v1.0
complete
Algorithm
Algorithm_27838_C
import numpy as np import pandas as pd from urllib.request import urlopen def collect_dataset() -> np.matrix: """ Download and return the dataset as a matrix. >>> data = collect_dataset() >>> data.shape (150, 4) """ pass def euclidean_distance(point1: np.array, point2: np.array) -> float: ...
import numpy as np import pandas as pd from urllib.request import urlopen def collect_dataset(): url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv" df = pd.read_csv(url) data = df.drop(columns=['species']).values return data def euclidean_distance(point1, point2): retur...
import pytest import numpy as np from solution import collect_dataset, euclidean_distance, assign_clusters, update_centroids, compute_wcss, run_k_means def test_collect_dataset(): data = collect_dataset() assert data.shape == (150, 4) # Iris dataset should have 150 rows and 4 features def test_euclidean_dist...
[ { "docstring": null, "function_declaration": "def collect_dataset():", "function_name": "collect_dataset", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(...
[ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\nfrom urllib import request\n\ndef collect_dataset():\n url = \"https://raw.githubusercontent.com/mwaskom/seaborn-data...
trial_gpt4o_2
{ "original_instruction": "### Implementation of Simple K-Means Clustering\n\nYou are required to implement the K-Means clustering algorithm from scratch. Your task is to:\n1. Download and process a given dataset.\n2. Implement the K-Means algorithm to cluster the data points.\n3. Evaluate the clustering performance ...
0.740755
Algorithm_27838
C
[ "collect_dataset", "euclidean_distance", "assign_clusters", "update_centroids", "compute_wcss", "run_k_means" ]
6
[ [ "assign_clusters", "euclidean_distance" ], [ "compute_wcss", "euclidean_distance" ], [ "run_k_means", "assign_clusters" ], [ "run_k_means", "compute_wcss" ], [ "run_k_means", "update_centroids" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
95e59b73062b7c2bc05b4be2bfa6b01698b85ba0
a3546bd982b665fe4ce31b1d6bcfb3a8cc0dd1ba
v1.0
complete
Algorithm
Algorithm_27224_C
[Completion Task in Python] """ Implement the following functions: 1. fit_knn_model(): This function fits the KNN model with the provided training features, labels, and number of neighbors to consider. def fit_knn_model(features: list[list[float]], labels: list[int], k: int) -> dict: return {'features': features,...
import math from collections import Counter def fit_knn_model(features, labels, k): """ Fits the KNN model with the provided training features and labels. Parameters: features (list[list[float]]): 2D list of feature values for training instances. labels (list[int]): List of labels correspondin...
import pytest from solution import fit_knn_model, predict_instances, calculate_accuracy def test_fit_knn_model(): features = [[1, 2], [2, 3], [3, 4]] labels = [0, 1, 0] k = 2 model = fit_knn_model(features, labels, k) assert model['features'] == features assert model['labels'] == labels ass...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\nfrom collections import Counter\n\ndef fit_knn_model(features, labels, k):\n \"\"\"\n Fits the KNN model using given training data.\n \n ...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment: Implementing K-Nearest Neighbors (KNN)\n\n**Objective**: Implement the K-Nearest Neighbors (KNN) algorithm to classify a set of instances. You will use the provided KNN model and utility functions as a reference to create new components to demonstrate your understandi...
0.57438
Algorithm_27224
C
[ "fit_knn_model", "euclidean_distance", "predict_instances", "calculate_accuracy" ]
4
[ [ "predict_instances", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
27318a4fef7f5efe5f65b2441ad7004b96a7bb77
08bae9c566cca865ac93c1c54fb57cb3d18d331e
v1.0
complete
Algorithm
Algorithm_26228_C
def is_rotated_palindrome(s: str) -> bool: """ Determine whether the given string can be rotated to form a palindrome. Check if the given string s can be rotated (or shifted) any number of positions to become a palindrome. >>> is_rotated_palindrome("aab") == True >>> is_rotated_palindrome("abc") ==...
def is_palindrome(s): """ Helper function to check if a given string is a palindrome. """ return s == s[::-1] def is_rotated_palindrome(s: str) -> bool: """ Determine whether the given string can be rotated to form a palindrome. """ if len(s) <= 1: return True # Constru...
def test_is_rotated_palindrome_positive(): assert is_rotated_palindrome("aab") == True assert is_rotated_palindrome("baab") == True assert is_rotated_palindrome("aba") == True assert is_rotated_palindrome("aaaa") == True assert is_rotated_palindrome("a") == True def test_is_rotated_palindrome_n...
[ { "docstring": "Helper function to check if a given string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Determine whether the given string can be rotated to form a palindrome.", "function_...
[ 0, 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def is_rotated_palindrome(s):\n \"\"\"\n Returns True if the string s can be rotated to form a palindrome.\n \"\"\"\n def is_palindrome(t):\n ...
trial_gpt4o_3
{ "original_instruction": "### Coding Question\n\n#### Context\n\nYou are familiar with the concept of palindrome strings, which are strings that read the same forward and backward. Checking if a string is a palindrome is a common programming exercise. However, let's take it a step further and explore the concept of ...
0.835739
Algorithm_26228
C
[ "is_palindrome", "is_rotated_palindrome" ]
2
[ [ "is_rotated_palindrome", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
false
[]
true
d43e3aa6d5d239cd2535365c255fe128644fb53c
4c12ed43adcff0a4e651282d38f2d3a25157995e
v1.0
complete
Algorithm
Algorithm_31252_C
def custom_atbash_encode(plain: str) -> str: """ Converts a given string using the atbash cipher. >>> custom_atbash_encode("hello world!") 'svool dliow!' >>> custom_atbash_encode("abc xyz") 'zyx cba' >>> custom_atbash_encode("123-456-789") '123-456-789' >>> custom_atbash_encode("the quic...
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": "### Question:\n\nYou are to implement a function that calculates a modified version of the atbash cipher algorithm with additional features and constraints.\n\n**Objective:**\nWrite two functions, `custom_atbash_encode` and `custom_atbash_decode`.\n\n1. `custom_atbash_encode(plain: str) -> ...
0.686849
Algorithm_31252
C
[ "custom_atbash_encode", "custom_atbash_decode" ]
2
[ [ "custom_atbash_decode", "custom_atbash_encode" ] ]
1
[]
false
[]
false
pytest
false
[]
true
ea96c84ef3b47b3e6f4ea49958136b52428c6d5e
82b37def6a4e96ea05791312ebab516e57814117
v1.0
complete
Algorithm
Algorithm_40007_C
markdown ## Task Write a function `find_shortest_route(n: int, edges: List[Tuple[int, int, int]], required_stops: List[int]) -> List[int]:` to determine the shortest route traveling through a series of required stops using Dijkstra's algorithm as described. Your function should return the shortest route as a list of lo...
import heapq from typing import List, Tuple def dijkstra(graph: List[List[Tuple[int, int]]], start: int) -> List[int]: """ Implements Dijkstra's algorithm to find the shortest path from 'start' to all other nodes. Parameters: - graph: Adjacency list representation of the graph where graph[u] is a ...
def test_dijkstra_basic(): graph = [ [(1, 2), (2, 4)], [(0, 2), (2, 1)], [(0, 4), (1, 1)] ] assert dijkstra(graph, 0) == [0, 2, 3] assert dijkstra(graph, 1) == [2, 0, 1] assert dijkstra(graph, 2) == [3, 1, 0] def test_find_shortest_route_case1(): assert find_shortes...
[ { "docstring": "Implements Dijkstra's algorithm to find the shortest path from 'start' to all other nodes.\n\nParameters:\n- graph: Adjacency list representation of the graph where graph[u] is a list of tuples (v, w)\n representing an edge from u to v with weight w.\n- start: The starting node.\n\nRetur...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import heapq\nfrom typing import List, Tuple, Dict\n\ndef dijkstra(n: int, graph: Dict[int, List[Tuple[int, int]]], start: int) -> Dict[int, int]:\n # Initial...
trial_gpt4o_6
{ "original_instruction": "### Scenario:\nYou have been hired as a software developer by a logistics company to streamline their package delivery tracking system. They require a function to determine the shortest delivery route between different locations while considering some locations as mandatory stops.\n\n### Ta...
0.662695
Algorithm_40007
C
[ "dijkstra", "find_shortest_route" ]
2
[ [ "find_shortest_route", "dijkstra" ] ]
1
[]
false
[]
false
pytest
false
[]
true
6238d8ed7edf510a040667551d27159eabbaa82e
7d6b7b397e62457c4e5d5f1f5ec14f63132e0aab
v1.0
complete
Algorithm
Algorithm_32532_C
from typing import List def find_longest_word(s: str, dictionary: List[str]) -> str: """ Given a collection of words and a specific word, find the longest word in the collection that can be constructed by deleting some characters of the specific word without rearranging the characters. >>> find_longest_wo...
from typing import List def can_form_by_deleting(s: str, word: str) -> bool: it = iter(s) return all(char in it for char in word) def find_longest_word(s: str, dictionary: List[str]) -> str: possible_words = [ word for word in dictionary if can_form_by_deleting(s, word) ] # Sort primarily ...
from solution import find_longest_word def test_example_case(): s = "abpcplea" dictionary = ["ale","apple","monkey","plea"] assert find_longest_word(s, dictionary) == "apple" def test_multiple_solution_lexicographically_smallest(): s = "abpcplea" dictionary = ["a", "b", "c"] assert find_longes...
[ { "docstring": null, "function_declaration": "def can_form_by_deleting(s, word):", "function_name": "can_form_by_deleting", "parameter_list": "(s, word)" }, { "docstring": null, "function_declaration": "def find_longest_word(s, dictionary):", "function_name": "find_longest_word", ...
[ 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef find_longest_word(s: str, dictionary: List[str]) -> str:\n def can_form(word):\n it = iter(s)\n return all(char i...
trial_gpt4o_6
{ "original_instruction": "### Problem Statement\nGiven a collection of words and a specific word, find the longest word in the collection that can be constructed by deleting some characters of the specific word without rearranging the characters.\n\n### Function Signature\n```python\ndef find_longest_word(s: str, di...
0.799171
Algorithm_32532
C
[ "can_form_by_deleting", "find_longest_word" ]
2
[ [ "find_longest_word", "can_form_by_deleting" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ee2bbd9959120d2be093ce14a6a866bd32567ee1
61c283cdf23018c6cb8bed79ec23d903014692f1
v1.0
complete
Algorithm
Algorithm_30811_C
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 extracted data. ...
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": "### Question: Log Analyzer for Web Server\n\n#### Objective:\nAs 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 standard...
0.729142
Algorithm_30811
C
[ "parse_log_entry", "parse_log_file", "most_frequent_ip", "error_rate" ]
4
[ [ "parse_log_file", "parse_log_entry" ] ]
1
[]
false
[]
false
pytest
true
[]
true
917d341ef3d4a191152c1ffca745c089e2e5b460
aa616b383e24f3fb989909026209a35f33e6a3e5
v1.0
complete
Algorithm
Algorithm_28593_C
from typing import List 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: s...
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": "### Huffman Encoding\n\nHuffman 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.\n\n#### Input Format:\n1. A path to the input text file containing ...
0.499453
Algorithm_28593
C
[ "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
80338ede841e574ec614aa8d21e53ecfeaa9736f
86c6d4bd02e527f2eeb0c63d3539d7656717a11e
v1.0
complete
Algorithm
Algorithm_979_C
def is_mersenne_prime(num: int) -> bool: """ Determine if a given positive integer 'num' is a Mersenne prime. A Mersenne prime is a prime number that is one less than a power of two. >>> is_mersenne_prime(3) True >>> is_mersenne_prime(7) True >>> is_mersenne_prime(15) False ...
import math def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def is_mersenne_prim...
from solution import is_mersenne_prime def test_is_mersenne_prime(): assert is_mersenne_prime(3) == True # p = 2 -> 2^2 - 1 = 3 assert is_mersenne_prime(7) == True # p = 3 -> 2^3 - 1 = 7 assert is_mersenne_prime(31) == True # p = 5 -> 2^5 - 1 = 31 assert is_mersenne_prime(127) == True # p = 7 ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_mersenne_prime(num):", "function_name": "is_mersenne_prime", "parameter_list": "(num)" } ]
[ 0, 1, 1, 0, 0, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Determine if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ret...
trial_gpt4o_1
{ "original_instruction": "### Problem Description\nCreate a function that determines if a given positive integer `num` is a Mersenne prime. A Mersenne prime is a prime number that is one less than a power of two, i.e., it is a number of the form `2^p - 1` where `p` is also a prime number.\n\n### Constraints\n* The f...
0.770958
Algorithm_979
C
[ "is_prime", "is_mersenne_prime" ]
2
[ [ "is_mersenne_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c053750c0acd235692fa8a2c35499debc3495aff
e7ba9061727d312e4ebe1ae009e269457c3a883a
v1.0
complete
Algorithm
Algorithm_15738_C
class Node: def __init__(self, timestamp: int, value: int): self.timestamp = timestamp self.value = value self.left = None self.right = None self.size = 1 # Size of the subtree including this node def insert_bst(root: Node, timestamp: int, value: int) -> Node: """Insert...
class Node: def __init__(self, timestamp: int, value: int): self.timestamp = timestamp self.value = value self.left = None self.right = None self.size = 1 # Size of the subtree including this node def insert_bst(root: Node, timestamp: int, value: int) -> Node: if root i...
import pytest def create_bst_with_values(): root = None root = insert_bst(root, 50, 1) root = insert_bst(root, 30, 2) root = insert_bst(root, 70, 3) root = insert_bst(root, 20, 4) root = insert_bst(root, 40, 5) root = insert_bst(root, 60, 6) root = insert_bst(root, 80, 7) return roo...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, timestamp: int, value: int):\n self.timestamp = timestamp\n self.value = value\n self.left = None\n ...
trial_gpt4o_9
{ "original_instruction": "### Problem Statement\n\nIn a database system, we often need to keep track of data insertion events and the timestamps associated with them. One efficient way to manage this is by using a binary search tree (BST) where each node contains a timestamp and an associated value. For this problem...
0.456814
Algorithm_15738
C
[ "insert_bst", "find_nth_largest", "find_kth_smallest" ]
3
[ [ "find_nth_largest", "find_kth_smallest" ] ]
1
[]
false
[ "Node" ]
true
pytest
false
[]
true
413dfc033cb0a54be8da911a2b51151ac11be853
ee43d4cf1bf512548c2446a30660acfe18682543
v1.0
complete
Algorithm
Algorithm_24158_C
from typing import List, Tuple import time def merge_sort(data: List[int]) -> List[int]: if len(data) <= 1: return data mid = len(data) // 2 left = merge_sort(data[:mid]) right = merge_sort(data[mid:]) return merge(left, right) def merge(left: List[int], right: List[int]) -> List[int]: ...
from typing import List, Tuple import time def merge_sort(data: List[int]) -> List[int]: if len(data) <= 1: return data mid = len(data) // 2 left = merge_sort(data[:mid]) right = merge_sort(data[mid:]) return merge(left, right) def merge(left: List[int], right: List[int]) -> List[int]: ...
from solution import sort_comparison def test_sort_comparison_empty_list(): merge_time, quick_time = sort_comparison([]) assert merge_time >= 0 assert quick_time >= 0 def test_sort_comparison_single_element(): data = [1] merge_time, quick_time = sort_comparison(data) assert merge_time >= 0 ...
[ { "docstring": null, "function_declaration": "def merge_sort(data):", "function_name": "merge_sort", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "doc...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport time\n\ndef merge_sort(data: List[int]) -> List[int]:\n if len(data) <= 1:\n return data\n mid = len(data) //...
trial_gpt4o_9
{ "original_instruction": "### Data Structure Comparison: Sorting Algorithm Efficiency\n\n#### Context:\nAs a software engineer, you are tasked with optimizing a data processing pipeline. You need to compare the efficiencies of different sorting algorithms on various types of input data. Your goal is to implement a f...
0.56166
Algorithm_24158
C
[ "merge_sort", "merge", "quick_sort", "sort_comparison" ]
4
[ [ "merge_sort", "merge" ], [ "sort_comparison", "merge_sort" ], [ "sort_comparison", "quick_sort" ] ]
3
[]
false
[]
false
pytest
true
[]
true
005709c466e866b00e9dc1aa91fcd416fc59fdfc
18201ac3c13e20b0e7026458aca56e0bdb5fc53b
v1.0
complete
Algorithm
Algorithm_6964_C
import random from typing import List, Callable, Any, Tuple class MultiObjectiveProblem: def __init__(self, objectives: List[Callable], population: List[Any], mutation_rate: float, crossover_rate: float): """Initialize the multi-objective problem with the given objectives, initial population, mutation rate...
import random from typing import List, Callable, Any, Tuple class MultiObjectiveProblem: def __init__(self, objectives: List[Callable], population: List[Any], mutation_rate: float, crossover_rate: float): self.objectives = objectives self.population = population self.mutation_rate = mutatio...
import pytest def test_multiobjective_genetic_algorithm(): def objective1(solution): return sum(x**2 for x in solution) def objective2(solution): return sum((x - 2)**2 for x in solution) initial_population = [[random.uniform(-10, 10) for _ in range(3)] for _ in range(50)] multi_obj_p...
[]
[ 0, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "import random\nfrom typing import List, Callable, Tuple, Any\n\nclass MultiObjectiveProblem:\n def __init__(self, objectives: List[Callable], population: List...
trial_gpt4o_9
{ "original_instruction": "### Coding Assessment: Genetic Algorithm for TSP\n\n#### Problem Statement\nYou are provided with an implementation of a Genetic Algorithm (GA) for the Traveling Salesman Problem (TSP). Your task is to implement a similar optimization algorithm but for a multi-objective optimization problem...
0.530314
Algorithm_6964
C
[ "dominates", "genetic_algorithm_multi_objective" ]
2
[ [ "genetic_algorithm_multi_objective", "dominates" ] ]
1
[]
false
[ "MultiObjectiveProblem" ]
true
pytest
false
[]
true
8c5e369878c7cd9119a5e93e34d63ff73049cbda
9e8119b4149ebfee11f91b559c99922d784f018a
v1.0
complete
Algorithm
Algorithm_12990_C
def reverse_string(s: str) -> str: """ Reverses a given string. >>> reverse_string("hello") == "olleh" >>> reverse_string("") == "" >>> reverse_string("a") == "a" >>> reverse_string("racecar") == "racecar" """ def is_palindrome(s: str) -> bool: """ Checks if a given string is a palindrome. ...
def reverse_string(s): """ Returns the given string reversed. """ return s[::-1] def is_palindrome(s): """ Checks if the given string is a palindrome. """ reversed_s = reverse_string(s) return s == reversed_s def count_vowels(s): """ Counts the number of vowels (a, e, i, o,...
from solution import reverse_string, is_palindrome, count_vowels, find_substring, capitalize_words def test_reverse_string(): assert reverse_string("hello") == "olleh" assert reverse_string("") == "" assert reverse_string("a") == "a" assert reverse_string("racecar") == "racecar" def test_is_palindrome...
[ { "docstring": "Returns the given string reversed.", "function_declaration": "def reverse_string(s):", "function_name": "reverse_string", "parameter_list": "(s)" }, { "docstring": "Checks if the given string is a palindrome.", "function_declaration": "def is_palindrome(s):", "functio...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl", "solution_code": "def reverse_string(s):\n \"\"\"\n Reverses a given string.\n \"\"\"\n return s[::-1]\n\ndef is_palindrome(s):\n \"\"\"\n Checks if a given stri...
trial_gpt4o_9
{ "original_instruction": "### Scenario\nYou have joined a software company that is building a new text processing library. One component of this library involves handling strings and implementing essential text manipulation functions. Your task is to create a set of string utility functions which will be crucial for...
0.752768
Algorithm_12990
C
[ "reverse_string", "is_palindrome", "count_vowels", "find_substring", "capitalize_words" ]
5
[ [ "is_palindrome", "reverse_string" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3c52e350d45ada1817151c1b64527954225c1f66
d6666aa1f84f072e12e26257072d71600e1528a6