version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Filter
Filter_4577_I
result = ''.join([…………………………]) scenarios = [ ('title', 'name', 'custodian agency', 'telephone number (voice)', '_DOCUMENT'), ('year', 'iata code', 'icao code', 'substring of document', 'argo, iat'), ('title', 'iata code and document id', 'airport name', 'standard baggage allowance', 'argo'), ] ** Write a g...
from itertools import permutations def generate_combinations(scenario): """ Returns all possible combinations of the elements in the scenario tuple. """ all_combinations = [] for perm in permutations(scenario): all_combinations.append(''.join(perm)) return all_combinations def generate...
from solution import generate_combinations, generate_all_scenarios def test_generate_combinations(): scenario = ('a', 'b') combinations = generate_combinations(scenario) expected_combinations = ['ab', 'ba'] assert sorted(combinations) == sorted(expected_combinations) def test_generate_combinations_lar...
[ { "docstring": "Returns all possible combinations of the elements in the scenario tuple.", "function_declaration": "def generate_combinations(scenario):", "function_name": "generate_combinations", "parameter_list": "(scenario)" }, { "docstring": "Applies generate_combinations to all scenario...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef generate_combinations(scenario):\n \"\"\"\n Generates all possible combinations of elements in the scenario tuple.\n \n Args:\n scenario (tuple): A tuple...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004577", "row_id": 4577, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_13876']" }
0.528626
Filter_4577
I
[ "generate_combinations", "generate_all_scenarios" ]
2
[ [ "generate_all_scenarios", "generate_combinations" ] ]
1
[]
false
[]
false
pytest
true
[]
true
39f3ea8c10aa8b1a4ad58aac5cca58c34517f803
11121c38acdf5daf29c496b1f3e354d6c6912139
v1.0
instruct
Filter
Filter_4597_I
I have a file with 100,000 lines, each containing a key-value pair. The key is a string and the value is an integer. The file is too large to fit in memory, so I need to process it in chunks. How can I read it efficiently in Python?
def process_large_file(file_path, chunk_size=1000): """ Processes a large file in chunks. Parameters: - file_path (str): the path to the file to process. - chunk_size (int): the number of lines to process at a time. Returns: - results (list of dict): a list containing dictionaries ...
from solution import process_large_file, process_chunk def test_process_chunk(): chunk = ["key1 1", "key2 2", "key3 3"] expected = {"key1": 1, "key2": 2, "key3": 3} assert process_chunk(chunk) == expected def test_process_large_file(): # Simulate a file and write it out for the test file_content =...
[ { "docstring": "Processes a large file in chunks.\n\nParameters:\n- file_path (str): the path to the file to process.\n- chunk_size (int): the number of lines to process at a time.\n\nReturns:\n- results (list of dict): a list containing dictionaries of key-value pairs.", "function_declaration": "def proces...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def process_large_file(file_path, chunk_size=1024):\n \"\"\"\n Reads a large file with key-value pairs in chunks and processes each chunk.\n \n :param file_path: Path to the large ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004597", "row_id": 4597, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_13941']" }
0.474524
Filter_4597
I
[ "process_large_file", "process_chunk" ]
2
[ [ "process_large_file", "process_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2cc5d75544047938cfde756d923803d4b586266f
e6f38af3971d0f863521b085d80eb1f548aad2c4
v1.0
instruct
Filter
Filter_4611_I
Given a list of integers, implement an in-place algorithm to sort the list. The algorithm should be designed such that it minimises the number of writes to the list. Here is a Python solution using an in-place implementation of merge sort. The idea is to sort subarrays and keep track of segments that are sorted. ```py...
def merge(arr, low, mid, high): """ In-place merge function to merge two sorted subarrays within an array. :arr: list of integers :low: Starting index of the first sorted subarray :mid: Ending index of the first sorted subarray (Starting index+1 of the second sorted subarray) :high: Ending ...
from solution import merge_sort_in_place def test_merge_sort_in_place_empty(): arr = [] assert merge_sort_in_place(arr) == [] def test_merge_sort_in_place_single_element(): arr = [1] assert merge_sort_in_place(arr) == [1] def test_merge_sort_in_place_sorted(): arr = [1, 2, 3, 4, 5] assert mer...
[ { "docstring": "In-place merge function to merge two sorted subarrays within an array.\n\n:arr: list of integers\n:low: Starting index of the first sorted subarray\n:mid: Ending index of the first sorted subarray (Starting index+1 of the second sorted subarray)\n:high: Ending index of the second sorted subarray...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def partition(arr, low, high):\n \"\"\"\n Partition the array using the last element as pivot\n \n :arr: list of integers\n :low: lower index\n :high: higher index\n \"\"\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004611", "row_id": 4611, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_13966']" }
0.561657
Filter_4611
I
[ "merge", "merge_sort_in_place" ]
2
[ [ "merge_sort_in_place", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9d2e66c9551c68fa42a50598f1d0145034d6c53b
1741a04d900e08b5d3f88ed278c40971b50c2397
v1.0
instruct
Filter
Filter_4656_I
```python def factorial(n): """ Calculate the factorial of a given integer n. Parameters: n (int): The input integer for which the factorial needs to be calculated. Returns: int: The factorial of n. """ # Define a variable to store the factorial value, initially set to 1. ...
from concurrent.futures import ThreadPoolExecutor def factorial_chunk(start, end): result = 1 for i in range(start, end + 1): result *= i return result def parallel_factorial(n, num_threads=4): """ Calculate the factorial of a given integer n using parallel computation. Parameters...
from solution import parallel_factorial def test_parallel_factorial_small_numbers(): assert parallel_factorial(0) == 1 assert parallel_factorial(1) == 1 assert parallel_factorial(2) == 2 assert parallel_factorial(3) == 6 def test_parallel_factorial_medium_numbers(): assert parallel_factorial(5) ==...
[ { "docstring": null, "function_declaration": "def factorial_chunk(start, end):", "function_name": "factorial_chunk", "parameter_list": "(start, end)" }, { "docstring": "Calculate the factorial of a given integer n using parallel computation.\n\nParameters:\nn (int): The input integer for whi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\n\ndef partial_factorial(start, end):\n \"\"\"\n Partial factorial calculation from start to end (inclusive).\n \"\"\"\n result = 1\n for i in range(start...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004656", "row_id": 4656, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14121']" }
0.792116
Filter_4656
I
[ "factorial_chunk", "parallel_factorial" ]
2
[ [ "parallel_factorial", "factorial_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
66aac8ef893f5206bdd818dad8da6500769fba51
f8d945e8e4a97cead1fd4d9bff161f39d99c09ed
v1.0
instruct
Filter
Filter_4673_I
import random def randommove(list_of_properties): getRandom = list_of_properties[random.randint(1,len(list_of_properties) - 1)] return getRandom def allPlayersrandmove(list_of_players): newlistOfProperties = list_of_properties removeProperty = randommove(newlistOfProperties) newlistOfProperties.remo...
import random def randommove(list_of_properties): getRandom = list_of_properties[random.randint(0,len(list_of_properties) - 1)] return getRandom def allPlayersrandmove(list_of_players, list_of_properties): newListOfProperties = list_of_properties.copy() player_properties = {} for player in list_of...
from solution import randommove, allPlayersrandmove def test_randommove_single_item(): properties = ["House"] assert randommove(properties) == "House" def test_randommove_multiple_items(): properties = ["House", "Car", "Bike"] assert randommove(properties) in properties def test_allPlayersrandmove_al...
[ { "docstring": null, "function_declaration": "def randommove(list_of_properties):", "function_name": "randommove", "parameter_list": "(list_of_properties)" }, { "docstring": null, "function_declaration": "def allPlayersrandmove(list_of_players, list_of_properties):", "function_name":...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef randommove(list_of_properties):\n getRandom = list_of_properties[random.randint(0,len(list_of_properties) - 1)]\n return getRandom\n\ndef allPlayersrandmove(list_of_...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004673", "row_id": 4673, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14171']" }
0.474918
Filter_4673
I
[ "randommove", "allPlayersrandmove" ]
2
[ [ "allPlayersrandmove", "randommove" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8c4ca7699732b92ad48e2ea165b7a71a35cc170c
d806d609f99060424b26c9b39bdb52d4818b161c
v1.0
instruct
Filter
Filter_4704_I
def is_prime(n): """Check if a number is prime.""" if n < 2: return False for i in range(2, n): if n % i == 0: return False return True def get_prime_stats(start, end): """Compute various statistics about prime numbers.""" prime_count = 0 prime_sum = 0 primes = [] for num in range(start...
def is_prime(n): """ Check if a number is prime. """ if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def get_prime_stats(start, end): """ Compute various statistics about prime numbers in a range. """ ...
from solution import is_prime, get_prime_stats def test_is_prime(): assert is_prime(2) is True assert is_prime(3) is True assert is_prime(4) is False assert is_prime(17) is True assert is_prime(18) is False assert is_prime(19) is True assert is_prime(0) is False assert is_prime(1) is Fa...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Compute various statistics about prime numbers in a range.", "function_declaration": "def get_prime_stats(start, end):", "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004704", "row_id": 4704, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14323']" }
0.749886
Filter_4704
I
[ "is_prime", "get_prime_stats" ]
2
[ [ "get_prime_stats", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
94cf36a4ee734166a68efc9135cf9ae13441b353
83ad3fff9075c4c0daeab7ca8e7e2c365a8c7d39
v1.0
instruct
Filter
Filter_4731_I
def check_self_loop(Graph, node): return Graph[node][node] != 0 def find_all_self_loops(Graph): self_loops = [] for node in Graph: if check_self_loop(Graph, node): self_loops.append(node) return self_loops def find_all_self_loops_another_way(Graph): self_loops = [node for node ...
def check_self_loop(Graph, node): """ Check if there is a self-loop on the given node in the graph. :param Graph: A dictionary representing an adjacency matrix of the graph. :param node: A node in the graph. :return: True if there is a self-loop, False otherwise. """ return Graph[node][node]...
import pytest from solution import check_self_loop, find_all_self_loops, find_all_self_loops_another_way def test_check_self_loop(): graph = { 'A': {'A': 1, 'B': 2}, 'B': {'A': 0, 'B': 0} } assert check_self_loop(graph, 'A') == True assert check_self_loop(graph, 'B') == False def test_...
[ { "docstring": "Check if there is a self-loop on the given node in the graph.\n:param Graph: A dictionary representing an adjacency matrix of the graph.\n:param node: A node in the graph.\n:return: True if there is a self-loop, False otherwise.", "function_declaration": "def check_self_loop(Graph, node):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_self_loop(Graph, node):\n \"\"\"\n Checks if a given node has a self-loop in the graph.\n \n Parameters:\n - Graph (dict): A dictionary where keys are node names and v...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004731", "row_id": 4731, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14418']" }
0.510872
Filter_4731
I
[ "check_self_loop", "find_all_self_loops", "find_all_self_loops_another_way" ]
3
[ [ "find_all_self_loops", "check_self_loop" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f7dc4a47c1547600b00f7d55b2ad204adf8abc3d
133e78da86c6856fdcb701df5eb15891b93ea9a2
v1.0
instruct
Filter
Filter_4744_I
def calculate_hash(string): """ This function takes in a string and returns a hash value that represents the given string. The algorithm of this hash function is not relevant to the solution. """ hash_value = 0 for char in string: hash_value = hash_value * 31 + ord(char) return hash_...
def calculate_hash(string): """ This function takes in a string and returns a hash value that represents the given string. The algorithm of this hash function is not relevant to the solution. """ hash_value = 0 for char in string: hash_value = hash_value * 31 + ord(char) return hash_...
from solution import calculate_hash, hash_equal, solve def test_calculate_hash(): assert calculate_hash("abc") == calculate_hash("abc") assert calculate_hash("abc") != calculate_hash("abcd") assert calculate_hash("hello") != calculate_hash("world") def test_hash_equal(): assert hash_equal("abc", "abc"...
[ { "docstring": "This function takes in a string and returns a hash value that represents the given string.\nThe algorithm of this hash function is not relevant to the solution.", "function_declaration": "def calculate_hash(string):", "function_name": "calculate_hash", "parameter_list": "(string)" ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_hash(string):\n \"\"\"\n This function takes in a string and returns a hash value that represents the given string.\n The algorithm of this hash function is not relevant...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004744", "row_id": 4744, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14468']" }
0.578376
Filter_4744
I
[ "calculate_hash", "hash_equal", "solve" ]
3
[ [ "hash_equal", "calculate_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e397fcb41f53a6314906ecbabd3b81745e5df817
5c7221803682a0bf15eb6c32da05814003c2351f
v1.0
instruct
Filter
Filter_4766_I
CPU Stress Test Write a program that will stress test a CPU. The program should make multiple concurrent requests to perform mathematical calculations, which will simulate a stress on the CPU. Your Task Write a program in Python that will send n concurrent requests to calculate the nth Fibonacci number using recurs...
import multiprocessing import time from datetime import datetime import psutil def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) def run_fibonacci(n): fibonacci(n) def monitor_cpu_usage(duration): usage = [] start_time = time.time() while time....
import pytest from solution import fibonacci, run_fibonacci, monitor_cpu_usage, run_processes def test_fibonacci(): assert fibonacci(0) == 0 assert fibonacci(1) == 1 assert fibonacci(2) == 1 assert fibonacci(3) == 2 assert fibonacci(10) == 55 def test_run_fibonacci(): assert run_fibona...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def run_fibonacci(n):", "function_name": "run_fibonacci", "parameter_list": "(n)" }, { "docstring": nul...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\nimport time\nfrom datetime import datetime\nimport psutil\n\ndef fibonacci(n):\n if n <= 1:\n return n\n else:\n return fibonacci(n-1) + fibonacci(n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004766", "row_id": 4766, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14539']" }
0.555561
Filter_4766
I
[ "fibonacci", "run_fibonacci", "monitor_cpu_usage", "run_processes", "main" ]
5
[ [ "run_fibonacci", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[ "psutil" ]
false
2942053ff4062d2582d44da459aca279fe6bff2d
d95a5eb605318b852db7c90a1b6804270f97c8f6
v1.0
instruct
Filter
Filter_4768_I
import random def generate_password(length): chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!" if length < 8: print("Password length should be at least 8 characters.") return None password = ''.join(random.choice(chars) for _ in range(length)) retu...
import random def generate_password(length): """ Generates a random password of a given length. The password consists of digits, lowercase, uppercase letters, and special characters. """ chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!" if length < 8: print(...
from solution import generate_password, generate_unique_passwords def test_generate_password_length(): password = generate_password(10) assert len(password) == 10 def test_generate_password_minimum_length(): password = generate_password(8) assert len(password) == 8 def test_generate_password_characte...
[ { "docstring": "Generates a random password of a given length.\nThe password consists of digits, lowercase, uppercase letters, and special characters.", "function_declaration": "def generate_password(length):", "function_name": "generate_password", "parameter_list": "(length)" }, { "docstrin...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef generate_password(length):\n \"\"\"\n Generate a random password of the specified length.\n Args:\n - length (int): The length of the password.\n \n Retu...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004768", "row_id": 4768, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14543']" }
0.700116
Filter_4768
I
[ "generate_password", "generate_unique_passwords" ]
2
[ [ "generate_unique_passwords", "generate_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0a0f61bd48fc73ea603cfbda4bdd3957c29dfa6b
974dd254a7428d0af21e9c17385b56302cd5b144
v1.0
instruct
Filter
Filter_4803_I
An adventure module has been created for the popular open-world fantasy role-playing game. The designers want to generate graphics for various objects in the game, but they need to know the object's position and orientation within a 3D space. They have a few standard objects, and they need to rotate and translate these...
import numpy as np def quaternion_rotation(quaternion, vector): """ Rotates a vector using a quaternion. Parameters: quaternion : list or np.array (size: 4) The quaternion used for rotation (w, x, y, z). vector : list or np.array (size: 3) The vector to be rotated. Returns: ...
def test_quaternion_rotation_90_degrees(): vector = [1, 0, 0] quaternion = [np.cos(np.pi / 4), 0, 0, np.sin(np.pi / 4)] # 90 degrees rotation around Z axis rotated_vector = quaternion_rotation(quaternion, vector) expected_vector = [0, 1, 0] assert np.allclose(rotated_vector, expected_vector, atol=1...
[ { "docstring": "Rotates a vector using a quaternion.\n\nParameters:\nquaternion : list or np.array (size: 4)\n The quaternion used for rotation (w, x, y, z).\nvector : list or np.array (size: 3)\n The vector to be rotated.\n\nReturns:\nnp.array\n The rotated vector.", "function_declaration": "def q...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef quaternion_rotation(quaternion, vector):\n \"\"\"\n Rotates a vector using a quaternion.\n\n Parameters:\n quaternion : list or np.array (size: 4)\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004803", "row_id": 4803, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14672']" }
0.339744
Filter_4803
I
[ "quaternion_rotation", "quaternion_mult", "translate" ]
3
[ [ "quaternion_rotation", "quaternion_mult" ] ]
1
[]
false
[]
false
pytest
false
[ "numpy" ]
false
dd7a0fd112a8c0d72eb64148dc509d1e022258c8
93cdb632ef7659c9e1f906f125345cdb7bc430db
v1.0
instruct
Filter
Filter_4812_I
In the game of Hangman, a player guesses the word by predicting letters. For each incorrect prediction, a part of a picture of a hangman's gallows is drawn. The game continues until the word is guessed or the gallows is complete and the player who is guessing the word is hanged. In this problem, each letter of the orig...
def isBadChar(A1, A2): """ Returns True if characters A1 and A2 are different, otherwise False. """ return A1 != A2 def isBadWord(S1, S2): """ Returns True if two strings S1 and S2 are different, otherwise False. """ if len(S1) != len(S2): return True for i in range(len(S1))...
from solution import isBadChar, isBadWord def test_isBadChar(): assert isBadChar('a', 'b') == True assert isBadChar('a', 'a') == False assert isBadChar('A', 'a') == True assert isBadChar('Z', 'Z') == False def test_isBadWord(): assert isBadWord(['h', 'e', 'l', 'l', 'o'], ['h', 'e', 'l', 'l', 'o'])...
[ { "docstring": "Returns True if characters A1 and A2 are different, otherwise False.", "function_declaration": "def isBadChar(A1, A2):", "function_name": "isBadChar", "parameter_list": "(A1, A2)" }, { "docstring": "Returns True if two strings S1 and S2 are different, otherwise False.", "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def isBadChar(A1, A2):\n \"\"\"\n Returns true if A1 is not equal to A2, otherwise returns false.\n \"\"\"\n return A1 != A2\n\ndef isBadWord(S1, S2):\n \"\"\"\n Returns true...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004812", "row_id": 4812, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14710']" }
0.594008
Filter_4812
I
[ "isBadChar", "isBadWord" ]
2
[ [ "isBadWord", "isBadChar" ] ]
1
[]
false
[]
false
pytest
true
[]
true
48f402a1c695ec58f568942ab8c9dd4d83743993
2b51420e4a55f8f84d5994ca4e70cbb0d7b01e32
v1.0
instruct
Filter
Filter_4813_I
This code solves a dynamic programming problem. **Just copy and paste the following code verbatim.** ```python def solve(l, ans): n = len(l) previous_best = cartesian_product(n, ans) for i in range(1, n): for j in range(i): a = previous_best[(i - 1, j)] b = previous_best[(i ...
def cartesian_product(n, ans, l): dp_dict = {} keys = [(i, j) for i in range(n) for j in range(n)] # Generate (0,0) to (n-1, n-1) for k in keys: if k[1] < len(l) and k[0] == k[1]: dp_dict[k] = l[k[1]] # Initialization with l values when k[0] and k[1] are the same and j is less than th...
from solution import cartesian_product, solve def test_cartesian_product(): l = [1, 2, 3] ans = [1, 2, 3] n = len(l) expected_output = { (0, 0): 1, (0, 1): float('-inf'), (0, 2): float('-inf'), (1, 0): float('-inf'), (1, 1): 2, (1, 2): float('-inf'), (2, 0): float('-inf'), (2, 1...
[ { "docstring": null, "function_declaration": "def cartesian_product(n, ans, l):", "function_name": "cartesian_product", "parameter_list": "(n, ans, l)" }, { "docstring": null, "function_declaration": "def solve(l, ans):", "function_name": "solve", "parameter_list": "(l, ans)" }...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def cartesian_product(n, ans, l):\n dp_dict = {}\n keys = [(i, j) for i in range(n) for j in range(n)]\n for k in keys:\n if k[0] == k[1] and k[1] < len(l):\n dp_dic...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004813", "row_id": 4813, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14712']" }
0.58382
Filter_4813
I
[ "cartesian_product", "solve" ]
2
[ [ "solve", "cartesian_product" ] ]
1
[]
false
[]
false
pytest
true
[]
true
28b2ee9a520df5297ee5d00f1ecf4fe5e5938e73
be8c9c9ebb5a559b7d623d970840f77a97c9bf2e
v1.0
instruct
Filter
Filter_4839_I
import heapq import random def rselect(A, k): if len(A) == 1: return A[0] mid = len(A)//2 pivot = random.choice(A) left = [x for x in A if x<pivot ] middle = [x for x in A if x == pivot] right = [x for x in A if x > pivot] if k <= len(left): return rselect(left, k) elif...
import random def partition(arr, low, high): """ This function partitions the array and returns the index of the pivot """ pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[h...
from solution import find_kth_smallest def test_kth_smallest(): assert find_kth_smallest([12, 4, 5, 6, 8, 10, 2, 1], 3) == 4 assert find_kth_smallest([12, 4, 5, 6, 8, 10, 2, 1], 1) == 1 assert find_kth_smallest([1, 2, 3, 4, 5, 6, 7, 8], 5) == 5 assert find_kth_smallest([8, 7, 6, 5, 4, 3, 2, 1], 6) == 6...
[ { "docstring": "This function partitions the array and returns the index of the pivot", "function_declaration": "def partition(arr, low, high):", "function_name": "partition", "parameter_list": "(arr, low, high)" }, { "docstring": "This function selects a random pivot element and partitions ...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef partition(A, low, high):\n pivot = A[high]\n i = low\n for j in range(low, high):\n if A[j] < pivot:\n A[i], A[j] = A[j], A[i]\n i +=...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004839", "row_id": 4839, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14814']" }
0.697934
Filter_4839
I
[ "partition", "randomized_partition", "rselect", "find_kth_smallest" ]
4
[ [ "find_kth_smallest", "rselect" ], [ "randomized_partition", "partition" ], [ "rselect", "randomized_partition" ] ]
3
[]
false
[]
false
pytest
true
[]
true
88f770402a0e4200b332983165b2c5a1dd6deedd
ac228375c3aec4784109c6f429778e0b1c822939
v1.0
instruct
Filter
Filter_4870_I
import math def get_normal(): a = int(input("Enter the real coefficient a: ")) b = int(input("Enter the imaginary coefficient b: ")) coefficient = complex(a, b) magnitude = math.sqrt(coefficient.real **2 + coefficient.imag**2 ) return coefficient, magnitude def clickCompute(): coefficient ,...
import math def compute_magnitude(coefficient): """ Computes the magnitude of a complex number. Args: coefficient (complex): A complex number. Returns: float: The magnitude of the complex number. """ return math.sqrt(coefficient.real ** 2 + coefficient.imag ** 2) def get_norm...
from solution import compute_magnitude, get_normal, clickCompute def test_compute_magnitude(): assert compute_magnitude(complex(3, 4)) == 5.0 assert compute_magnitude(complex(0, 0)) == 0.0 assert compute_magnitude(complex(1, 1)) == math.sqrt(2) assert compute_magnitude(complex(5, 12)) == 13.0 def test...
[ { "docstring": "Computes the magnitude of a complex number.\n\nArgs:\ncoefficient (complex): A complex number.\n\nReturns:\nfloat: The magnitude of the complex number.", "function_declaration": "def compute_magnitude(coefficient):", "function_name": "compute_magnitude", "parameter_list": "(coefficie...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef get_normal(a, b):\n \"\"\"\n Takes real and imaginary coefficients 'a' and 'b', and returns the complex number \n and its magnitude.\n \n Args:\n - a (int)...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004870", "row_id": 4870, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_14915']" }
0.435071
Filter_4870
I
[ "compute_magnitude", "get_normal", "clickCompute" ]
3
[ [ "clickCompute", "get_normal" ], [ "get_normal", "compute_magnitude" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4903ab895194866f10c9f2b8e8405771a5860b49
fffb2c38b00f13d0641d1b6e089e4c0767424b4e
v1.0
instruct
Filter
Filter_4907_I
import random import time def generate_random_list(length): """ Generate random list of integers of specified length """ return [random.randint(-1000000, 1000000) for _ in range(length)] def insertion_sort(nums): """ Sort list of numbers using Insertion Sort algorithm """ for i in range(len(nums)): ...
import random import timeit import matplotlib.pyplot as plt def generate_random_list(length, seed=None): """Generate random list of integers of specified length.""" if seed is not None: random.seed(seed) return [random.randint(-1000000, 1000000) for _ in range(length)] def insertion_sort(nums): ...
import pytest from solution import generate_random_list, insertion_sort, bubble_sort, python_sort def test_generate_random_list(): lst = generate_random_list(10, seed=42) assert len(lst) == 10 assert all(isinstance(x, int) for x in lst) def test_insertion_sort(): assert insertion_sort([3, 2, 1]) == [1...
[ { "docstring": "Generate random list of integers of specified length.", "function_declaration": "def generate_random_list(length, seed=None):", "function_name": "generate_random_list", "parameter_list": "(length, seed=None)" }, { "docstring": "Sort list of numbers using Insertion Sort algori...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport timeit\nimport matplotlib.pyplot as plt\n\ndef generate_random_list(length):\n \"\"\" Generate random list of integers of specified length \"\"\"\n return [random.r...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004907", "row_id": 4907, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15074']" }
0.659532
Filter_4907
I
[ "generate_random_list", "insertion_sort", "bubble_sort", "python_sort", "measure_sorting_time", "plot_data", "main" ]
7
[ [ "measure_sorting_time", "generate_random_list" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
f9c3bec91bab403b3a55e82a008a8194fa4f6bbb
b556d105f51856fc7811a2d22d964ca42723053f
v1.0
instruct
Filter
Filter_4914_I
import random def holland_newton() -> None: x = random.uniform(0, 2) eps = 1e-9 f_x = x ** 2 - 2 while abs(f_x) >= eps: f_dx = 2 * x if f_dx == 0: break x = x - f_x / f_dx f_x = x ** 2 - 2 return x print(holland_newton()) Here's a code that attempts to ...
import random def newton_sqrt(n) -> float: """ Uses Newton's method to find the square root of a given number n. """ if n < 0: raise ValueError("Cannot compute square root of a negative number.") if n == 0: return 0 x = random.uniform(0, n) eps = 1e-9 f_x = x ** 2 - n ...
from solution import newton_sqrt, sqrt_consecutive_integers def test_newton_sqrt(): assert abs(newton_sqrt(2) - 2**0.5) < 1e-9 assert abs(newton_sqrt(4) - 2) < 1e-9 assert abs(newton_sqrt(9) - 3) < 1e-9 assert abs(newton_sqrt(0)) < 1e-9 def test_newton_sqrt_negative_number(): try: newton_s...
[ { "docstring": "Uses Newton's method to find the square root of a given number n.", "function_declaration": "def newton_sqrt(n):", "function_name": "newton_sqrt", "parameter_list": "(n)" }, { "docstring": "Uses Newton's method to find the square roots of consecutive integers from start to en...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef holland_newton(n: int) -> float:\n \"\"\"\n Uses Newton's method to find the square root of an integer n.\n \"\"\"\n x = random.uniform(0, n)\n eps = 1e-9\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004914", "row_id": 4914, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15117']" }
0.526813
Filter_4914
I
[ "newton_sqrt", "sqrt_consecutive_integers" ]
2
[ [ "sqrt_consecutive_integers", "newton_sqrt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
815dfc14d7e5969dbb88008e439da50bb01e40b8
77384f1560e54170b39746beffec15f9bcca0fff
v1.0
instruct
Filter
Filter_4948_I
create a terminal-based game for rock-paper-scissors. Input will have to user to choose either rock, paper or scissors. The choices will be validated to see if they are one of the three allowed. Game wins decided by - Rock beats scissors - Scissors beats paper - Paper beats Rock Use a while loop to keep the game g...
import random def get_computer_choice(): """Randomly select either rock, paper, or scissors for the computer.""" choices = ["rock", "paper", "scissors"] return random.choice(choices) def determine_winner(user_choice, computer_choice): """Determine the winner based on user and computer choices.""" ...
def test_get_computer_choice(): choices = ["rock", "paper", "scissors"] for _ in range(10): assert get_computer_choice() in choices def test_determine_winner(): assert determine_winner("rock", "scissors") == "user" assert determine_winner("scissors", "paper") == "user" assert determine_winn...
[ { "docstring": "Randomly select either rock, paper, or scissors for the computer.", "function_declaration": "def get_computer_choice():", "function_name": "get_computer_choice", "parameter_list": "()" }, { "docstring": "Determine the winner based on user and computer choices.", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Function to get a random choice for computer from rock, paper, scissors.\n \"\"\"\n return random.choice(['rock', 'paper', 's...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004948", "row_id": 4948, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15236']" }
0.548066
Filter_4948
I
[ "get_computer_choice", "determine_winner", "validate_choice", "rock_paper_scissors_game" ]
4
[ [ "rock_paper_scissors_game", "determine_winner" ], [ "rock_paper_scissors_game", "get_computer_choice" ], [ "rock_paper_scissors_game", "validate_choice" ] ]
3
[]
false
[]
false
pytest
false
[]
true
7b3f9d2ba2b4611c1c0805b61d352dee2aae83ef
e208c4d0b7bb4b27df34a4f7f6f2280276876747
v1.0
instruct
Filter
Filter_4951_I
def find_index(arr, target, dict_of_indices): if target in dict_of_indices: return dict_of_indices[target] return None def binary_search(arr, target): dict_of_indices = {} for i, num in enumerate(arr): dict_of_indices[num] = i return find_index(arr, target, dict_of_indices) def mai...
def find_index(arr, target, dict_of_indices): """ Finds the index of the target in the array using the precomputed dictionary of indices. Returns the index if found, otherwise returns None. """ if target in dict_of_indices: return dict_of_indices[target] return None def binary_search(ar...
from solution import binary_search, find_index def test_find_index_existing_element(): arr = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] dict_of_indices = {num: i for i, num in enumerate(arr)} assert find_index(arr, 23, dict_of_indices) == 5 def test_find_index_non_existing_element(): arr = [2, 5, 8, 12, 16...
[ { "docstring": "Finds the index of the target in the array using the precomputed dictionary of indices.\nReturns the index if found, otherwise returns None.", "function_declaration": "def find_index(arr, target, dict_of_indices):", "function_name": "find_index", "parameter_list": "(arr, target, dict...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_index(arr, target, dict_of_indices):\n \"\"\"\n Finds the index of the target in the array using the precomputed dictionary of indices.\n Returns the index if found, otherwis...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004951", "row_id": 4951, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15251']" }
0.63648
Filter_4951
I
[ "find_index", "binary_search" ]
2
[ [ "binary_search", "find_index" ] ]
1
[]
false
[]
false
pytest
true
[]
true
37be03e67ebc4b5c74a04748eaf10f80c0c5bc34
99cb1975cf69e2d1ec3ba45a1aeb2ac71ab1660f
v1.0
instruct
Filter
Filter_4964_I
### A program in Python with Flask Web Application with routing, returning images Here I am creating simple RESTful API to retrieve an image. I am using Flask, a popular web framework in python for build application. Routing for retrieving an image from static folder is implemented. Every image that is being returned w...
from flask import Flask, send_file, request import os app = Flask(__name__) # Define image endpoint @app.route('/image', methods=['GET']) @app.route('/image/<path:path>', methods=['GET']) def get_image(path=None): if path is None: return 'No image with that path', 400 image_path = f'static/{path}' ...
import pytest from solution import get_MIME def test_get_MIME_jpg(): assert get_MIME('example.jpg') == 'image/jpeg' def test_get_MIME_jpeg(): assert get_MIME('example.jpeg') == 'image/jpeg' def test_get_MIME_png(): assert get_MIME('example.png') == 'image/png' def test_get_MIME_gif(): assert get_MIM...
[ { "docstring": null, "function_declaration": "def get_image(path=None):", "function_name": "get_image", "parameter_list": "(path=None)" }, { "docstring": null, "function_declaration": "def get_MIME(image_path):", "function_name": "get_MIME", "parameter_list": "(image_path)" } ]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, send_file\nimport os\n\napp = Flask(__name__)\n\n# Define image endpoint\n@app.route('/image', methods=['GET'])\n@app.route('/image/<path:path>', methods=['GET'])\ndef...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004964", "row_id": 4964, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15299']" }
0.562545
Filter_4964
I
[ "get_image", "get_MIME" ]
2
[ [ "get_image", "get_MIME" ] ]
1
[]
false
[]
false
pytest
true
[ "flask" ]
false
552d6b9be081b22265a9d2354b5f6171fec64365
90192d45490540a1313bf5b7e955e3a1a956aee5
v1.0
instruct
Filter
Filter_4976_I
I have two file objects, p_oisLive and p_oisLive_c. They are arrays of pointers in two of the same conforming dimensions (the first dimension is the same), but differ in their second dimension size, and hence overall length as well. For instance: - p_oisLive: "4x4" - p_oisLive_c: "4x3". You see that the first dimension...
def map_indices(dim1, dim2): """ Maps out all the indices for a 2D array given its dimensions. """ output = [] for i in range(dim1): indices = [] for j in range(dim2): indices.append(i * dim2 + j) output.append(f'i: {i} | j = {", ".join(map(str, indices))}') r...
from solution import map_indices, print_mapped_indices def test_map_indices(): assert map_indices(4, 4) == [ 'i: 0 | j = 0, 1, 2, 3', 'i: 1 | j = 4, 5, 6, 7', 'i: 2 | j = 8, 9, 10, 11', 'i: 3 | j = 12, 13, 14, 15' ] assert map_indices(4, 3) == [ 'i: 0 | j = 0, 1, 2',...
[ { "docstring": "Maps out all the indices for a 2D array given its dimensions.", "function_declaration": "def map_indices(dim1, dim2):", "function_name": "map_indices", "parameter_list": "(dim1, dim2)" }, { "docstring": "Prints out the mapped indices based on the dimensions provided", "fu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def map_indices(dimension1, dimension2):\n \"\"\"\n Maps the indices for 2D arrays with the given dimensions.\n \n Parameters:\n - dimension1: int, size of the first dimension.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004976", "row_id": 4976, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15344']" }
0.42272
Filter_4976
I
[ "map_indices", "print_mapped_indices" ]
2
[ [ "print_mapped_indices", "map_indices" ] ]
1
[]
false
[]
false
pytest
true
[]
true
137e174ecb2dcfbcdd3cfa4e18786a56441d76e0
96b3d0158ace6106c60e9ab2a06d04ec95d0fbba
v1.0
instruct
Filter
Filter_4981_I
def aggregate(scores, size): aggregated_scores = [] for score in scores: aggregated_score = 0 for part in score: aggregated_score += part aggregated_scores.append(aggregated_score / len(score)) return aggregated_scores def calculate_weighted_score(scores, thresholds): ...
def aggregate(scores, size): """ Computes the average of each sublist in scores. Args: scores: A list of lists where each inner list contains numerical scores. size: An integer (not used in computation). Returns: A list containing the average score of each sublist in scores. """ ...
from solution import aggregate, calculate_weighted_score, evaluate_community_enrichment def test_aggregate(): assert aggregate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [2.0, 5.0, 8.0] assert aggregate([[10, 10], [20, 20], [30, 30]], 2) == [10.0, 20.0, 30.0] assert aggregate([[1]], 1) == [1.0] assert ag...
[ { "docstring": "Computes the average of each sublist in scores.\n\nArgs:\nscores: A list of lists where each inner list contains numerical scores.\nsize: An integer (not used in computation).\n\nReturns:\nA list containing the average score of each sublist in scores.", "function_declaration": "def aggregate...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def aggregate(scores, size):\n \"\"\"\n Aggregates the scores by averaging each inner list of scores.\n\n Args:\n scores (list of lists): The scores to aggregate.\n size (int): ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004981", "row_id": 4981, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15374']" }
0.555494
Filter_4981
I
[ "aggregate", "calculate_weighted_score", "evaluate_community_enrichment" ]
3
[ [ "evaluate_community_enrichment", "aggregate" ], [ "evaluate_community_enrichment", "calculate_weighted_score" ] ]
2
[]
false
[]
false
pytest
true
[]
true
32fa9959c093d3512ad59a3e8fff0aca5774b937
8c2e0e8db46daea8911af83c8b699f7b045cb9c8
v1.0
instruct
Filter
Filter_4997_I
body_order_func_activerai: def foo(my_list): if len(my_list) < 2: return my_list else: midpoint = (len(my_list) + 1 )// 2 return binary_search(my_list[:midpoint], my_list[midpoint:]) This function aims to split a list in half and search each half for an element, but there seems to be a m...
def binary_search(left_list, right_list): """ This is a placeholder function for binary search. """ # Implementation of binary_search is not provided, this is a placeholder return left_list + right_list def foo(my_list): if len(my_list) < 2: return my_list else: midpoint = (...
from solution import foo def test_foo_single_element(): assert foo([1]) == [1] def test_foo_two_elements(): assert foo([1, 2]) == [1, 2] def test_foo_multiple_elements(): # Assuming binary search merges the two halves correctly assert foo([1, 2, 3, 4]) == [1, 2, 3, 4] def test_foo_odd_number_of_elem...
[ { "docstring": "This is a placeholder function for binary search.", "function_declaration": "def binary_search(left_list, right_list):", "function_name": "binary_search", "parameter_list": "(left_list, right_list)" }, { "docstring": null, "function_declaration": "def foo(my_list):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def foo(my_list):\n def binary_search(left, right):\n return left + right\n\n if len(my_list) < 2:\n return my_list\n else:\n midpoint = len(my_list) // 2\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004997", "row_id": 4997, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15458']" }
0.471552
Filter_4997
I
[ "binary_search", "foo" ]
2
[ [ "foo", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
993ff006a5539cef6d5874e6ab200155229c2004
014ad47f880593b0baedea91160cb3171028e197
v1.0
instruct
Filter
Filter_5018_I
import heapq import time def heapify(arr): for i in range(len(arr)//2-1, -1, -1): heapify_helper(arr, i) def heapify_helper(arr, i): smallest = i left = 2 * i + 1 right = 2 * i + 2 if left < len(arr) and arr[i] > arr[left]: smallest = left if right < len(arr) and arr[smallest...
def heapify(arr, n, i): """ Function to heapify a subtree rooted at index i. n is the size of the heap. """ largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is greater than root ...
from solution import heap_sort def test_heap_sort_unsorted_array(): assert heap_sort([4, 1, 7, 3, 8, 5]) == [1, 3, 4, 5, 7, 8] def test_heap_sort_empty_array(): assert heap_sort([]) == [] def test_heap_sort_single_element(): assert heap_sort([1]) == [1] def test_heap_sort_sorted_array(): assert heap...
[ { "docstring": "Function to heapify a subtree rooted at index i.\nn is the size of the heap.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": null, "function_declaration": "def heap_sort(arr):", "functi...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def heapify(arr):\n for i in range(len(arr)//2-1, -1, -1):\n heapify_helper(arr, i, len(arr))\n\ndef heapify_helper(arr, i, n):\n smallest = i\n left = 2 * i + 1\n right = 2...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005018", "row_id": 5018, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15534']" }
0.562051
Filter_5018
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
14e57b6d80862bf81942b03a5bb3914bd0780232
91330e08a324c81603588da06ea29c92724d0609
v1.0
instruct
Filter
Filter_5056_I
def is_prime(n): """Check if a number is prime.""" if n < 2: return False for i in range(2, n): if n % i == 0: return False return True def all_primes(n): """Generate all prime numbers up to n.""" primes = [] for i in range(2, n+1): if is_prime(i): ...
def is_prime(n): """Check if a number is prime.""" if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def all_primes(n): """Generate all prime numbers up to n.""" primes = [] for i in range(2, n+1): if is_pr...
from solution import is_prime, all_primes def test_is_prime(): assert not is_prime(0) assert not is_prime(1) assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(11) def test_all_primes(): assert all_primes(1) == [] ...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generate all prime numbers up to n.", "function_declaration": "def all_primes(n):", "function_name": "all_primes", "pa...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ret...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005056", "row_id": 5056, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15691']" }
0.829549
Filter_5056
I
[ "is_prime", "all_primes" ]
2
[ [ "all_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f167eb9d6d89cc7f82e628183c6c6d0dbe6efca1
0cd7dba3b89627af6849539adf4768c6a385d799
v1.0
instruct
Filter
Filter_5065_I
### Context In the game of Blackjack, a player is dealt two cards face up, while the dealer gets one card face up and one card face down. To play, the player submits their hand based on a score calculated using the total value of all cards in their hand. The cards 2-10 are worth their value in points, Jacks/Queens/King...
import random def deal_card(): """Deals a single card with a random face value.""" faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] return random.choice(faces) def calculate_score(hand): """Calculates the score for a given hand, considering Aces.""" score = 0 ...
from solution import deal_card, calculate_score, play_round, play_blackjack_rounds def test_deal_card(): card = deal_card() assert card in ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] def test_calculate_score_no_aces(): hand = ['2', '3', '4'] score = calculate_score(h...
[ { "docstring": "Deals a single card with a random face value.", "function_declaration": "def deal_card():", "function_name": "deal_card", "parameter_list": "()" }, { "docstring": "Calculates the score for a given hand, considering Aces.", "function_declaration": "def calculate_score(hand...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef deal_card():\n \"\"\"Deals a single card with a random face value.\"\"\"\n faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005065", "row_id": 5065, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15721']" }
0.585023
Filter_5065
I
[ "deal_card", "calculate_score", "play_round", "play_blackjack_rounds" ]
4
[ [ "play_blackjack_rounds", "play_round" ], [ "play_round", "calculate_score" ], [ "play_round", "deal_card" ] ]
3
[]
false
[]
false
pytest
true
[]
true
a709c7f299c98603cc62acd54651726bd7f265a5
84da1c66b01a046eae1bda02612451be12e93fe1
v1.0
instruct
Filter
Filter_5089_I
from collections import defaultdict def convert_config_property(config_dict, property_to_convert): converted_dict = defaultdict(dict) for server in config_dict: for device in config_dict[server]: assert device not in converted_dict[server], f"Duplicate device config in server {server}"...
from collections import defaultdict def convert_config_property(config_dict, properties_to_convert): converted_dict = defaultdict(dict) for server in config_dict: for device in config_dict[server]: assert device not in converted_dict[server], f"Duplicate device config in server {server...
from solution import convert_config_general def test_single_conversion(): config_dict = { "SERVER-01": { "NIC-INT-01": { "Type": "1Gb", "Speed": "1000 Mbps" } } } properties_to_convert = ["Type"] expected = { "SERVER-01": {...
[ { "docstring": null, "function_declaration": "def convert_config_property(config_dict, properties_to_convert):", "function_name": "convert_config_property", "parameter_list": "(config_dict, properties_to_convert)" }, { "docstring": null, "function_declaration": "def convert_config_genera...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict\n\ndef convert_config_property(config_dict, properties_to_convert):\n converted_dict = defaultdict(dict)\n \n for server in config_dict:\n f...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005089", "row_id": 5089, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15782']" }
0.481322
Filter_5089
I
[ "convert_config_property", "convert_config_general", "main" ]
3
[ [ "convert_config_general", "convert_config_property" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a85448eec68384bc789507fcb8afe44e97696f73
ba17fd0836b96a4d504f8f6795894ee51f67893f
v1.0
instruct
Filter
Filter_5097_I
import turtle import time t = turtle.Turtle() side_length = 5 def draw_square(t, side_length): for _ in range(4): t.forward(side_length) t.right(90) def draw_square_spiral(side_length, num_squares): for k in range(num_squares): draw_square(t, side_length) t.right(10) ...
import turtle def draw_square(t, side_length): """ Draws a square with the given side length using the turtle t. """ for _ in range(4): t.forward(side_length) t.right(90) def draw_square_spiral(t, side_length, num_squares): """ Draws a spiral of squares starting with the given ...
from solution import draw_square, draw_square_spiral def test_draw_square(monkeypatch): """ Test the draw_square function by capturing the turtle commands. """ commands = [] class MockTurtle: def forward(self, dist): commands.append(f"forward({dist})") def right(self, a...
[ { "docstring": "Draws a square with the given side length using the turtle t.", "function_declaration": "def draw_square(t, side_length):", "function_name": "draw_square", "parameter_list": "(t, side_length)" }, { "docstring": "Draws a spiral of squares starting with the given side length\na...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\n\ndef draw_square(t, side_length):\n \"\"\"\n Draws a square with the given side length using the turtle t.\n \"\"\"\n for _ in range(4):\n t.forward(side_len...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005097", "row_id": 5097, "seed_ids": "['Meta-Llama-3.1-70B-Instruct_15819']" }
0.665033
Filter_5097
I
[ "draw_square", "draw_square_spiral" ]
2
[ [ "draw_square_spiral", "draw_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c71ed17a93c76416648f9bcf4cca73713cd4ce05
1d9910340bb8d842d5faeaca9633d548f4ee521b
v1.0
instruct
Filter
Filter_5123_I
I have a large dataset of points in n-dimensional space, and I want to apply the k-means clustering algorithm to group similar points together. Can you provide a high-quality, readable, and well-documented code for implementing k-means clustering in Python?
import numpy as np def initialize_centroids(X, k): """ Randomly initialize the centroids by selecting k unique points from the dataset X. Parameters: X (numpy.ndarray): The dataset, shape (m, n), where m is the number of points and n is the number of dimensions. k (int): The number of clusters. ...
from solution import initialize_centroids, assign_clusters, update_centroids, kmeans import numpy as np def test_initialize_centroids(): np.random.seed(0) # For reproducibility in tests X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) centroids = initialize_centroids(X, 2) assert centroids.shape == (2, ...
[ { "docstring": "Randomly initialize the centroids by selecting k unique points from the dataset X.\n\nParameters:\nX (numpy.ndarray): The dataset, shape (m, n), where m is the number of points and n is the number of dimensions.\nk (int): The number of clusters.\n\nReturns:\nnumpy.ndarray: The initialized centro...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef k_means(X, k, max_iters=100):\n \"\"\"\n Apply K-means clustering algorithm to group similar points together.\n\n Parameters:\n X (np.array): Dataset of p...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005123", "row_id": 5123, "seed_ids": "['Llama-3.3-70B-Instruct_15869']" }
0.608074
Filter_5123
I
[ "initialize_centroids", "assign_clusters", "update_centroids", "kmeans" ]
4
[ [ "kmeans", "assign_clusters" ], [ "kmeans", "initialize_centroids" ], [ "kmeans", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
4b90c1182890217e224527f6c7d59a70c795b515
a1ff6eb353d7c3d5f36f5b2db195c5e9f39715d8
v1.0
instruct
Filter
Filter_5153_I
In this problem, you will write a simple Python script that will allow you to create, read, update and delete (CRUD) a list of books stored in a JSON file.
import json import os BOOKS_FILE = 'books.json' def load_books(): if os.path.exists(BOOKS_FILE): with open(BOOKS_FILE, 'r') as file: return json.load(file) return [] def save_books(books): with open(BOOKS_FILE, 'w') as file: json.dump(books, file) def create_book(title, autho...
import os import pytest from solution import create_book, read_books, update_book, delete_book, BOOKS_FILE @pytest.fixture(autouse=True) def run_around_tests(): # Code that will run before each test if os.path.exists(BOOKS_FILE): os.remove(BOOKS_FILE) yield # Code that will run after each test ...
[ { "docstring": null, "function_declaration": "def load_books():", "function_name": "load_books", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def save_books(books):", "function_name": "save_books", "parameter_list": "(books)" }, { "docstring": n...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport os\n\ndef load_books(file_path):\n if os.path.exists(file_path):\n with open(file_path, \"r\") as file:\n return json.load(file)\n return []\n\ndef ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005153", "row_id": 5153, "seed_ids": "['Llama-3.3-70B-Instruct_15945']" }
0.55704
Filter_5153
I
[ "load_books", "save_books", "create_book", "read_books", "update_book", "delete_book" ]
6
[ [ "create_book", "load_books" ], [ "create_book", "save_books" ], [ "delete_book", "load_books" ], [ "delete_book", "save_books" ], [ "read_books", "load_books" ], [ "update_book", "load_books" ], [ "update_book", "save_books" ] ]
7
[]
false
[]
false
pytest
true
[]
true
f769e7c0d96898479acdfa7e0533b47c5d65307c
b82ef0e6c2e5510dcf042f4307bcb9724bec939a
v1.0
instruct
Filter
Filter_5154_I
I have a Python script that takes a graph as input and returns the shortest path between two nodes. The graph is represented as an adjacency list where each key is a node and its corresponding value is another dictionary. The inner dictionary's keys are the neighboring nodes and its values are the edge weights. For e...
import sys import heapq def heuristic(node, goal): return 0 # This is my attempt to make the heuristic function return 0 for all nodes def shortest_path(graph, start, goal): queue = [] heapq.heappush(queue, (0, start)) came_from = {start: None} cost_so_far = {start: 0} while queue: _...
from solution import shortest_path def test_shortest_path_basic(): graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } assert shortest_path(graph, 'A', 'D') == ['A', 'B', 'C', 'D'] def test_shortest_path_dir...
[ { "docstring": null, "function_declaration": "def heuristic(node, goal):", "function_name": "heuristic", "parameter_list": "(node, goal)" }, { "docstring": null, "function_declaration": "def shortest_path(graph, start, goal):", "function_name": "shortest_path", "parameter_list": ...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport heapq\n\ndef heuristic(node, goal):\n \"\"\"\n Returns 0 for all nodes to ensure the algorithm behaves like Dijkstra's algorithm.\n \"\"\"\n return 0 \n\ndef sho...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005154", "row_id": 5154, "seed_ids": "['Llama-3.3-70B-Instruct_15946']" }
0.476588
Filter_5154
I
[ "heuristic", "shortest_path" ]
2
[ [ "shortest_path", "heuristic" ] ]
1
[]
false
[]
false
pytest
true
[]
true
394fe4ad8dcf6215209e21bf9295775eb3fd6c7a
03815f2323a1a6c17562ac14a743f72d3221bde2
v1.0
instruct
Filter
Filter_5173_I
Here is the code from a simple function to simulate a rock, paper, scissors game. I want to add the functionality to play the game in a best-of-three format. ```python def play_game(): while True: user_choice = input("Enter a choice (rock, paper, scissors): ").lower() while user_choice not in ["roc...
import random def play_one_round(user_choice, computer_choice): """ Plays a single round of Rock, Paper, Scissors. Returns the result of the round: "win", "lose", or "tie". """ if user_choice == computer_choice: return "tie" elif user_choice == "rock": return "win" if computer_c...
from solution import play_one_round def test_play_one_round(): # Ties assert play_one_round("rock", "rock") == "tie" assert play_one_round("paper", "paper") == "tie" assert play_one_round("scissors", "scissors") == "tie" # User wins assert play_one_round("rock", "scissors") == "win" assert...
[ { "docstring": "Plays a single round of Rock, Paper, Scissors.\nReturns the result of the round: \"win\", \"lose\", or \"tie\".", "function_declaration": "def play_one_round(user_choice, computer_choice):", "function_name": "play_one_round", "parameter_list": "(user_choice, computer_choice)" }, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef play_one_round(user_choice, computer_choice):\n \"\"\"\n Plays a single round of Rock, Paper, Scissors.\n Returns the result of the round: \"win\", \"lose\", or \...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005173", "row_id": 5173, "seed_ids": "['Llama-3.3-70B-Instruct_15994']" }
0.52045
Filter_5173
I
[ "play_one_round", "best_of_three" ]
2
[ [ "best_of_three", "play_one_round" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1610939ebbedd028c09d605028541d288787cf1f
203300444a36522c78e06bd5c75b4bdeca847d6e
v1.0
instruct
Filter
Filter_5200_I
### Overview of the Problem The company wants to set up an automated system for handling the order process for custom phone cases. The system should be able to generate a unique order number, store the customer's information, calculate the total cost of the order, and print out a receipt. ### Requirements * The syst...
import uuid class Customer: def __init__(self, name, address, phone_number, email): self.name = name self.address = address self.phone_number = phone_number self.email = email class Order: def __init__(self, customer, order_number): self.customer = customer self...
from solution import Customer, Order, Item, generate_order_number, create_customer, create_order, add_items_to_order def test_generate_order_number(): order_number = generate_order_number() assert len(order_number) == 5 assert order_number.isdigit() def test_create_customer(): customer = create_custom...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import uuid\n\nclass Customer:\n def __init__(self, name, address, phone_number, email):\n self.name = name\n self.address = address\n self.phone_number = phone_number\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005200", "row_id": 5200, "seed_ids": "['Llama-3.3-70B-Instruct_16058']" }
0.478768
Filter_5200
I
[ "generate_order_number", "create_customer", "create_order", "add_items_to_order" ]
4
[ [ "create_order", "generate_order_number" ] ]
1
[]
false
[ "Customer", "Order", "Item" ]
true
pytest
true
[]
true
7fecb2b52d24973ab23fd86b05894e6b852d7098
4a52ff7ab6dfa6bd049faf1647a07689231457e7
v1.0
instruct
Filter
Filter_5210_I
I have been given a task to create a computer program that implements a simple calculator for basic arithmetic operations such as addition, subtraction, multiplication, and division. The user should be able to input two numbers and choose the operation they want to perform. The program should be able to handle invalid ...
def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def div(x, y): if y == 0: raise ZeroDivisionError("Cannot divide by zero!") return x / y def calculate(num1, num2, operation): if operation == "+": return add(num1, num2) elif operation ==...
def test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0 assert add(0, 0) == 0 def test_sub(): assert sub(2, 3) == -1 assert sub(-1, -1) == 0 assert sub(0, 0) == 0 def test_mul(): assert mul(2, 3) == 6 assert mul(-1, 1) == -1 assert mul(0, 3) == 0 def test_div(): assert di...
[ { "docstring": null, "function_declaration": "def add(x, y):", "function_name": "add", "parameter_list": "(x, y)" }, { "docstring": null, "function_declaration": "def sub(x, y):", "function_name": "sub", "parameter_list": "(x, y)" }, { "docstring": null, "function_dec...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add(x, y):\n return x + y\n\ndef sub(x, y):\n return x - y\n\ndef mul(x, y):\n return x * y\n\ndef div(x, y):\n if y == 0:\n raise ZeroDivisionError(\"Cannot divide by z...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005210", "row_id": 5210, "seed_ids": "['Llama-3.3-70B-Instruct_16078']" }
0.603047
Filter_5210
I
[ "add", "sub", "mul", "div", "calculate" ]
5
[ [ "calculate", "add" ], [ "calculate", "div" ], [ "calculate", "mul" ], [ "calculate", "sub" ] ]
4
[]
false
[]
false
pytest
false
[]
true
30634e003a7b18f7d679d7dc519bd2d338cea772
372ebbd08340e416d96422f01f3df2d6d618b524
v1.0
instruct
Filter
Filter_5215_I
I have a python script that makes a boid within a game using the "boid" rules (separation, alignment & cohesion). There are 3 rules that each boid must follow: 1. Separation: Steer to avoid crowding local flockmates 2. Alignment: Steer towards the average heading of the local flock 3. Cohesion: Steer to move toward the...
import numpy as np class Boid: def __init__(self, position, velocity): self.position = np.array(position) self.velocity = np.array(velocity) def calculate_distance(boid1, boid2): return np.linalg.norm(boid1.position - boid2.position) def calculate_separation(boid, neighbors, radius): sepa...
import pytest from solution import Boid, calculate_separation, calculate_alignment, calculate_cohesion def test_calculate_separation(): boid = Boid([0, 0], [1, 1]) neighbors = [Boid([1, 1], [0, 1]), Boid([5, 5], [1, 1])] separation = calculate_separation(boid, neighbors, radius=2) assert separation.all...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_boid_behavior(boid, flock, radius):\n separation = [0, 0]\n alignment = [0, 0]\n cohesion = [0, 0]\n count = 0\n\n for neighbor in flock:\n distance = ((boi...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005215", "row_id": 5215, "seed_ids": "['Llama-3.3-70B-Instruct_16093']" }
0.424913
Filter_5215
I
[ "calculate_distance", "calculate_separation", "calculate_alignment", "calculate_cohesion" ]
4
[ [ "calculate_alignment", "calculate_distance" ], [ "calculate_cohesion", "calculate_distance" ], [ "calculate_separation", "calculate_distance" ] ]
3
[]
false
[ "Boid" ]
true
pytest
true
[ "numpy" ]
false
6616c8242f3d5e30e6d4d6ddc12d3c3b3babe83d
e6ca90a016649685af69fac83ab82e4ddb738afa
v1.0
instruct
Filter
Filter_5223_I
I have two binary search trees, and I want to merge them into one. I can merge these trees by appending the nodes of the second tree to the first tree in a way that maintains the BST property. Here is what I mean: Let `T1` and `T2` be two binary search trees, and let `L1` and `L2` be the lists of all the nodes in `T1`...
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def inorder_traversal(tree): if tree is None: return [] return inorder_traversal(tree.left) + [tree.val] + inorder_traversal(tree.right) def sorted_list_to_bst(nums): if not nums: ...
from solution import Node, inorder_traversal, sorted_list_to_bst, merge_trees def test_inorder_traversal(): tree = Node(2) tree.left = Node(1) tree.right = Node(3) assert inorder_traversal(tree) == [1, 2, 3] def test_sorted_list_to_bst(): sorted_list = [1, 2, 3, 4, 5, 6] bst = sorted_list_to_b...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\ndef inorder_traversal(tree):\n if tree is None:\n return []\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005223", "row_id": 5223, "seed_ids": "['Llama-3.3-70B-Instruct_16109']" }
0.462335
Filter_5223
I
[ "inorder_traversal", "sorted_list_to_bst", "merge_trees" ]
3
[ [ "merge_trees", "inorder_traversal" ], [ "merge_trees", "sorted_list_to_bst" ] ]
2
[]
false
[ "Node" ]
true
pytest
true
[]
true
d3a52f1bc13418e82ba84bbad5147cdf6d19aa06
aa4368be0e0e8a406d4e2dfa5f88561ac7bbb393
v1.0
instruct
Filter
Filter_5237_I
### Login Functionality #### Problem Statement Implement a login functionality where users can create an account, login, and logout. The user data should be stored in a SQLite database. #### Requirements * The system should have the following features: * User registration: The system should allow new users to ...
import sqlite3 import getpass import hashlib import os import secrets # Connect to SQLite database. It will be created if it doesn't exist. conn = sqlite3.connect('users.db') # Create a cursor object c = conn.cursor() # Create table if not exists with username and password hashed c.execute('''CREATE TABLE IF NOT EXI...
import sqlite3 import os import hashlib import secrets def test_register_user(): conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute('''CREATE TABLE users (username TEXT PRIMARY KEY, salt BLOB, password BLOB)''') username = 'testuser' password = 'password123' salt = secrets.token_by...
[ { "docstring": null, "function_declaration": "def register_user():", "function_name": "register_user", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def login_user():", "function_name": "login_user", "parameter_list": "()" }, { "docstring": null,...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "import sqlite3\nimport getpass\nimport hashlib\nimport os\nimport secrets\n\n# Connect to SQLite database. It will be created if it doesn't exist.\nconn = sqlite3.conn...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005237", "row_id": 5237, "seed_ids": "['Llama-3.3-70B-Instruct_16141']" }
0.67965
Filter_5237
I
[ "register_user", "login_user", "logout_user", "login_system" ]
4
[ [ "login_system", "login_user" ], [ "login_system", "logout_user" ], [ "login_system", "register_user" ] ]
3
[]
false
[]
false
pytest
false
[]
true
f6b954c95e2ff312809a94a9b73751aca4dd8d43
5e4b70b79079ab51a9e4ab60278154663bc62c70
v1.0
instruct
Filter
Filter_5267_I
I have two lists, one of names and one of emails. I want to create a dictionary where the keys are the names and the values are the corresponding emails. Here is what I have so far: ```python names = ['John', 'Emma', 'Oliver', 'Ava'] emails = ['john@example.com', 'emma@example.com', 'oliver@example.com', 'ava@example...
import re def is_valid_email(email): pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" return bool(re.match(pattern, email)) def create_valid_email_dict(names, emails): name_email_dict = {name: email for name, email in zip(names, emails) if is_valid_email(email)} return name_email_dict # ...
from solution import is_valid_email, create_valid_email_dict def test_is_valid_email(): assert is_valid_email('john@example.com') == True assert is_valid_email('john.example.com') == False assert is_valid_email('john@com') == False assert is_valid_email('john@.example.com') == False assert is_valid...
[ { "docstring": null, "function_declaration": "def is_valid_email(email):", "function_name": "is_valid_email", "parameter_list": "(email)" }, { "docstring": null, "function_declaration": "def create_valid_email_dict(names, emails):", "function_name": "create_valid_email_dict", "pa...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef is_valid_email(email):\n pattern = r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n return bool(re.match(pattern, email))\n\nnames = ['John', 'Emma', 'Oliver', '...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005267", "row_id": 5267, "seed_ids": "['Llama-3.3-70B-Instruct_16207']" }
0.575199
Filter_5267
I
[ "is_valid_email", "create_valid_email_dict" ]
2
[ [ "create_valid_email_dict", "is_valid_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9bfff54bb6811b732e765598dd286c547feb7b16
89c483be4b119f8f0116437ee5e5d1dfd4eca391
v1.0
instruct
Filter
Filter_5310_I
Here is a function `fibonacci(n)` that generates a list of Fibonacci numbers up to the nth term. ```python def fibonacci(n): fib_sequence = [0, 1] while len(fib_sequence) < n: fib_sequence.append(fib_sequence[-1] + fib_sequence[-2]) return fib_sequence ``` I would like to create another function `f...
def fibonacci_generator(): """ A generator to produce successive numbers in the Fibonacci sequence. """ a, b = 0, 1 yield a yield b while True: a, b = b, a + b yield b def fibonacci_index(num): """ Returns the index of the given Fibonacci number in the sequence. ...
from solution import fibonacci_index def test_fibonacci_index_found(): assert fibonacci_index(0) == 0 assert fibonacci_index(1) == 1 assert fibonacci_index(8) == 6 assert fibonacci_index(13) == 7 assert fibonacci_index(21) == 8 def test_fibonacci_index_not_found(): assert fibonacci_index(4) ==...
[ { "docstring": "A generator to produce successive numbers in the Fibonacci sequence.", "function_declaration": "def fibonacci_generator():", "function_name": "fibonacci_generator", "parameter_list": "()" }, { "docstring": "Returns the index of the given Fibonacci number in the sequence.\nIf ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def fibonacci_index(num):\n \"\"\"\n Returns the index of the given Fibonacci number in the Fibonacci sequence.\n \n Uses a generator to generate the Fibonacci sequence on the fly....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005310", "row_id": 5310, "seed_ids": "['Llama-3.3-70B-Instruct_16319']" }
0.629374
Filter_5310
I
[ "fibonacci_generator", "fibonacci_index" ]
2
[ [ "fibonacci_index", "fibonacci_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
991ef676928d134f611ea2cafb5a73ec18c8e332
9c8a1e2f5166570f4b42d6b05ddfea157e98ec9a
v1.0
instruct
Filter
Filter_5330_I
I have a binary tree where each node is associated with a value and two child nodes. The tree is not balanced. I need a function that will determine if the tree is a binary search tree (BST) and return the maximum and minimum values in the tree. Here is a basic binary tree implementation in Python: ```python class T...
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def is_bst_and_find_min_max(node, min_val=float('-inf'), max_val=float('inf')): if node is None: return True, floa...
from solution import TreeNode, BinaryTree, check_bst_and_get_min_max def test_empty_tree(): tree = BinaryTree() assert check_bst_and_get_min_max(tree) == (True, None, None) def test_single_node_tree(): tree = BinaryTree() tree.root = TreeNode(10) assert check_bst_and_get_min_max(tree) == (True, 10...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\nclass BinaryTree:\n def __init__(self):\n self.roo...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005330", "row_id": 5330, "seed_ids": "['Llama-3.3-70B-Instruct_16365']" }
0.601941
Filter_5330
I
[ "is_bst_and_find_min_max", "check_bst_and_get_min_max" ]
2
[ [ "check_bst_and_get_min_max", "is_bst_and_find_min_max" ] ]
1
[]
false
[ "TreeNode", "BinaryTree" ]
true
pytest
true
[]
true
20b51a6dba7d333e51b84f808f7b1d5b18e2cf12
ad06b90178951e807e6f22f17524cc38f7fc3f0b
v1.0
instruct
Filter
Filter_5353_I
Can I get an executable code for a simple "Rock, Paper, Scissors" game with user input validation?
import random def get_computer_choice(): """ Randomly return one of 'rock', 'paper', 'scissors' as the computer's choice. """ return random.choice(['rock', 'paper', 'scissors']) def determine_winner(player_choice, computer_choice): """ Determines the winner between the player and the computer....
from solution import get_computer_choice, determine_winner, validate_user_choice, play_game def test_get_computer_choice(): choices = ['rock', 'paper', 'scissors'] assert get_computer_choice() in choices def test_determine_winner(): assert determine_winner('rock', 'scissors') == 'Player wins' assert d...
[ { "docstring": "Randomly return one of 'rock', 'paper', 'scissors' as the computer's choice.", "function_declaration": "def get_computer_choice():", "function_name": "get_computer_choice", "parameter_list": "()" }, { "docstring": "Determines the winner between the player and the computer.\nR...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_user_choice():\n \"\"\"\n Prompts the user for their choice and validates the input.\n \"\"\"\n choices = ['rock', 'paper', 'scissors']\n user_choice = ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005353", "row_id": 5353, "seed_ids": "['Llama-3.3-70B-Instruct_16404']" }
0.40859
Filter_5353
I
[ "get_computer_choice", "determine_winner", "validate_user_choice", "play_game" ]
4
[ [ "play_game", "determine_winner" ], [ "play_game", "get_computer_choice" ], [ "play_game", "validate_user_choice" ] ]
3
[]
false
[]
false
pytest
true
[]
true
a3401eb492792fa43465b74d01b311f4f36b5b1f
36bb49aea74e26546cb06df344ed979ad0cdda85
v1.0
instruct
Filter
Filter_5362_I
I have a long list of English words and I want to find out which words are most similar to each other in terms of their spellings. To do this, I want to write a Python program that calculates the Levenshtein distance between all pairs of words in the list, then prints out the pairs with the smallest distances. The Le...
def levenshtein_distance(word1, word2): """ Calculate the Levenshtein distance between two words. """ m = len(word1) n = len(word2) dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j for i i...
from solution import levenshtein_distance, find_closest_word_pairs def test_levenshtein_distance(): assert levenshtein_distance("kitten", "sitting") == 3 assert levenshtein_distance("flaw", "lawn") == 2 assert levenshtein_distance("gumbo", "gambol") == 2 assert levenshtein_distance("book", "back") == 2...
[ { "docstring": "Calculate the Levenshtein distance between two words.", "function_declaration": "def levenshtein_distance(word1, word2):", "function_name": "levenshtein_distance", "parameter_list": "(word1, word2)" }, { "docstring": "Find the pairs of words with the smallest Levenshtein dist...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def levenshtein_distance(word1, word2):\n \"\"\"\n Calculate the Levenshtein distance between two words.\n \"\"\"\n m = len(word1)\n n = len(word2)\n dp = [[0 for _ in range(...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005362", "row_id": 5362, "seed_ids": "['Llama-3.3-70B-Instruct_16423']" }
0.671538
Filter_5362
I
[ "levenshtein_distance", "find_closest_word_pairs" ]
2
[ [ "find_closest_word_pairs", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d867b5aae40fbd930046c0187d89882ef008573d
cf608f72515989c61c8816368ae6c982b62d464d
v1.0
instruct
Filter
Filter_5375_I
You have been tasked with writing a program that can take in a series of points and return the closest pair of points. The points are represented as tuples of two floats, and the distance between two points is calculated using the Euclidean distance formula.
import math def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def closest_pair(points): """ Returns the closest pair of points from a list of points. Points are repr...
from solution import euclidean_distance, closest_pair def test_euclidean_distance(): assert euclidean_distance((0, 0), (0, 0)) == 0 assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5) assert math.isclose(euclidean_distance((1, 1), (4, 5)), 5) assert math.isclose(euclidean_distance((1.5, 3.5), (4...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Returns the closest pair of points from a list of points.\n...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom itertools import combinations\n\ndef euclidean_distance(p1, p2):\n \"\"\"\n Returns the Euclidean distance between two points p1 and p2.\n Each point is represented ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005375", "row_id": 5375, "seed_ids": "['Llama-3.3-70B-Instruct_16456']" }
0.665512
Filter_5375
I
[ "euclidean_distance", "closest_pair" ]
2
[ [ "closest_pair", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
92ce001c087deba4dfb75484f7dedbe9c90b10f6
4260e9500d8a91ba89c42384e381c36bb92f9599
v1.0
instruct
Filter
Filter_5384_I
I want to build a simple text-based adventure game for my kids. I'd like to use Python. What are the basic steps and components I'll need to create this game?
class Room: def __init__(self, name, description): self.name = name self.description = description self.exits = {} self.items = [] def set_exit(self, direction, room): self.exits[direction] = room def add_item(self, item): self.items.append(item) class Pla...
import pytest from solution import Room, Player, create_game, process_command def test_room_description(): room = Room("Test Room", "A test room.") assert room.description == "A test room." def test_room_exits(): room1 = Room("Room1", "First room") room2 = Room("Room2", "Second room") room1.set_ex...
[]
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "class TextAdventureGame:\n def __init__(self, player_name):\n self.player_name = player_name\n self.current_location = \"Home\"\n self.game_ove...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005384", "row_id": 5384, "seed_ids": "['Llama-3.3-70B-Instruct_16475']" }
0.383909
Filter_5384
I
[ "create_game", "process_command", "play_game" ]
3
[ [ "play_game", "create_game" ], [ "play_game", "process_command" ] ]
2
[]
false
[ "Room", "Player" ]
true
pytest
true
[]
true
9043c882c8c61846f274d711b1fede4748394b8e
2dc0af53a2c56ac2c3629951326dbd313fe3e8d3
v1.0
instruct
Filter
Filter_5409_I
### Overview of Human Language Processing Human language is complex and has many variations. It includes speech, text, and gesture. However, the core elements are words, syntax, and semantics. Words are the basic units of language and have meanings. Syntax is how words are combined into phrases and sentences. Semantics...
import random def respond_to_greeting(input_text): # List of possible responses to a greeting responses = ["Hello!", "Hi!", "Hey!", "Hi there!"] return random.choice(responses) def answer_weather_question(input_text): # List of possible responses to a weather question responses = ["The weather is ...
from solution import respond_to_greeting, answer_weather_question, provide_information, sentiment_analysis, chatbot def test_respond_to_greeting(): assert respond_to_greeting("hi") in ["Hello!", "Hi!", "Hey!", "Hi there!"] def test_answer_weather_question(): assert answer_weather_question("weather") in ["The ...
[ { "docstring": null, "function_declaration": "def respond_to_greeting(input_text):", "function_name": "respond_to_greeting", "parameter_list": "(input_text)" }, { "docstring": null, "function_declaration": "def answer_weather_question(input_text):", "function_name": "answer_weather_q...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef respond_to_greeting(input_text):\n # List of possible responses to a greeting\n responses = [\"Hello!\", \"Hi!\", \"Hey!\", \"Hi there!\"]\n return random.choice(...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005409", "row_id": 5409, "seed_ids": "['Llama-3.3-70B-Instruct_16542']" }
0.500975
Filter_5409
I
[ "respond_to_greeting", "answer_weather_question", "provide_information", "sentiment_analysis", "chatbot" ]
5
[ [ "chatbot", "answer_weather_question" ], [ "chatbot", "provide_information" ], [ "chatbot", "respond_to_greeting" ], [ "chatbot", "sentiment_analysis" ] ]
4
[]
false
[]
false
pytest
true
[]
true
dba78eda0aa791ef41a7b404dc8b97f21210587c
d9d24b858ff6344ec3ef5b01dc691a81e46c80a8
v1.0
instruct
Filter
Filter_5446_I
I have a list of numbers and I need to find the maximum value and append it to the list, then I need to repeat this process several times. My code is as follows: ``` import random def generate_list(size): return [random.randint(0, 100) for _ in range(size)] def find_max(lst): return max(lst) def append_max(l...
def generate_list(size): """ Generates a list of given size with random integers between 0 and 100. """ import random return [random.randint(0, 100) for _ in range(size)] def find_max(lst): """ Finds the maximum value in the list. Returns an integer. """ return max(lst) def append_...
from solution import generate_list, find_max, append_max, repeat_process def test_generate_list(): lst = generate_list(5) assert len(lst) == 5 assert all(isinstance(x, int) and 0 <= x <= 100 for x in lst) def test_find_max(): assert find_max([3, 1, 4, 1, 5, 9]) == 9 assert find_max([1, 2, 3, 4, 5]...
[ { "docstring": "Generates a list of given size with random integers between 0 and 100.", "function_declaration": "def generate_list(size):", "function_name": "generate_list", "parameter_list": "(size)" }, { "docstring": "Finds the maximum value in the list. Returns an integer.", "functio...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef generate_list(size):\n \"\"\"\n Generates a list of random integers between 0 and 100 of given size.\n \"\"\"\n return [random.randint(0, 100) for _ in range(s...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005446", "row_id": 5446, "seed_ids": "['Llama-3.3-70B-Instruct_16652']" }
0.610765
Filter_5446
I
[ "generate_list", "find_max", "append_max", "repeat_process" ]
4
[ [ "append_max", "find_max" ], [ "repeat_process", "append_max" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c4da341666df0523636c0b20e3d1c08cdd9599f8
59deb7a0fd769d33cb7cb4624dcdb2f73ee879b6
v1.0
instruct
Filter
Filter_5468_I
I have a question about recursion in programming. I'm trying to solve a problem where I need to generate all permutations of a given array, but with a twist: I need to avoid generating duplicate permutations. For example, if the input array is `[1, 2, 2]`, the output should be `[[1, 2, 2], [2, 1, 2], [2, 2, 1]]`, wit...
def permute_unique(nums): """ Generates all unique permutations of the input list nums. """ def backtrack(start=0): if start == len(nums): result.add(tuple(nums[:])) return for i in range(start, len(nums)): nums[start], nums[i] = nums[i], nums...
from solution import permute_unique_sorted def test_permute_unique_no_duplicates(): assert sorted(permute_unique_sorted([1, 2, 3])) == sorted([[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]) def test_permute_unique_with_duplicates(): assert sorted(permute_unique_sorted([1, 2, 2])) == sorted...
[ { "docstring": "Generates all unique permutations of the input list nums.", "function_declaration": "def permute_unique(nums):", "function_name": "permute_unique", "parameter_list": "(nums)" }, { "docstring": null, "function_declaration": "def permute_unique_sorted(nums):", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def permute_unique(nums):\n \"\"\"\n Generate all unique permutations of the given list of numbers.\n \n Args:\n nums: List[int] - The input list of numbers.\n \n Returns:...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005468", "row_id": 5468, "seed_ids": "['Llama-3.3-70B-Instruct_16694']" }
0.621189
Filter_5468
I
[ "permute_unique", "permute_unique_sorted" ]
2
[ [ "permute_unique_sorted", "permute_unique" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bffab132f130f525c5da8bb42da2086e3f963042
0424741cdb78c5daa723893f332f752bf5377e68
v1.0
instruct
Filter
Filter_5487_I
I have a problem. I have two lists, `list1` and `list2`. `list1` contains integers and `list2` contains strings. I want to create a new list of tuples, where each tuple contains a number from `list1` and a string from `list2`, such that the string is a possible word that can be formed by concatenating the digits of the...
def get_letter_combinations(number): """ Given a number, returns all possible letter combinations considering both single and double digit mappings. """ def dfs(digits): if not digits: return [""] if digits in memo: return memo[digits] res = [] ...
def test_get_letter_combinations(): assert set(get_letter_combinations(12)) == {"ab", "l"} assert set(get_letter_combinations(23)) == {"bc", "w"} assert set(get_letter_combinations(123)) == {"abc", "lc", "aw"} assert set(get_letter_combinations(10)) == {"j"} assert set(get_letter_combinations(102)) ...
[ { "docstring": "Given a number, returns all possible letter combinations considering both single and double digit mappings.", "function_declaration": "def get_letter_combinations(number):", "function_name": "get_letter_combinations", "parameter_list": "(number)" }, { "docstring": "Finds poss...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def convert_to_letter_combinations(num):\n \"\"\"Converts a number into a list of all possible string combinations using letters\"\"\"\n def helper(s):\n if not s:\n re...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005487", "row_id": 5487, "seed_ids": "['Llama-3.3-70B-Instruct_16729']" }
0.627067
Filter_5487
I
[ "get_letter_combinations", "find_possible_words" ]
2
[ [ "find_possible_words", "get_letter_combinations" ] ]
1
[]
false
[]
false
pytest
false
[]
true
0729462c2ef69a824a7ab02d939cf37966c015ad
f8983d884d1484816a95f84a8d21f566b26f3941
v1.0
instruct
Filter
Filter_5489_I
I have a countdown timer that counts from 10 to 0, and I need to trigger a function when it reaches 0. Here's my code so far: ``` import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) ...
import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 print('Time Up!!') trigger_function() def trigger_function(): """ Function to trigger when the countdown ...
from solution import countdown, trigger_function import time def test_countdown(monkeypatch): captured_output = [] def mock_time_sleep(seconds): return def mock_print(*args, **kwargs): captured_output.append(args[0]) monkeypatch.setattr(time, 'sleep', mock_time_sleep) ...
[ { "docstring": null, "function_declaration": "def countdown(t):", "function_name": "countdown", "parameter_list": "(t)" }, { "docstring": "Function to trigger when the countdown reaches 0.\nImplement required functionality here.", "function_declaration": "def trigger_function():", "f...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef countdown(t, time_up_callback):\n \"\"\"\n A function to countdown from t seconds to 0, \n with a callback function to be called when countdown reaches 0.\n \n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005489", "row_id": 5489, "seed_ids": "['Llama-3.3-70B-Instruct_16733']" }
0.491633
Filter_5489
I
[ "countdown", "trigger_function" ]
2
[ [ "countdown", "trigger_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0d713cb6175fd8ff9e1bd58ed904afe73ef29e02
fc7284b3c1522348769572cc7948637a160d8e76
v1.0
instruct
Filter
Filter_5493_I
I've been searching for a way to create a script that takes a password and a file name as input, and then uses the provided password to encrypt the file specified by the file name.
from cryptography.fernet import Fernet import base64 import os def generate_key(password): """ Generate a key based on the provided password. """ password_bytes = password.encode('utf-8') key = base64.urlsafe_b64encode(password_bytes.ljust(32)[:32]) return key def encrypt_file(password, file_n...
from solution import generate_key, encrypt_file import os def test_generate_key(): key = generate_key("my_password") assert isinstance(key, bytes) assert len(key) == 44 def test_encrypt_file(tmp_path): # Create a temporary file test_file = tmp_path / "testfile.txt" test_file.write_text("This i...
[ { "docstring": "Generate a key based on the provided password.", "function_declaration": "def generate_key(password):", "function_name": "generate_key", "parameter_list": "(password)" }, { "docstring": "Encrypt the file specified by file_name using the provided password.", "function_decl...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from cryptography.fernet import Fernet\nimport base64\nimport os\n\ndef generate_key(password):\n \"\"\"\n Generates a key based on the provided password.\n \"\"\"\n password_bytes...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005493", "row_id": 5493, "seed_ids": "['Llama-3.3-70B-Instruct_16739']" }
0.590193
Filter_5493
I
[ "generate_key", "encrypt_file" ]
2
[ [ "encrypt_file", "generate_key" ] ]
1
[]
false
[]
false
pytest
true
[ "cryptography" ]
false
59000969edb2910ffb5b4f739958e32dbb0a9c5e
855ec56ec0bbd29029278aff2e905c3fc93a25e3
v1.0
instruct
Filter
Filter_5495_I
I've been tasked with developing a set of algorithms to solve for the shortest path in a graph. I've been given the following directed graph with the edge weights: | | A | B | C | D | | --- | --- | --- | --- | --- | | A | 0 | 4 | 0 | 2 | | B | 0 | 0 | 8 | 0 | | C | 0 | 0 | 0 | 3 | | D | 0 | 0 | 0 | 0 | I need to fin...
import heapq def dijkstra(graph, start, end): """ Finds the shortest path in a directed graph from start to end using Dijkstra's algorithm. :param graph: Dictionary representation of the graph where the keys are nodes and values are lists of tuples (neighbor, weight). :param start: The starting no...
import pytest from solution import dijkstra, shortest_path_A_to_D def test_dijkstra_shortest_path(): graph = { 'A': [('B', 4), ('D', 2)], 'B': [('C', 8)], 'C': [('D', 3)], 'D': [] } cost, path = dijkstra(graph, 'A', 'D') assert cost == 2 assert path == ['A', 'D'...
[ { "docstring": "Finds the shortest path in a directed graph from start to end using Dijkstra's algorithm.\n\n:param graph: Dictionary representation of the graph where the keys are nodes and values are lists of tuples (neighbor, weight).\n:param start: The starting node.\n:param end: The ending node.\n:return: ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef dijkstra(graph, start, end):\n \"\"\"\n Finds the shortest path in a directed graph from start to end using Dijkstra's algorithm.\n \n :param graph: Dictionary ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005495", "row_id": 5495, "seed_ids": "['Llama-3.3-70B-Instruct_16741']" }
0.559977
Filter_5495
I
[ "dijkstra", "shortest_path_A_to_D" ]
2
[ [ "shortest_path_A_to_D", "dijkstra" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2586e9fbbb0bb3e6f55f2ba7f6aa723f92155225
039f2e439d9576d46c62434dacde729723e5c70b
v1.0
instruct
Filter
Filter_5522_I
I have the following tasks: 1. **Write a Python code that solves a small Sudoku puzzle using backtracking**. 2. **Do not use any external libraries**, only built-in Python features. 3. **Ensure the code is readable and maintainable**. 4. **Test the code with a simple puzzle**. Here is the puzzle I will use for testing...
def is_valid(board, row, col, num): """ Check if it's valid to place `num` in the given position on the board. """ # Check the row for i in range(9): if board[row][i] == num: return False # Check the column for i in range(9): if board[i][col] == num: ...
from solution import solve_sudoku def test_sudoku_solver(): puzzle = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0...
[ { "docstring": "Check if it's valid to place `num` in the given position on the board.", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Solves the Sudoku puzzle using backtracking.", ...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if placing num on the board at (row, col) is valid.\n \"\"\"\n # Check if num is not in the current row, column and 3x3 sub-gri...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005522", "row_id": 5522, "seed_ids": "['Llama-3.3-70B-Instruct_16801']" }
0.523122
Filter_5522
I
[ "is_valid", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8836a41ab686f625adb35fa0912b1c5e26351c48
f259a9971e061fe08eee89bfa3c024e023db1904
v1.0
instruct
Filter
Filter_5528_I
You've been given a task to plot a route on a map. You'll be given an array of points (x, y), and you need to calculate the shortest path that visits each point exactly once and returns to the starting point. This is a classic Traveling Salesman Problem (TSP). Here's a sample input: ``` points = [(0, 0), (0, 2), (2, 2...
import math def calculate_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) def nearest_neighbor(points): """ Solve the Traveling Salesman Problem using the Nearest Neighbor algor...
from solution import nearest_neighbor, calculate_distance def test_calculate_distance(): assert calculate_distance((0, 0), (3, 4)) == 5.0 assert calculate_distance((1, 1), (4, 5)) == 5.0 assert calculate_distance((2, 3), (5, 7)) == math.sqrt(25) def test_nearest_neighbor_single_point(): assert nearest...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def calculate_distance(point1, point2):", "function_name": "calculate_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Solve the Traveling Salesman Problem using the Nearest Neig...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return math.sqrt((point1[0] - point2[0]) ** 2 + (p...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005528", "row_id": 5528, "seed_ids": "['Llama-3.3-70B-Instruct_16813']" }
0.586717
Filter_5528
I
[ "calculate_distance", "nearest_neighbor" ]
2
[ [ "nearest_neighbor", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
802d1b86d4994eeb14464e6266f77477623686d4
8774f258002a7342c29222be0e8ae97dd3aae2b4
v1.0
instruct
Filter
Filter_5543_I
I have a JSON string that represents a complex object, and I'd like to flatten it into a single-level dictionary. The object has the following structure: ```json { "name": "John Doe", "age": 30, "address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip...
import json def flatten_json(json_obj, parent_key='', sep='.'): """ Flatten a nested json object. Args: json_obj (dict): The input JSON object to flatten. parent_key (str): The base key string to prefix to keys. sep (str): Separator to use between parent and child keys. Returns: ...
from solution import flatten_json_str def test_flatten_simple_json(): json_str = '{"name": "John Doe", "age": 30}' expected = { "name": "John Doe", "age": 30 } assert flatten_json_str(json_str) == expected def test_flatten_nested_json(): json_str = ''' { "name": "John D...
[ { "docstring": "Flatten a nested json object.\n\nArgs:\njson_obj (dict): The input JSON object to flatten.\nparent_key (str): The base key string to prefix to keys.\nsep (str): Separator to use between parent and child keys.\n\nReturns:\ndict: A flattened dictionary.", "function_declaration": "def flatten_j...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\n\ndef flatten_json(y):\n out = {}\n\n def flatten(x, name=''):\n if type(x) is dict:\n for a in x:\n flatten(x[a], name + a + '.')\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005543", "row_id": 5543, "seed_ids": "['Llama-3.3-70B-Instruct_16845']" }
0.615047
Filter_5543
I
[ "flatten_json", "flatten_json_str" ]
2
[ [ "flatten_json_str", "flatten_json" ] ]
1
[]
false
[]
false
pytest
true
[]
true
45405b7d5f53d9a2f81bca966c34a8fc3a7d4005
c7acd786c64c0b2874dce55dab3e3c1de9e4b56e
v1.0
instruct
Filter
Filter_5545_I
In this problem, you will write a Python program to find the shortest path between two points on a grid with obstacles. The grid will be represented as a 2D list, where 0 represents an open space and 1 represents an obstacle. The start and end points will be represented as tuples of two integers, representing the row a...
from collections import deque def is_valid_move(grid, x, y): """ Check if the move is valid within the grid boundaries and not an obstacle. """ if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == 0: return True return False def shortest_path(grid, start, end): """ Fin...
from solution import shortest_path def test_shortest_path_simple(): grid = [ [0, 0, 0], [0, 1, 0], [0, 0, 0] ] assert shortest_path(grid, (0, 0), (2, 2)) == 4 def test_shortest_path_no_obstacles(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] asser...
[ { "docstring": "Check if the move is valid within the grid boundaries and not an obstacle.", "function_declaration": "def is_valid_move(grid, x, y):", "function_name": "is_valid_move", "parameter_list": "(grid, x, y)" }, { "docstring": "Finds the shortest path between start and end points on...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef shortest_path(grid, start, end):\n \"\"\"\n Returns the length of the shortest path between start and end points on the grid with obstacles.\n\n P...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005545", "row_id": 5545, "seed_ids": "['Llama-3.3-70B-Instruct_16849']" }
0.684387
Filter_5545
I
[ "is_valid_move", "shortest_path" ]
2
[ [ "shortest_path", "is_valid_move" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eed60d7cc635a4a1ab2a5eb6ed4ea826ae4c1689
8439db94d5aeb2d83ffb0bff3cf2e0bc77947a82
v1.0
instruct
Filter
Filter_5547_I
I have a CSV file that contains a ton of entries with columns 'id', 'name', 'date', and 'description'. I want to create a new column 'date_parsed' and populate it with a parsed version of the 'date' column. I want to create a new CSV that includes the new column 'date_parsed'. I have a custom function `parse_date` th...
import pandas as pd def parse_date(date_str): """ Custom function to parse a date string and return it in the desired format. """ from datetime import datetime # Assuming desired format is 'YYYY-MM-DD' try: parsed_date = datetime.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d') e...
import pandas as pd from io import StringIO import pytest from solution import parse_date, add_parsed_date_column @pytest.fixture def sample_csv(): data = """id,name,date,description 1,John Doe,12/25/2020,Sample description here 2,Jane Smith,07/04/2021,Another sample description 3,Foo Bar,invalid date,Yet another ...
[ { "docstring": "Custom function to parse a date string and return it in the desired format.", "function_declaration": "def parse_date(date_str):", "function_name": "parse_date", "parameter_list": "(date_str)" }, { "docstring": "This function reads from an input CSV, parses the 'date' column ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\n\ndef parse_date(date_str):\n \"\"\"\n Custom function to parse dates from a string representation to desired format\n \"\"\"\n # Implement the desired date pa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005547", "row_id": 5547, "seed_ids": "['Llama-3.3-70B-Instruct_16852']" }
0.554252
Filter_5547
I
[ "parse_date", "add_parsed_date_column" ]
2
[ [ "add_parsed_date_column", "parse_date" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
9c3d574c50b33891d1da83bfe13ebcb29ed5fbcd
2495acfde32594ecab322333e04beb73aab7a905
v1.0
instruct
Filter
Filter_5594_I
I have 10 friends, and I want to create a task list for each of them. Each task list should have 7 tasks, and one of the tasks should be a specific task that I want all of them to do, which is "Learn Python". Here is a sample task list for one friend: ``` Task List for John 1. Learn Python 2. Review math concepts 3. ...
def generate_task_list(name): tasks = [ "Learn Python", "Review math concepts", "Practice coding challenges", "Read a book on algorithms", "Watch tutorials on data structures", "Join online communities for programmers", "Participate in coding competitions" ...
import os def read_task_list_file(name): with open(f"{name}.txt", "r") as file: return file.readlines() def test_generate_task_list(): from solution import generate_task_list name = "TestFriend" generate_task_list(name) expected_tasks = [ "Task List for TestFriend\n", ...
[ { "docstring": null, "function_declaration": "def generate_task_list(name):", "function_name": "generate_task_list", "parameter_list": "(name)" }, { "docstring": null, "function_declaration": "def generate_task_lists_for_friends(names):", "function_name": "generate_task_lists_for_fri...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_task_list(name):\n tasks = [\n \"Learn Python\",\n \"Review math concepts\",\n \"Practice coding challenges\",\n \"Read a book on algorithms\",\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005594", "row_id": 5594, "seed_ids": "['Llama-3.3-70B-Instruct_16957']" }
0.52011
Filter_5594
I
[ "generate_task_list", "generate_task_lists_for_friends" ]
2
[ [ "generate_task_lists_for_friends", "generate_task_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fdd395607323bafa9214cee8e4141c70c89f73a8
01cbe500ab47b900a77b79e5d85abdfd970bbc24
v1.0
instruct
Filter
Filter_5600_I
So I want to create a program that has a main menu that allows the user to select an option from a list. Each option will run a different function. I'm using Python for this. Here's an idea of what I want it to look like: ``` Main Menu 1. Option 1 2. Option 2 3. Option 3 4. Exit ``` And then when you select an option,...
def main_menu(): """ Display the main menu options. """ print("Main Menu") print("1. Option 1") print("2. Option 2") print("3. Option 3") print("4. Exit") def option1(): print("You have selected option 1") def option2(): print("You have selected option 2") def option3(): p...
import pytest from io import StringIO from unittest.mock import patch from solution import main_menu, handle_choice def test_main_menu(capsys): # Capture the output of main_menu() main_menu() captured = capsys.readouterr() assert "Main Menu" in captured.out assert "1. Option 1" in captured.out ...
[ { "docstring": "Display the main menu options.", "function_declaration": "def main_menu():", "function_name": "main_menu", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def option1():", "function_name": "option1", "parameter_list": "()" }, { "doc...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def main_menu():\n print(\"Main Menu\")\n print(\"1. Option 1\")\n print(\"2. Option 2\")\n print(\"3. Option 3\")\n print(\"4. Exit\")\n\ndef option1():\n print(\"You have s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005600", "row_id": 5600, "seed_ids": "['Llama-3.3-70B-Instruct_16969']" }
0.399882
Filter_5600
I
[ "main_menu", "option1", "option2", "option3", "handle_choice", "main" ]
6
[ [ "handle_choice", "option1" ], [ "handle_choice", "option2" ], [ "handle_choice", "option3" ] ]
3
[]
false
[]
false
pytest
true
[]
true
e087c6785be3be57cd42dd41a365d7ff34e56406
f3acde86e1efbb9cde1ada8c2ace734670f2ea04
v1.0
instruct
Filter
Filter_5617_I
We are given a non-empty, connected, undirected graph, which is represented by an adjacency list. Each node of the graph is labeled with a unique positive integer. The goal is to find the path in the graph that visits each node exactly once and returns to the starting node, which is also known as a Hamiltonian cycle. H...
from itertools import permutations import sys def validate_graph(graph): if not graph: raise ValueError("The graph should not be empty.") for node, edges in graph.items(): if not edges: raise ValueError(f"Node {node} has no edges.") for dest, weight in edges.items(): ...
from solution import get_hamiltonian_cycle, validate_graph import pytest def test_validate_graph(): valid_graph = { 1: {2: 1, 3: 4}, 2: {1: 1, 3: 2}, 3: {1: 4, 2: 2} } validate_graph(valid_graph) empty_graph = {} with pytest.raises(ValueError): validate_graph(em...
[ { "docstring": null, "function_declaration": "def validate_graph(graph):", "function_name": "validate_graph", "parameter_list": "(graph)" }, { "docstring": null, "function_declaration": "def get_hamiltonian_cycle(graph, start_node):", "function_name": "get_hamiltonian_cycle", "pa...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\nimport sys\n\ndef get_hamiltonian_cycle(graph, start_node):\n \"\"\"\n Finds the Hamiltonian cycle with the minimum weight in a weighted, connected, u...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005617", "row_id": 5617, "seed_ids": "['Llama-3.3-70B-Instruct_17013']" }
0.611355
Filter_5617
I
[ "validate_graph", "get_hamiltonian_cycle" ]
2
[ [ "get_hamiltonian_cycle", "validate_graph" ] ]
1
[]
false
[]
false
pytest
true
[]
true
105213f1461dd9052cc2e2e5b27fa6b327210ef2
84cc24e641b48a788b21a480c23c587aed96d0be
v1.0
instruct
Filter
Filter_5621_I
I have a list of locations and their corresponding coordinates. Can you help me create a program that will allow me to input the coordinates and find the location. Below is a sample of the list: 1. 795 Folsom St Lat: 37.7859 Lon: -122.4061 2. 795 5th St Lat: 37.7858 Lon: -122.4060 3. 795 6th St ...
import math locations = [ {"address": "795 Folsom St", "lat": 37.7859, "lon": -122.4061}, {"address": "795 5th St", "lat": 37.7858, "lon": -122.4060}, {"address": "795 6th St", "lat": 37.7857, "lon": -122.4062}, # Add more locations as needed ] def haversine(lat1, lon1, lat2, lon2): """ Calcul...
from solution import find_closest_location def test_find_closest_location(): assert find_closest_location(37.7859, -122.4061) == "795 Folsom St" assert find_closest_location(37.7858, -122.4060) == "795 5th St" assert find_closest_location(37.7857, -122.4062) == "795 6th St"
[ { "docstring": "Calculate the great circle distance in kilometers between two points \non the earth (specified in decimal degrees)", "function_declaration": "def haversine(lat1, lon1, lat2, lon2):", "function_name": "haversine", "parameter_list": "(lat1, lon1, lat2, lon2)" }, { "docstring": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\nlocations = [\n {\"address\": \"795 Folsom St\", \"lat\": 37.7859, \"lon\": -122.4061},\n {\"address\": \"795 5th St\", \"lat\": 37.7858, \"lon\": -122.4060},\n {\"addr...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005621", "row_id": 5621, "seed_ids": "['Llama-3.3-70B-Instruct_17021']" }
0.505846
Filter_5621
I
[ "haversine", "find_closest_location" ]
2
[ [ "find_closest_location", "haversine" ] ]
1
[]
false
[]
false
pytest
true
[]
true
083cc320f9814125c19eed7cdacb5c01466c4648
33a72ae5991b3bb56188fc96336ebe9e774e0150
v1.0
instruct
Filter
Filter_5622_I
### Task 3: Pseudocode for the Algorithm Now that we have a clear understanding of the problem and the basic approach, let's create a pseudocode for the algorithm. The algorithm should: * Start with an initial solution (initial guess) * Check if the initial solution is valid (i.e., it satisfies the constraints) ...
import random import math def generate_random_solution(): # Generate a list of random numbers between -10 and 10 return [random.uniform(-10, 10) for _ in range(10)] def is_valid(solution): # Check if the sum of the squares of the numbers is less than 100 return sum(x**2 for x in solution) < 100 def i...
from solution import generate_random_solution, is_valid, is_better, perturb, optimize def test_generate_random_solution(): solution = generate_random_solution() assert len(solution) == 10 assert all(-10 <= x <= 10 for x in solution) def test_is_valid(): assert is_valid([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) ...
[ { "docstring": null, "function_declaration": "def generate_random_solution():", "function_name": "generate_random_solution", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def is_valid(solution):", "function_name": "is_valid", "parameter_list": "(solution...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport math\n\ndef generate_random_solution():\n # Generate a list of random numbers between -10 and 10\n return [random.uniform(-10, 10) for _ in range(10)]\n\ndef is_val...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005622", "row_id": 5622, "seed_ids": "['Llama-3.3-70B-Instruct_17022']" }
0.587205
Filter_5622
I
[ "generate_random_solution", "is_valid", "is_better", "perturb", "optimize" ]
5
[ [ "optimize", "is_better" ], [ "optimize", "is_valid" ], [ "optimize", "perturb" ] ]
3
[]
false
[]
false
pytest
true
[]
true
36b7dc57d2a92ee5c38017cf367be31cc429cf6e
38802719b1c8797b7f68fe9665afdc1607d50025
v1.0
instruct
Filter
Filter_5651_I
I have a list of words. I want to check whether any of the words are repeated. I also want to check if any pairs of words are anagrams of each other. Here's a list of words: "listen", "enlist", "tinsel", "inlets", "cat", "dog", "sun", "run", "runt" Can I have a Python code to accomplish the above?
def are_words_repeated(words): """ Check whether any of the words are repeated. """ return len(words) != len(set(words)) def are_anagrams(word1, word2): """ Check if two words are anagrams of each other. """ return sorted(word1) == sorted(word2) def find_anagram_pairs(words): """ ...
from solution import are_words_repeated, are_anagrams, find_anagram_pairs def test_are_words_repeated(): assert are_words_repeated(["listen", "enlist", "tinsel", "inlets", "cat", "dog", "sun", "run", "runt"]) == False assert are_words_repeated(["listen", "enlist", "tinsel", "listen", "cat", "dog", "sun", "run"...
[ { "docstring": "Check whether any of the words are repeated.", "function_declaration": "def are_words_repeated(words):", "function_name": "are_words_repeated", "parameter_list": "(words)" }, { "docstring": "Check if two words are anagrams of each other.", "function_declaration": "def are...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_repeated_and_anagrams(words_list):\n \"\"\"\n This function checks for repeated words and anagrams in the list.\n \"\"\"\n repeated_words = set()\n anagram_pairs = set(...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005651", "row_id": 5651, "seed_ids": "['Llama-3.3-70B-Instruct_17093']" }
0.601155
Filter_5651
I
[ "are_words_repeated", "are_anagrams", "find_anagram_pairs" ]
3
[ [ "find_anagram_pairs", "are_anagrams" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6dc012309cfc452e717f0abfdebd050a1a3cf05f
3c309f3daf3fba6e0e4eb3fa48f51bc0a8c8fef8
v1.0
instruct
Filter
Filter_5669_I
I have a JSON data file named `data.json` in the following format: ```json [ { "id": 1, "name": "John Doe", "age": 30 }, { "id": 2, "name": "Jane Doe", "age": 25 } ] ``` I want to write a Python script to read this file, sort the data by "age" in descending order, and then write the sort...
import json def read_json(file_path): """ Reads a JSON file and returns its content. """ try: with open(file_path, 'r') as file: data = json.load(file) return data except FileNotFoundError: raise Exception(f"The file {file_path} was not found.") except json.J...
import json from solution import read_json, write_json, sort_by_age_descending, process_json import os def test_read_json(): data = [ {"id": 1, "name": "John Doe", "age": 30}, {"id": 2, "name": "Jane Doe", "age": 25} ] test_file = 'test_data.json' with open(test_file, 'w') as file: ...
[ { "docstring": "Reads a JSON file and returns its content.", "function_declaration": "def read_json(file_path):", "function_name": "read_json", "parameter_list": "(file_path)" }, { "docstring": "Writes the given data to a JSON file.", "function_declaration": "def write_json(data, file_pa...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\n\ndef read_json(file_path):\n \"\"\"\n Reads a JSON file and returns its content.\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n data = json....
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005669", "row_id": 5669, "seed_ids": "['Llama-3.3-70B-Instruct_17127']" }
0.581518
Filter_5669
I
[ "read_json", "write_json", "sort_by_age_descending", "process_json" ]
4
[ [ "process_json", "read_json" ], [ "process_json", "sort_by_age_descending" ], [ "process_json", "write_json" ] ]
3
[]
false
[]
false
pytest
true
[]
true
b562c6bdd06dfc1cc84be6dd57a9fba15132b18d
7693c180656923f78b05857711baf57dc481a8ed
v1.0
instruct
Filter
Filter_5677_I
I have a JSON data that describes a bunch of rectangles. Each rectangle is described by a dictionary with keys 'x', 'y', 'width', and 'height'. I want to write a function that takes in a list of these rectangles and returns a new list with only the rectangles that do not overlap with any other rectangles. Here's an ex...
def is_overlap(rect1, rect2): """ Check if there is an overlap between two rectangles. """ if rect1["x"] < rect2["x"] + rect2["width"] and rect1["x"] + rect1["width"] > rect2["x"] and rect1["y"] < rect2["y"] + rect2["height"] and rect1["y"] + rect1["height"] > rect2["y"]: return True return ...
from solution import get_non_overlapping_rectangles, is_overlap def test_is_overlap(): assert is_overlap({"x": 0, "y": 0, "width": 10, "height": 10}, {"x": 5, "y": 5, "width": 5, "height": 5}) == True assert is_overlap({"x": 0, "y": 0, "width": 10, "height": 10}, {"x": 15, "y": 15, "width": 5, "height": 5}) ==...
[ { "docstring": "Check if there is an overlap between two rectangles.", "function_declaration": "def is_overlap(rect1, rect2):", "function_name": "is_overlap", "parameter_list": "(rect1, rect2)" }, { "docstring": "Returns a list of rectangles that do not overlap with any other rectangles in t...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def rectangles_overlap(r1, r2):\n \"\"\"\n Check if two rectangles overlap.\n \"\"\"\n return not (r1['x'] + r1['width'] <= r2['x'] or\n r1['x'] >= r2['x'] + r2['wid...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005677", "row_id": 5677, "seed_ids": "['Llama-3.3-70B-Instruct_17151']" }
0.515859
Filter_5677
I
[ "is_overlap", "get_non_overlapping_rectangles" ]
2
[ [ "get_non_overlapping_rectangles", "is_overlap" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a652820b797c24ffcd9dc5d4284b6bc273791ffd
b56d45a99b700f423fac72b2523d466a920bb425
v1.0
instruct
Filter
Filter_5681_I
I have a Python program that uses a list to store objects. How do I sort this list in a custom order based on multiple attributes of the objects in the list?
from functools import cmp_to_key class CustomObject: def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2 def custom_sort_key(obj1, obj2): """ Custom comparator function that sorts based on attribute1 first, then by attribute2 if attrib...
from solution import CustomObject, sort_custom_objects def test_sort_custom_objects_empty(): objects = [] sorted_objects = sort_custom_objects(objects) assert sorted_objects == [] def test_sort_custom_objects_single_element(): obj = CustomObject(1, 2) objects = [obj] sorted_objects = sort_cust...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sort_objects_by_multiple_attributes(obj_list, *attributes):\n \"\"\"\n Sorts a list of objects based on multiple attributes.\n\n Parameters:\n obj_list (list): List of objects ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005681", "row_id": 5681, "seed_ids": "['Llama-3.3-70B-Instruct_17159']" }
0.61618
Filter_5681
I
[ "custom_sort_key", "sort_custom_objects" ]
2
[ [ "sort_custom_objects", "custom_sort_key" ] ]
1
[]
false
[ "CustomObject" ]
true
pytest
true
[]
true
08a033487b5f9bdfcce6e4d35b3c041dd958dcf2
808cf99523f03fd8692f2480617c89c93209f595
v1.0
instruct
Filter
Filter_5683_I
I am trying to implement an algorithm for solving the "word chain" game. The goal is to start with a given word, and change one letter at a time to form a new word, with each new word being in a list of valid words. I'd like to find the shortest chain of words, where the only valid operations are 1. inserting a lett...
from collections import deque, defaultdict def preprocess_words(valid_words): pattern_dict = defaultdict(set) for word in valid_words: for i in range(len(word)): pattern = word[:i] + '*' + word[i+1:] pattern_dict[pattern].add(word) return pattern_dict def get_neighbors(word...
def test_word_chain_1(): valid_words = ["hot","dot","lot","log","cog"] start_word = "hot" end_word = "cog" assert word_chain(start_word, end_word, valid_words) == ["hot", "dot", "dog", "cog"] or \ word_chain(start_word, end_word, valid_words)==["hot", "lot", "log", "cog"] def test_word_chain...
[ { "docstring": null, "function_declaration": "def preprocess_words(valid_words):", "function_name": "preprocess_words", "parameter_list": "(valid_words)" }, { "docstring": null, "function_declaration": "def get_neighbors(word, pattern_dict):", "function_name": "get_neighbors", "p...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef get_neighbors(word, valid_set):\n neighbors = []\n # generate words by replacing each character\n for i in range(len(word)):\n for c in 'ab...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005683", "row_id": 5683, "seed_ids": "['Llama-3.3-70B-Instruct_17161']" }
0.541278
Filter_5683
I
[ "preprocess_words", "get_neighbors", "word_chain" ]
3
[ [ "word_chain", "get_neighbors" ], [ "word_chain", "preprocess_words" ] ]
2
[]
false
[]
false
pytest
false
[]
true
8574ea5c9393d1f7e390034c5f19b06ad4cf6724
b73b61570a9f577998aea3da47625e91e2350fff
v1.0
instruct
Filter
Filter_5691_I
In this task, you will be creating a simple text-based calculator. The calculator should be able to perform basic arithmetic operations like addition, subtraction, multiplication, and division. The program should first display a menu to the user with options to perform different operations. The user can then select an...
def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): if b == 0: return "Error: Cannot divide by zero." return a / b def calculator(): print("Select operation:") print("1. Add") print("2. Subtract") print("3. Multi...
def test_add(): assert add(3, 5) == 8 assert add(-1, 1) == 0 assert add(0, 0) == 0 def test_subtract(): assert subtract(10, 5) == 5 assert subtract(-1, -1) == 0 assert subtract(0, 5) == -5 def test_multiply(): assert multiply(4, 5) == 20 assert multiply(-1, 1) == -1 assert multiply...
[ { "docstring": null, "function_declaration": "def add(a, b):", "function_name": "add", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def subtract(a, b):", "function_name": "subtract", "parameter_list": "(a, b)" }, { "docstring": null, "fu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divid...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005691", "row_id": 5691, "seed_ids": "['Llama-3.3-70B-Instruct_17181']" }
0.543239
Filter_5691
I
[ "add", "subtract", "multiply", "divide", "calculator" ]
5
[ [ "calculator", "add" ], [ "calculator", "divide" ], [ "calculator", "multiply" ], [ "calculator", "subtract" ] ]
4
[]
false
[]
false
pytest
false
[]
true
dd37ab9221cdec650d5513bd29bce58256c8da74
51c7ff88760ad6e14b6080665c0418c96b6ae3d5
v1.0
instruct
Filter
Filter_5708_I
You've been tasked with writing a program that implements the "Guess My Number" game. The computer thinks of a random number between 1 and 100, and the user has to guess the number. After each guess, the program tells the user if their guess was higher or lower than the number the computer thought of. Here's the code...
import random def get_valid_guess(): """Get a valid guess from the user.""" while True: try: guess = int(input("Guess a number: ")) if 1 <= guess <= 100: return guess else: print("Please enter a number between 1 and 100.") exce...
import pytest from unittest.mock import patch from solution import get_valid_guess, guess_my_number, play_game def test_get_valid_guess(): with patch('builtins.input', side_effect=['abc', '150', '50']): assert get_valid_guess() == 50 with patch('builtins.input', side_effect=['-10', '75']): ass...
[ { "docstring": "Get a valid guess from the user.", "function_declaration": "def get_valid_guess():", "function_name": "get_valid_guess", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def guess_my_number():", "function_name": "guess_my_number", "parameter...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_valid_guess():\n \"\"\"Get a valid guess from the user.\"\"\"\n while True:\n try:\n guess = int(input(\"Guess a number: \"))\n if 1...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005708", "row_id": 5708, "seed_ids": "['Llama-3.3-70B-Instruct_17231']" }
0.591621
Filter_5708
I
[ "get_valid_guess", "guess_my_number", "play_game" ]
3
[ [ "guess_my_number", "get_valid_guess" ], [ "play_game", "guess_my_number" ] ]
2
[]
false
[]
false
pytest
true
[]
true
10ddf871874753b8f518b4edef23aa19803ca1f7
be58a8f14f7559fe082749d7dbf08bf8921ec6fa
v1.0
instruct
Filter
Filter_5719_I
I have a function that draws a rectangle and I want to add the functionality to make it draw a rectangle with rounded corners. How would I go about doing this?
import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch def draw_rounded_rectangle(ax, x, y, width, height, radius): """ Draws a rectangle with rounded corners on a given axis. Parameters: - ax: the axis to draw the rectangle on - x: the x-coordinate of the bottom left co...
import pytest import matplotlib.pyplot as plt from solution import draw_rounded_rectangle, create_figure_with_rounded_rectangle def test_draw_rounded_rectangle(): fig, ax = plt.subplots() draw_rounded_rectangle(ax, 1, 1, 4, 2, 0.5) # No assert needed as this is a visual test def test_create_figure_with_ro...
[ { "docstring": "Draws a rectangle with rounded corners on a given axis.\n\nParameters:\n- ax: the axis to draw the rectangle on\n- x: the x-coordinate of the bottom left corner of the rectangle\n- y: the y-coordinate of the bottom left corner of the rectangle\n- width: the width of the rectangle\n- height: the ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def draw_rectangle(canvas, x, y, width, height, radius):\n \"\"\"\n Draws a rectangle with rounded corners on the given canvas.\n \n Parameters:\n - canvas: the canvas object wh...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005719", "row_id": 5719, "seed_ids": "['Llama-3.3-70B-Instruct_17258']" }
0.474212
Filter_5719
I
[ "draw_rounded_rectangle", "create_figure_with_rounded_rectangle" ]
2
[ [ "create_figure_with_rounded_rectangle", "draw_rounded_rectangle" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
04f8efd68f6814294aa18637508c0eb74f6fa38f
c4c4fe4819a0b27336995fc0384fcc2d02142466
v1.0
instruct
Filter
Filter_5731_I
Here is the problem I'm facing: I have a Python script that is supposed to check if an object is a list and if so, perform some action on it. However, the script fails to recognize some lists, especially when the object is a list-like object but not an actual list (e.g., a NumPy array or a Pandas Series). Here's the ...
import collections.abc import numpy as np import pandas as pd def is_list(obj): """ Checks if the object is list-like. """ return isinstance(obj, (list, np.ndarray, pd.Series, collections.abc.Sequence)) and not isinstance(obj, str) def process_list(obj): if is_list(obj): # Perform some act...
import numpy as np import pandas as pd from solution import is_list, process_list def test_is_list(): assert is_list([1, 2, 3]) == True assert is_list((1, 2, 3)) == True assert is_list(np.array([1, 2, 3])) == True assert is_list(pd.Series([1, 2, 3])) == True assert is_list("string") == False as...
[ { "docstring": "Checks if the object is list-like.", "function_declaration": "def is_list(obj):", "function_name": "is_list", "parameter_list": "(obj)" }, { "docstring": null, "function_declaration": "def process_list(obj):", "function_name": "process_list", "parameter_list": "(o...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\nfrom collections.abc import Iterable\n\ndef is_list_like(obj):\n \"\"\"\n Checks if the object is list-like.\n Returns True for lists, NumPy a...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005731", "row_id": 5731, "seed_ids": "['Llama-3.3-70B-Instruct_17278']" }
0.460491
Filter_5731
I
[ "is_list", "process_list" ]
2
[ [ "process_list", "is_list" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
5ed27b92405bf67ba67c39edc443e9429f5b53cd
ebbdc910173c664c7c791602187a2688bcab0f2f
v1.0
instruct
Filter
Filter_5754_I
I would like to create a Python script to generate an invoice and I have the following template: ``` { "invoice_number": "", "date": "", "bill_to": { "name": "", "address": "", "city": "", "state": "", "zip": "", "country": "" }, "ship_to": { ...
import json from datetime import datetime def calculate_sub_total(items): """ Calculate the sub total of the items. """ return sum(item['price'] * item['quantity'] for item in items) def calculate_tax_amount(sub_total, tax_rate): """ Calculate the tax amount based on sub total and tax rate. ...
import os import json from solution import generate_invoice, calculate_sub_total, calculate_tax_amount def test_calculate_sub_total(): items = [ {"item_id": 1, "description": "item1", "price": 10.0, "quantity": 2}, {"item_id": 2, "description": "item2", "price": 5.0, "quantity": 3} ] assert...
[ { "docstring": "Calculate the sub total of the items.", "function_declaration": "def calculate_sub_total(items):", "function_name": "calculate_sub_total", "parameter_list": "(items)" }, { "docstring": "Calculate the tax amount based on sub total and tax rate.", "function_declaration": "d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nfrom datetime import datetime\n\ndef calculate_totals(items, tax_rate):\n sub_total = sum(item['price'] * item['quantity'] for item in items)\n tax_amount = sub_total * (tax...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005754", "row_id": 5754, "seed_ids": "['Llama-3.3-70B-Instruct_17338']" }
0.485525
Filter_5754
I
[ "calculate_sub_total", "calculate_tax_amount", "generate_invoice" ]
3
[ [ "generate_invoice", "calculate_sub_total" ], [ "generate_invoice", "calculate_tax_amount" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b54ff4e5fbbd078f41a17600128bb382405e7453
6484f9b15697803998cefbc108c446cf3c3c60c4
v1.0
instruct
Filter
Filter_5770_I
I have a script that monitors a website and prints out the time it takes for the page to load. I want to add an additional feature: If the page load time exceeds 5 seconds, it will send an email to me. Here is an example of what I have: ```python import time import requests def check_website(url): start_time = ...
import time import requests import smtplib from email.mime.text import MIMEText def send_email(subject, body, to_email): from_email = "your_email@example.com" password = "your_password" msg = MIMEText(body) msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email server = sm...
import time import requests from unittest.mock import patch, Mock from solution import check_website, send_email def test_send_email(): with patch('smtplib.SMTP_SSL') as mock_smtp: instance = mock_smtp.return_value send_email("Test Subject", "Test Body", "test@example.com") instance.login.a...
[ { "docstring": null, "function_declaration": "def send_email(subject, body, to_email):", "function_name": "send_email", "parameter_list": "(subject, body, to_email)" }, { "docstring": null, "function_declaration": "def check_website(url, notification_email):", "function_name": "check...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport requests\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef check_website(url, threshold=5):\n start_time = time.time()\n response = requests.get(url)\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005770", "row_id": 5770, "seed_ids": "['Llama-3.3-70B-Instruct_17371']" }
0.492619
Filter_5770
I
[ "send_email", "check_website" ]
2
[ [ "check_website", "send_email" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
5c2071a61e45f1ec0f15e1ad5fefef15300afc35
ad05cb0e7a45b4e414de9344625e922953944b5a
v1.0
instruct
Filter
Filter_5772_I
I have a collection of coins in a jar. Each time I add a coin to the jar, I record the date and the type of coin (penny, nickel, dime, quarter). The data is stored in a csv file. I want to write a script that can tell me the number of coins of each type that I have, and also the total value of the coins in the jar. H...
import csv from collections import defaultdict def read_coins(file_path): """ Reads a CSV file containing the coin data and returns a list of coin types. """ coins = [] with open(file_path, mode='r') as infile: reader = csv.reader(infile) next(reader) # Skip header row if there is ...
from solution import read_coins, count_coins, calculate_total_value, analyze_coins import tempfile import csv def test_read_coins(): with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file: writer = csv.writer(temp_file) writer.writerow(['date', 'coin_type']) writer.writerow([...
[ { "docstring": "Reads a CSV file containing the coin data and returns a list of coin types.", "function_declaration": "def read_coins(file_path):", "function_name": "read_coins", "parameter_list": "(file_path)" }, { "docstring": "Counts the number of each type of coin.", "function_declar...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\n\ndef count_coins(csv_file_path):\n \"\"\"\n Reads a CSV file containing the record of coins added to the jar\n and returns the count of each type of coin and total value....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005772", "row_id": 5772, "seed_ids": "['Llama-3.3-70B-Instruct_17375']" }
0.554383
Filter_5772
I
[ "read_coins", "count_coins", "calculate_total_value", "analyze_coins" ]
4
[ [ "analyze_coins", "calculate_total_value" ], [ "analyze_coins", "count_coins" ], [ "analyze_coins", "read_coins" ] ]
3
[]
false
[]
false
pytest
true
[]
true
9fc0231289286ee4dbe1223fb9da16b95d84af2b
505ce0f1189d56f688c7a1731e1a52e2f94bfb42
v1.0
instruct
Filter
Filter_5806_I
### Overview The goal of this assignment is to build a simple version of the classic game Hangman. The game works as follows: * The computer chooses a word from a predefined list of words. * The player tries to guess the word by suggesting letters. * For each letter that is not in the word, the computer draws a p...
import random HANGMAN_PICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O ...
from solution import getRandomWord, displayBoard def test_getRandomWord(): word_list = ['apple', 'banana', 'cherry'] word = getRandomWord(word_list) assert word in word_list def test_displayBoard(capsys): HANGMAN_PICS = [''' +---+ | | | | | | =...
[ { "docstring": null, "function_declaration": "def getRandomWord(wordList):", "function_name": "getRandomWord", "parameter_list": "(wordList)" }, { "docstring": null, "function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):", "function_name":...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005806", "row_id": 5806, "seed_ids": "['Llama-3.3-70B-Instruct_17449']" }
0.499799
Filter_5806
I
[ "getRandomWord", "displayBoard", "getGuess", "playAgain", "hangman" ]
5
[ [ "hangman", "displayBoard" ], [ "hangman", "getGuess" ], [ "hangman", "getRandomWord" ], [ "hangman", "playAgain" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7ea538ab38c5edd872741c9ff0493b2ead367435
23d5f80d5eb18f75656ab04975b14e6d2eef98ad
v1.0
instruct
Filter
Filter_5808_I
### Assignment 5: Word Scramble Game #### Overview For this assignment, you'll create a Word Scramble game using Python. The game should randomly select a word from a predefined list of words, scramble the letters, and then challenge the user to unscramble the word. #### Game Rules 1. The game should randomly select a...
import random # List of words for the game words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "ice cream", "jackfruit"] def scramble_word(word): """ Scramble the letters of the word using random.shuffle(). """ word_list = list(word) random.shuffle(word_list) ...
import pytest from solution import scramble_word def test_scramble_word(): word = "example" scrambled = scramble_word(word) assert set(scrambled) == set(word) assert scrambled != word # Highly unlikely they match def test_empty_word(): assert scramble_word("") == "" def test_single_chara...
[ { "docstring": "Scramble the letters of the word using random.shuffle().", "function_declaration": "def scramble_word(word):", "function_name": "scramble_word", "parameter_list": "(word)" }, { "docstring": "Runs the word scramble game.", "function_declaration": "def play_game():", "f...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\n# List of words for the game\nwords = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\", \"fig\", \"grape\", \"honeydew\", \"ice cream\", \"jackfruit\"]\n\ndef scra...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005808", "row_id": 5808, "seed_ids": "['Llama-3.3-70B-Instruct_17455']" }
0.665681
Filter_5808
I
[ "scramble_word", "play_game" ]
2
[ [ "play_game", "scramble_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
23e385d8dab9950da8d3f6eab052aced18b1abd0
746a358da913879cf0b9f48087f1a48f4437999a
v1.0
instruct
Filter
Filter_5815_I
I am looking for a way to dynamically generate a set of unique and random JSON data for testing purposes. I would like the data to be in the following format: ``` { "data": [ { "id": 1, "name": "John Doe", "age": 25, "address": { "street": "123 Main St", "city": "Anytown", ...
import json import random import string def generate_random_name(): first_names = ["John", "Jane", "Alex", "Emily", "Michael", "Sarah", "David", "Laura"] last_names = ["Doe", "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller"] return f"{random.choice(first_names)} {random.choice(last_names...
from solution import generate_random_name, generate_random_age, generate_random_address, generate_random_data_set import string import random def test_generate_random_name(): name = generate_random_name() assert isinstance(name, str) and len(name.split()) == 2 def test_generate_random_age(): age = generat...
[ { "docstring": null, "function_declaration": "def generate_random_name():", "function_name": "generate_random_name", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def generate_random_age():", "function_name": "generate_random_age", "parameter_list": "()"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport random\nimport string\n\ndef random_name():\n first_names = [\"John\", \"Jane\", \"Alex\", \"Emily\", \"Chris\", \"Katie\"]\n last_names = [\"Doe\", \"Smith\", \"John...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005815", "row_id": 5815, "seed_ids": "['Llama-3.3-70B-Instruct_17472']" }
0.592246
Filter_5815
I
[ "generate_random_name", "generate_random_age", "generate_random_address", "generate_random_data_entry", "generate_random_data_set" ]
5
[ [ "generate_random_data_entry", "generate_random_address" ], [ "generate_random_data_entry", "generate_random_age" ], [ "generate_random_data_entry", "generate_random_name" ], [ "generate_random_data_set", "generate_random_data_entry" ] ]
4
[]
false
[]
false
pytest
true
[]
true
c36ed95f69623c813aa70bd0352c70988e28e7f6
19d933269640383043c81b871ced116fb17c4afe
v1.0
instruct
Filter
Filter_5818_I
### Programming Challenge: # Question 1: Create a program that will take a list of numbers as input and output the sum of the squares of those numbers. # Question 2: Then, modify the program to also calculate and output the average of the squares of the input numbers.
def sum_of_squares(numbers): """ Returns the sum of the squares of the given list of numbers. """ return sum(x ** 2 for x in numbers) def average_of_squares(numbers): """ Returns the average of the squares of the given list of numbers. """ if not numbers: return 0 return sum...
from solution import sum_of_squares, average_of_squares def test_sum_of_squares_with_positive_numbers(): assert sum_of_squares([1, 2, 3, 4]) == 30 def test_sum_of_squares_with_negative_numbers(): assert sum_of_squares([-1, -2, -3, -4]) == 30 def test_sum_of_squares_with_mixed_sign_numbers(): assert sum_o...
[ { "docstring": "Returns the sum of the squares of the given list of numbers.", "function_declaration": "def sum_of_squares(numbers):", "function_name": "sum_of_squares", "parameter_list": "(numbers)" }, { "docstring": "Returns the average of the squares of the given list of numbers.", "f...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sum_of_squares(numbers):\n \"\"\"\n Returns the sum of the squares of the given list of numbers.\n \"\"\"\n return sum(x ** 2 for x in numbers)\n\ndef average_of_squares(number...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005818", "row_id": 5818, "seed_ids": "['Llama-3.3-70B-Instruct_17479']" }
0.636801
Filter_5818
I
[ "sum_of_squares", "average_of_squares" ]
2
[ [ "average_of_squares", "sum_of_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2bbabab38d5155a28e106ce5ec6347a778409fc1
f4c2a9210e0a80516c22f60238e1140a4dc792a2
v1.0
instruct
Filter
Filter_5871_I
### User Story As a user, I want to be able to create a new user account, so I can log in to the system. ### Acceptance Criteria * The system shall provide a user registration page. * The user shall be able to enter their details (name, email, password). * The system shall validate the user's input data (name, email, ...
import sqlite3 import re def initialize_db(): """ Initialize the database and create the users table. """ conn = sqlite3.connect('users.db') cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, ...
import pytest import sqlite3 from solution import initialize_db, create_new_user, login_user, validate_user_input, check_user_exists def setup_module(module): """ Setup the test module by initializing the database. """ initialize_db() conn = sqlite3.connect('users.db') cursor = conn.cursor() ...
[ { "docstring": "Initialize the database and create the users table.", "function_declaration": "def initialize_db():", "function_name": "initialize_db", "parameter_list": "()" }, { "docstring": "Validates user input.", "function_declaration": "def validate_user_input(name, email, password...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sqlite3\nfrom hashlib import sha256\n\ndef create_connection(db_file):\n \"\"\" create a database connection to a SQLite database \"\"\"\n conn = None\n try:\n conn = sq...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005871", "row_id": 5871, "seed_ids": "['Llama-3.3-70B-Instruct_17605']" }
0.505028
Filter_5871
I
[ "initialize_db", "validate_user_input", "check_user_exists", "create_new_user", "login_user" ]
5
[ [ "create_new_user", "check_user_exists" ], [ "create_new_user", "validate_user_input" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e7aba07da8556fb2de173779715bb3be554b613d
a14bd8e1e52087d04f6f2d7afba636d3d58dec38
v1.0
instruct
Filter
Filter_5880_I
In a digital image, each pixel is represented by a set of three values: red, green, and blue, which are integers in the range [0,255]. The intensity of a pixel is defined as the sum of its red, green, and blue values. Write a program that reads an image and displays the intensity value of each pixel.
from typing import List, Tuple def calculate_pixel_intensity(pixel: Tuple[int, int, int]) -> int: """ Returns the intensity of a pixel. The intensity is defined as the sum of the red, green, and blue values of the pixel. :param pixel: (red, green, blue) tuple where each value is in range [0, 255] ...
from solution import calculate_pixel_intensity, image_intensity def test_calculate_pixel_intensity(): assert calculate_pixel_intensity((255, 255, 255)) == 765 assert calculate_pixel_intensity((0, 0, 0)) == 0 assert calculate_pixel_intensity((128, 64, 32)) == 224 assert calculate_pixel_intensity((255, 0...
[ { "docstring": "Returns the intensity of a pixel.\nThe intensity is defined as the sum of the red, green, and blue values of the pixel.\n\n:param pixel: (red, green, blue) tuple where each value is in range [0, 255]\n:return: intensity value of the pixel", "function_declaration": "def calculate_pixel_intens...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_pixel_intensity(red, green, blue):\n \"\"\"\n Returns the intensity of a pixel based on its red, green, and blue values.\n The intensity is defined as the sum of the red, gree...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005880", "row_id": 5880, "seed_ids": "['Llama-3.3-70B-Instruct_17624']" }
0.477294
Filter_5880
I
[ "calculate_pixel_intensity", "image_intensity" ]
2
[ [ "image_intensity", "calculate_pixel_intensity" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d4b990e2429b9628db654a3e415fb43cc33f0336
b7af1c87a4d1afd7a428f5ca3dcaf93e4e04db39
v1.0
instruct
Filter
Filter_5894_I
You've been asked to write a function `merge_sort` that takes an array of integers as input, sorts it in ascending order using the merge sort algorithm, and returns the sorted array. The function should be able to handle arrays of any size and should be efficient. Here is a high-level action plan for implementing the...
def merge_sort(arr): """ Sorts an array of integers using the merge sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = arr[:mid] right_half = arr[mid:] left_half = merge_sort(left_half) right_half = merge_sort(right_half) return merge(left...
from solution import merge_sort def test_merge_sort_empty_array(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_already_sorted(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_order(): assert m...
[ { "docstring": "Sorts an array of integers using the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merges two sorted arrays into one sorted array.", "function_declaration": "def merge(le...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array in ascending order using the merge sort algorithm.\n \n Args:\n arr: List of integers to be sorted.\n \n Returns:\n A new...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005894", "row_id": 5894, "seed_ids": "['Llama-3.3-70B-Instruct_17646']" }
0.710287
Filter_5894
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a3e41af3d3b32b2f79be1049cf30f02489a5b456
a1f0c8a1a55847394b0598492eba362f01ddb82e
v1.0
instruct
Filter
Filter_5908_I
I've been tasked with creating a simple game in python where the player has to guess the number. The game needs to be simple, but I want to add some basic functionality to make it more interesting. To start with, I'd like to create a base game that meets the following requirements: 1. The game should ask the player f...
import random def get_player_name(): """Gets the player's name""" return input("Hello, what is your name? ") def generate_random_number(): """Generates a random number between 1 and 100""" return random.randint(1, 100) def guess_number_game(): """Main function to run the guess number game""" ...
import pytest from unittest.mock import patch from solution import guess_number_game, get_player_name, generate_random_number def test_get_player_name(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: "Alice") assert get_player_name() == "Alice" def test_generate_random_number(): num = generat...
[ { "docstring": "Gets the player's name", "function_declaration": "def get_player_name():", "function_name": "get_player_name", "parameter_list": "()" }, { "docstring": "Generates a random number between 1 and 100", "function_declaration": "def generate_random_number():", "function_na...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_player_name():\n \"\"\"Gets the player's name from standard input.\"\"\"\n name = input(\"Hello, what is your name? \")\n return name\n\ndef generate_random_n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005908", "row_id": 5908, "seed_ids": "['Llama-3.3-70B-Instruct_17678']" }
0.537434
Filter_5908
I
[ "get_player_name", "generate_random_number", "guess_number_game" ]
3
[ [ "guess_number_game", "generate_random_number" ], [ "guess_number_game", "get_player_name" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2864f5169e2f7118997ef9ddb4f027dbaa71d663
efdbc4e88e9aea1c53bd8e2e25fb5186e8d65ce6
v1.0
instruct
Filter
Filter_5909_I
I have developed a simple Sudoku game and I'm trying to add the functionality to solve the game using a backtracking algorithm. I'm having trouble figuring out how to implement the algorithm correctly. Do you have any tips or resources to help me understand and implement this?
def is_valid(board, row, col, num): """ Check if it's valid to place the num in the given position on the Sudoku board. """ # Check the row for i in range(9): if board[row][i] == num: return False # Check the column for i in range(9): if board[i][col] == num: ...
from solution import is_valid, solve_sudoku def test_is_valid(): board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, ...
[ { "docstring": "Check if it's valid to place the num in the given position on the Sudoku board.", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Solve the Sudoku using backtracking algo...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if it's safe to place `num` in the cell at `board[row][col]`.\n \"\"\"\n # Check if `num` is not in the current row or column\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005909", "row_id": 5909, "seed_ids": "['Llama-3.3-70B-Instruct_17680']" }
0.395454
Filter_5909
I
[ "is_valid", "solve_sudoku", "find_empty_position" ]
3
[ [ "solve_sudoku", "find_empty_position" ], [ "solve_sudoku", "is_valid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4659f2e3551da77068363deba8e5296b338383db
9a99114b517e9fd58848020baf755cc02b079ffb
v1.0
instruct
Filter
Filter_5913_I
I have a combination lock with 10 numbers (0-9). I forgot the combination, but I can try combinations in any order and the lock will tell me if I'm correct or not. I want to write a program to try all possible combinations to open the lock. Here are the rules: - The combination is 3 digits long. - Each digit can be a...
import itertools def try_combination(combination): """ This function should be replaced with the actual lock functionality. For testing purposes, assume a fixed combination. """ fixed_combination = "123" # Assuming the fixed combination is "123". return combination == fixed_combination def op...
from solution import try_combination, open_lock def test_try_combination_correct(): assert try_combination("123") == True def test_try_combination_incorrect(): assert try_combination("000") == False assert try_combination("999") == False assert try_combination("124") == False def test_open_lock_found...
[ { "docstring": "This function should be replaced with the actual lock functionality.\nFor testing purposes, assume a fixed combination.", "function_declaration": "def try_combination(combination):", "function_name": "try_combination", "parameter_list": "(combination)" }, { "docstring": "Trie...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef try_combination(combination):\n \"\"\"\n This function should be replaced with the actual lock functionality.\n For testing purposes, assume a fixed combinatio...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005913", "row_id": 5913, "seed_ids": "['Llama-3.3-70B-Instruct_17689']" }
0.505546
Filter_5913
I
[ "try_combination", "open_lock" ]
2
[ [ "open_lock", "try_combination" ] ]
1
[]
false
[]
false
pytest
true
[]
true
825b2e3f07128e70f662d890bd758ce3bc8746c3
a17e71793f7efb7dfa28b4dadd50b1e8ed0c99c0
v1.0
instruct
Filter
Filter_5977_I
**1305. All Elements in Two Binary Search Trees Medium In this problem, you are given the roots of two binary search trees, `root1` and `root2`, and you need to return a list containing all the elements of both trees in ascending order.
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def in_order_traversal(root): result = [] if root: result = in_order_traversal(root.left) result.append(root.val) result = result + in_order_t...
import pytest from solution import TreeNode, getAllElements def test_single_trees(): root1 = TreeNode(2, TreeNode(1), TreeNode(3)) root2 = TreeNode(7, TreeNode(6), TreeNode(8)) assert getAllElements(root1, root2) == [1, 2, 3, 6, 7, 8] def test_mixed_trees(): root1 = TreeNode(1, None, TreeNode(8)) ...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Optional\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = l...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005977", "row_id": 5977, "seed_ids": "['Llama-3.3-70B-Instruct_17845']" }
0.481504
Filter_5977
I
[ "in_order_traversal", "merge_sorted_lists", "getAllElements" ]
3
[ [ "getAllElements", "in_order_traversal" ], [ "getAllElements", "merge_sorted_lists" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
998e879552f1fe8bb3deae5070e41694b9fc1aa9
349e51e84d473b10f6c130d011cdb5665bccd2c3
v1.0
instruct
Filter
Filter_6011_I
I've been given a task to find the shortest path between two nodes in a graph. I've decided to use Dijkstra's algorithm, but I'm having trouble implementing it in Python. I want to implement Dijkstra's algorithm for a graph represented as an adjacency list, and I want to find the shortest path between two given nodes. ...
import heapq def dijkstra(graph, start, end): queue = [] heapq.heappush(queue, (0, start)) distances = {node: float('infinity') for node in graph} distances[start] = 0 shortest_path = {start: None} while queue: (dist, current_node) = heapq.heappop(queue) if current_node == end...
import pytest from solution import dijkstra def test_dijkstra_basic(): graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } start_node = 'A' end_node = 'D' distances, path = dijkstra(graph, start_node,...
[ { "docstring": null, "function_declaration": "def dijkstra(graph, start, end):", "function_name": "dijkstra", "parameter_list": "(graph, start, end)" }, { "docstring": null, "function_declaration": "def get_path(shortest_path, start, end):", "function_name": "get_path", "paramete...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef dijkstra(graph, start, end):\n queue = []\n heapq.heappush(queue, (0, start))\n distances = {node: float('infinity') for node in graph}\n distances[start] = 0\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006011", "row_id": 6011, "seed_ids": "['Llama-3.3-70B-Instruct_17921']" }
0.460072
Filter_6011
I
[ "dijkstra", "get_path" ]
2
[ [ "dijkstra", "get_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7fe8ef62f031107019a036b714837d969c1cb3c2
77a13cfc5e3e65c2b985b6689221d13cb448bc2b
v1.0
instruct
Filter
Filter_6024_I
### Project Overview This project requires you to create a Guessing Game. The Guessing Game will have the following features: 1. The computer will think of a random number between 1 and 100 (inclusive). 2. The user will be asked to guess the number. 3. After each guess, the computer will tell the user if their guess i...
import random def generate_random_number(): """Generate a random number between 1 and 100.""" return random.randint(1, 100) def get_user_guess(): """Get the user's guess.""" while True: try: guess = int(input("Guess a number between 1 and 100: ")) if 1 <= guess <= 100: ...
from solution import generate_random_number, check_guess def test_generate_random_number(): for _ in range(100): number = generate_random_number() assert 1 <= number <= 100 def test_check_guess(): # Test when guess is too low assert check_guess(50, 75) == "low" # Test when guess i...
[ { "docstring": "Generate a random number between 1 and 100.", "function_declaration": "def generate_random_number():", "function_name": "generate_random_number", "parameter_list": "()" }, { "docstring": "Get the user's guess.", "function_declaration": "def get_user_guess():", "functi...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef generate_random_number():\n \"\"\"Generate a random number between 1 and 100.\"\"\"\n return random.randint(1, 100)\n\ndef get_user_guess(input_func=input):\n \"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006024", "row_id": 6024, "seed_ids": "['Llama-3.3-70B-Instruct_17944']" }
0.592936
Filter_6024
I
[ "generate_random_number", "get_user_guess", "check_guess", "play_game", "main" ]
5
[ [ "play_game", "check_guess" ], [ "play_game", "generate_random_number" ], [ "play_game", "get_user_guess" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5da417e074e66c7feef6dac65a9fd02488accd80
6056f9437a4d548c6a1ec0d397f277ec7bd1057a
v1.0
instruct
Filter
Filter_6035_I
I am trying to write a program that generates an image of a random maze. I'm using Python and Pillow for this task. The problem is that I'm struggling to get the maze to look anything like a maze. The lines that make up the maze are not meeting at the corners, and there are gaps between them. Here's my code so far: `...
import random from PIL import Image, ImageDraw def generate_maze(num_cells_x, num_cells_y, cell_size): width = num_cells_x * cell_size height = num_cells_y * cell_size # Create a new image img = Image.new('RGB', (width, height), (255, 255, 255)) draw = ImageDraw.Draw(img) # Create a 2D list t...
from solution import generate_maze def test_maze_dimensions(): img = generate_maze(50, 50, 10) width, height = img.size assert width == 500 assert height == 500 def test_maze_wall_and_passages(): img = generate_maze(10, 10, 10) pixels = img.load() # Check for presence of black pixels (wal...
[ { "docstring": null, "function_declaration": "def generate_maze(num_cells_x, num_cells_y, cell_size):", "function_name": "generate_maze", "parameter_list": "(num_cells_x, num_cells_y, cell_size)" }, { "docstring": null, "function_declaration": "def save_maze_image(filename, num_cells_x=5...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom PIL import Image, ImageDraw\n\ndef generate_maze(num_cells_x, num_cells_y, cell_size):\n width = num_cells_x * cell_size\n height = num_cells_y * cell_size\n\n # C...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006035", "row_id": 6035, "seed_ids": "['Llama-3.3-70B-Instruct_17986']" }
0.454497
Filter_6035
I
[ "generate_maze", "save_maze_image" ]
2
[ [ "save_maze_image", "generate_maze" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
eae39d67ca40416aa96784ce1ecf18818d6909be
f90838d1d402796eadaf93dc9ad0cd2331f1dd3c
v1.0
instruct
Filter
Filter_6046_I
I have a binary tree and I need to find the diameter of the tree, which is the longest path between any two nodes in the tree. This path may or may not pass through the root. Here is my code: ``` class Node: def __init__(self, data): self.data = data self.left = None self.right = None def ...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def height_and_diameter(node): if node is None: return 0, 0 # height, diameter left_height, left_diameter = height_and_diameter(node.left) right_height, right_diameter = heigh...
from solution import Node, diameter def test_diameter_single_node(): root = Node(1) assert diameter(root) == 1 # The longest path is just the root itself def test_diameter_linear_tree(): # Tree structure: # 1 # \ # 2 # \ # 3 root = Node(1) root.right = Node...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\ndef diameter_and_height(node):\n \"\"\"\n Helper function tha...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006046", "row_id": 6046, "seed_ids": "['Llama-3.3-70B-Instruct_18005']" }
0.508308
Filter_6046
I
[ "height_and_diameter", "diameter" ]
2
[ [ "diameter", "height_and_diameter" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
82aada2e24089791487f001a4c270d6f34ddc862
36a0f7049c71fed7e969eb4b45fc6fef01922945
v1.0
instruct
Filter
Filter_6047_I
It is required to generate a random sample of 5000 valid IPv6 addresses. In computing, a valid IPv6 address is a string of 8 groups of 4 hexadecimal digits (from 0000 to ffff), separated by the colon character (:). How would you develop a Python program to do this?
import random def generate_ipv6_address(): """ Generates a single valid IPv6 address. """ return ':'.join(f'{random.randint(0, 0xffff):04x}' for _ in range(8)) def generate_ipv6_addresses(count=5000): """ Generates 'count' number of valid IPv6 addresses. """ return [generate_ipv6_addre...
from solution import generate_ipv6_address, generate_ipv6_addresses def test_generate_ipv6_address_format(): ipv6 = generate_ipv6_address() parts = ipv6.split(':') assert len(parts) == 8 for part in parts: assert len(part) == 4 assert part.isalnum() def test_generate_ipv6_addresses_cou...
[ { "docstring": "Generates a single valid IPv6 address.", "function_declaration": "def generate_ipv6_address():", "function_name": "generate_ipv6_address", "parameter_list": "()" }, { "docstring": "Generates 'count' number of valid IPv6 addresses.", "function_declaration": "def generate_i...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef generate_random_ipv6():\n \"\"\"\n Generate a single random valid IPv6 address.\n \"\"\"\n return ':'.join(f'{random.randint(0, 65535):04x}' for _ in range(8))...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006047", "row_id": 6047, "seed_ids": "['Llama-3.3-70B-Instruct_18006']" }
0.553151
Filter_6047
I
[ "generate_ipv6_address", "generate_ipv6_addresses" ]
2
[ [ "generate_ipv6_addresses", "generate_ipv6_address" ] ]
1
[]
false
[]
false
pytest
true
[]
true
282995355a6433cbb31e550708c7641f27f6dc19
e7d90b0ba54694347f702c15bd4d12f8b92f0bf5
v1.0
instruct
Filter
Filter_6053_I
Here is a list of 10 numbers: 1, 2, 3, 7, 13, 17, 19, 23, 29, 31. Can you write a program in python to generate a new list that contains all the elements from the original list and two additional numbers that are prime, between 2 and 50?
def is_prime(n): """ Returns True if the number n is a prime number, False otherwise. """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def extend_prime_list(original_list): """ Takes an original list of n...
from solution import is_prime, extend_prime_list 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 def test_extend_prime_list(): original_list = [1, 2, ...
[ { "docstring": "Returns True if the number n is a prime number, False otherwise.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Takes an original list of numbers and extends it by adding two prime \nnumbers between 2 and ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_list_with_primes(original_list):\n \"\"\"\n Returns a new list that contains all the elements from the original list and two additional numbers that are prime, between 2 and...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006053", "row_id": 6053, "seed_ids": "['Llama-3.3-70B-Instruct_18023']" }
0.54138
Filter_6053
I
[ "is_prime", "extend_prime_list" ]
2
[ [ "extend_prime_list", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a6103acd7e82c6694f707eab500433ade2716d43
681a2f9ff6a7131473dc156dd25d0b952c92367c
v1.0
instruct
Filter
Filter_6055_I
I have a user interface that requires a method to find the nearest neighbor to a given location. I want to implement this using a k-d tree data structure. Given a set of coordinates and a target coordinate, I need to write a function that builds a k-d tree and uses it to find the nearest neighbor to the target locati...
import math class KDNode: def __init__(self, point, axis, left=None, right=None): self.point = point self.axis = axis self.left = left self.right = right def build_kd_tree(points, depth=0): if not points: return None k = len(points[0]) # Dimension of the space ...
from solution import find_nearest def test_find_nearest_with_simple_case(): points = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] target = (6, 7) assert find_nearest(points, target) == (5, 6) def test_find_nearest_with_single_point(): points = [(1, 2)] target = (3, 4) assert find_nearest(points, ...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\nclass KDNode:\n def __init__(self, point, axis, left=None, right=None):\n self.point = point\n self.axis = axis\n self.left = left\n self.right = ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006055", "row_id": 6055, "seed_ids": "['Llama-3.3-70B-Instruct_18029']" }
0.712612
Filter_6055
I
[ "build_kd_tree", "distance_squared", "find_nearest_neighbor", "find_nearest" ]
4
[ [ "find_nearest", "build_kd_tree" ], [ "find_nearest", "find_nearest_neighbor" ], [ "find_nearest_neighbor", "distance_squared" ] ]
3
[]
false
[ "KDNode" ]
true
pytest
true
[]
true
063ec689bd1840edbf3cbd2a9b427071bbf1277f
2b4931b860e44e6bbc4a5055cc6d2774cba2a6c0
v1.0
instruct
Filter
Filter_6065_I
Here is the code I have so far for my quiz game: ```python import random from random import shuffle def quiz_game(): questions = { "What is the capital of France": "Paris", "What is the largest planet in our solar system": "Jupiter", "What is the largest mammal": "Blue whale", "What...
import random from random import shuffle def add_custom_questions(): custom_questions = {} while True: question = input("Enter a question (or 'done' to finish): ") if question.lower() == 'done': break answer = input("Enter the answer: ") custom_questions[question] = ...
from unittest.mock import patch from solution import quiz_game, add_custom_questions def test_add_custom_questions(): input_values = ['What is 2 + 2?', '4', 'done'] expected_output = {'What is 2 + 2?': '4'} with patch('builtins.input', side_effect=input_values): assert add_custom_questions() == exp...
[ { "docstring": null, "function_declaration": "def add_custom_questions():", "function_name": "add_custom_questions", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def quiz_game():", "function_name": "quiz_game", "parameter_list": "()" } ]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom random import shuffle\n\n\ndef input_questions():\n \"\"\"\n Allows users to input their own set of questions and answers.\n \"\"\"\n questions = {}\n while ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006065", "row_id": 6065, "seed_ids": "['Llama-3.3-70B-Instruct_18052']" }
0.395177
Filter_6065
I
[ "add_custom_questions", "quiz_game" ]
2
[ [ "quiz_game", "add_custom_questions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e491976ac77c60fb0526f5a190473169bf68ed7
b07b0042e14b2d979ad2c3d7382edb31af4ee9a9
v1.0
instruct
Filter
Filter_6071_I
Can you make a simple 2-player text-based game in Python where players take turns rolling a dice?
import random def roll_dice(): """ Simulates rolling a six-sided dice. """ return random.randint(1, 6) def play_game(): """ Initiates a 2-player dice rolling game. Players take turns to roll a dice. """ player_scores = [0, 0] current_turn = 0 winning_score = 20 while True:...
from solution import roll_dice, play_game def test_roll_dice(): for _ in range(100): result = roll_dice() assert 1 <= result <= 6, f"roll_dice produced an invalid result: {result}" # Note: Since play_game involves user input and random elements, it's very challenging to write unit tests for this f...
[ { "docstring": "Simulates rolling a six-sided dice.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Initiates a 2-player dice rolling game. Players take turns to roll a dice.", "function_declaration": "def play_game():...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided dice.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_game():\n \"\"\"\n Initiates a 2-player di...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006071", "row_id": 6071, "seed_ids": "['Llama-3.3-70B-Instruct_18065']" }
0.412846
Filter_6071
I
[ "roll_dice", "play_game" ]
2
[ [ "play_game", "roll_dice" ] ]
1
[]
false
[]
false
pytest
true
[]
true
954f6029318cbd043d9b4292bf4892e66aa113af
ed9e57250a1cfb2cbc423ed8be30e7fb40d3a951
v1.0
instruct
Filter
Filter_6073_I
I have 3 boolean variables: a, b, and c. I want to create all possible combinations of these variables and evaluate a conditional statement for each combination. The statement is: (a and b) or (not c). How can I do this in Python?
def evaluate_condition(a, b, c): """ Evaluates the conditional statement (a and b) or (not c) for given boolean values of a, b, and c. """ return (a and b) or (not c) def generate_combinations_and_evaluate(): """ Generates all possible combinations of boolean variables a, b, and c, and evaluate...
from solution import evaluate_condition, generate_combinations_and_evaluate def test_evaluate_condition(): # Test cases for evaluating the condition assert evaluate_condition(True, True, True) == True assert evaluate_condition(True, True, False) == True assert evaluate_condition(True, False, True) == F...
[ { "docstring": "Evaluates the conditional statement (a and b) or (not c) for given boolean values of a, b, and c.", "function_declaration": "def evaluate_condition(a, b, c):", "function_name": "evaluate_condition", "parameter_list": "(a, b, c)" }, { "docstring": "Generates all possible combi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def evaluate_boolean_combinations():\n \"\"\"\n Evaluates the given boolean condition (a and b) or (not c) for all combinations of inputs a, b, and c.\n Returns a dictionary with each...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006073", "row_id": 6073, "seed_ids": "['Llama-3.3-70B-Instruct_18069']" }
0.557724
Filter_6073
I
[ "evaluate_condition", "generate_combinations_and_evaluate" ]
2
[ [ "generate_combinations_and_evaluate", "evaluate_condition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e1b04e6452b97ac2f07a402960c66bdd1ecaaf8
9cd71eba8f7f82ef617d6cb80534027b4bf18f0d
v1.0
instruct
Filter
Filter_6120_I
Here is the assignment: Create a program to calculate the area of a triangle, given the lengths of its sides. If the lengths are invalid, the program should display the message "Invalid side lengths. Please try again." and continue to prompt the user. After the user enters valid side lengths, the program should calc...
import math def validate_triangle_sides(a, b, c): """ Validates if the three lengths can form a triangle. Returns True if valid, otherwise returns False. """ return a + b > c and b + c > a and c + a > b def calculate_semi_perimeter(a, b, c): """ Calculates the semi-perimeter of a triangle...
def test_validate_triangle_sides(): assert validate_triangle_sides(3, 4, 5) == True assert validate_triangle_sides(1, 1, 2) == False assert validate_triangle_sides(5, 12, 13) == True assert validate_triangle_sides(10, 1, 2) == False assert validate_triangle_sides(8, 10, 5) == True def test_calculat...
[ { "docstring": "Validates if the three lengths can form a triangle. \nReturns True if valid, otherwise returns False.", "function_declaration": "def validate_triangle_sides(a, b, c):", "function_name": "validate_triangle_sides", "parameter_list": "(a, b, c)" }, { "docstring": "Calculates the...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_valid_triangle(a, b, c):\n \"\"\"\n Checks if the given sides a, b, and c can form a triangle.\n \"\"\"\n if a + b > c and a + c > b and b + c > a:\n r...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006120", "row_id": 6120, "seed_ids": "['Llama-3.3-70B-Instruct_18179']" }
0.670491
Filter_6120
I
[ "validate_triangle_sides", "calculate_semi_perimeter", "calculate_area_of_triangle" ]
3
[ [ "calculate_area_of_triangle", "calculate_semi_perimeter" ], [ "calculate_area_of_triangle", "validate_triangle_sides" ] ]
2
[]
false
[]
false
pytest
false
[]
true
e9315f501a6538a89f0c8a70639ee42e911567ef
9453857bd4f167515b8b2f2bfebc6bd9aafb2ec7
v1.0
instruct
Filter
Filter_6128_I
I have a .txt file with a list of students and their corresponding student IDs. I want to create a simple command line interface (CLI) that allows me to add, remove, edit, and list students from the file. How can I accomplish this in Python?
import sys FILE_PATH = 'students.txt' def read_students(): try: with open(FILE_PATH, 'r') as file: lines = file.readlines() students = [line.strip().split(',') for line in lines] return {student[0]: student[1] for student in students} except FileNotFoundError: ...
import os import pytest from solution import add_student, remove_student, edit_student, list_students, FILE_PATH @pytest.fixture(autouse=True) def run_before_and_after_tests(): yield if os.path.exists(FILE_PATH): os.remove(FILE_PATH) def test_add_student(): add_student('John Doe', '12345') stu...
[ { "docstring": null, "function_declaration": "def read_students():", "function_name": "read_students", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def write_students(students):", "function_name": "write_students", "parameter_list": "(students)" }, ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\nFILE_NAME = \"students.txt\"\n\ndef load_students():\n students = {}\n try:\n with open(FILE_NAME, \"r\") as f:\n for line in f:\n if line....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006128", "row_id": 6128, "seed_ids": "['Llama-3.3-70B-Instruct_18206']" }
0.462481
Filter_6128
I
[ "read_students", "write_students", "add_student", "remove_student", "edit_student", "list_students", "main" ]
7
[ [ "add_student", "read_students" ], [ "add_student", "write_students" ], [ "edit_student", "read_students" ], [ "edit_student", "write_students" ], [ "list_students", "read_students" ], [ "remove_student", "read_students" ], [ "remove_stude...
7
[]
false
[]
false
pytest
true
[]
true
c9b2b182b00e86861b6086094890831cfd780b76
39445cca21740108b65f040734d11cd47608a823
v1.0
instruct
Filter
Filter_6134_I
I have a function called `get_tree_info` that returns a dictionary with information about a tree. The dictionary has the following keys: `id`, `name`, `species`, `location`, `age`, and `height`. The function takes in a tree ID as a parameter. Here is a sample dictionary that `get_tree_info` might return: ```python tre...
def get_tree_info(tree_id): """ Mock function to return tree information. """ sample_trees = { 1: {'id': 1, 'name': 'Tree1', 'species': 'Oak', 'location': 'New York', 'age': 50, 'height': 100}, 2: {'id': 2, 'name': 'Tree2', 'species': 'Pine', 'location': 'Oregon', 'age': 30, 'height': 60...
def test_get_tree_stats(): result = get_tree_stats(1) expected = { 'id': 1, 'name': 'Tree1', 'species': 'Oak', 'location': 'New York', 'age': 50, 'height': 100, 'health_score': 75.0, 'growth_rate': 2.0 } assert result == expected def test_...
[ { "docstring": "Mock function to return tree information.", "function_declaration": "def get_tree_info(tree_id):", "function_name": "get_tree_info", "parameter_list": "(tree_id)" }, { "docstring": "Retrieves tree information and calculates additional statistics: health_score and growth_rate....
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_tree_info(tree_id):\n \"\"\"\n Mock function to return tree information.\n \"\"\"\n sample_trees = {\n 1: {'id': 1, 'name': 'Tree1', 'species': 'Oak', 'location': 'N...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006134", "row_id": 6134, "seed_ids": "['Llama-3.3-70B-Instruct_18217']" }
0.621464
Filter_6134
I
[ "get_tree_info", "get_tree_stats" ]
2
[ [ "get_tree_stats", "get_tree_info" ] ]
1
[]
false
[]
false
pytest
false
[]
true
75178d4ecd078e26566678600dcb6e6b066d61c2
95345fb0dff4e7cbf867bf5c150d86fba4335253
v1.0
instruct
Filter
Filter_6139_I
### Technical Requirements 1. The solution should be in Python 3. 2. The function `get_valid_urls` should be defined with a single argument, which is a list of URLs. 3. All URLs in the input list should be checked for validity. 4. The function should return a list of valid URLs. 5. A URL is considered valid if it can ...
from urllib.parse import urlparse def get_valid_urls(urls): """ Returns a list of valid URLs. A URL is considered valid if it can be parsed and has a valid schema (http or https) and a valid network location. """ return [url for url in urls if is_valid_url(url)] def is_valid_url(url): """ ...
from solution import get_valid_urls, is_valid_url def test_is_valid_url(): # Test valid URLs assert is_valid_url("http://example.com") == True assert is_valid_url("https://example.com") == True assert is_valid_url("https://subdomain.example.com/path?query=1") == True # Test invalid URLs assert...
[ { "docstring": "Returns a list of valid URLs.\nA URL is considered valid if it can be parsed and has a valid schema (http or https) and a valid network location.", "function_declaration": "def get_valid_urls(urls):", "function_name": "get_valid_urls", "parameter_list": "(urls)" }, { "docstri...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom urllib.parse import urlparse\n\ndef get_valid_urls(urls):\n \"\"\"\n Returns a list of valid URLs from the input list.\n A URL is considered valid if it has a schema (...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006139", "row_id": 6139, "seed_ids": "['Llama-3.3-70B-Instruct_18224']" }
0.769167
Filter_6139
I
[ "get_valid_urls", "is_valid_url" ]
2
[ [ "get_valid_urls", "is_valid_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dde69d3ff71406b482e0dee52977e6ff63f9778e
f5069eeaa1076c31249b980dd01e049e83b39b5c
v1.0
instruct
Filter
Filter_6143_I
You can use Python's built-in `functools` module to create a function that takes another function as an argument and returns a new function that "wraps" the original function. The new function produced by the wrapper function should keep the original function's docstring and other metadata. Here's a simple decorator t...
import functools def my_decorator(enabled=True): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if enabled: print("Something is happening before the function is called.") value = func(*args, **kwargs) if enabled: ...
from solution import my_decorator, say_hello def test_decorator_enabled(capfd): """ Test decorator functionality when enabled. """ say_hello() out, err = capfd.readouterr() assert "Something is happening before the function is called." in out assert "Hello!" in out assert "Something is ...
[ { "docstring": null, "function_declaration": "def my_decorator(enabled=True):", "function_name": "my_decorator", "parameter_list": "(enabled=True)" }, { "docstring": "Print a hello message.", "function_declaration": "def say_hello():", "function_name": "say_hello", "parameter_lis...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import functools\n\ndef my_decorator(enabled=True):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n if enabled:\n p...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006143", "row_id": 6143, "seed_ids": "['Llama-3.3-70B-Instruct_18228']" }
0.4789
Filter_6143
I
[ "my_decorator", "say_hello" ]
2
[ [ "say_hello", "my_decorator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9800228abfe6c3131e763e2048f9d9656496ef6f
6adcd2695717423ae89d7c142a34e0f4c87a2394
v1.0
instruct
Filter
Filter_6175_I
Can you help me write a Python script to find all the prime numbers within a given range?
def is_prime(n): """ 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 += 6 return True...
from solution import is_prime, find_primes_in_range 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(1) == False assert is_prime(0) == False assert is_prime(-5) == False assert is_prime(17)...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers in the given range [start, end].", "function_declaration": "def find_primes_in_range(start...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_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 % 2 == 0 or n % 3 == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006175", "row_id": 6175, "seed_ids": "['Llama-3.3-70B-Instruct_18303']" }
0.716297
Filter_6175
I
[ "is_prime", "find_primes_in_range" ]
2
[ [ "find_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eea39e70c1dc0f8f00e632c8e4aade5f2f9090ce
31bf377fe864d5459a1547fffc400d0ea73323e3