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_9626_I
I'm looking for a way to optimize an existing algorithm for sorting a list of items, with the aim of improving its performance. The algorithm in question is a simple implementation of Bubble Sort. Here are the details of the algorithm: # Step-by-step analysis of the problem: 1. **The existing algorithm**: The algorit...
def merge_sort(lst): """ Merge Sort algorithm to sort a list of items. Args: lst (list): The list of items to be sorted. Returns: list: The sorted list of items. """ if len(lst) <= 1: return lst # Find the middle point to divide the array into two halves mid = ...
from solution import merge_sort def test_merge_sort_random_list(): assert merge_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90] def test_merge_sort_small_list(): assert merge_sort([5, 2, 8, 1, 9]) == [1, 2, 5, 8, 9] def test_merge_sort_sorted_list(): assert merge_sort([1, 2, 3, 4, 5]) ...
[ { "docstring": "Merge Sort algorithm to sort a list of items.\n\nArgs:\n lst (list): The list of items to be sorted.\n\nReturns:\n list: The sorted list of items.", "function_declaration": "def merge_sort(lst):", "function_name": "merge_sort", "parameter_list": "(lst)" }, { "docstring"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(lst):\n \"\"\"\n Merge Sort algorithm.\n\n Args:\n lst (list): The list of items to be sorted.\n\n Returns:\n list: The sorted list of items.\n \"\"...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009626", "row_id": 9626, "seed_ids": "['Llama-3.3-70B-Instruct_26156']" }
0.48933
Filter_9626
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bf3c07325a91611deb3a8e3017513b2d994be93c
7b8dde733b907a85e0a96d47467ff7a09aa2e45e
v1.0
instruct
Filter
Filter_9637_I
### Task 1: Create a Python Program to Validate a Password The program should check for the following: - The password should be at least 8 characters long. - The password should have at least 2 digits. - The password should have at least 1 uppercase letter. - The password should have at least 1 lowercase letter. - The ...
import random import string def validate_password(password): """ Validates if the password meets the required conditions: - At least 8 characters long - At least 2 digits - At least 1 uppercase letter - At least 1 lowercase letter - At least 1 special character """ if len(password) ...
from solution import validate_password, generate_password def test_validate_password_success(): assert validate_password('A1a!A1a!') == True assert validate_password('Pwd1!Pwd1!') == True def test_validate_password_fail_length(): assert validate_password('A1a!') == False def test_validate_password_fail_d...
[ { "docstring": "Validates if the password meets the required conditions:\n- At least 8 characters long\n- At least 2 digits\n- At least 1 uppercase letter\n- At least 1 lowercase letter\n- At least 1 special character", "function_declaration": "def validate_password(password):", "function_name": "valida...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport string\n\ndef is_valid_password(password):\n if len(password) < 8:\n return False\n if sum(c.isdigit() for c in password) < 2:\n return False\n if ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009637", "row_id": 9637, "seed_ids": "['Llama-3.3-70B-Instruct_26184']" }
0.784984
Filter_9637
I
[ "validate_password", "generate_password" ]
2
[ [ "generate_password", "validate_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
07a8599fe1dedfd4cce3e24a01f599f64cadcbbf
c6d8a5374062ed834b1a735f34a42bf0ea7d0c3b
v1.0
instruct
Filter
Filter_9647_I
I have a file called `colors.txt` containing the following text: ``` red green blue yellow orange purple ``` I have written a Python script to read the contents of this file and print the colors. ```python def read_colors(filename): try: with open(filename, 'r') as file: colors = [line.strip...
def read_colors(filename): try: with open(filename, 'r') as file: colors = [line.strip() for line in file.readlines()] return colors except FileNotFoundError: print(f"Sorry, the file {filename} does not exist.") return [] def add_color(filename, color): color...
import os from solution import read_colors, add_color, delete_color, search_color TEST_FILENAME = 'test_colors.txt' def setup_module(module): with open(TEST_FILENAME, 'w') as file: file.write("red\ngreen\nblue\nyellow\norange\npurple\n") def teardown_module(module): os.remove(TEST_FILENAME) def test...
[ { "docstring": null, "function_declaration": "def read_colors(filename):", "function_name": "read_colors", "parameter_list": "(filename)" }, { "docstring": null, "function_declaration": "def add_color(filename, color):", "function_name": "add_color", "parameter_list": "(filename,...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def read_colors(filename):\n try:\n with open(filename, 'r') as file:\n colors = [line.strip() for line in file.readlines()]\n return colors\n except FileNot...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009647", "row_id": 9647, "seed_ids": "['Llama-3.3-70B-Instruct_26198']" }
0.53756
Filter_9647
I
[ "read_colors", "add_color", "delete_color", "search_color" ]
4
[ [ "add_color", "read_colors" ], [ "delete_color", "read_colors" ], [ "search_color", "read_colors" ] ]
3
[]
false
[]
false
pytest
true
[]
true
c0646c66860f4f5afca6946627f6b149a8924f25
78bb60686224b0b1757931676c5d4f79a00d9430
v1.0
instruct
Filter
Filter_9655_I
I have a project that involves writing a program to solve the 8-puzzle problem. The 8-puzzle is a sliding puzzle that consists of a 3x3 grid of tiles, with 8 numbered tiles and a blank tile. The goal is to rearrange the tiles so that they are in order from 1 to 8, with the blank tile at the bottom right corner. Here ...
from collections import deque def is_solvable(puzzle): """ Check if the given puzzle configuration is solvable. """ flat_puzzle = sum(puzzle, []) inversions = 0 for i in range(len(flat_puzzle)): for j in range(i + 1, len(flat_puzzle)): if flat_puzzle[i] and flat_puzzle[j] an...
from solution import solve_8_puzzle def test_solvable_puzzle(): initial_state = [ [1, 2, 3], [4, 0, 6], [7, 5, 8] ] solution = solve_8_puzzle(initial_state) assert solution is not None assert solve_8_puzzle([[1, 2, 3], [4, 5, 6], [7, 8, 0]]) is not None def test_unsolvable_...
[ { "docstring": "Check if the given puzzle configuration is solvable.", "function_declaration": "def is_solvable(puzzle):", "function_name": "is_solvable", "parameter_list": "(puzzle)" }, { "docstring": "Find the position of the blank tile (0).\nReturns a tuple (row, col).", "function_dec...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from queue import PriorityQueue\n\nclass Node:\n def __init__(self, puzzle, parent=None, move=\"\", depth=0, cost=0):\n self.puzzle = puzzle\n self.parent = parent\n se...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009655", "row_id": 9655, "seed_ids": "['Llama-3.3-70B-Instruct_26218']" }
0.511227
Filter_9655
I
[ "is_solvable", "find_blank_position", "swap_positions", "is_goal", "get_neighbors", "solve_8_puzzle" ]
6
[ [ "get_neighbors", "find_blank_position" ], [ "get_neighbors", "swap_positions" ], [ "solve_8_puzzle", "get_neighbors" ], [ "solve_8_puzzle", "is_goal" ], [ "solve_8_puzzle", "is_solvable" ] ]
5
[]
false
[]
false
pytest
true
[]
true
9a51581ff14268572474c4d6f5b2dc7ba86bc3cb
9fe6751bf8e09ea0ddb728128b223f749f873a90
v1.0
instruct
Filter
Filter_9669_I
Here is a Python script that uses recursion and memoization to calculate the nth Fibonacci number: ``` import functools def fibonacci(n, memo={}): if n <= 0: return 0 elif n == 1: return 1 elif n not in memo: memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, memo) return memo[n] `...
import functools def fibonacci(n, memo={}): if n <= 0: return 0 elif n == 1: return 1 elif n not in memo: memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, memo) return memo[n] def sum_of_fibonacci(n): total = 0 for i in range(n+1): total += fibonacci(i) retur...
from solution import fibonacci, sum_of_fibonacci def test_fibonacci_base_cases(): assert fibonacci(0) == 0 assert fibonacci(1) == 1 def test_fibonacci_recursive_cases(): assert fibonacci(5) == 5 assert fibonacci(10) == 55 def test_sum_of_fibonacci_base_case(): assert sum_of_fibonacci(0) == 0 ...
[ { "docstring": null, "function_declaration": "def fibonacci(n, memo={}):", "function_name": "fibonacci", "parameter_list": "(n, memo={})" }, { "docstring": null, "function_declaration": "def sum_of_fibonacci(n):", "function_name": "sum_of_fibonacci", "parameter_list": "(n)" } ]
[ 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 fibonacci(n, memo={}):\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n elif n not in memo:\n memo[n] = fibonacci(n-1, memo) + fibonacc...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009669", "row_id": 9669, "seed_ids": "['Llama-3.3-70B-Instruct_26241']" }
0.615273
Filter_9669
I
[ "fibonacci", "sum_of_fibonacci" ]
2
[ [ "sum_of_fibonacci", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
30a6beb0f845ce19ff6e5eb166bdfe1251c7dd64
de0df0033a46e7610ef4e2ab9f910edd17b086b2
v1.0
instruct
Filter
Filter_9710_I
Here is the Python solution for the problem: ```python def find_gcd(num1, num2): while num2 != 0: num1, num2 = num2, num1 % num2 return num1 def count_common_divisors(num1, num2): count = 0 gcd_value = find_gcd(num1, num2) for i in range(1, gcd_value + 1): if gcd_value % i == 0: ...
def find_gcd(num1, num2): """ Returns the greatest common divisor (GCD) of num1 and num2. """ while num2 != 0: num1, num2 = num2, num1 % num2 return num1 def count_common_divisors(num1, num2): """ Returns the count of common divisors of num1 and num2. """ count = 0 gcd_v...
from solution import find_gcd, count_common_divisors def test_find_gcd(): assert find_gcd(48, 18) == 6 assert find_gcd(54, 24) == 6 assert find_gcd(7, 3) == 1 assert find_gcd(25, 5) == 5 assert find_gcd(100, 0) == 100 def test_count_common_divisors(): assert count_common_divisors(48, 18) == 4 ...
[ { "docstring": "Returns the greatest common divisor (GCD) of num1 and num2.", "function_declaration": "def find_gcd(num1, num2):", "function_name": "find_gcd", "parameter_list": "(num1, num2)" }, { "docstring": "Returns the count of common divisors of num1 and num2.", "function_declarati...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_gcd(num1, num2):\n while num2 != 0:\n num1, num2 = num2, num1 % num2\n return num1\n\ndef count_common_divisors(num1, num2):\n count = 0\n gcd_value = find_gcd(num1...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009710", "row_id": 9710, "seed_ids": "['Llama-3.3-70B-Instruct_26337']" }
0.723007
Filter_9710
I
[ "find_gcd", "count_common_divisors" ]
2
[ [ "count_common_divisors", "find_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
14eeae478c8367c2e23bf29196cdf6d2c753037b
e534c4fdd09bd060e37f0315893994ff8b76de76
v1.0
instruct
Filter
Filter_9737_I
You can use the following variables: username, email, id You can use the following functions: start() - Starts a session AndWait() - Makes the program wait for a certain amount of time AndWait() is not available in this context. You can use the following modules: os time (You can use sleep function from this module) Y...
import time def start(): """ Simulates starting a session. """ print("Session started.") time.sleep(1) def start_sessions(users): """ Starts a session for a list of users with their emails and ids. Args: users (list): List of dictionaries with keys 'username', 'email', and...
from solution import start_sessions users = [ {"username": "user1", "email": "user1@example.com", "id": 1}, {"username": "user2", "email": "user2@example.com", "id": 2}, {"username": "user3", "email": "user3@example.com", "id": 3} ] def test_start_sessions(capsys): start_sessions(users) captured =...
[ { "docstring": "Simulates starting a session.", "function_declaration": "def start():", "function_name": "start", "parameter_list": "()" }, { "docstring": "Starts a session for a list of users with their emails and ids.\n\nArgs:\n users (list): List of dictionaries with keys 'username', '...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef start_session(username, email, user_id):\n \"\"\"\n Starts a session for the user and prints the session details.\n \"\"\"\n print(f\"Session started for user: {...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009737", "row_id": 9737, "seed_ids": "['Llama-3.3-70B-Instruct_26395']" }
0.409226
Filter_9737
I
[ "start", "start_sessions" ]
2
[ [ "start_sessions", "start" ] ]
1
[]
false
[]
false
pytest
true
[]
true
77471d0c60675e755242258d42f310094b0f84b0
48fbb8550b3e20a5458ca47a70918a4d287e9b98
v1.0
instruct
Filter
Filter_9782_I
I have a list of latitude and longitude coordinates and I want to calculate the distance between each pair of points. I can use the Haversine formula to calculate the distance between two points on a sphere (such as the Earth) given their longitudes and latitudes. I want to write this in Python and I want to include ...
import math def haversine_distance(lat1, lon1, lat2, lon2): """ Calculate the distance between two points on the Earth's surface. Parameters: lat1 (float): Latitude of the first point lon1 (float): Longitude of the first point lat2 (float): Latitude of the second point lon2 (float): Longit...
import pytest from solution import haversine_distance, calculate_distances def test_haversine_distance_valid(): assert pytest.approx(haversine_distance(52.5200, 13.4050, 48.8566, 2.3522), 0.1) == 878.7 def test_haversine_distance_invalid_latitude(): with pytest.raises(ValueError): haversine_distance(-...
[ { "docstring": "Calculate the distance between two points on the Earth's surface.\n\nParameters:\nlat1 (float): Latitude of the first point\nlon1 (float): Longitude of the first point\nlat2 (float): Latitude of the second point\nlon2 (float): Longitude of the second point\n\nReturns:\nfloat: Distance between th...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import List, Tuple, Dict\n\ndef validate_coordinates(lat: float, lon: float):\n \"\"\"\n Validate the latitude and longitude coordinates.\n \n Parameters:\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009782", "row_id": 9782, "seed_ids": "['Llama-3.3-70B-Instruct_26521']" }
0.6314
Filter_9782
I
[ "haversine_distance", "calculate_distances" ]
2
[ [ "calculate_distances", "haversine_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8ab8bb824473ff07d0d9e88db0fce43397306b24
a1f931dd0e437b38758e42596d16bbdab3e48bdf
v1.0
instruct
Filter
Filter_9789_I
Develop a Python solution that reads a given markdown file, extracts the headers, and converts then into a table of contents. The solution should provide the ability to extract specific headers (e.g., H1, H2, etc.) and the option to output the result in different formats (e.g., markdown, JSON, etc.).
import re import json def read_markdown(file_path): with open(file_path, 'r', encoding='utf-8') as file: return file.readlines() def extract_headers(contents, header_levels=['h1', 'h2', 'h3', 'h4', 'h5', 'h6']): headers = [] header_patterns = { 'h1': re.compile(r'^# (.*)'), 'h2': r...
from solution import read_markdown, extract_headers, format_toc, generate_toc import tempfile import json # Create a temporary markdown file for testing markdown_content = """ # Header 1 Some content here. ## Header 1.1 Some other content. ### Header 1.1.1 Yet another content piece. ## Header 1.2 Additional content. #...
[ { "docstring": null, "function_declaration": "def read_markdown(file_path):", "function_name": "read_markdown", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def extract_headers(contents, header_levels=['h1', 'h2', 'h3', 'h4', 'h5', 'h6']):", "funct...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nimport json\n\ndef read_markdown(file_path):\n with open(file_path, 'r', encoding='utf-8') as file:\n return file.readlines()\n\ndef extract_headers(contents, header_level...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009789", "row_id": 9789, "seed_ids": "['Llama-3.3-70B-Instruct_26540']" }
0.461214
Filter_9789
I
[ "read_markdown", "extract_headers", "format_toc", "generate_toc" ]
4
[ [ "generate_toc", "extract_headers" ], [ "generate_toc", "format_toc" ], [ "generate_toc", "read_markdown" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2ab9b8c082edabc39e41cb708e10dd3eb3bdaace
7da5b74928b6e28c8b8e90ade5c4fab7084a994c
v1.0
instruct
Filter
Filter_9794_I
I have a function that gets the day of the week given a specific date, I need to check if a specific date is in a certain day of the week (e.g., all Tuesdays). Here is my function: ```python from datetime import datetime, timedelta def get_day_of_week(date_str): """ This function takes a date string in the f...
from datetime import datetime def get_day_of_week(date_str): """ This function takes a date string in the format 'YYYY-MM-DD' and returns the day of the week as a string. Args: date_str (str): The date string in 'YYYY-MM-DD' format. Returns: str: The day of the week. """ date ...
from solution import get_day_of_week, is_tuesday def test_get_day_of_week(): assert get_day_of_week('2023-10-03') == 'Tuesday' assert get_day_of_week('2023-10-04') == 'Wednesday' assert get_day_of_week('2023-10-05') == 'Thursday' def test_is_tuesday(): assert is_tuesday('2023-10-03') == True asser...
[ { "docstring": "This function takes a date string in the format 'YYYY-MM-DD' and returns the day of the week as a string.\n\nArgs:\ndate_str (str): The date string in 'YYYY-MM-DD' format.\n\nReturns:\nstr: The day of the week.", "function_declaration": "def get_day_of_week(date_str):", "function_name": ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_tuesday(date_str):\n \"\"\"\n This function checks if a given date string is a Tuesday.\n \n Args:\n date_str (str): The date string in 'YYYY-MM-DD' format.\n \n Re...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009794", "row_id": 9794, "seed_ids": "['Llama-3.3-70B-Instruct_26549']" }
0.676656
Filter_9794
I
[ "get_day_of_week", "is_tuesday" ]
2
[ [ "is_tuesday", "get_day_of_week" ] ]
1
[]
false
[]
false
pytest
true
[]
true
345b0329e0e918d59fc16d16c93de2f2b08ad8a0
bb9c480627931126785f2c8a6c72956862676f12
v1.0
instruct
Filter
Filter_9807_I
I have an array of numbers and a method to generate a number within a certain range. I want to find the median of the array. If the array is empty, I want to generate a number within the range, add it to the array, and then calculate the median. Here is my current implementation: ```python import random import numpy ...
import random import numpy as np def generate_number(min_val, max_val): return random.randint(min_val, max_val) def calculate_median(array, min_val=1, max_val=100): if len(array) == 0: array.append(generate_number(min_val, max_val)) return np.median(array)
from solution import calculate_median, generate_number import pytest def test_calculate_median_empty_list(): # Ensure the function modifies the list and appends a generated number numbers = [] median = calculate_median(numbers) assert len(numbers) == 1 assert median == numbers[0] def test_calculat...
[ { "docstring": null, "function_declaration": "def generate_number(min_val, max_val):", "function_name": "generate_number", "parameter_list": "(min_val, max_val)" }, { "docstring": null, "function_declaration": "def calculate_median(array, min_val=1, max_val=100):", "function_name": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport numpy as np\n\ndef generate_number(min_val, max_val):\n return random.randint(min_val, max_val)\n\ndef calculate_median(array):\n if len(array) == 0:\n gener...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009807", "row_id": 9807, "seed_ids": "['Llama-3.3-70B-Instruct_26589']" }
0.572367
Filter_9807
I
[ "generate_number", "calculate_median" ]
2
[ [ "calculate_median", "generate_number" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
bf921c530f437aff15432d0511b084548a8fe98a
ca281de6fd628c840c1fe4a10d09006a95837053
v1.0
instruct
Filter
Filter_9820_I
I'm trying to achieve the following in a Python program: 1. Print 5 random integers between -10000 and 10000 (inclusive), each on a new line. 2. Take these 5 random integers as input and find the maximum and minimum values. 3. Calculate the sum of the numbers excluding the maximum and minimum values. 4. Use a for loop ...
import random def print_5_random_integers(): random_integers = [random.randint(-10000, 10000) for _ in range(5)] for number in random_integers: print(number) return random_integers def find_max_min(lst): return max(lst), min(lst) def sum_excluding_max_min(lst): max_val, min_val = find_max...
from solution import (print_5_random_integers, find_max_min, sum_excluding_max_min, print_each_number, print_until_max, recursive_sum) def test_find_max_min(): lst = [3, 5, -2, 9, 0] max_val, min_val = find_max_min(lst) assert max_val == 9 assert min_val == -2 def test_sum_excl...
[ { "docstring": null, "function_declaration": "def print_5_random_integers():", "function_name": "print_5_random_integers", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def find_max_min(lst):", "function_name": "find_max_min", "parameter_list": "(lst)" ...
[ 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_random_integers(n, start, end):\n \"\"\"\n Generates `n` random integers between `start` and `end` (inclusive).\n \"\"\"\n random_integers = [random.r...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009820", "row_id": 9820, "seed_ids": "['Llama-3.3-70B-Instruct_26614']" }
0.586709
Filter_9820
I
[ "print_5_random_integers", "find_max_min", "sum_excluding_max_min", "print_each_number", "print_until_max", "recursive_sum" ]
6
[ [ "sum_excluding_max_min", "find_max_min" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1741b2d3ee0c2d670b6f6eeb51e4598faa3e1c3
6d42522f0de82a33853b071e89c898e4e9bfb3cd
v1.0
instruct
Filter
Filter_9829_I
Here is a Python function that calculates the greatest common divisor (GCD) of two integers using recursion: ```python def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) ``` How would you modify it to also calculate the least common multiple (LCM) of the two integers? You could provi...
def gcd(a, b): """ Returns the greatest common divisor of a and b using recursion. """ if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): """ Returns the least common multiple of a and b. """ if a == 0 or b == 0: return 0 return abs(a * b) // g...
from solution import gcd, lcm def test_gcd(): assert gcd(48, 18) == 6 assert gcd(101, 103) == 1 assert gcd(56, 0) == 56 assert gcd(0, 34) == 34 assert gcd(0, 0) == 0 # Normally undefined but returns 0 as per current implementation def test_lcm(): assert lcm(4, 5) == 20 assert lcm(6, 8) ==...
[ { "docstring": "Returns the greatest common divisor of a and b using recursion.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple of a and b.", "function_declaration": "def lcm(a, b):", ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b using recursion.\n \"\"\"\n if b == 0:\n return a\n else:\n return gcd(b, a % b)\n\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009829", "row_id": 9829, "seed_ids": "['Llama-3.3-70B-Instruct_26644']" }
0.670909
Filter_9829
I
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0d7fe48e564995af09cf2592ce27db485986ce0b
e17dd0bda59e1bc1c3f917ce9e043953a490847c
v1.0
instruct
Filter
Filter_9831_I
Please write a code for a rock, paper, scissor game written in Python ```python import random def game(): while True: user_choice = input("Enter a choice (rock, paper, scissor): ").lower() possible_choices = ["rock", "paper", "scissor"] computer_choice = random.choice(possible_choices) ...
import random def get_winner(user_choice, computer_choice): if user_choice == computer_choice: return "tie" elif user_choice == "rock": if computer_choice == "scissor": return "user" else: return "computer" elif user_choice == "paper": if computer_cho...
from solution import get_winner def test_tie(): assert get_winner("rock", "rock") == "tie" assert get_winner("paper", "paper") == "tie" assert get_winner("scissor", "scissor") == "tie" def test_user_wins(): assert get_winner("rock", "scissor") == "user" assert get_winner("paper", "rock") == "user"...
[ { "docstring": null, "function_declaration": "def get_winner(user_choice, computer_choice):", "function_name": "get_winner", "parameter_list": "(user_choice, computer_choice)" }, { "docstring": null, "function_declaration": "def game():", "function_name": "game", "parameter_list"...
[ 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_winner(user_choice, computer_choice):\n if user_choice == computer_choice:\n return \"tie\"\n elif user_choice == \"rock\":\n if computer_choice ==...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009831", "row_id": 9831, "seed_ids": "['Llama-3.3-70B-Instruct_26647']" }
0.586424
Filter_9831
I
[ "get_winner", "game" ]
2
[ [ "game", "get_winner" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f845b476a33820d4706934b2a16ecf89daaeb8b4
ad8e5c899f667af10db2feb7313d2683b115866f
v1.0
instruct
Filter
Filter_9850_I
I have two functions, `func1` and `func2`, that return the same type of data. Is it possible to call `func2` from within `func1`, and vice versa, assuming both functions are defined but not yet called, and both functions are in the same scope?
def func1(n): """ Example function that calls func2. Recursively decreases n until it reaches 0. """ if n <= 0: return "func1 end" else: return func2(n-1) def func2(n): """ Example function that calls func1. Recursively decreases n until it reaches 1. """ if ...
from solution import func1, func2 def test_func1_calls_func2(): assert func1(1) == "func2 end" # func1(1) calls func2(0) which returns "func2 end" assert func1(2) == "func1 end" # func1(2) calls func2(1) => func2(1) calls func1(0) = "func1 end" assert func1(3) == "func2 end" # func1(3) calls func2(2) =>...
[ { "docstring": "Example function that calls func2.\nRecursively decreases n until it reaches 0.", "function_declaration": "def func1(n):", "function_name": "func1", "parameter_list": "(n)" }, { "docstring": "Example function that calls func1.\nRecursively decreases n until it reaches 1.", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def func1():\n # Implementation of func1\n return func2()\n\ndef func2():\n # Implementation of func2\n return \"func2 was called\"", "test_code": "from solution import func1, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009850", "row_id": 9850, "seed_ids": "['Llama-3.3-70B-Instruct_26696']" }
0.23499
Filter_9850
I
[ "func1", "func2" ]
2
[ [ "func1", "func2" ], [ "func2", "func1" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7c7a9aca7e147389b90321b3aedd8859908cdef0
da4e2829ca34bb6c6e5f0590ca7721c90a7ba93f
v1.0
instruct
Filter
Filter_9877_I
I have 3 users: User A, User B, and User C. User A can only view items in category 1. User B can view items in categories 1 and 2. User C can view all items. How would you implement the permission system for this? Please provide a simple example in Python. Let's assume the category of an item is stored in `ite...
class User: def __init__(self, name, viewable_categories): self.name = name self.viewable_categories = viewable_categories class Item: def __init__(self, category): self.category = category def can_view_item(user, item): """ Check if the user can view a specific item based on t...
from solution import User, Item, can_view_item, can_view_all_items def test_can_view_item(): user_a = User("User A", [1]) user_b = User("User B", [1, 2]) user_c = User("User C", [1, 2, 3]) item1 = Item(1) item2 = Item(2) item3 = Item(3) assert can_view_item(user_a, item1) == True ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class User:\n def __init__(self, name, viewable_categories):\n self.name = name\n self.viewable_categories = viewable_categories\n\nclass Item:\n def __init__(self, categor...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009877", "row_id": 9877, "seed_ids": "['Llama-3.3-70B-Instruct_26768']" }
0.342785
Filter_9877
I
[ "can_view_item", "can_view_all_items" ]
2
[ [ "can_view_all_items", "can_view_item" ] ]
1
[]
false
[ "User", "Item" ]
true
pytest
true
[]
true
d528b31e030043dd53657d037bb19157da9c20b4
81b19eb7ecd5b2e3f1caf4627fbed23f880d9d36
v1.0
instruct
Filter
Filter_9891_I
I have a very specific task. I want to make a program that can play a game of Tic Tac Toe with a user, where the user is X and the computer is O. I have a basic understanding of python, but I'm not sure how to implement the logic. Can you help me create a simple implementation of a Tic Tac Toe game using Python?
import random def print_board(board): """ Prints the current state of the Tic Tac Toe board. """ for row in board: print(" | ".join(row)) print("-" * 5) def check_winner(board, mark): """ Checks if the given mark ('X' for user, 'O' for computer) has won the game. """ ...
from solution import print_board, check_winner, is_board_full, get_computer_move, user_move def test_print_board(capsys): board = [ [' ', 'X', ' '], ['O', 'X', ' '], [' ', 'O', ' '] ] print_board(board) captured = capsys.readouterr() assert captured.out == " | X | \n-----\...
[ { "docstring": "Prints the current state of the Tic Tac Toe board.", "function_declaration": "def print_board(board):", "function_name": "print_board", "parameter_list": "(board)" }, { "docstring": "Checks if the given mark ('X' for user, 'O' for computer) has won the game.", "function_d...
[ 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 print_board(board):\n for row in board:\n print(\" | \".join(row))\n print(\"-\" * 5)\n\ndef check_win(board, player):\n # Check rows, columns, and dia...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009891", "row_id": 9891, "seed_ids": "['Llama-3.3-70B-Instruct_26804']" }
0.336033
Filter_9891
I
[ "print_board", "check_winner", "is_board_full", "get_computer_move", "user_move", "play_game" ]
6
[ [ "play_game", "check_winner" ], [ "play_game", "get_computer_move" ], [ "play_game", "is_board_full" ], [ "play_game", "print_board" ], [ "play_game", "user_move" ] ]
5
[]
false
[]
false
pytest
true
[]
true
f240d56d47666ad6193c76cc31e32c4ccf9d1eef
198d39a34a443c5bf099b4d15480d2bac1741c10
v1.0
instruct
Filter
Filter_9892_I
I'm writing a program to solve a Sudoku puzzle. The Sudoku puzzle is passed as a 2D list of integers, where 0 represents an empty space. I want to implement a backtracking algorithm to solve the puzzle. Here is my current implementation: ```python def is_valid(board, row, col, num): # Check the row for x in r...
def is_valid(board, row, col, num): """ Check if it's valid to place num at board[row][col] """ # Check the row for x in range(9): if board[row][x] == num: return False # Check the column for x in range(9): if board[x][col] == num: return False #...
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 num at board[row][col]", "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 algorithm", "functio...
[ 1, 1, 1 ]
3
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 it's valid to place the num in the given row and column of the board.\n \"\"\"\n # Check the row\n for x in range(9):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009892", "row_id": 9892, "seed_ids": "['Llama-3.3-70B-Instruct_26806']" }
0.492131
Filter_9892
I
[ "is_valid", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aaafef8d9d1920a4caefcbec7ef3ac129264f43d
7ac387ae3024ffc64cd0095bc4cd028afb7cc9ba
v1.0
instruct
Filter
Filter_9901_I
How would you implement the logic for a game where players can move their characters in a grid-based dungeon? Here is an example of how the dungeon is represented: ```python dungeon = [ [1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 1, 1, ...
def can_move(dungeon, position, direction): """ Determines if a move is valid in the dungeon. :param dungeon: List[List[int]] - 2D array representing the dungeon :param position: Tuple[int, int] - Current position of the player as (row, col) :param direction: str - Direction of the movement ('u...
from solution import can_move, move_player dungeon = [ [1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1] ] def test_can_move_valid_up(): assert can_move(dungeon, (2, 2), 'up') == (True, (1, 2)) def test_can_move_valid_do...
[ { "docstring": "Determines if a move is valid in the dungeon.\n\n:param dungeon: List[List[int]] - 2D array representing the dungeon\n:param position: Tuple[int, int] - Current position of the player as (row, col)\n:param direction: str - Direction of the movement ('up', 'down', 'left', 'right')\n:return: Tuple...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class DungeonGame:\n def __init__(self, dungeon, player_pos):\n self.dungeon = dungeon\n self.player_pos = player_pos\n\n def can_move(self, direction):\n x, y = sel...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009901", "row_id": 9901, "seed_ids": "['Llama-3.3-70B-Instruct_26835']" }
0.629707
Filter_9901
I
[ "can_move", "move_player" ]
2
[ [ "move_player", "can_move" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4b27ed019b67c588d90fef1f921248e912c4da2a
66c07291ebe4a18297df998ad80ba67c8abc3b24
v1.0
instruct
Filter
Filter_9943_I
### Task: Hangman Game #### Overview You will create a simple Hangman game using Python. The computer will choose a word from a predefined list, and the player will have to guess the word by suggesting letters. For each incorrect guess, the computer will draw a part of a hangman's gallows. The game will end when the pl...
import random def choose_random_word(words_list): """ Chooses a random word from the provided list. """ return random.choice(words_list) def display_current_progress(word, guesses): """ Displays the current progress of the guessed word with underscores for unguessed letters. """ return...
import pytest from unittest.mock import patch from solution import choose_random_word, display_current_progress, hangman def test_choose_random_word(): words_list = ['apple', 'banana', 'cherry'] word = choose_random_word(words_list) assert word in words_list def test_display_current_progress(): word =...
[ { "docstring": "Chooses a random word from the provided list.", "function_declaration": "def choose_random_word(words_list):", "function_name": "choose_random_word", "parameter_list": "(words_list)" }, { "docstring": "Displays the current progress of the guessed word with underscores for ung...
[ 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 hangman(words):\n \"\"\"\n A simple Hangman game.\n \n Args:\n words (list of str): List of words for the game to choose from.\n \n Returns:\n str:...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009943", "row_id": 9943, "seed_ids": "['Llama-3.3-70B-Instruct_26926']" }
0.555018
Filter_9943
I
[ "choose_random_word", "display_current_progress", "hangman" ]
3
[ [ "hangman", "choose_random_word" ], [ "hangman", "display_current_progress" ] ]
2
[]
false
[]
false
pytest
true
[]
true
867d417c8749802c8e3c4913c99f548568f4c0d5
58ff41faf31065fcaf5ef111af0229b36e36755f
v1.0
instruct
Filter
Filter_9951_I
I have two functions: `is_prime(n)` and `get_primes(n)`. `is_prime(n)` checks if a number `n` is prime, and `get_primes(n)` generates all prime numbers up to `n`. I want to use these functions to solve Project Euler problem 10. Project Euler problem 10 states: The sum of the primes below 10 is 17. Find the sum of all...
def is_prime(n): """ Checks if a number n is prime. """ if n < 2: return False if n in (2, 3): return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 retu...
from solution import is_prime, get_primes, sum_of_primes_below 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(19) == True assert is_prime(1) == False assert i...
[ { "docstring": "Checks if a number n is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generates all prime numbers up to n (exclusive).", "function_declaration": "def get_primes(n):", "function_name": "get_...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number n is prime.\n \n Parameters:\n n (int): The number to check.\n \n Returns:\n bool: True if n is prime, False otherwise.\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009951", "row_id": 9951, "seed_ids": "['Llama-3.3-70B-Instruct_26940']" }
0.642433
Filter_9951
I
[ "is_prime", "get_primes", "sum_of_primes_below" ]
3
[ [ "sum_of_primes_below", "get_primes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e533829bdae43a79690a427ef45947c4ddcc0a3b
852013362f192e87c0623e03f1e6c77f0c1c89c5
v1.0
instruct
Filter
Filter_9978_I
Provide the merge sort algorithm in Python using recursion.
def merge_sort(arr): """ Sorts an array in ascending order using the merge sort algorithm. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left, righ...
from solution import merge_sort, merge def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_even_number_elements(): assert merge_sort([4, 2, 3, 1]) == [1, 2, 3, 4] def test_merge_sort_odd_number_elements(): assert merge_sort([5, 2, 9, 1, 5]) == [1, 2, 5, 5, 9] def test...
[ { "docstring": "Sorts an array in ascending order 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 m...
[ 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 if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n l...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009978", "row_id": 9978, "seed_ids": "['Llama-3.3-70B-Instruct_26994']" }
0.654384
Filter_9978
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a1bb89f9cbded28209fda5f7b818743f26bafb65
337f85cfa980888cd8e41b3e8ea87e8ecf50df8f
v1.0
instruct
Filter
Filter_10003_I
You have a function that can encrypt a string by shifting each letter by a certain number of positions down the alphabet. The function is called `caesar_cipher`. Here is the function: ```python def caesar_cipher(text, shift): result = "" for char in text: if char.isalpha(): ascii_offset = 97...
def caesar_cipher_decrypt(text, shift): """ Decrypts the given text using the Caesar cipher technique with the specified shift. """ return caesar_cipher(text, -shift) def caesar_cipher(text, shift): """ Encrypts or decrypts the given text using the Caesar cipher technique with the specified shi...
from solution import caesar_cipher, caesar_cipher_decrypt def test_caesar_cipher_encrypt(): assert caesar_cipher("hello", 3) == "khoor" def test_caesar_cipher_decrypt(): assert caesar_cipher_decrypt("khoor", 3) == "hello" def test_caesar_cipher_with_non_alpha(): assert caesar_cipher("hello, world!", 3) =...
[ { "docstring": "Decrypts the given text using the Caesar cipher technique with the specified shift.", "function_declaration": "def caesar_cipher_decrypt(text, shift):", "function_name": "caesar_cipher_decrypt", "parameter_list": "(text, shift)" }, { "docstring": "Encrypts or decrypts the giv...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def caesar_cipher_decrypt(text, shift):\n # To decrypt, we simply negate the shift value\n return caesar_cipher(text, -shift)", "test_code": "from solution import caesar_cipher_decry...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010003", "row_id": 10003, "seed_ids": "['Llama-3.3-70B-Instruct_27045']" }
0.781597
Filter_10003
I
[ "caesar_cipher_decrypt", "caesar_cipher" ]
2
[ [ "caesar_cipher_decrypt", "caesar_cipher" ] ]
1
[]
false
[]
false
pytest
true
[]
true
554a9cffd6c667b8531a83d95e43458fa91cc010
1ff96f52e9cfff95f8924206c3f84b044755ddae
v1.0
instruct
Filter
Filter_10015_I
We are given a module named "library" with the following functions: - `is_valid_isbn(isbn)`: Checks if the provided ISBN is valid. - `get_book_info(isbn)`: Retrieves information about a book with the given ISBN. How would we implement these two functions in Python? Also, provide example usage of these functions.
import re # Function to validate ISBN def is_valid_isbn(isbn: str) -> bool: """ Check if the provided ISBN is valid. ISBN can be either 10 or 13 characters long """ if len(isbn) == 10: return bool(re.match(r'^\d{9}[\dX]$', isbn)) and _is_valid_isbn_10(isbn) elif len(isbn) == 13: ...
from solution import is_valid_isbn, get_book_info def test_is_valid_isbn_10(): assert is_valid_isbn("123456789X") == True assert is_valid_isbn("1234567890") == False assert is_valid_isbn("123456789X0") == False # Invalid length def test_is_valid_isbn_13(): assert is_valid_isbn("9783161484100") == Tru...
[ { "docstring": "Check if the provided ISBN is valid.\nISBN can be either 10 or 13 characters long", "function_declaration": "def is_valid_isbn(isbn):", "function_name": "is_valid_isbn", "parameter_list": "(isbn)" }, { "docstring": null, "function_declaration": "def _is_valid_isbn_10(isbn...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_valid_isbn(isbn):\n \"\"\"\n Checks if the provided ISBN is valid.\n An ISBN is considered valid if it is either 10 or 13 characters long and consists solely of digits.\n \n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010015", "row_id": 10015, "seed_ids": "['Llama-3.3-70B-Instruct_27067']" }
0.478384
Filter_10015
I
[ "is_valid_isbn", "_is_valid_isbn_10", "_is_valid_isbn_13", "get_book_info" ]
4
[ [ "get_book_info", "is_valid_isbn" ], [ "is_valid_isbn", "_is_valid_isbn_10" ], [ "is_valid_isbn", "_is_valid_isbn_13" ] ]
3
[]
false
[]
false
pytest
true
[]
true
00096a0fda3636c592b5b310b41343e76f81ed13
90066a1e7d045d707fc78befc884647941bdeb8e
v1.0
instruct
Filter
Filter_10021_I
### Successor: Write a function `successor` that takes in a node of a binary tree and returns the node with the smallest key greater than the input node's key.
class TreeNode: def __init__(self, key=0, left=None, right=None): self.key = key self.left = left self.right = right def find_min(node): """ Finds the node with the minimum key in a binary tree. """ while node.left is not None: node = node.left return node def s...
from solution import TreeNode, successor def test_successor_with_right_subtree(): root = TreeNode(20) root.left = TreeNode(10) root.right = TreeNode(30) root.left.left = TreeNode(5) root.left.right = TreeNode(15) assert successor(root, root.left).key == 15 def test_successor_without_right_subt...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, key=0, left=None, right=None):\n self.key = key\n self.left = left\n self.right = right\n\ndef find_min(node):\n \"\"\"\n Fin...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010021", "row_id": 10021, "seed_ids": "['Llama-3.3-70B-Instruct_27082']" }
0.587223
Filter_10021
I
[ "find_min", "successor" ]
2
[ [ "successor", "find_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
366ddf212cc7695434e2a3de11bfd085442a8924
64b926339e75fc547a199ffb21e91758f8092214
v1.0
instruct
Filter
Filter_10038_I
How to build a simple neural network from scratch in Python ====================================================== Building a simple neural network from scratch in Python can be a fun and rewarding experience. In this tutorial, we will guide you through the process of building a basic neural network using only Python ...
import numpy as np def sigmoid(x): """ Compute the sigmoid of x. """ return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): """ Compute the derivative of the sigmoid function. """ return x * (1 - x) def initialize_weights(input_size, hidden_size, output_size): """ Initializes ...
from solution import sigmoid, sigmoid_derivative, initialize_weights, feedforward, backpropagation, train_neural_network, predict import numpy as np def test_sigmoid(): assert np.isclose(sigmoid(0), 0.5) def test_sigmoid_derivative(): assert np.isclose(sigmoid_derivative(0.5), 0.25) def test_initialize_weigh...
[ { "docstring": "Compute the sigmoid of x.", "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": "Compute the derivative of the sigmoid function.", "function_declaration": "def sigmoid_derivative(x):", "function_name": "sigm...
[ 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 sigmoid(x):\n \"\"\"\n Compute the sigmoid of x.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n \"\"\"\n Compute the derivat...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010038", "row_id": 10038, "seed_ids": "['Llama-3.3-70B-Instruct_27124']" }
0.418539
Filter_10038
I
[ "sigmoid", "sigmoid_derivative", "initialize_weights", "feedforward", "backpropagation", "train_neural_network", "predict" ]
7
[ [ "backpropagation", "sigmoid_derivative" ], [ "feedforward", "sigmoid" ], [ "predict", "feedforward" ], [ "train_neural_network", "backpropagation" ], [ "train_neural_network", "feedforward" ], [ "train_neural_network", "initialize_weights" ] ]
6
[]
false
[]
false
pytest
true
[ "numpy" ]
false
d6bc3c1b822e64fc12e6096edcbab172bdf9d285
a40774c2663ffad2a4048add4423c81e82079f26
v1.0
instruct
Filter
Filter_10041_I
### Algorithm Description The algorithm generates all possible permutations of a given string and checks each permutation to see if it is a palindrome. ### Algorithm Steps 1. Generate all permutations of the input string. 2. Check each permutation to see if it is a palindrome. 3. If a palindrome permutation is found, ...
from itertools import permutations def generate_permutations(input_string: str) -> list[str]: """ Generate all permutations of the input string. Args: input_string (str): The string to generate permutations for. Returns: list[str]: A list of all permutations of the input string. """ r...
from solution import generate_permutations, is_palindrome, find_palindrome_permutations def test_generate_permutations(): assert set(generate_permutations('abc')) == set(['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) assert set(generate_permutations('aab')) == set(['aab', 'aba', 'baa']) assert generate_permut...
[ { "docstring": "Generate all permutations of the input string.\n\nArgs:\ninput_string (str): The string to generate permutations for.\n\nReturns:\nlist[str]: A list of all permutations of the input string.", "function_declaration": "def generate_permutations(input_string):", "function_name": "generate_p...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef generate_permutations(input_string: str) -> list[str]:\n \"\"\"\n Generate all permutations of the input string.\n\n Args:\n input_string ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010041", "row_id": 10041, "seed_ids": "['Llama-3.3-70B-Instruct_27132']" }
0.764681
Filter_10041
I
[ "generate_permutations", "is_palindrome", "find_palindrome_permutations", "main" ]
4
[ [ "find_palindrome_permutations", "generate_permutations" ], [ "find_palindrome_permutations", "is_palindrome" ] ]
2
[]
false
[]
false
pytest
true
[]
true
30680f6694875653d9b5b8c8073946f2dcc29f5f
cf08bd17bcd4426414ea2035b864e2c30097eefe
v1.0
instruct
Filter
Filter_10076_I
I am looking for a way to create a text-based adventure game in which the user can make choices and based on their input, the story unfolds accordingly. Here is an example of what I am trying to achieve: ``` You are standing at the entrance of a dark cave. There are two paths to choose from: 1. Go left 2. Go right C...
def display_message(message): """ Displays a message to the user. """ print(message) def get_user_choice(): """ Gets the user's choice and returns it as a string. """ return input("Choose a path (1/2): ") def start_game(): """ Starts the text-based adventure game. """ d...
import builtins from unittest.mock import patch from solution import start_game, display_message, get_user_choice, go_left_path, go_right_path def test_display_message(capsys): display_message("Test Message") captured = capsys.readouterr() assert captured.out == "Test Message\n" @patch('builtins.input', r...
[ { "docstring": "Displays a message to the user.", "function_declaration": "def display_message(message):", "function_name": "display_message", "parameter_list": "(message)" }, { "docstring": "Gets the user's choice and returns it as a string.", "function_declaration": "def get_user_choic...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def start_game():\n locations = {\n \"cave_entrance\": (\"You are standing at the entrance of a dark cave.\\nThere are two paths to choose from:\\n1. Go left\\n2. Go right\\n\", \n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010076", "row_id": 10076, "seed_ids": "['Llama-3.3-70B-Instruct_27202']" }
0.447985
Filter_10076
I
[ "display_message", "get_user_choice", "start_game", "go_left_path", "go_right_path" ]
5
[ [ "go_left_path", "display_message" ], [ "go_right_path", "display_message" ], [ "start_game", "display_message" ], [ "start_game", "get_user_choice" ], [ "start_game", "go_left_path" ], [ "start_game", "go_right_path" ] ]
6
[]
false
[]
false
pytest
true
[]
true
9b83a4922150efbe167bc5fd172de7cab3076c71
1ec6a6df36729024941bc2ff389b8280b7b8aed0
v1.0
instruct
Filter
Filter_10079_I
I'm looking for a way to generate a set of random hex color codes, but I need them to be grouped by hue. For example, I want to generate 20 random hex color codes, but I want 5 of them to be in the blue hue range, 5 in the green hue range, 5 in the red hue range, and 5 in the yellow hue range. Is there a way to do this...
import random def random_hex_color_by_hue(hue_range): """ Generates a random hex color within a specific hue range. Parameters: hue_range (tuple): A tuple containing the lower and upper bounds of the hue in degrees. Returns: str: A random hex color code. """ import colorsys ...
from solution import random_hex_color_by_hue, generate_grouped_hex_colors def test_random_hex_color_by_hue_range(): hue_range = (210, 270) # Blue range for _ in range(10): color = random_hex_color_by_hue(hue_range) assert len(color) == 7 # Check if hex color length is 7 assert color[0...
[ { "docstring": "Generates a random hex color within a specific hue range.\n\nParameters:\nhue_range (tuple): A tuple containing the lower and upper bounds of the hue in degrees.\n\nReturns:\nstr: A random hex color code.", "function_declaration": "def random_hex_color_by_hue(hue_range):", "function_name...
[ 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 random_hex_color_by_hue(hue_range):\n \"\"\"\n Generates a random hex color within a specific hue range.\n \n Parameters:\n hue_range (tuple): A tuple conta...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010079", "row_id": 10079, "seed_ids": "['Llama-3.3-70B-Instruct_27210']" }
0.52411
Filter_10079
I
[ "random_hex_color_by_hue", "generate_grouped_hex_colors" ]
2
[ [ "generate_grouped_hex_colors", "random_hex_color_by_hue" ] ]
1
[]
false
[]
false
pytest
true
[]
true
835af0d7d9dcecfc589f5b51c9524f1d6c77d373
5740a81b139a3f5717c1fe20c83c59e19b4c527d
v1.0
instruct
Filter
Filter_10088_I
In this task, you will create a Python program that implements a simple scheme to encrypt and decrypt messages using the Caesar Cipher method.
def caesar_cipher_encrypt(text, shift): """ Encrypts the given text using Caesar Cipher. :param text: String to be encrypted. :param shift: Number of positions to shift each character. :return: Encrypted text. """ encrypted_text = [] for char in text: if char.isalpha(): ...
from solution import caesar_cipher_encrypt, caesar_cipher_decrypt def test_caesar_cipher_encrypt(): assert caesar_cipher_encrypt("abc", 3) == "def" assert caesar_cipher_encrypt("ABC", 3) == "DEF" assert caesar_cipher_encrypt("xyz", 1) == "yza" assert caesar_cipher_encrypt("XYZ", 1) == "YZA" assert ...
[ { "docstring": "Encrypts the given text using Caesar Cipher.\n:param text: String to be encrypted.\n:param shift: Number of positions to shift each character.\n:return: Encrypted text.", "function_declaration": "def caesar_cipher_encrypt(text, shift):", "function_name": "caesar_cipher_encrypt", "par...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def caesar_encrypt(message, shift):\n \"\"\"\n Encrypts the given message using Caesar Cipher with the specified shift.\n \n Args:\n message (str): The message to be encrypted.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010088", "row_id": 10088, "seed_ids": "['Llama-3.3-70B-Instruct_27233']" }
0.66535
Filter_10088
I
[ "caesar_cipher_encrypt", "caesar_cipher_decrypt" ]
2
[ [ "caesar_cipher_decrypt", "caesar_cipher_encrypt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b07cc47a75d5a77f70d4df2baedb620ca30847ff
aac48b661d3468cacddd8c9ed6aa1957f1627723
v1.0
instruct
Filter
Filter_10122_I
I have a set of rectangles, and I need to check if any two rectangles are intersecting. The rectangles have an x, y coordinates and a width and height. Here is my code: ```python def check_intersection(rect1, rect2): # Check if two rectangles intersect if (rect1['x'] < rect2['x'] + rect2['width'] and r...
def check_intersection(rect1, rect2): """ Check if two rectangles intersect. rect1 and rect2 are dictionaries with keys: 'x', 'y', 'width', 'height'. """ if (rect1['x'] < rect2['x'] + rect2['width'] and rect1['x'] + rect1['width'] > rect2['x'] and rect1['y'] < rect2['y'] + rect2['hei...
def test_two_intersecting_rectangles(): rectangles = [ {'x': 0, 'y': 0, 'width': 2, 'height': 2}, {'x': 1, 'y': 1, 'width': 2, 'height': 2} ] assert check_all_intersections(rectangles) == True def test_two_non_intersecting_rectangles(): rectangles = [ {'x': 0, 'y': 0, 'width': 2...
[ { "docstring": "Check if two rectangles intersect.\nrect1 and rect2 are dictionaries with keys: 'x', 'y', 'width', 'height'.", "function_declaration": "def check_intersection(rect1, rect2):", "function_name": "check_intersection", "parameter_list": "(rect1, rect2)" }, { "docstring": "Check i...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_intersection(rect1, rect2):\n \"\"\"\n Check if two rectangles intersect.\n \"\"\"\n if (rect1['x'] < rect2['x'] + rect2['width'] and\n rect1['x'] + rect1['width']...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010122", "row_id": 10122, "seed_ids": "['Llama-3.3-70B-Instruct_27307']" }
0.546647
Filter_10122
I
[ "check_intersection", "check_all_intersections" ]
2
[ [ "check_all_intersections", "check_intersection" ] ]
1
[]
false
[]
false
pytest
false
[]
true
c726edb77609426dc7e8a4f7c2def1f393178213
8d2057a26b07f109c7ddbd5f28df274bb91051c1
v1.0
instruct
Filter
Filter_10126_I
I was thinking about how to tackle the problem of processing a large number of transactions. How would one approach this using Python?
import multiprocessing def process_transaction(transaction): """ Process a single transaction. This is a placeholder function and should be implemented based on actual transaction processing logic. Args: transaction (dict): A dictionary representing a transaction. Returns: str: A stri...
import multiprocessing import pytest from solution import process_transaction, process_transactions def test_process_transaction(): transaction = {"id": 1, "amount": 100} assert process_transaction(transaction) == "Processed transaction 1" def test_process_transactions(): transactions = [{"id": 1, "amoun...
[ { "docstring": "Process a single transaction.\nThis is a placeholder function and should be implemented based on actual transaction processing logic.\n\nArgs:\ntransaction (dict): A dictionary representing a transaction.\n\nReturns:\nstr: A string indicating that the transaction was processed.", "function_d...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\n\ndef process_transactions(transactions):\n \"\"\"\n Processes a large list of transactions by distributing the work across multiple CPU cores.\n \n Args:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010126", "row_id": 10126, "seed_ids": "['Llama-3.3-70B-Instruct_27313']" }
0.35985
Filter_10126
I
[ "process_transaction", "process_transactions" ]
2
[ [ "process_transactions", "process_transaction" ] ]
1
[]
false
[]
false
pytest
true
[]
true
24288401f7a9115f81950d6af5217eb6b5e768d5
634f35842cef7e9c4c612eba637716317745c028
v1.0
instruct
Filter
Filter_10188_I
I have the following code: ``` def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left, right): merged = [] left_index = 0 right_index = 0 ...
class User: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def __repr__(self): return f'{self.first_name} {self.last_name} {self.age}' def merge_sort_users(users): if len(users) <= 1: return use...
from solution import User, merge_sort_users def test_merge_sort_users_empty_list(): assert merge_sort_users([]) == [] def test_merge_sort_users_single_user(): users = [User('John', 'Doe', 30)] assert merge_sort_users(users) == users def test_merge_sort_users_sorted_list(): users = [User('Alice', 'Won...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class User:\n def __init__(self, first_name, last_name, age):\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n\n def __repr__(self):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010188", "row_id": 10188, "seed_ids": "['Llama-3.3-70B-Instruct_27441']" }
0.583252
Filter_10188
I
[ "merge_sort_users", "merge_users" ]
2
[ [ "merge_sort_users", "merge_users" ] ]
1
[]
false
[ "User" ]
true
pytest
true
[]
true
0fa7b4b409747b98177d3b6cf216f9b9335779ca
d1ad7ee1dbb5297f7f81fc938f9679b01b88fa25
v1.0
instruct
Filter
Filter_10193_I
Here is the code: ``` def get_artists_by_genre(genre): genre = genre.lower() artists = [] for artist in data['artists']: if genre in artist['genres']: artists.append(artist['name']) return artists ``` How to get the total number of unique artists that belong to the given genre? Ple...
def get_artists_by_genre(genre, data): """ Returns a list of unique artist names that belong to the given genre. :param genre: Genre to search for. :param data: Data containing artist information. :return: List of unique artist names. """ genre = genre.lower() artists = set() for ar...
import pytest from solution import get_artists_by_genre, count_unique_artists_by_genre @pytest.fixture def mock_data(): return { 'artists': [ {'name': 'Artist1', 'genres': ['rock', 'pop']}, {'name': 'Artist2', 'genres': ['jazz']}, {'name': 'Artist3', 'genres': ['rock']},...
[ { "docstring": "Returns a list of unique artist names that belong to the given genre.\n\n:param genre: Genre to search for.\n:param data: Data containing artist information.\n:return: List of unique artist names.", "function_declaration": "def get_artists_by_genre(genre, data):", "function_name": "get_a...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Assuming data is a global dictionary defined like:\ndata = {\n 'artists': [\n {'name': 'Artist1', 'genres': ['rock', 'pop']},\n {'name': 'Artist2', 'genres': ['rock', 'jazz'...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010193", "row_id": 10193, "seed_ids": "['Llama-3.3-70B-Instruct_27454']" }
0.565186
Filter_10193
I
[ "get_artists_by_genre", "count_unique_artists_by_genre" ]
2
[ [ "count_unique_artists_by_genre", "get_artists_by_genre" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d17ae77b49928d5edf62a0e7779c35c9eaa8052b
e065533e2fe9024b4280e7a1f655e21da1c56e04
v1.0
instruct
Filter
Filter_10200_I
### Reproducing a paper: "Beacon Payments: Ensuring Timely Payments in Bitcoin" The paper discusses an extension to the Bitcoin protocol to enable more timely payments. The main idea is to assign a "beacon" to each block, which is used to prove that a certain number of blocks have been mined after a given block. This a...
import random import numpy as np import matplotlib.pyplot as plt def simulate_block_creation(rate, duration): """ Simulate block creation using a Poisson distribution. """ return np.cumsum(np.random.poisson(rate, duration)) def calculate_confirmation_time(block_times, k): confirmation_times = [] for ...
from solution import simulate_beacon_payment_system, plot_average_waiting_times def test_simulate_beacon_payment_system(): k_values = [1, 2, 3, 5, 10] block_rate = 600 # Average time in seconds between blocks (10 minutes) simulation_duration = 1000 # Number of blocks to simulate ks, avg_times = simu...
[ { "docstring": "Simulate block creation using a Poisson distribution. ", "function_declaration": "def simulate_block_creation(rate, duration):", "function_name": "simulate_block_creation", "parameter_list": "(rate, duration)" }, { "docstring": null, "function_declaration": "def calculate...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef simulate_beacon_system(mean_block_time, simulation_time, k_values):\n np.random.seed(0) # For reproducibility\n \n # Poisso...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010200", "row_id": 10200, "seed_ids": "['Llama-3.3-70B-Instruct_27471']" }
0.490895
Filter_10200
I
[ "simulate_block_creation", "calculate_confirmation_time", "simulate_beacon_payment_system", "plot_average_waiting_times" ]
4
[ [ "simulate_beacon_payment_system", "calculate_confirmation_time" ], [ "simulate_beacon_payment_system", "simulate_block_creation" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
95d49f656e5d82bce0c859eb2751b6dcbfbc568d
c344be589696b594bd9ee912513afcf47a267cfe
v1.0
instruct
Filter
Filter_10211_I
Here is the Python code I have written so far for a Rock Paper Scissors game: ``` import random def get_computer_choice(): choices = ["rock", "paper", "scissors"] return random.choice(choices) def get_user_choice(): user_choice = input("Please enter a choice (rock, paper, scissors): ") while user_choi...
import random def get_computer_choice(): choices = ["rock", "paper", "scissors"] return random.choice(choices) def get_user_choice(): user_choice = input("Please enter a choice (rock, paper, scissors): ") while user_choice not in ["rock", "paper", "scissors"]: user_choice = input("Invalid choi...
import pytest from unittest.mock import patch from solution import get_computer_choice, get_user_choice, determine_winner, play_game def test_determine_winner(): assert determine_winner("rock", "scissors") == "You win!" assert determine_winner("scissors", "paper") == "You win!" assert determine_winner("pap...
[ { "docstring": null, "function_declaration": "def get_computer_choice():", "function_name": "get_computer_choice", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def get_user_choice():", "function_name": "get_user_choice", "parameter_list": "()" }, { ...
[ 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_computer_choice():\n choices = [\"rock\", \"paper\", \"scissors\"]\n return random.choice(choices)\n\ndef get_user_choice():\n user_choice = input(\"Please en...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010211", "row_id": 10211, "seed_ids": "['Llama-3.3-70B-Instruct_27488']" }
0.525615
Filter_10211
I
[ "get_computer_choice", "get_user_choice", "determine_winner", "play_game" ]
4
[ [ "play_game", "determine_winner" ], [ "play_game", "get_computer_choice" ], [ "play_game", "get_user_choice" ] ]
3
[]
false
[]
false
pytest
true
[]
true
89237ab27d0e9b327df4ea6e9a6ee37289fa5272
b29d42a118024a46323d1c4b44100491fd4bbd74
v1.0
instruct
Filter
Filter_10225_I
You've been tasked with writing a Python function `find_closest_pair` that takes a list of points in n-dimensional space as input and returns the pair of points that have the closest Euclidean distance between them.
import math from itertools import combinations def euclidean_distance(point1, point2): """ Calculate the Euclidean distance between two points in n-dimensional space. """ return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2))) def find_closest_pair(points): """ Find the pair of poi...
from solution import find_closest_pair def test_find_closest_pair_two_points(): points = [(0, 0), (1, 1)] assert find_closest_pair(points) == ((0, 0), (1, 1)) def test_find_closest_pair_multiple_points(): points = [(1, 2), (2, 3), (3, 4), (10, 10)] assert find_closest_pair(points) == ((1, 2), (2, 3)) ...
[ { "docstring": "Calculate the Euclidean distance between two points in n-dimensional space.", "function_declaration": "def euclidean_distance(point1, point2):", "function_name": "euclidean_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Find the pair of points that have th...
[ 0, 0, 1 ]
1
medium
0.333
{ "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(point1, point2):\n \"\"\"Calculate the Euclidean distance between two points in n-dimensional space.\"\"\"\n ret...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010225", "row_id": 10225, "seed_ids": "['Llama-3.3-70B-Instruct_27524']" }
0.665417
Filter_10225
I
[ "euclidean_distance", "find_closest_pair" ]
2
[ [ "find_closest_pair", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
572865ae7734f261c316ec1aead4ca6d4bc82de3
5c89681fc0eceac315b8ff7193a4885219b694e8
v1.0
instruct
Filter
Filter_10228_I
Here is the code: ``` def total_tips(tips): """Return the total tips for a given list of tips""" return sum(tips) ``` However, I need to add another function to calculate the average tip given a list of tips, and also include a function to calculate the percentage of tips above a certain limit. What would be th...
def total_tips(tips): """Return the total tips for a given list of tips""" return sum(tips) def calc_average_tip(tips): """Return the average tip given a list of tips""" if not tips: return 0 return total_tips(tips) / len(tips) def calc_percent_tips_above(tips, limit): """Return the pe...
from solution import total_tips, calc_average_tip, calc_percent_tips_above def test_total_tips(): assert total_tips([1.0, 2.0, 3.0]) == 6.0 assert total_tips([]) == 0 def test_calc_average_tip(): assert calc_average_tip([1.0, 2.0, 3.0]) == 2.0 assert calc_average_tip([5.0, 5.0, 5.0, 5.0]) == 5.0 a...
[ { "docstring": "Return the total tips for a given list of tips", "function_declaration": "def total_tips(tips):", "function_name": "total_tips", "parameter_list": "(tips)" }, { "docstring": "Return the average tip given a list of tips", "function_declaration": "def calc_average_tip(tips)...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def total_tips(tips):\n \"\"\"Return the total tips for a given list of tips\"\"\"\n return sum(tips)\n\ndef calc_average_tip(tips):\n \"\"\"Return the average tip given a list of tip...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010228", "row_id": 10228, "seed_ids": "['Llama-3.3-70B-Instruct_27528']" }
0.526372
Filter_10228
I
[ "total_tips", "calc_average_tip", "calc_percent_tips_above" ]
3
[ [ "calc_average_tip", "total_tips" ] ]
1
[]
false
[]
false
pytest
true
[]
true
276ae304d58b0bf59e00b34ca88bfb67337517e3
f7ae74f67b239a962394ac7919257ffb564b07d4
v1.0
instruct
Filter
Filter_10320_I
Can you write a code that runs indefinitely until the program is stopped, allowing a user to input a number and then displays the prime factors of the number?
def prime_factors(n): """ Returns a list of prime factors of the given number n. """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors def run(): ...
from solution import prime_factors def test_prime_factors(): assert prime_factors(10) == [2, 5] assert prime_factors(20) == [2, 2, 5] assert prime_factors(13) == [13] assert prime_factors(1) == [] assert prime_factors(100) == [2, 2, 5, 5] assert prime_factors(37) == [37] assert prime_factor...
[ { "docstring": "Returns a list of prime factors of the given number n.", "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": "Runs an infinite loop that takes user input for a number and prints the prime factors.", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def prime_factors(n):\n \"\"\"\n Returns the prime factors of the given number n.\n \"\"\"\n factors = []\n d = 2\n while n >= d:\n if n % d == 0:\n factors...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010320", "row_id": 10320, "seed_ids": "['Llama-3.3-70B-Instruct_27727']" }
0.538229
Filter_10320
I
[ "prime_factors", "run" ]
2
[ [ "run", "prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
decc5881b9f1734320f2d5b34b7c33c476255299
7b173a6b07e1e673e16cd0cda4cb0a89e5254910
v1.0
instruct
Filter
Filter_10322_I
I understand that there is no formula for the nth prime number, but I am looking for an algorithm to find it. Can you provide a simple algorithm in Python to find the nth prime number?
def is_prime(num): """ Helper function to check if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return F...
from solution import nth_prime def test_first_prime(): assert nth_prime(1) == 2 def test_second_prime(): assert nth_prime(2) == 3 def test_third_prime(): assert nth_prime(3) == 5 def test_tenth_prime(): assert nth_prime(10) == 29 def test_twenty_fifth_prime(): assert nth_prime(25) == 97
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Function to find the nth prime number.", "function_declaration": "def nth_prime(n):", "function_nam...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 ==...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010322", "row_id": 10322, "seed_ids": "['Llama-3.3-70B-Instruct_27730']" }
0.606884
Filter_10322
I
[ "is_prime", "nth_prime" ]
2
[ [ "nth_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b967fdb62613e909975990d03cf35144557b4e8b
cbb5d1acc5050986e909ec4e0a3256cf715b5c2f
v1.0
instruct
Filter
Filter_10370_I
Here's a list of algorithms and data structures with their time complexities: 1. Merge Sort: O(n log n) 2. Bubble Sort: O(n^2) 3. Binary Search: O(log n) 4. Linear Search: O(n) 5. Hash Table: O(1) average case, O(n) worst case 6. Stack: O(1) for push and pop operations 7. Queue: O(1) for enqueue and dequeue operations ...
def merge_sort(arr): if len(arr) > 1: mid = len(arr)//2 left_half = arr[:mid] right_half = arr[mid:] merge_sort(left_half) merge_sort(right_half) i = j = k = 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: ...
from solution import merge_sort, binary_search, sort_and_search def test_merge_sort(): assert merge_sort([4, 2, 5, 3, 2, 4, 3, 2]) == [2, 2, 2, 3, 3, 4, 4, 5] assert merge_sort([1, 3, 2]) == [1, 2, 3] assert merge_sort([]) == [] assert merge_sort([5, 5, 5]) == [5, 5, 5] def test_binary_search(): s...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def binary_search(arr, target):", "function_name": "binary_search", "parameter_list": "(arr, target)" }...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n\n merge_sort(left_half)\n merge_sort(righ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010370", "row_id": 10370, "seed_ids": "['Llama-3.3-70B-Instruct_27852']" }
0.484169
Filter_10370
I
[ "merge_sort", "binary_search", "sort_and_search" ]
3
[ [ "sort_and_search", "binary_search" ], [ "sort_and_search", "merge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
75b9ce02e6406cb9e69d4786b1f60aaf9f9b703f
d6b670cd62b22729b094a99dcf5f02d3ac0dcd76
v1.0
instruct
Filter
Filter_10397_I
### Introduction The project involves the redesign of an existing parking system to improve its efficiency and user experience. The existing system uses a simple ticket-based mechanism where users pay for parking spots based on the time they use. However, this system has several drawbacks, including long queues, diffic...
import math class ParkingSpot: def __init__(self, spot_id, location, is_available, spot_type): self.spot_id = spot_id self.location = location self.is_available = is_available self.spot_type = spot_type # Type of the parking spot, e.g., 'handicapped', 'compact', 'regular' class Us...
import pytest from solution import ParkingSpot, User, calculate_distance, allocate_parking_spot def test_calculate_distance(): assert calculate_distance((0, 0), (3, 4)) == 5.0 assert calculate_distance((1, 1), (1, 1)) == 0.0 def test_allocate_parking_spot(): parking_spots = [ ParkingSpot(1, (0...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\nclass ParkingSpot:\n def __init__(self, spot_id, location, is_available, is_covered=False, has_ev_charger=False):\n self.spot_id = spot_id\n self.location = loc...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010397", "row_id": 10397, "seed_ids": "['Llama-3.3-70B-Instruct_27920']" }
0.366115
Filter_10397
I
[ "calculate_distance", "allocate_parking_spot" ]
2
[ [ "allocate_parking_spot", "calculate_distance" ] ]
1
[]
false
[ "ParkingSpot", "User" ]
true
pytest
true
[]
true
524ce2a0889e5b141445ed0f564b2e9260702f14
31a29b40e690a482be92f15ff4b83775f8d5cf0d
v1.0
instruct
Filter
Filter_10402_I
I've been given a large dataset of text documents and I'm interested in performing topic modeling on them using Latent Dirichlet Allocation (LDA). I'm a Python programmer and I would like to use the popular `scikit-learn` library, which has an implementation of LDA. However, I've noticed that `scikit-learn`'s LDA imple...
from sklearn.decomposition import LatentDirichletAllocation from sklearn.feature_extraction.text import CountVectorizer from joblib import Parallel, delayed import numpy as np def parallel_fit_lda(data_chunk, n_topics, max_iter, random_state): """ Fits LDA model to a chunk of data. """ vectorizer = Cou...
from solution import parallel_fit_lda, fit_parallel_lda import pytest def test_parallel_fit_lda(): data = ["This is the first document.", "This document is the second document.", "And this is the third one."] n_topics = 2 max_iter = 10 random_state = 42 model, vectorizer = parallel_fit_lda(data, n_...
[ { "docstring": "Fits LDA model to a chunk of data.", "function_declaration": "def parallel_fit_lda(data_chunk, n_topics, max_iter, random_state):", "function_name": "parallel_fit_lda", "parameter_list": "(data_chunk, n_topics, max_iter, random_state)" }, { "docstring": "Fits LDA model in par...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom joblib import Parallel, delayed\nimport numpy as np\n\ndef parall...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010402", "row_id": 10402, "seed_ids": "['Llama-3.3-70B-Instruct_27939']" }
0.368599
Filter_10402
I
[ "parallel_fit_lda", "fit_parallel_lda" ]
2
[ [ "fit_parallel_lda", "parallel_fit_lda" ] ]
1
[]
false
[]
false
pytest
true
[ "joblib", "numpy", "sklearn" ]
false
8355963d15be73ca149aa82cad76be0efddd5d93
6f256f8df81360a23b58567febde8d50e6280d75
v1.0
instruct
Filter
Filter_10454_I
Here is the Python solution for the problem. ```python def calculate_gcd(a, b): while b != 0: a, b = b, a % b return a def find_lcm(a, b): gcd = calculate_gcd(a, b) return abs(a * b) // gcd def find_gcf_lcm(a, b): return calculate_gcd(a, b), find_lcm(a, b) ``` The code provided is calculat...
def calculate_gcd(a, b): while b != 0: a, b = b, a % b return a def find_lcm(a, b): gcd = calculate_gcd(a, b) return abs(a * b) // gcd def find_gcf_lcm(a, b): return calculate_gcd(a, b), find_lcm(a, b)
from solution import calculate_gcd, find_lcm, find_gcf_lcm def test_calculate_gcd(): assert calculate_gcd(54, 24) == 6 assert calculate_gcd(48, 180) == 12 assert calculate_gcd(100, 10) == 10 assert calculate_gcd(7, 3) == 1 assert calculate_gcd(0, 5) == 5 def test_find_lcm(): assert find_lcm(4,...
[ { "docstring": null, "function_declaration": "def calculate_gcd(a, b):", "function_name": "calculate_gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def find_lcm(a, b):", "function_name": "find_lcm", "parameter_list": "(a, b)" }, { "docst...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_gcd(a, b):\n \"\"\"\n Calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.\n \"\"\"\n while b != 0:\n a, b = b, a % b\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010454", "row_id": 10454, "seed_ids": "['Llama-3.3-70B-Instruct_28048']" }
0.725732
Filter_10454
I
[ "calculate_gcd", "find_lcm", "find_gcf_lcm" ]
3
[ [ "find_gcf_lcm", "calculate_gcd" ], [ "find_gcf_lcm", "find_lcm" ], [ "find_lcm", "calculate_gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
ff2b14b164d5658368dd7aa5bb2536d799c412ae
1f6332d60d3d197fac328b59993512d368f5e019
v1.0
instruct
Filter
Filter_10466_I
I have a function in python that draws a square on a 2D grid. Now I want to animate this function so it looks like the square is bouncing around the grid. Here are the basics of the function: ``` import matplotlib.pyplot as plt import matplotlib.patches as patches def draw_square(x, y): # Create a new figure ...
import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.animation import FuncAnimation # Function to draw a square on a 2D grid and update its position def draw_square(ax, x, y): square = patches.Rectangle((x, y), 1, 1, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(squ...
import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.animation import FuncAnimation from solution import draw_square def test_draw_square(): fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(0, 10) ax.set_aspect('equal') square = draw_square(ax, 1, 1) ...
[ { "docstring": null, "function_declaration": "def draw_square(ax, x, y):", "function_name": "draw_square", "parameter_list": "(ax, x, y)" }, { "docstring": null, "function_declaration": "def animate_square():", "function_name": "animate_square", "parameter_list": "()" }, { ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.animation as animation\n\ndef draw_animated_square():\n fig, ax = plt.subplots()\n ax.set_xlim(0,...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010466", "row_id": 10466, "seed_ids": "['Llama-3.3-70B-Instruct_28085']" }
0.419673
Filter_10466
I
[ "draw_square", "animate_square" ]
2
[ [ "animate_square", "draw_square" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
d5336a6399e5b26bd57a220a0d2d036afe99dd02
911d6676aa2c5532d9db47c6dbf1583dc4c29931
v1.0
instruct
Filter
Filter_10484_I
Okay, I'll try to be clear. I'm trying to write a program to generate a maze. I want to create a maze where the start and end points are against the outer edges of the maze. Specifically, I want the start point to be randomly located on the top edge of the maze and the end point to be randomly located on the bottom edg...
import random class Cell: def __init__(self, x, y): self.x = x self.y = y self.visited = False self.walls = {'north': True, 'south': True, 'east': True, 'west': True} def make_maze(width, height): cells = [[Cell(x, y) for y in range(height)] for x in range(width)] # Ra...
import pytest from solution import make_maze, Cell def test_maze_dimensions(): width, height = 21, 11 maze, start, end = make_maze(width, height) assert len(maze) == width assert len(maze[0]) == height def test_start_position(): width, height = 21, 11 maze, start, _ = make_maze(width, height) ...
[]
[ 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\nclass Cell:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.visited = False\n self.walls = {'north': True, 'south': True, 'east': T...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010484", "row_id": 10484, "seed_ids": "['Llama-3.3-70B-Instruct_28128']" }
0.55098
Filter_10484
I
[ "make_maze", "get_unvisited_neighbors", "remove_walls" ]
3
[ [ "make_maze", "get_unvisited_neighbors" ], [ "make_maze", "remove_walls" ] ]
2
[]
false
[ "Cell" ]
true
pytest
true
[]
true
b6bde0b6fa7851c5e88202dddfda1d362b9810bd
7fd9897609202130050c333187f81934fbb240b2
v1.0
instruct
Filter
Filter_10488_I
I have a list of integers in a text file, one integer per line. I need a Python script to read the list, calculate the sum of all the integers, and then write the sum to a new file. Here's an example of what the input file might look like: ``` 2 4 6 8 10 ``` And the output file should contain just the sum: ``` 30 `...
def read_integers_from_file(input_file): """ Reads integers from a file, one per line. """ with open(input_file, 'r') as file: numbers = file.readlines() return [int(number.strip()) for number in numbers] def write_sum_to_file(output_file, total): """ Writes the sum to a file. "...
import os from solution import read_integers_from_file, write_sum_to_file, sum_integers_in_file def test_read_integers_from_file(tmp_path): input_file = tmp_path / "input.txt" input_file.write_text("1\n2\n3\n4\n5\n") numbers = read_integers_from_file(input_file) assert numbers == [1, 2, 3, 4,...
[ { "docstring": "Reads integers from a file, one per line.", "function_declaration": "def read_integers_from_file(input_file):", "function_name": "read_integers_from_file", "parameter_list": "(input_file)" }, { "docstring": "Writes the sum to a file.", "function_declaration": "def write_s...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_sum(input_file, output_file):\n \"\"\"\n Reads integers from the input file, calculates the sum, and writes the result to the output file.\n \n Parameters:\n - inp...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010488", "row_id": 10488, "seed_ids": "['Llama-3.3-70B-Instruct_28136']" }
0.520747
Filter_10488
I
[ "read_integers_from_file", "write_sum_to_file", "sum_integers_in_file" ]
3
[ [ "sum_integers_in_file", "read_integers_from_file" ], [ "sum_integers_in_file", "write_sum_to_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
17b83ec4b9804c48c63f60bbaebec7819320e6d3
5c5cd5a12ec931f113bcb535f43464cd14a158bf
v1.0
instruct
Filter
Filter_10540_I
I am a beginner in programming and I am trying to learn Python. I have a beginner's course on Python programming and I am currently on the "Advanced Python" section of the course. I just finished learning about decorators in Python. I use a Python IDE like PyCharm. I can write basic Python scripts. I am having troub...
import time from functools import wraps def timer_decorator(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds") ...
import pytest from solution import sample_function, log_decorator, timer_decorator, role_required def test_sample_function_correct_role(): assert sample_function(1, 2, role='admin') == 3 def test_sample_function_incorrect_role(): with pytest.raises(PermissionError): sample_function(1, 2, role='user') ...
[ { "docstring": null, "function_declaration": "def timer_decorator(func):", "function_name": "timer_decorator", "parameter_list": "(func)" }, { "docstring": null, "function_declaration": "def log_decorator(func):", "function_name": "log_decorator", "parameter_list": "(func)" }, ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport functools\n\n# 1. Logging Function Calls\ndef log_function_call(func):\n \"\"\"\n A decorator that logs function call details\n \"\"\"\n @functools.wraps(func)\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010540", "row_id": 10540, "seed_ids": "['Llama-3.3-70B-Instruct_28265']" }
0.341641
Filter_10540
I
[ "timer_decorator", "log_decorator", "role_required", "sample_function" ]
4
[ [ "sample_function", "role_required" ] ]
1
[]
false
[]
false
pytest
true
[]
true
34662da61d1f00a242cca5c2c56b878846ee27ef
32e1c12bdcf053d9df7806cb7fd4663957a3bb01
v1.0
instruct
Filter
Filter_10543_I
Here is a problem I am working on: For each integer n ≥ 2, the function f(n) is defined as the smallest positive integer k such that n is a factor of k!. Here, k! denotes the factorial of k, which is the product of all positive integers less than or equal to k. For example, f(6) = 3 because 6 is a factor of 3! (which...
import math def find_f(n): """ Returns the smallest positive integer k such that n is a factor of k!. """ k = 1 while True: if math.factorial(k) % n == 0: return k k += 1 def find_f_range(a, b): """ For a given range [a, b], returns a dictionary of values of the...
from solution import find_f, find_f_range def test_find_f(): assert find_f(2) == 2 assert find_f(6) == 3 assert find_f(7) == 7 assert find_f(8) == 4 assert find_f(3) == 3 def test_find_f_range(): result = find_f_range(2, 7) expected = { 2: 2, 3: 3, 4: 4, 5: ...
[ { "docstring": "Returns the smallest positive integer k such that n is a factor of k!.", "function_declaration": "def find_f(n):", "function_name": "find_f", "parameter_list": "(n)" }, { "docstring": "For a given range [a, b], returns a dictionary of values of the form {n: f(n)}.", "func...
[ 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\ndef find_f(n):\n k = 1\n while True:\n if math.factorial(k) % n == 0:\n return k\n k += 1\n\ndef find_f_range(a, b):\n \"\"\"\n Find the fun...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010543", "row_id": 10543, "seed_ids": "['Llama-3.3-70B-Instruct_28272']" }
0.600591
Filter_10543
I
[ "find_f", "find_f_range" ]
2
[ [ "find_f_range", "find_f" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7fea86cd9686faeef74b6c93095fbf73e73c3bd3
f2d9d9880b7f1065e4181e93aba0bb9a12632b8a
v1.0
instruct
Filter
Filter_10546_I
I've been tasked with creating a script that can identify duplicate files in a given directory and its subdirectories. The script should be able to identify duplicates based on file content, not just filename. Could you provide an example of how I could implement this in Python?
import os import hashlib def get_file_hash(file_path, block_size=65536): """ Returns the SHA-256 hash of the file. """ hasher = hashlib.sha256() with open(file_path, 'rb') as file: while True: data = file.read(block_size) if not data: break ...
import os import tempfile from solution import get_file_hash, find_duplicate_files def test_get_file_hash(): with tempfile.NamedTemporaryFile(delete=False) as tmp_file: tmp_file.write(b'Test data.') tmp_file_path = tmp_file.name expected_hash = hashlib.sha256(b'Test data.').hexdigest() asse...
[ { "docstring": "Returns the SHA-256 hash of the file.", "function_declaration": "def get_file_hash(file_path, block_size=65536):", "function_name": "get_file_hash", "parameter_list": "(file_path, block_size=65536)" }, { "docstring": "Identifies duplicate files in the given directory and its ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport hashlib\n\ndef calculate_hash(file_path, chunk_size=1024):\n \"\"\"Calculate the MD5 hash of a file.\"\"\"\n hash_md5 = hashlib.md5()\n try:\n with open(file_...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010546", "row_id": 10546, "seed_ids": "['Llama-3.3-70B-Instruct_28277']" }
0.609946
Filter_10546
I
[ "get_file_hash", "find_duplicate_files" ]
2
[ [ "find_duplicate_files", "get_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
963da0162a845389f07bdd0818e1abfaafc0b220
02c2f1bb5d967166d330be0bb5c9561423f83953
v1.0
instruct
Filter
Filter_10548_I
Here's a problem: Write a program that takes two commands as input from the user, each command can be either one of the following: 'create', 'read', 'update', 'delete', 'list' And depending on the command, the program will perform the corresponding action on a dictionary. For example, if the user enters 'create', th...
def create(data, key, value): """ Adds a key-value pair to the dictionary. """ data[key] = value return "Item created" def read(data, key): """ Returns the value for the given key in the dictionary. """ if key in data: return data[key] else: return "Key not found...
def test_create(): data = {} result = create(data, "name", "Alice") assert result == "Item created" assert data == {"name": "Alice"} def test_read_existing_key(): data = {"name": "Alice"} result = read(data, "name") assert result == "Alice" def test_read_non_existing_key(): data = {"na...
[ { "docstring": "Adds a key-value pair to the dictionary.", "function_declaration": "def create(data, key, value):", "function_name": "create", "parameter_list": "(data, key, value)" }, { "docstring": "Returns the value for the given key in the dictionary.", "function_declaration": "def r...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create(data, key, value):\n \"\"\"\n Adds a key-value pair to the dictionary.\n \"\"\"\n data[key] = value\n return \"Item created\"\n\ndef read(data, key):\n \"\"\"\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010548", "row_id": 10548, "seed_ids": "['Llama-3.3-70B-Instruct_28279']" }
0.53506
Filter_10548
I
[ "create", "read", "update", "delete", "list_items", "process_command", "main" ]
7
[ [ "process_command", "create" ], [ "process_command", "delete" ], [ "process_command", "list_items" ], [ "process_command", "read" ], [ "process_command", "update" ] ]
5
[]
false
[]
false
pytest
false
[]
true
d9134da082b46a9453b95ca637881045c61d647c
26844bf3b4a326684d3d957a30b79fbdac77f1be
v1.0
instruct
Filter
Filter_10552_I
I've been playing with the idea of implementing a recursive algorithm to solve a specific problem. I want to know what the base case should be, how to make the recursive call, and how to handle the results of the recursive call. Here's a simple example of a recursive algorithm in Python to get us started: ```python d...
def max_crossing_sum(arr, low, mid, high): sum_left = float('-inf') sum_now = 0 for i in range(mid, low - 1, -1): sum_now += arr[i] if sum_now > sum_left: sum_left = sum_now sum_right = float('-inf') sum_now = 0 for j in range(mid + 1, high + 1): sum_now += a...
from solution import find_max_sum_subarray def test_example_case(): assert find_max_sum_subarray([-2, -3, 4, -1, -2, 1, 5, -3]) == 7 def test_all_negative_numbers(): assert find_max_sum_subarray([-8, -3, -6, -2, -5, -4]) == -2 def test_all_positive_numbers(): assert find_max_sum_subarray([2, 3, 4, 5, 7])...
[ { "docstring": null, "function_declaration": "def max_crossing_sum(arr, low, mid, high):", "function_name": "max_crossing_sum", "parameter_list": "(arr, low, mid, high)" }, { "docstring": null, "function_declaration": "def max_subarray_sum(arr, low, high):", "function_name": "max_sub...
[ 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": "def max_crossing_sum(arr, low, mid, high):\n sum_left = float('-inf')\n sum_now = 0\n for i in range(mid, low - 1, -1):\n sum_now += arr[i]\n if...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010552", "row_id": 10552, "seed_ids": "['Llama-3.3-70B-Instruct_28285']" }
0.554495
Filter_10552
I
[ "max_crossing_sum", "max_subarray_sum", "find_max_sum_subarray" ]
3
[ [ "find_max_sum_subarray", "max_subarray_sum" ], [ "max_subarray_sum", "max_crossing_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
efe4a4c09c9c57c19c528a1fd2320388eae3d16d
90c91c49027f14d623c895ae551036d3f24d2786
v1.0
instruct
Filter
Filter_10579_I
### Building a Calculator #### Problem Statement Create a Python program to simulate a simple calculator. The calculator should support addition, subtraction, multiplication, and division operations. #### Requirements * The program should be able to accept two numbers and an operation as input from the user. * The...
def add(x, y): """Return the sum of x and y""" return x + y def subtract(x, y): """Return the difference of x and y""" return x - y def multiply(x, y): """Return the product of x and y""" return x * y def divide(x, y): """Return the quotient of x and y""" if y == 0: raise Zero...
from solution import add, subtract, multiply, divide, calculator def test_add(): assert add(1, 2) == 3 assert add(-1, 1) == 0 assert add(-1, -1) == -2 assert add(1.5, 2.5) == 4.0 def test_subtract(): assert subtract(2, 1) == 1 assert subtract(1, 1) == 0 assert subtract(1, -1) == 2 asse...
[ { "docstring": "Return the sum of x and y", "function_declaration": "def add(x, y):", "function_name": "add", "parameter_list": "(x, y)" }, { "docstring": "Return the difference of x and y", "function_declaration": "def subtract(x, y):", "function_name": "subtract", "parameter_li...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add(x, y):\n \"\"\"Return the sum of x and y\"\"\"\n return x + y\n\ndef subtract(x, y):\n \"\"\"Return the difference of x and y\"\"\"\n return x - y\n\ndef multiply(x, y):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010579", "row_id": 10579, "seed_ids": "['Llama-3.3-70B-Instruct_28333']" }
0.616946
Filter_10579
I
[ "add", "subtract", "multiply", "divide", "calculator" ]
5
[ [ "calculator", "add" ], [ "calculator", "divide" ], [ "calculator", "multiply" ], [ "calculator", "subtract" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2c3a7a0b7afef493dc65336d4f30e58bebc28f61
d1d20831147e20c6f10179356619de6a28efe9da
v1.0
instruct
Filter
Filter_10590_I
Your goal is to write a code that will create a 5x5 grid with randomly distributed 1's and 0's, then have a function to change a cell to a 1 if it has at least 3 adjacent cells (including diagonals) that are 1's. If that condition is met, then change the cell to a 1 in the original grid. Here is the code I was workin...
import random def generate_grid(): grid = [[random.randint(0, 1) for _ in range(5)] for _ in range(5)] return grid def print_grid(grid): for row in grid: print(' '.join(map(str, row))) def check_adjacent_cells(grid, row, col): adjacent_cells = [] for i in range(max(0, row-1), min(5, row+2...
from solution import generate_grid, apply_rule_until_stable, print_grid def test_all_zeros_grid(): grid = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] updated_grid = apply_rule_until_stable(grid) for row in updated_gri...
[ { "docstring": null, "function_declaration": "def generate_grid():", "function_name": "generate_grid", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def print_grid(grid):", "function_name": "print_grid", "parameter_list": "(grid)" }, { "docstring...
[ 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 generate_grid():\n grid = [[random.randint(0, 1) for _ in range(5)] for _ in range(5)]\n return grid\n\ndef print_grid(grid):\n for row in grid:\n print(' ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010590", "row_id": 10590, "seed_ids": "['Llama-3.3-70B-Instruct_28360']" }
0.59811
Filter_10590
I
[ "generate_grid", "print_grid", "check_adjacent_cells", "update_grid", "apply_rule_until_stable" ]
5
[ [ "apply_rule_until_stable", "update_grid" ], [ "update_grid", "check_adjacent_cells" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b99f862fd282365e71d79c07e9c69034b6b76c0d
0ca234bb6f37fa4b77cf22c39a5f9330dcf3640a
v1.0
instruct
Filter
Filter_10611_I
I have a network with a mix of IPv4 and IPv6 addresses. I'm trying to write a script that pings a list of hosts and only logs the ones that are reachable. How can I implement this using Python?
import subprocess def ping(host): """ Returns True if the host is reachable, False otherwise. """ try: args = ["ping", "-c", "1", "-W", "1", host] result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return result.returncode == 0 except Exception as ...
from solution import ping, filter_reachable_hosts def test_ping_reachable_host(monkeypatch): def mock_run(*args, **kwargs): class MockResult: returncode = 0 return MockResult() monkeypatch.setattr(subprocess, 'run', mock_run) assert ping('192.168.1.1') == True def test_pin...
[ { "docstring": "Returns True if the host is reachable, False otherwise.", "function_declaration": "def ping(host):", "function_name": "ping", "parameter_list": "(host)" }, { "docstring": "Given a list of hosts, returns a list of reachable hosts.", "function_declaration": "def filter_reac...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import subprocess\n\ndef ping(host):\n \"\"\"\n Returns True if the host is reachable, False otherwise.\n \"\"\"\n try:\n args = [\"ping\", \"-c\", \"1\", \"-W\", \"1\", hos...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010611", "row_id": 10611, "seed_ids": "['Llama-3.3-70B-Instruct_28404']" }
0.674841
Filter_10611
I
[ "ping", "filter_reachable_hosts" ]
2
[ [ "filter_reachable_hosts", "ping" ] ]
1
[]
false
[]
false
pytest
true
[]
true
345fb86954c25fb3950daa2183dcead955706bec
3ffcbcd554acd814694d927445a144f6d30835ba
v1.0
instruct
Filter
Filter_10656_I
Here's a simple code that updates an integer value and sometimes skips updating it. The value is updated by adding a random number between -1 and 1. However, the update is skipped if the new value would exceed a specified range of -10 to 10. ```python import random def update_value(current_value): new_value = cu...
import random import matplotlib.pyplot as plt def update_value(current_value): new_value = current_value + random.uniform(-1, 1) if -10 <= new_value <= 10: return new_value else: return current_value def plot_trajectory(start_value, steps): values = [start_value] for _ in rang...
from solution import update_value, plot_trajectory def test_update_value_within_range(): for _ in range(100): new_val = update_value(0) assert -1 <= new_val <= 1 def test_update_value_at_bounds(): for _ in range(100): upper_bound_val = update_value(10) lower_bound_val = update_...
[ { "docstring": null, "function_declaration": "def update_value(current_value):", "function_name": "update_value", "parameter_list": "(current_value)" }, { "docstring": null, "function_declaration": "def plot_trajectory(start_value, steps):", "function_name": "plot_trajectory", "p...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport matplotlib.pyplot as plt\n\ndef update_value(current_value):\n \"\"\"\n Updates the current_value by adding a random number between -1 and 1.\n If the new value ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010656", "row_id": 10656, "seed_ids": "['Llama-3.3-70B-Instruct_28515']" }
0.443383
Filter_10656
I
[ "update_value", "plot_trajectory" ]
2
[ [ "plot_trajectory", "update_value" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
04d69ddf53ee63428d8c9d9fa690b856c40e9b78
925c3637d6e6c1429c2da3e400ff2a6c17d77610
v1.0
instruct
Filter
Filter_10657_I
I have a Python function called `my_function` that takes three arguments and returns a tuple. I'd like to create a new function, `my_new_function`, that calls `my_function` and returns the first element of the tuple returned by `my_function`. Here is the code I have so far: ```python def my_function(a, b, c): re...
def my_function(a, b, c): """ Returns a tuple where the first element is the sum of a and b, and the second element is the product of a and c. """ return a + b, a * c def my_new_function(a, b, c): """ Calls my_function and returns the first element of the tuple returned by my_function. ...
from solution import my_function, my_new_function def test_my_function(): assert my_function(1, 2, 3) == (3, 3) assert my_function(0, 0, 0) == (0, 0) assert my_function(-1, 1, 2) == (0, -2) assert my_function(2, -2, -3) == (0, -6) def test_my_new_function(): assert my_new_function(1, 2, 3) == 3 ...
[ { "docstring": "Returns a tuple where the first element is the sum of a and b,\nand the second element is the product of a and c.", "function_declaration": "def my_function(a, b, c):", "function_name": "my_function", "parameter_list": "(a, b, c)" }, { "docstring": "Calls my_function and retu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def my_function(a, b, c):\n return a + b, a * c\n\ndef my_new_function(a, b, c):\n return my_function(a, b, c)[0]", "test_code": "from solution import my_function, my_new_function\n\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010657", "row_id": 10657, "seed_ids": "['Llama-3.3-70B-Instruct_28518']" }
0.56562
Filter_10657
I
[ "my_function", "my_new_function" ]
2
[ [ "my_new_function", "my_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
19b9a919c1c7f1288d70c81c9fdd158fcf75127d
ae548b96012ae76838c7d1424f5c9d064fd7d750
v1.0
instruct
Filter
Filter_10659_I
Here is a Python code snippet: ```python def foo(a, b): """Docstring for foo function.""" pass def bar(a, b): """Docstring for bar function.""" pass ``` I need to add a new function baz that will call both foo and bar functions. Here is the implementation: ```python def foo(a, b): """Docstring fo...
def foo(a, b): """ Docstring for foo function. This function currently does not perform any operation. """ pass def bar(a, b): """ Docstring for bar function. This function currently does not perform any operation. """ pass def baz(a, b): """ Docstring for baz function....
from solution import foo, bar, baz def mock_foo(a, b): global foo_called foo_called = True def mock_bar(a, b): global bar_called bar_called = True def test_baz_calls_foo_and_bar(monkeypatch): global foo_called, bar_called foo_called = False bar_called = False monkeypatch.setattr(...
[ { "docstring": "Docstring for foo function.\nThis function currently does not perform any operation.", "function_declaration": "def foo(a, b):", "function_name": "foo", "parameter_list": "(a, b)" }, { "docstring": "Docstring for bar function.\nThis function currently does not perform any ope...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def foo(a, b):\n \"\"\"Docstring for foo function.\n \n This function takes in two arguments, `a` and `b`, but currently has no implementation.\n \"\"\"\n pass\n\ndef bar(a, b):...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010659", "row_id": 10659, "seed_ids": "['Llama-3.3-70B-Instruct_28524']" }
0.536514
Filter_10659
I
[ "foo", "bar", "baz" ]
3
[ [ "baz", "bar" ], [ "baz", "foo" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7062f26a7882baaf619f05505e0bb740bd9e0611
ee7cccb29551ef586f496b4422205fa21ea7228f
v1.0
instruct
Filter
Filter_10689_I
I have a reaction-diffusion system where I'm tracking the concentration of two species, let's call them A and B, in a 1D space. The reaction term is given by: dA/dt = -k*A*B dB/dt = k*A*B The diffusion term is the second derivative of the concentration with respect to space (i.e., d^2/dx^2). For simplicity, let's ass...
import numpy as np from scipy.integrate import odeint def reaction_diffusion_system(Y, t, k, D, dx, N): # Unpack concentrations of A and B A = Y[:N] B = Y[N:] # Calculate second derivatives using finite difference d2A_dx2 = np.zeros(N) d2B_dx2 = np.zeros(N) # Apply second derivati...
import numpy as np from scipy.integrate import odeint from solution import solve_reaction_diffusion, reaction_diffusion_system def test_initial_conditions(): x, t, solution = solve_reaction_diffusion(N=10, L=1.0, T=0.1, k=1.0, D=0.1, dt=0.01) A0 = np.exp(-((x - 1.0/4)**2) / (2*(1.0/8)**2)) B0 = np.exp(-((x...
[ { "docstring": null, "function_declaration": "def reaction_diffusion_system(Y, t, k, D, dx, N):", "function_name": "reaction_diffusion_system", "parameter_list": "(Y, t, k, D, dx, N)" }, { "docstring": null, "function_declaration": "def solve_reaction_diffusion(N=100, L=10.0, T=10.0, k=1...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.integrate import odeint\n\ndef reaction_diffusion(concs, t, k, D, dx, nx):\n A, B = concs[:nx], concs[nx:]\n \n dA = np.zeros_like(A)\n dB = np.zeros...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010689", "row_id": 10689, "seed_ids": "['Llama-3.3-70B-Instruct_28600']" }
0.327587
Filter_10689
I
[ "reaction_diffusion_system", "solve_reaction_diffusion" ]
2
[ [ "solve_reaction_diffusion", "reaction_diffusion_system" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
113c8145b74ff557154938410fe9f6b608f6713a
7547630f02c80839f1626e0bb93ccb260776a315
v1.0
instruct
Filter
Filter_10697_I
I've been trying to create a basic algorithm for a Sudoku game. I've written a code that creates a random board and then attempts to solve it using backtracking. However, I'm having trouble figuring out how to implement the backtracking correctly. Here is my code so far: ```python import random def is_valid(board, r...
def is_valid(board, row, col, num): """ Checks if placing 'num' at board[row][col] is valid according to Sudoku rules. """ for x in range(9): if board[row][x] == num or board[x][col] == num: return False start_row = row - row % 3 start_col = col - col % 3 for i in range(...
from solution import is_valid, solve_sudoku, create_board def test_is_valid(): valid_board = create_board() assert is_valid(valid_board, 0, 2, 4) == True assert is_valid(valid_board, 0, 2, 5) == False def test_solve_sudoku(): board = create_board() assert solve_sudoku(board) == True def test_solv...
[ { "docstring": "Checks if placing 'num' at board[row][col] is valid according to Sudoku rules.", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Solves the Sudoku board using backtrackin...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Checks if placing 'num' at board[row][col] is valid according to Sudoku rules.\n \"\"\"\n for x in range(9):\n if board[row][x...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010697", "row_id": 10697, "seed_ids": "['Llama-3.3-70B-Instruct_28615']" }
0.479694
Filter_10697
I
[ "is_valid", "solve_sudoku", "create_board", "print_board" ]
4
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c158872ab76268b70b5421a2099715fe5588c344
acaa8899128b814fd0941fed224fc181acf575bc
v1.0
instruct
Filter
Filter_10701_I
I have a series of triples, (a, b, c), where a is a string, b is a float and c is an integer. The values of b and c are used to calculate a new value, d. The formula for calculating d is d = b * c + 1. The new value d is then used to generate a new string, e, which is the string a repeated d times. I need to generate a...
def calculate_d(b: float, c: int) -> float: """ Calculate d using the formula d = b * c + 1. Args: b (float): A float value. c (int): An integer value. Returns: float: The calculated value of d. """ return b * c + 1 def generate_string(a: str, d: float) -> str: """ Gen...
def test_calculate_d(): assert calculate_d(2.5, 3) == 8.5 assert calculate_d(1.0, 2) == 3.0 assert calculate_d(3.0, 1) == 4.0 assert calculate_d(0.0, 10) == 1.0 def test_generate_string(): assert generate_string("hello", 8.5) == "hellohellohellohellohellohellohellohello" assert generate_string(...
[ { "docstring": "Calculate d using the formula d = b * c + 1.\n\nArgs:\nb (float): A float value.\nc (int): An integer value.\n\nReturns:\nfloat: The calculated value of d.", "function_declaration": "def calculate_d(b, c):", "function_name": "calculate_d", "parameter_list": "(b, c)" }, { "doc...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_d(b: float, c: int) -> float:\n \"\"\"\n Calculate d using the formula d = b * c + 1.\n \n Args:\n b (float): A float value.\n c (int): An integer value.\n\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010701", "row_id": 10701, "seed_ids": "['Llama-3.3-70B-Instruct_28621']" }
0.558599
Filter_10701
I
[ "calculate_d", "generate_string", "process_triple", "process_triples" ]
4
[ [ "process_triple", "calculate_d" ], [ "process_triple", "generate_string" ], [ "process_triples", "process_triple" ] ]
3
[]
false
[]
false
pytest
false
[]
true
437d3868fd21008d641ac33014eff8c626551ecd
f04b72de3c45762a3cdd91d0869542f419075e87
v1.0
instruct
Filter
Filter_10816_I
I have been tasked with creating a program that will help a user maintain a list of contacts. The program should allow the user to perform the following actions: - Add a contact - Delete a contact - Update a contact - List all contacts When adding a contact, the user should be prompted to enter the contact's first nam...
class Contact: def __init__(self, first_name, last_name, phone_number, email_address): self.first_name = first_name self.last_name = last_name self.phone_number = phone_number self.email_address = email_address def contact_exists(contacts, first_name, last_name): for contact in ...
import pytest from solution import Contact, contact_exists, find_contact, add_contact, delete_contact, update_contact, list_contacts @pytest.fixture def sample_contacts(): return [ Contact("Alice", "Smith", "1234567890", "alice@example.com"), Contact("Bob", "Brown", "0987654321", "bob@example.com")...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Contact:\n def __init__(self, first_name, last_name, phone_number, email_address):\n self.first_name = first_name\n self.last_name = last_name\n self.phone_number...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010816", "row_id": 10816, "seed_ids": "['Llama-3.3-70B-Instruct_28912']" }
0.429834
Filter_10816
I
[ "contact_exists", "find_contact", "add_contact", "delete_contact", "update_contact", "list_contacts", "main" ]
7
[ [ "add_contact", "contact_exists" ], [ "delete_contact", "find_contact" ], [ "update_contact", "contact_exists" ], [ "update_contact", "find_contact" ] ]
4
[]
false
[ "Contact" ]
true
pytest
true
[]
true
7ea3103f1607e406046c643cfdadda2a90e02d39
8b7715a3f10ec6654abacee1eec234ef25986e5e
v1.0
instruct
Filter
Filter_10828_I
I've got a dataset of cities with their respective zipcodes, and I want to create a Python script to find the closest city to a given city. To determine the distance between two cities, I'll use the Haversine formula, which calculates the distance between two points on a sphere (like the Earth) given their longitudes a...
import math def haversine_distance(lat1, lon1, lat2, lon2, radius=6371): """ Calculate the Haversine distance between two coordinates (latitude, longitude) on a sphere with the given radius. """ # Convert latitude and longitude from degrees to radians lat1, lon1, lat2, lon2 = map(math.radians, ...
from solution import closest_city, haversine_distance def test_haversine_distance(): assert round(haversine_distance(40.7128, -74.0060, 34.0522, -118.2437, 6371), 2) == 3935.75 def test_closest_city(): data = { "New York": {"zipcode": "10001", "latitude": 40.7128, "longitude": -74.0060}, "Los ...
[ { "docstring": "Calculate the Haversine distance between two coordinates (latitude, longitude)\non a sphere with the given radius.", "function_declaration": "def haversine_distance(lat1, lon1, lat2, lon2, radius=6371):", "function_name": "haversine_distance", "parameter_list": "(lat1, lon1, lat2, lo...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndata = {\n \"New York\": {\"zipcode\": \"10001\", \"latitude\": 40.7128, \"longitude\": -74.0060},\n \"Los Angeles\": {\"zipcode\": \"90001\", \"latitude\": 34.0522, \"lon...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010828", "row_id": 10828, "seed_ids": "['Llama-3.3-70B-Instruct_28930']" }
0.614721
Filter_10828
I
[ "haversine_distance", "closest_city" ]
2
[ [ "closest_city", "haversine_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8bdbe59ffc40ccfef198ba9597220c6931bb2846
b473356b0b9e5eebb29b23ffc6b731589c5416c8
v1.0
instruct
Filter
Filter_10835_I
Here's a simple Python program that calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm: ``` def gcd(a, b): while b != 0: a, b = b, a % b return a ``` However, I'm looking to modify this function to also take an optional `precision` argument that, when provided, wil...
def levenshtein_distance(a, b): """ Calculate the Levenshtein distance between two numbers by comparing their string representations. """ a_str = str(a) b_str = str(b) m = len(a_str) n = len(b_str) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = ...
from solution import gcd, levenshtein_distance def test_levenshtein_distance(): assert levenshtein_distance(123, 456) == 3 assert levenshtein_distance(1234, 1243) == 2 assert levenshtein_distance(101, 1) == 2 assert levenshtein_distance(567, 567) == 0 assert levenshtein_distance(0, 123456) == 6 de...
[ { "docstring": "Calculate the Levenshtein distance between two numbers by comparing their string representations.", "function_declaration": "def levenshtein_distance(a, b):", "function_name": "levenshtein_distance", "parameter_list": "(a, b)" }, { "docstring": "Returns the greatest common di...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def gcd(a, b, precision=None):\n \"\"\"\n Calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.\n If precision is specified, it calculates the Lev...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010835", "row_id": 10835, "seed_ids": "['Llama-3.3-70B-Instruct_28947']" }
0.594962
Filter_10835
I
[ "levenshtein_distance", "gcd" ]
2
[ [ "gcd", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
54bc70932f556989fd65735c5225e5ef0054b924
144091052100ab4ab3ae929a4fd53c0460049fa5
v1.0
instruct
Filter
Filter_10854_I
I have a piece of code in python that implements the merge sort algorithm. I want to implement a binary search algorithm to find a target value in the sorted array produced by the merge sort algorithm. Here is the code: ```python def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 ...
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left, right): merged = [] left_index = 0 right_index = 0 while left_index < len(left) and ...
from solution import merge_sort, binary_search def test_merge_sort(): assert merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13] assert merge_sort([4, 3, 2, 1]) == [1, 2, 3, 4] assert merge_sort([5]) == [5] assert merge_sort([]) == [] assert merge_sort([-3, -1, -2, 0]) == [-3, -2, -1, 0] de...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" }, { "docst...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left_half = merge_sort(arr[:mid])\n right_half = merge_sort(arr[mid:])\n return merge(left_h...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010854", "row_id": 10854, "seed_ids": "['Llama-3.3-70B-Instruct_28996']" }
0.647456
Filter_10854
I
[ "merge_sort", "merge", "binary_search" ]
3
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3af6f6d30d9fc4dc97f39e5dda1bea2ee7c0ab46
e2eb6054952061e0b83ea563ae1c835110dbe796
v1.0
instruct
Filter
Filter_10908_I
Here's the problem. I need an algorithm to generate the "m" most similar colors based on a given color. The color is defined as a 3-element vector of integers in the range [0, 255], representing the red, green, and blue (RGB) components of the color, respectively. I need the algorithm to take the following inputs: 1. ...
import math from typing import List def euclidean_distance(color1: List[int], color2: List[int]) -> float: """ Calculate the Euclidean distance between two colors. Color is represented as a list of three integers [r, g, b]. """ return math.sqrt(sum((c1 - c2) ** 2 for c1, c2 in zip(color1, color2)))...
from solution import most_similar_colors, euclidean_distance def test_euclidean_distance(): assert euclidean_distance([0, 0, 0], [0, 0, 0]) == 0 assert euclidean_distance([255, 0, 0], [0, 255, 0]) == math.sqrt(255**2 + 255**2) assert euclidean_distance([128, 128, 128], [128, 128, 128]) == 0 def test_most_...
[ { "docstring": "Calculate the Euclidean distance between two colors.\nColor is represented as a list of three integers [r, g, b].", "function_declaration": "def euclidean_distance(color1, color2):", "function_name": "euclidean_distance", "parameter_list": "(color1, color2)" }, { "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\nfrom typing import List\n\ndef euclidean_distance(color1: List[int], color2: List[int]) -> float:\n \"\"\"\n Calculate the Euclidean distance between two colors.\n Color ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010908", "row_id": 10908, "seed_ids": "['Llama-3.3-70B-Instruct_29118']" }
0.482542
Filter_10908
I
[ "euclidean_distance", "most_similar_colors" ]
2
[ [ "most_similar_colors", "euclidean_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a99ba6d031734ce2a4d8eafd7bce31e8b0d1070
a908ab2b89603ffda747eb37e7394065e13e39ac
v1.0
instruct
Filter
Filter_10913_I
Here is a Python function that needs documentation: ```python def sort_and_count_inversions(a): if len(a) <= 1: return a, 0 else: mid = len(a) // 2 left, left_count = sort_and_count_inversions(a[:mid]) right, right_count = sort_and_count_inversions(a[mid:]) merged, merged...
def sort_and_count_inversions(a): """ Sorts the array 'a' and counts the number of inversions. Parameters: a (list): The list of integers to be sorted and counted for inversions. Returns: tuple: A tuple containing the sorted list and the number of inversions. """ if len(a) <= 1: ...
from solution import sort_and_count_inversions, merge_and_count def test_sort_and_count_inversions_no_inversion(): arr = [1, 2, 3, 4, 5] sorted_arr, inv_count = sort_and_count_inversions(arr) assert sorted_arr == [1, 2, 3, 4, 5] assert inv_count == 0 def test_sort_and_count_inversions_one_inversion():...
[ { "docstring": "Sorts the array 'a' and counts the number of inversions.\n\nParameters:\na (list): The list of integers to be sorted and counted for inversions.\n\nReturns:\ntuple: A tuple containing the sorted list and the number of inversions.", "function_declaration": "def sort_and_count_inversions(a):",...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sort_and_count_inversions(a):\n \"\"\"\n Sorts the input array and counts the number of inversions using a modified merge sort algorithm.\n\n Parameters:\n a (list): A list of ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010913", "row_id": 10913, "seed_ids": "['Llama-3.3-70B-Instruct_29124']" }
0.603156
Filter_10913
I
[ "sort_and_count_inversions", "merge_and_count" ]
2
[ [ "sort_and_count_inversions", "merge_and_count" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0b02630cc31d485bb8f6d9b1e2dee00b9741c47a
592bfbb9dbd53ebaa61b2b6d981f823d6b73441d
v1.0
instruct
Filter
Filter_10971_I
Can you make a script that takes two colors, converts them to their hex (if they aren't already in hex) and then outputs the hex of their average color?
def hex_to_rgb(hex_color): """Convert hexadecimal color to RGB""" hex_color = hex_color.lstrip('#') return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) def rgb_to_hex(rgb_color): """Convert RGB color to hexadecimal""" return '#{:02x}{:02x}{:02x}'.format(*rgb_color) def average_color(hex_col...
def test_hex_to_rgb(): assert hex_to_rgb('#ffffff') == (255, 255, 255) assert hex_to_rgb('#000000') == (0, 0, 0) assert hex_to_rgb('#ff0000') == (255, 0, 0) def test_rgb_to_hex(): assert rgb_to_hex((255, 255, 255)) == '#ffffff' assert rgb_to_hex((0, 0, 0)) == '#000000' assert rgb_to_hex((255, 0...
[ { "docstring": "Convert hexadecimal color to RGB", "function_declaration": "def hex_to_rgb(hex_color):", "function_name": "hex_to_rgb", "parameter_list": "(hex_color)" }, { "docstring": "Convert RGB color to hexadecimal", "function_declaration": "def rgb_to_hex(rgb_color):", "functio...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def rgb_to_hex(rgb):\n \"\"\"\n Convert an RGB tuple to a HEX string.\n \"\"\"\n return '#%02x%02x%02x' % rgb\n\ndef hex_to_rgb(hex_color):\n \"\"\"\n Convert a HEX string to...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010971", "row_id": 10971, "seed_ids": "['Llama-3.3-70B-Instruct_29251']" }
0.427803
Filter_10971
I
[ "hex_to_rgb", "rgb_to_hex", "average_color" ]
3
[ [ "average_color", "hex_to_rgb" ], [ "average_color", "rgb_to_hex" ] ]
2
[]
false
[]
false
pytest
false
[]
true
9a1b9a92466155f80ebd2d692280a96d12d33d2e
909ba1b79a6868c8a683b3af2a1fe631d51b6634
v1.0
instruct
Filter
Filter_10998_I
I have many .flac files in directories, and within those directories, some of those files are also named the same. I want to rename them to have a unique filename. My goal is to rename the files to the following format: `artist - album (discnumber) - tracknumber - trackname.flac` I'm assuming that I will have to us...
import os import subprocess def get_flac_metadata(filepath): """ Retrieve metadata from a FLAC file using metaflac. """ metadata_keys = ["ARTIST", "ALBUM", "DISCNUMBER", "TRACKNUMBER", "TITLE"] metadata = {key: '' for key in metadata_keys} try: result = subprocess.run(['metaflac', ...
import os import subprocess from unittest import mock from solution import get_flac_metadata, rename_flac_files def test_get_flac_metadata(): filepath = "dummy.flac" metaflac_output = """METADATA block #2 type: 4 (VORBIS_COMMENT) is last: false length: 620 vendor string: reference libFLAC 1.2.1...
[ { "docstring": "Retrieve metadata from a FLAC file using metaflac.", "function_declaration": "def get_flac_metadata(filepath):", "function_name": "get_flac_metadata", "parameter_list": "(filepath)" }, { "docstring": "Traverse the directory, retrieve metadata of each FLAC file,\nand rename th...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport subprocess\n\ndef get_flac_metadata(filepath):\n \"\"\" Use metaflac to extract metadata from the given FLAC file. \"\"\"\n result = subprocess.run(['metaflac', '--expo...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010998", "row_id": 10998, "seed_ids": "['Llama-3.3-70B-Instruct_29298']" }
0.620778
Filter_10998
I
[ "get_flac_metadata", "rename_flac_files" ]
2
[ [ "rename_flac_files", "get_flac_metadata" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1ac6d3452cfd7c0e9398091b0a8a369a301791a
1cc49f95cdc49047e5db224bc2fc15af0e6defab
v1.0
instruct
Filter
Filter_11032_I
I have a long list of numbers, and I want to find the number of pairs of distinct elements that have a certain property (let's call it "being harmonious"). Two numbers are harmonious if the sum of their digits is equal to the sum of the digits of their product. For example, 23 and 34 are harmonious because: - The sum ...
def sum_of_digits(n): return sum(int(digit) for digit in str(n)) def count_harmonious_pairs(numbers): count = 0 n = len(numbers) for i in range(n): for j in range(i + 1, n): a, b = numbers[i], numbers[j] sum_digits_a = sum_of_digits(a) sum_digits_b = sum_of_d...
from solution import sum_of_digits, count_harmonious_pairs def test_sum_of_digits(): assert sum_of_digits(123) == 6 assert sum_of_digits(0) == 0 assert sum_of_digits(56) == 11 assert sum_of_digits(1001) == 2 def test_count_harmonious_pairs(): assert count_harmonious_pairs([12, 21]) == 0 assert...
[ { "docstring": null, "function_declaration": "def sum_of_digits(n):", "function_name": "sum_of_digits", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def count_harmonious_pairs(numbers):", "function_name": "count_harmonious_pairs", "parameter_list": "(n...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sum_of_digits(n):\n return sum(int(digit) for digit in str(n))\n\ndef count_harmonious_pairs(numbers):\n count = 0\n n = len(numbers)\n for i in range(n):\n for j in ran...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011032", "row_id": 11032, "seed_ids": "['Llama-3.3-70B-Instruct_29380']" }
0.595446
Filter_11032
I
[ "sum_of_digits", "count_harmonious_pairs" ]
2
[ [ "count_harmonious_pairs", "sum_of_digits" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c2b33196f5cbdabd7c670822162ec093ab1cfefe
5eeae0a4ee03f823158ef8588ae3277ecba7cf13
v1.0
instruct
Filter
Filter_11035_I
I want to learn how to import a JSON file. Here is a sample JSON file called 'data.json' ```json { "name": "John Doe", "age": 30, "city": "New York" } ``` Can you show me a basic example of how to import this JSON file into Python and print out the contents?
import json def read_json_file(file_path): """ Reads a JSON file and returns its contents. :param file_path: Path to the JSON file. :return: Contents of the JSON file as a dictionary. """ with open(file_path, 'r') as file: data = json.load(file) return data def print_json_cont...
import json import os from solution import read_json_file, print_json_contents # Helper function to create a sample json file def create_sample_json(file_path, content): with open(file_path, 'w') as f: json.dump(content, f) # Set up sample JSON content and file path test_json_content = { "name": "John...
[ { "docstring": "Reads a JSON file and returns its contents.\n\n:param file_path: Path to the JSON file.\n:return: Contents of the JSON file as a dictionary.", "function_declaration": "def read_json_file(file_path):", "function_name": "read_json_file", "parameter_list": "(file_path)" }, { "do...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\n\ndef read_json_file(file_path):\n \"\"\"\n Reads a JSON file and returns its contents.\n \n :param file_path: Path to the JSON file.\n :return: Contents of the JSO...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011035", "row_id": 11035, "seed_ids": "['Llama-3.3-70B-Instruct_29387']" }
0.549389
Filter_11035
I
[ "read_json_file", "print_json_contents" ]
2
[ [ "print_json_contents", "read_json_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bc00e89e0142acb9747426164bb6cccea8fac906
8fc9b8ea26014bb02321b2370bba24b58bdb93f3
v1.0
instruct
Filter
Filter_11072_I
In this problem, we will be dealing with a binary search tree. A binary search tree is a binary tree with the following properties: - The left subtree of a node contains only nodes with keys less than the node's key. - The right subtree of a node contains only nodes with keys greater than the node's key. - Both the ...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorder_traversal(root): result = [] stack = [] current = root while current or stack: while current: stack.append(current) ...
from solution import TreeNode, is_valid_bst def test_valid_bst(): root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) assert is_valid_bst(root) == True def test_invalid_bst_with_equal_values(): root = TreeNode(2) root.left = TreeNode(2) root.right = TreeNode(3) assert i...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_valid_bst(root):\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011072", "row_id": 11072, "seed_ids": "['Llama-3.3-70B-Instruct_29459']" }
0.589603
Filter_11072
I
[ "inorder_traversal", "is_valid_bst" ]
2
[ [ "is_valid_bst", "inorder_traversal" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
fbbb1490a3519fe0d4424b733ffacc0275178a96
96240a28f837fa0176888830ef0e5c6be573ab90
v1.0
instruct
Filter
Filter_11084_I
I have a programming task where I need to find the maximum length of a subarray with a given sum. My task involves finding this maximum length for multiple arrays and multiple sums. I was thinking of using a hashmap to store the cumulative sum and the corresponding indices of the elements in the array. Then for each s...
def max_len_subarray(arr, target_sum): """ This function calculates the maximum length of a subarray with a given sum using a hashmap. Args: arr (list): The input array. target_sum (int): The target sum. Returns: int: The maximum length of the subarray with the target sum. """ pref...
from solution import max_len_subarray, max_len_subarrays def test_max_len_subarray_single(): assert max_len_subarray([1, -1, 5, -2, 3], 3) == 4 assert max_len_subarray([-2, -1, 2, 1], 1) == 2 assert max_len_subarray([1, 2, 3, 4], 10) == 4 assert max_len_subarray([1, 2, 3, 4], 11) == 0 assert max_le...
[ { "docstring": "This function calculates the maximum length of a subarray with a given sum using a hashmap.\n\nArgs:\narr (list): The input array.\ntarget_sum (int): The target sum.\n\nReturns:\nint: The maximum length of the subarray with the target sum.", "function_declaration": "def max_len_subarray(arr,...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_len_subarray(arr, target_sum):\n \"\"\"\n This function calculates the maximum length of a subarray with a given sum.\n\n Args:\n arr (list): The input array.\n target_s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011084", "row_id": 11084, "seed_ids": "['Llama-3.3-70B-Instruct_29496']" }
0.659433
Filter_11084
I
[ "max_len_subarray", "max_len_subarrays" ]
2
[ [ "max_len_subarrays", "max_len_subarray" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1fde2b7ea172659ba72cccbd2d615af8ea732b25
00c97d39e241681035bc5cd4dc6f3e65b61b39c4
v1.0
instruct
Filter
Filter_11086_I
### Developing a Simple Chatbot Using Python #### Introduction Chatbots are computer programs designed to simulate conversation with human users either through text or voice interactions. In this section, we will build a simple chatbot using Python. The chatbot will be able to have a basic conversation with the user. F...
import random # Define a dictionary with intents and responses intents = { 'greeting': { 'patterns': ['hello', 'hi', 'hey'], 'responses': ['Hi, how are you?', 'Hello!', 'Hey, what\'s up?'] }, 'goodbye': { 'patterns': ['bye', 'goodbye', 'see you'], 'responses': ['Goodbye!', '...
from solution import match_intent, get_response, chatbot_response def test_match_intent_greeting(): assert match_intent('hello') == 'greeting' assert match_intent('hi') == 'greeting' assert match_intent('hey') == 'greeting' def test_match_intent_goodbye(): assert match_intent('bye') == 'goodbye' a...
[ { "docstring": "Match the user input to an intent.", "function_declaration": "def match_intent(user_input):", "function_name": "match_intent", "parameter_list": "(user_input)" }, { "docstring": "Get a random response for the matched intent.", "function_declaration": "def get_response(use...
[ 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# Define a dictionary with intents and responses\nintents = {\n 'greeting': {\n 'patterns': ['hello', 'hi', 'hey'],\n 'responses': ['Hi, how are you?', 'Hello...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011086", "row_id": 11086, "seed_ids": "['Llama-3.3-70B-Instruct_29499']" }
0.567098
Filter_11086
I
[ "match_intent", "get_response", "chatbot_response" ]
3
[ [ "chatbot_response", "get_response" ], [ "get_response", "match_intent" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a1e35d0c68f5b5a10e14350f2f5435b1cdd9ef99
695247aa765125090b2d5b2d6322f98305462bd7
v1.0
instruct
Filter
Filter_11098_I
I want to use Python to create a program that can convert Celsius to Fahrenheit. What's the best way to do this, and are there any specific libraries or modules I should be using? Also, are there any other temperature conversion functions that I could easily add to this program to make it more useful? Lastly, to ma...
def convert_c_to_f(celsius): """ Convert Celsius to Fahrenheit. Parameters: celsius (float): Temperature in Celsius Returns: float: Temperature in Fahrenheit """ return (celsius * 9/5) + 32 def convert_f_to_c(fahrenheit): """ Convert Fahrenheit to Celsius. Par...
from solution import convert_c_to_f, convert_f_to_c, convert_c_to_k, convert_k_to_c def test_convert_c_to_f(): assert convert_c_to_f(0) == 32 assert convert_c_to_f(100) == 212 assert convert_c_to_f(-40) == -40 def test_convert_f_to_c(): assert convert_f_to_c(32) == 0 assert convert_f_to_c(212) == ...
[ { "docstring": "Convert Celsius to Fahrenheit.\n\nParameters:\ncelsius (float): Temperature in Celsius\n\nReturns:\nfloat: Temperature in Fahrenheit", "function_declaration": "def convert_c_to_f(celsius):", "function_name": "convert_c_to_f", "parameter_list": "(celsius)" }, { "docstring": "C...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def convert_c_to_f(celsius):\n \"\"\"\n Convert Celsius to Fahrenheit.\n \n Parameters:\n celsius (float): Temperature in Celsius\n \n Returns:\n float: Temperature in ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011098", "row_id": 11098, "seed_ids": "['Llama-3.3-70B-Instruct_29533']" }
0.420965
Filter_11098
I
[ "convert_c_to_f", "convert_f_to_c", "convert_c_to_k", "convert_k_to_c", "simple_menu" ]
5
[ [ "simple_menu", "convert_c_to_f" ], [ "simple_menu", "convert_c_to_k" ], [ "simple_menu", "convert_f_to_c" ], [ "simple_menu", "convert_k_to_c" ] ]
4
[]
false
[]
false
pytest
true
[]
true
a26ac6f2e3a7226332c6faa60c6bceb8cf4fe638
4d3b74a22b134f85425bb25f539e01430bb0ef84
v1.0
instruct
Filter
Filter_11137_I
I'm building a simple calendar application that allows users to store events. The events have a title, description, date, and time. I want to add the functionality to export these events to an iCal (.ics) file. Can you help me with that?
from datetime import datetime import pytz def escape_ics_text(text): text = text.replace("\\", "\\\\") text = text.replace(";", "\\;") text = text.replace(",", "\\,") text = text.replace("\n", "\\n") return text def generate_ics(events): """ Generates an iCal (.ics) file content from a lis...
from solution import generate_ics def test_generate_ics_single_event(): events = [ { "title": "Meeting with Bob", "description": "Discuss the new project requirements.", "date": "2023-12-10", "time": "15:00" } ] ics = generate_ics(events) ...
[ { "docstring": null, "function_declaration": "def escape_ics_text(text):", "function_name": "escape_ics_text", "parameter_list": "(text)" }, { "docstring": "Generates an iCal (.ics) file content from a list of events.\n\nParameters:\nevents (list): A list of dictionaries, each representing a...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import datetime\n\nclass Event:\n def __init__(self, title, description, event_date, event_time):\n self.title = title\n self.description = description\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011137", "row_id": 11137, "seed_ids": "['Llama-3.3-70B-Instruct_29633']" }
0.246531
Filter_11137
I
[ "escape_ics_text", "generate_ics" ]
2
[ [ "generate_ics", "escape_ics_text" ] ]
1
[]
false
[]
false
pytest
true
[ "pytz" ]
false
f32af72a2984ddcf20df09fc2ffb60693f62622a
867a3d34ec33f1c2f9fabfebdf5a509b414435e7
v1.0
instruct
Filter
Filter_11184_I
### Quicksort Algorithm #### Overview Quicksort is a divide-and-conquer algorithm that sorts an array by selecting a 'pivot' element and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted. #### Implementatio...
def median_of_three(arr, low, high): mid = (low + high) // 2 if arr[low] > arr[mid]: arr[low], arr[mid] = arr[mid], arr[low] if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] if arr[mid] > arr[high]: arr[mid], arr[high] = arr[high], arr[mid] return arr[mid] ...
from solution import quicksort def test_quicksort_empty(): assert quicksort([]) == [] def test_quicksort_single_element(): assert quicksort([1]) == [1] def test_quicksort_sorted(): assert quicksort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_quicksort_reverse_sorted(): assert quicksort([5, 4, 3, 2,...
[ { "docstring": null, "function_declaration": "def median_of_three(arr, low, high):", "function_name": "median_of_three", "parameter_list": "(arr, low, high)" }, { "docstring": null, "function_declaration": "def quicksort(arr):", "function_name": "quicksort", "parameter_list": "(a...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def quicksort(arr):\n if len(arr) <= 1:\n return arr\n \n # Finding the median of the first, middle, and last elements as the pivot\n first = arr[0]\n middle = arr[len(ar...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011184", "row_id": 11184, "seed_ids": "['Llama-3.3-70B-Instruct_29726']" }
0.62296
Filter_11184
I
[ "median_of_three", "quicksort" ]
2
[ [ "quicksort", "median_of_three" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c5573ba00329ca0d75403d9c95316166f6852b62
885d9c8db11fc4d894ab0935cd1e0ecc89928d74
v1.0
instruct
Filter
Filter_11186_I
### Introduction to Clustering Algorithms Clustering is an unsupervised machine learning algorithm used to group similar data points into clusters based on their features. The goal is to identify patterns or structures in the data that are not easily visible by other methods like classification or regression. In this p...
import numpy as np def initialize_centroids(data, k): """ Initialize the centroids of each cluster randomly. Args: data (np.array): The input data. k (int): The number of clusters. Returns: centroids (np.array): The initialized centroids. """ # Randomly sel...
import numpy as np from solution import initialize_centroids, assign_clusters, update_centroids, kmeans_clustering def test_initialize_centroids(): data = np.array([ [1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0] ]) k = 2 centroids = initialize_centroi...
[ { "docstring": "Initialize the centroids of each cluster randomly.\n\nArgs:\n data (np.array): The input data.\n k (int): The number of clusters.\n \nReturns:\n centroids (np.array): The initialized centroids.", "function_declaration": "def initialize_centroids(data, k):", "function_name": "...
[ 0, 0, 1 ]
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 initialize_centroids(data, k):\n \"\"\"\n Initialize the centroids of each cluster randomly.\n\n Args:\n data (np.array): The input data.\n k (...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011186", "row_id": 11186, "seed_ids": "['Llama-3.3-70B-Instruct_29728']" }
0.789895
Filter_11186
I
[ "initialize_centroids", "assign_clusters", "update_centroids", "kmeans_clustering" ]
4
[ [ "kmeans_clustering", "assign_clusters" ], [ "kmeans_clustering", "initialize_centroids" ], [ "kmeans_clustering", "update_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy" ]
false
9526b60b79299dd0152adb68bc51c5f1dfa92d78
39c9a60a6fc273db2c2ed33617f929d9ba77e7ac
v1.0
instruct
Filter
Filter_11202_I
I have a script that I've written to convert data between different formats, such as JSON, CSV, and Excel. I've been asked to add support for converting data to and from Avro. I'm currently using the `fastavro` library. However, I'm finding that the library doesn't support generating Avro schema from the existing dat...
import json from collections.abc import Mapping, Sequence def infer_avro_type(value): """ Infers the Avro type of a given Python value. """ if value is None: return "null" elif isinstance(value, bool): return "boolean" elif isinstance(value, int): return "long" elif ...
from solution import infer_avro_schema def test_infer_avro_schema_simple(): data = [ {"name": "John", "age": 30, "is_employee": True} ] expected_schema = { "type": "record", "name": "Person", "fields": [ {"name": "name", "type": "string"}, {"name": "a...
[ { "docstring": "Infers the Avro type of a given Python value.", "function_declaration": "def infer_avro_type(value):", "function_name": "infer_avro_type", "parameter_list": "(value)" }, { "docstring": "Infers the Avro schema from the given data.", "function_declaration": "def infer_avro_...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nfrom collections.abc import Mapping, Sequence\n\ndef infer_avro_type(value):\n \"\"\"\n Infers the Avro type of a given Python value.\n \"\"\"\n if value is None:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011202", "row_id": 11202, "seed_ids": "['Llama-3.3-70B-Instruct_29769']" }
0.305898
Filter_11202
I
[ "infer_avro_type", "infer_avro_schema" ]
2
[ [ "infer_avro_schema", "infer_avro_type" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e32bb766ac9da3baf1ed3fa44d79006f260a4cef
9219246a3bafe46b74f50bec123d5b18fb56b352
v1.0
instruct
Filter
Filter_11211_I
In this task, we will create a simple command-line calculator that takes basic arithmetic expressions as input and evaluates them. 1. Create a dictionary that maps the operator symbols to their corresponding functions from the operator module. 2. Create a dictionary that maps the operator symbols to their correspon...
import operator as op import re # Mapping of operator symbols to their corresponding functions from the operator module operator_functions = { '+': op.add, '*': op.mul, } # Mapping of operator symbols to their corresponding string representations for printing purposes operator_strings = { '+': '+', '*...
from solution import calculator, Node def test_calculator_simple_addition(): assert calculator("1 + 2") == 3 def test_calculator_simple_multiplication(): assert calculator("2 * 3") == 6 def test_calculator_mixed_operations(): assert calculator("2 + 3 * 4") == 14 def test_calculator_multiplication_first(...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import operator as op\nimport re\n\n# Mapping of operator symbols to their corresponding functions from the operator module\noperator_functions = {\n \"+\": op.add,\n \"*\": op.mul,\n}\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011211", "row_id": 11211, "seed_ids": "['Llama-3.3-70B-Instruct_29792']" }
0.67126
Filter_11211
I
[ "parse_factor", "parse_term", "parse_expression", "evaluate", "calculator", "main" ]
6
[ [ "calculator", "evaluate" ], [ "calculator", "parse_expression" ], [ "parse_expression", "parse_term" ], [ "parse_term", "parse_factor" ] ]
4
[]
false
[ "Node" ]
true
pytest
true
[]
true
b20180bccd98e1d538a8ecb16af04ef0f7adb4a8
b5cb9ee2fb3d0fc5a94148eeb58451ec96edcca7
v1.0
instruct
Filter
Filter_11232_I
### Introduction to Algorithms and Data Structures #### Problem: Higher-Lower Game The higher-lower game is a popular internet game where two cards are shown face-up on the screen, and the player has to guess whether the next card will be higher or lower in rank than the current card. Write a program that simulates thi...
import random # Define a class for the Card class Card: def __init__(self, suit, value): self.suit = suit self.value = value def __repr__(self): return f"{self.value} of {self.suit}" # Define a class for the Deck class Deck: def __init__(self): self.cards = [] self...
from solution import Card, Deck, card_value, play_game def test_card_value(): assert card_value(Card('Hearts', '2')) == 2 assert card_value(Card('Diamonds', '10')) == 10 assert card_value(Card('Clubs', 'Jack')) == 11 assert card_value(Card('Spades', 'Ace')) == 14 def test_deck_creation(): deck = D...
[]
[ 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\nclass Card:\n def __init__(self, suit, value):\n self.suit = suit\n self.value = value\n\n def __repr__(self):\n return f\"{self.value} of {self.sui...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011232", "row_id": 11232, "seed_ids": "['Llama-3.3-70B-Instruct_29852']" }
0.637664
Filter_11232
I
[ "card_value", "play_game" ]
2
[ [ "play_game", "card_value" ] ]
1
[]
false
[ "Card", "Deck" ]
true
pytest
true
[]
true
a474a9f596e66492b15c3d280bcd3a9443879c26
d899ec2527bfcfc0b54bbb5c023d82617eb39f04
v1.0
instruct
Filter
Filter_11252_I
### Overview of Project The project is to develop a basic text-based interactive game. The game will be designed to test the player's knowledge in a specific domain. The player will be presented with a series of questions and their answers will be evaluated. The game will keep track of the player's score and provide f...
import random # List of questions, options, and answers questions = [ { "question": "Who was the first president of the United States?", "options": ["A) George Washington", "B) John Adams", "C) Thomas Jefferson", "D) James Madison"], "answer": "A" }, { "question": "What year...
from solution import display_question, check_answer, play_game def test_check_answer_correct(): assert check_answer("A", "A") == True def test_check_answer_incorrect(): assert check_answer("B", "A") == False def test_display_question(monkeypatch): test_question = { "question": "Who was the first ...
[ { "docstring": null, "function_declaration": "def display_question(question):", "function_name": "display_question", "parameter_list": "(question)" }, { "docstring": null, "function_declaration": "def check_answer(player_answer, correct_answer):", "function_name": "check_answer", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\n# List of questions, options, and answers\nquestions = [\n {\n \"question\": \"Who was the first president of the United States?\",\n \"options\": [\"A) Georg...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011252", "row_id": 11252, "seed_ids": "['Llama-3.3-70B-Instruct_29889']" }
0.512575
Filter_11252
I
[ "display_question", "check_answer", "play_game", "main" ]
4
[ [ "play_game", "check_answer" ], [ "play_game", "display_question" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e0cc209dbf2ffaf768f4c6076da612741eb355fb
b0483013443cec1b8e47abbf5252ecc20ad243b5
v1.0
instruct
Filter
Filter_11258_I
Here are the twelve days of Christmas: 1. A Partridge in a Pear Tree 2. Two Turtle Doves 3. Three French Hens 4. Four Calling Birds 5. Five Golden Rings 6. Six Geese a Laying 7. Seven Swans a Swimming 8. Eight Maids a Milking 9. Nine Ladies Dancing 10. Eleven Pipers Piping 11. Twelve Drummers Drum...
def twelve_days_of_christmas(): """ Prints the lyrics of the 'Twelve Days of Christmas' song with the correct gifts """ gifts = [ "A Partridge in a Pear Tree", "Two Turtle Doves", "Three French Hens", "Four Calling Birds", "Five Golden Rings", "Six Geese a...
from solution import twelve_days_of_christmas, get_ordinal def test_get_ordinal(): assert get_ordinal(1) == '1st' assert get_ordinal(2) == '2nd' assert get_ordinal(3) == '3rd' assert get_ordinal(4) == '4th' assert get_ordinal(11) == '11th' assert get_ordinal(21) == '21st' assert get_ordinal...
[ { "docstring": "Prints the lyrics of the 'Twelve Days of Christmas' song with the correct gifts", "function_declaration": "def twelve_days_of_christmas():", "function_name": "twelve_days_of_christmas", "parameter_list": "()" }, { "docstring": "Returns the ordinal representation of a number",...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def twelve_days_of_christmas():\n \"\"\"\n Prints the lyrics of the \"Twelve Days of Christmas\" song.\n \"\"\"\n days = [\n \"A Partridge in a Pear Tree\",\n \"Two T...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011258", "row_id": 11258, "seed_ids": "['Llama-3.3-70B-Instruct_29905']" }
0.526123
Filter_11258
I
[ "twelve_days_of_christmas", "get_ordinal" ]
2
[ [ "twelve_days_of_christmas", "get_ordinal" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b506e497cb3b9515444f47752351dfb41de8971e
cb9e3d98f61b36b08f14f0d5af1c9dccdc30aad0
v1.0
instruct
Filter
Filter_11261_I
I have a little project that requires some text analysis. What I'm trying to do is write a program that can take a folder of text files, read each file, and then output the total word count of each file. I'm comfortable with the basics of Python, but I've never worked with files before. Could you provide an example of...
import os def count_words_in_file(file_path): """ Returns the total word count for the given file. """ with open(file_path, 'r', encoding='utf-8') as file: text = file.read() words = text.split() return len(words) def count_words_in_files_in_folder(folder_path): """ Ret...
import os import pytest from solution import count_words_in_file, count_words_in_files_in_folder def test_count_words_in_file(tmp_path): file_path = tmp_path / "test_file.txt" file_content = "hello world" file_path.write_text(file_content, encoding='utf-8') assert count_words_in_file(file_path) =...
[ { "docstring": "Returns the total word count for the given file.", "function_declaration": "def count_words_in_file(file_path):", "function_name": "count_words_in_file", "parameter_list": "(file_path)" }, { "docstring": "Returns a dictionary where the keys are filenames and the values are th...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef count_words_in_file(filepath):\n \"\"\"\n Counts the number of words in a given text file.\n \n Parameters:\n filepath (str): The path to the text file.\n \n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011261", "row_id": 11261, "seed_ids": "['Llama-3.3-70B-Instruct_29914']" }
0.754757
Filter_11261
I
[ "count_words_in_file", "count_words_in_files_in_folder" ]
2
[ [ "count_words_in_files_in_folder", "count_words_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
29fc1a64c5bc1803cf430f3d5ae1b46b5357e402
2ff33740ad440c97bd98fe95f3c4c4700c0a0c0a
v1.0
instruct
Filter
Filter_11270_I
I have an existing function that generates a random number within a specific range. I also have another function that checks if a given number is prime or not. Now I would like to create a new function called `generatePrimeNumber` which uses the existing functions to generate a random prime number within a given range...
import random def generateRandomNumber(min_value, max_value): return random.randint(min_value, max_value) def isPrime(n): """Check if 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 generatePrim...
from solution import generateRandomNumber, isPrime, generatePrimeNumber def test_generateRandomNumber(): random.seed(0) # For reproducibility in tests assert 1 <= generateRandomNumber(1, 10) <= 10 assert 20 <= generateRandomNumber(20, 30) <= 30 def test_isPrime(): assert isPrime(2) == True assert...
[ { "docstring": null, "function_declaration": "def generateRandomNumber(min_value, max_value):", "function_name": "generateRandomNumber", "parameter_list": "(min_value, max_value)" }, { "docstring": "Check if number is prime.", "function_declaration": "def isPrime(n):", "function_name...
[ 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 generateRandomNumber(min_value, max_value):\n return random.randint(min_value, max_value)\n\ndef isPrime(n):\n \"\"\"Check if number is prime.\"\"\"\n if n < 2:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011270", "row_id": 11270, "seed_ids": "['Llama-3.3-70B-Instruct_29934']" }
0.523335
Filter_11270
I
[ "generateRandomNumber", "isPrime", "generatePrimeNumber" ]
3
[ [ "generatePrimeNumber", "generateRandomNumber" ], [ "generatePrimeNumber", "isPrime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
78aeec295dc50011b6be6e31a8d7d90cf78af2a0
9582cfbdd09e52e51ecb4f0d1a2d103d3febfd70
v1.0
instruct
Filter
Filter_11274_I
I have this function: ``` def find_gcd(num1, num2): while num2 != 0: num1, num2 = num2, num1 % num2 return num1 ``` I want to use it to find the GCD of two numbers that the user will input. How do I do it? Please provide a full code example. Also, do you have any advice on how to improve the functio...
def find_gcd(num1, num2): """ Returns the greatest common divisor (GCD) of num1 and num2 using the Euclidean algorithm. """ while num2 != 0: num1, num2 = num2, num1 % num2 return num1 def find_gcd_of_three_numbers(num1, num2, num3): """ Returns the greatest common divisor (GCD) of t...
from solution import find_gcd, find_gcd_of_three_numbers def test_find_gcd(): assert find_gcd(54, 24) == 6 assert find_gcd(101, 103) == 1 assert find_gcd(100, 25) == 25 assert find_gcd(0, 5) == 5 assert find_gcd(5, 0) == 5 assert find_gcd(0, 0) == 0 def test_find_gcd_of_three_numbers(): as...
[ { "docstring": "Returns the greatest common divisor (GCD) of num1 and num2 using the Euclidean algorithm.", "function_declaration": "def find_gcd(num1, num2):", "function_name": "find_gcd", "parameter_list": "(num1, num2)" }, { "docstring": "Returns the greatest common divisor (GCD) of three...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_gcd(num1, num2):\n \"\"\"\n Returns the Greatest Common Divisor (GCD) of num1 and num2 using the Euclidean algorithm.\n \"\"\"\n while num2 != 0:\n num1, num2 = num...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011274", "row_id": 11274, "seed_ids": "['Llama-3.3-70B-Instruct_29942']" }
0.775019
Filter_11274
I
[ "find_gcd", "find_gcd_of_three_numbers", "main" ]
3
[ [ "find_gcd_of_three_numbers", "find_gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1d5063040bac41a33e3e98ee66e47d698a90fddc
00838dc120b6272143ba7ba04a35b9e2cb2c0b0b
v1.0
instruct
Filter
Filter_11277_I
I want to write a program that can play Tic Tac Toe against a human opponent. I want to use a simple text-based interface and I want to keep track of the number of wins, losses, and draws for both the human and the AI. Here is a code that I have so far: ``` import random def print_board(board): print(" {} | {} | ...
import random def print_board(board): print(" {} | {} | {} ".format(board[0], board[1], board[2])) print("---+---+---") print(" {} | {} | {} ".format(board[3], board[4], board[5])) print("---+---+---") print(" {} | {} | {} ".format(board[6], board[7], board[8])) def check_winner(board): winnin...
from solution import print_board, check_winner, get_ai_move def test_print_board(capsys): board = ["X", "O", "X", " ", "X", "O", "O", " ", "X"] print_board(board) captured = capsys.readouterr() expected_output = " X | O | X \n---+---+---\n | X | O \n---+---+---\n O | | X \n" assert captured.out...
[ { "docstring": null, "function_declaration": "def print_board(board):", "function_name": "print_board", "parameter_list": "(board)" }, { "docstring": null, "function_declaration": "def check_winner(board):", "function_name": "check_winner", "parameter_list": "(board)" }, { ...
[ 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 print_board(board):\n print(\" {} | {} | {} \".format(board[0], board[1], board[2]))\n print(\"---+---+---\")\n print(\" {} | {} | {} \".format(board[3], board[4]...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011277", "row_id": 11277, "seed_ids": "['Llama-3.3-70B-Instruct_29948']" }
0.543655
Filter_11277
I
[ "print_board", "check_winner", "get_ai_move", "game" ]
4
[ [ "game", "check_winner" ], [ "game", "get_ai_move" ], [ "game", "print_board" ] ]
3
[]
false
[]
false
pytest
true
[]
true
9d037109bdd9fce9420a0d85bea01c08cb071a36
e6347921a3f85b412cd9d0cac955793ab11b6d5e
v1.0
instruct
Filter
Filter_11287_I
Is it possible to create a 2D fluid simulation in pure Python without using any external libraries (not even NumPy)?
import math def initialize_grid(size): grid = [[0.0 for _ in range(size)] for _ in range(size)] return grid def add_source(x, s, dt): size = len(x) for i in range(size): for j in range(size): x[i][j] += dt * s[i][j] def diffuse(b, x, x0, diff, dt): size = len(x) a = dt * d...
from solution import initialize_grid, add_source, diffuse, advect, set_bnd, project, step def test_initialize_grid(): grid = initialize_grid(4) assert len(grid) == 4 assert len(grid[0]) == 4 assert grid[0][0] == 0.0 def test_add_source(): grid = initialize_grid(4) source = initialize_grid(4) ...
[ { "docstring": null, "function_declaration": "def initialize_grid(size):", "function_name": "initialize_grid", "parameter_list": "(size)" }, { "docstring": null, "function_declaration": "def add_source(x, s, dt):", "function_name": "add_source", "parameter_list": "(x, s, dt)" }...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add_source(x, s, dt):\n \"\"\"\n Adds sources to the fluid.\n \"\"\"\n size = len(x)\n for i in range(size):\n for j in range(size):\n x[i][j] += dt * s[i]...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011287", "row_id": 11287, "seed_ids": "['Llama-3.3-70B-Instruct_29970']" }
0.307531
Filter_11287
I
[ "initialize_grid", "add_source", "diffuse", "advect", "set_bnd", "project", "step" ]
7
[ [ "advect", "set_bnd" ], [ "diffuse", "set_bnd" ], [ "project", "set_bnd" ], [ "step", "add_source" ], [ "step", "advect" ], [ "step", "diffuse" ], [ "step", "initialize_grid" ], [ "step", "project" ] ]
8
[]
false
[]
false
pytest
true
[]
true
f371fa7269cceb9f4b602dfd82ec57e8ffc661ff
32cc73095736c926b88b24b6e77333c99bd82730
v1.0
instruct
Filter
Filter_11296_I
I'm trying to generate the smallest triangle number that is also a product of three primes. I'd like to write some Python code to do this but I'm struggling to start. Can you provide a code skeleton for this task?
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def generate_primes(n): primes = [] num = 2 while len(primes) < n: if is_prime(num): primes.append(num) num += 1 retur...
from solution import (is_prime, generate_primes, is_triangle_number, find_smallest_triangle_product_of_primes, smallest_triangle_number_product_of_three_primes) def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == Fal...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def generate_primes(n):", "function_name": "generate_primes", "parameter_list": "(n)" }, { "docstring": n...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef generate_primes(n):\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011296", "row_id": 11296, "seed_ids": "['Llama-3.3-70B-Instruct_29985']" }
0.551786
Filter_11296
I
[ "is_prime", "generate_primes", "is_triangle_number", "find_smallest_triangle_product_of_primes", "smallest_triangle_number_product_of_three_primes" ]
5
[ [ "find_smallest_triangle_product_of_primes", "is_triangle_number" ], [ "generate_primes", "is_prime" ], [ "smallest_triangle_number_product_of_three_primes", "find_smallest_triangle_product_of_primes" ], [ "smallest_triangle_number_product_of_three_primes", "generate_pri...
4
[]
false
[]
false
pytest
true
[]
true
d897419ec1d752d2178b081f1011c8663a444363
43195859adf4b352bd4708e77781406663ce4851
v1.0
instruct
Filter
Filter_11302_I
I've already made a basic Rock Paper Scissors game. Now I want to create a new version that plays against the computer. I can simulate user input with `input()` to get the user's choice. Here are my requirements: * The computer's choices must be randomly selected without using `random.choice()` * I must be able t...
import time # Function to generate a random number without using random.choice() def generate_random_number(): return int(time.time() * 1000) % 3 def determine_computer_choice(rock_count): if rock_count % 3 == 0: return "rock" elif rock_count % 3 == 1: return "paper" else: re...
import pytest from solution import generate_random_number, determine_computer_choice, play_round def test_generate_random_number(): num = generate_random_number() assert 0 <= num < 3 def test_determine_computer_choice(): assert determine_computer_choice(0) == "rock" assert determine_computer_choice(1)...
[ { "docstring": null, "function_declaration": "def generate_random_number():", "function_name": "generate_random_number", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def determine_computer_choice(rock_count):", "function_name": "determine_computer_choice", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport math\n\ndef generate_random_number():\n \"\"\"\n Generates a pseudo-random number in the range [0, 2] based on the system time.\n \"\"\"\n return math.floor((ma...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011302", "row_id": 11302, "seed_ids": "['Llama-3.3-70B-Instruct_29999']" }
0.551889
Filter_11302
I
[ "generate_random_number", "determine_computer_choice", "play_round", "play_game", "main" ]
5
[ [ "play_game", "determine_computer_choice" ], [ "play_game", "play_round" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b60c804ce93f63abaaf8899c6b056cfb6f221073
527bd2089fcf10e3a074cdae09cf63f753c8c0a4
v1.0
instruct
Filter
Filter_11308_I
I have a question about running a command-line application from within another command-line application. The scenario is as follows: I have a simple command-line application, let's call it "app1", that takes one argument which is the name of a file I want to process. For example: ``` $ ./app1 file.txt ``` Now, I want ...
import subprocess def run_app1(file_name): """ Runs app1 with the given file name and returns its output. Args: - file_name (str): The name of the file to process with app1. Returns: - output (str): The output of app1. """ result = subprocess.run(['./app1', file_name], capture...
from solution import run_app1, generate_file_name from unittest.mock import patch import subprocess @patch('subprocess.run') def test_run_app1_success(mock_subprocess_run): # Mock the subprocess.run to return a successful result mock_result = subprocess.CompletedProcess(args=['./app1', 'file.txt'], returncode=...
[ { "docstring": "Runs app1 with the given file name and returns its output.\n\nArgs:\n- file_name (str): The name of the file to process with app1.\n\nReturns:\n- output (str): The output of app1.", "function_declaration": "def run_app1(file_name):", "function_name": "run_app1", "parameter_list": "(f...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# app1.py\nimport sys\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(f\"Usage: {sys.argv[0]} <filename>\")\n sys.exit(1)\n\n filename = sys.argv[1]\n t...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011308", "row_id": 11308, "seed_ids": "['Llama-3.3-70B-Instruct_30013']" }
0.390062
Filter_11308
I
[ "run_app1", "run_app2", "generate_file_name" ]
3
[ [ "run_app2", "generate_file_name" ], [ "run_app2", "run_app1" ] ]
2
[]
false
[]
false
pytest
true
[]
true
346047240077241aaf9429b78acf44dbc220c2e7
e73c0dcd66638a861506f4e6d3fc9cd54e45d300
v1.0
instruct
Filter
Filter_11329_I
I have a simulation where I have a list of points on a 2D plane. I want to add a "leader" point which will move towards a target point and I want the rest of the points to follow the leader. I can represent each point as a dictionary with 'x' and 'y' keys. I can move each point by changing the 'x' and 'y' values. He...
import math def move_towards(p, target, step_size): """ Moves point `p` toward `target` by `step_size`. """ direction_x = target['x'] - p['x'] direction_y = target['y'] - p['y'] distance = math.sqrt(direction_x**2 + direction_y**2) if distance == 0: return p unit_vector_x = dire...
import pytest from solution import move_towards, follow_leader def test_move_towards(): p = {'x': 0, 'y': 0} target = {'x': 3, 'y': 4} step_size = 5 new_p = move_towards(p, target, step_size) assert math.isclose(new_p['x'], 3) assert math.isclose(new_p['y'], 4) def test_follow_leader(): po...
[ { "docstring": "Moves point `p` toward `target` by `step_size`.", "function_declaration": "def move_towards(p, target, step_size):", "function_name": "move_towards", "parameter_list": "(p, target, step_size)" }, { "docstring": "Moves the leader point towards the target and adjusts the follow...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef move_leader(leader, target, step_size=1.0):\n \"\"\"\n Moves the leader point towards the target point by a given step size.\n \"\"\"\n # Calculate the direction...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011329", "row_id": 11329, "seed_ids": "['Llama-3.3-70B-Instruct_30064']" }
0.446398
Filter_11329
I
[ "move_towards", "follow_leader" ]
2
[ [ "follow_leader", "move_towards" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f01e20574eeb32089d42e5ade3cadb34627751b1
b46f186b7aa8881f72cd64b505fbe045236c1d3d
v1.0
instruct
Filter
Filter_11346_I
I have the following function in Python: ```python def calculate_fuel(mass): return max(0, mass // 3 - 2) ``` How can I apply this function to each element of a list of masses, and sum up the results? Here are some example masses: ```python masses = [10, 18, 20, 1969, 100756] ``` I can achieve this using a for ...
def calculate_fuel(mass): return max(0, mass // 3 - 2) def calculate_total_fuel(masses): total_fuel = 0 fuel_masses = masses[:] while fuel_masses: new_fuel_masses = [] for mass in fuel_masses: fuel = calculate_fuel(mass) if fuel > 0: total_fuel +=...
from solution import calculate_fuel, total_fuel_map, total_fuel_list_comprehension, total_fuel_numpy from solution import total_recursive_fuel_map, total_recursive_fuel_list_comprehension, total_recursive_fuel_numpy def test_calculate_fuel(): assert calculate_fuel(12) == 2 assert calculate_fuel(14) == 2 as...
[ { "docstring": null, "function_declaration": "def calculate_fuel(mass):", "function_name": "calculate_fuel", "parameter_list": "(mass)" }, { "docstring": null, "function_declaration": "def calculate_total_fuel(masses):", "function_name": "calculate_total_fuel", "parameter_list": ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_fuel(mass):\n return max(0, mass // 3 - 2)\n\ndef calculate_total_fuel(masses):\n total_fuel = 0\n fuel_masses = masses[:]\n while fuel_masses:\n new_fuel_mass...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011346", "row_id": 11346, "seed_ids": "['Llama-3.3-70B-Instruct_30096']" }
0.565505
Filter_11346
I
[ "calculate_fuel", "calculate_total_fuel", "total_fuel_map", "total_fuel_list_comprehension", "total_fuel_numpy", "total_recursive_fuel_map", "total_recursive_fuel_list_comprehension", "total_recursive_fuel_numpy" ]
8
[ [ "calculate_total_fuel", "calculate_fuel" ], [ "total_fuel_list_comprehension", "calculate_fuel" ], [ "total_fuel_map", "calculate_fuel" ], [ "total_recursive_fuel_list_comprehension", "calculate_fuel" ], [ "total_recursive_fuel_map", "calculate_fuel" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
20dadff55d093d5796d40d4d60bf33a1e70b2847
800881140ccf6785c84dd15a2bd3ae02d539cb0a
v1.0
instruct
Filter
Filter_11354_I
I'd like to simulate a particle moving in a 2D space with the following conditions: 1. The particle has an initial position (x, y) and an initial velocity (vx, vy). 2. At each time step, the particle's velocity is updated based on a force that's proportional to its current velocity. 3. The particle's position is then ...
def update_velocity(vx, vy, force_coefficient=0.1): """ Updates the velocity of the particle based on a force proportional to current velocity. The force is applied in the opposite direction to simulate a damping effect. """ dvx = -force_coefficient * vx dvy = -force_coefficient * vy return ...
from solution import update_velocity, update_position, simulate_particle def test_update_velocity(): vx, vy = 1.0, 1.0 new_vx, new_vy = update_velocity(vx, vy, force_coefficient=0.1) assert new_vx == 0.9 assert new_vy == 0.9 def test_update_position(): x, y = 0.0, 0.0 vx, vy = 1.0, 1.0 new...
[ { "docstring": "Updates the velocity of the particle based on a force proportional to current velocity.\nThe force is applied in the opposite direction to simulate a damping effect.", "function_declaration": "def update_velocity(vx, vy, force_coefficient=0.1):", "function_name": "update_velocity", "...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def update_velocity(vx, vy, force_coefficient=0.1):\n \"\"\"\n Updates the velocity of the particle based on a force proportional to current velocity.\n The force is applied in the op...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00011354", "row_id": 11354, "seed_ids": "['Llama-3.3-70B-Instruct_30118']" }
0.356322
Filter_11354
I
[ "update_velocity", "update_position", "simulate_particle" ]
3
[ [ "simulate_particle", "update_position" ], [ "simulate_particle", "update_velocity" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e1ba0a18099c87e5df85032bea00473e7a473945
f7f1917c356f21ce9cdbf086eb146458d4cebe24
v1.0
instruct
Filter
Filter_11404_I
I've been having issues with a program I'm writing. I've tried a lot of different things but can't seem to get it working right. I was hoping you could help me figure out what's going on and provide a clear explanation of how to fix it. In this problem, we need to implement a function that sorts an array of integers i...
def merge_sort(arr): # Base case: If the array has one or zero elements, it is already sorted. if len(arr) <= 1: return arr # Split the array into two halves. mid = len(arr) // 2 left_half = arr[:mid] right_half = arr[mid:] # Recursively sort the two halves. left_half = merge_s...
from solution import merge_sort def test_merge_sort_empty(): 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 merge_s...
[ { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "parameter_list": "(left, right)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n # Base case: If the array has one or zero elements, it is already sorted.\n if len(arr) <= 1:\n return arr\n\n # Split the array into two halves.\n mi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011404", "row_id": 11404, "seed_ids": "['Llama-3.3-70B-Instruct_30254']" }
0.605703
Filter_11404
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
85fa3c3ce1df96e4a097256543928a08fcfaa97e
0c556af02ed2efeb9b0cd39984c985d1ae59e464
v1.0
instruct
Filter
Filter_11422_I
I have a list of students and I want to check if they are eligible for a scholarship. The eligibility criteria is as follows: - Age: The student must be between 18 and 25 years old (inclusive). - Average grade: The student must have an average grade of 80 or higher. - Attendance: The student must have an attendance of...
def is_eligible(student): return ( 18 <= student["age"] <= 25 and student["average_grade"] >= 80 and student["attendance"] >= 90 ) def eligible_students(students): return [student for student in students if is_eligible(student)] students = [ { "name": "John Doe", ...
from solution import is_eligible, eligible_students def test_is_eligible(): student_1 = {"name": "Alice", "age": 20, "average_grade": 85, "attendance": 90} assert is_eligible(student_1) == True student_2 = {"name": "Bob", "age": 17, "average_grade": 85, "attendance": 90} assert is_eligible(student...
[ { "docstring": null, "function_declaration": "def is_eligible(student):", "function_name": "is_eligible", "parameter_list": "(student)" }, { "docstring": null, "function_declaration": "def eligible_students(students):", "function_name": "eligible_students", "parameter_list": "(st...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_eligible(student):\n \"\"\"\n Checks if a student is eligible for a scholarship based on the criteria.\n Criteria:\n - Age: 18 to 25 (inclusive)\n - Average grade: 80 or ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011422", "row_id": 11422, "seed_ids": "['Llama-3.3-70B-Instruct_30297']" }
0.598933
Filter_11422
I
[ "is_eligible", "eligible_students" ]
2
[ [ "eligible_students", "is_eligible" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab15130ac3e68ccaed0fb4ba160c0a2558d6c377
e8d8005e8bb80cfd15cc365cea0b8cd1c9c1d863
v1.0
instruct
Filter
Filter_11438_I
I've been given a task to create a program to create a program that generates an image based on user input. The user will input a string and the image will be generated based on the string's attributes such as length, vowels, consonants etc. For simplicity, let's start with a basic shape - a rectangle. The characteris...
from PIL import Image, ImageDraw def count_vowels(s: str) -> int: """ Count the number of vowels in the given string """ vowels = 'aeiouAEIOU' return sum(1 for char in s if char in vowels) def generate_rectangle_image(input_string: str, output_path: str) -> None: """ Generate a rectangle i...
from solution import count_vowels, generate_rectangle_image import pytest from PIL import Image def test_count_vowels(): assert count_vowels("hello") == 2 assert count_vowels("world") == 1 assert count_vowels("AEIOUaeiou") == 10 assert count_vowels("bcdfg") == 0 def test_generate_rectangle_image(tmp_p...
[ { "docstring": "Count the number of vowels in the given string", "function_declaration": "def count_vowels(s):", "function_name": "count_vowels", "parameter_list": "(s)" }, { "docstring": "Generate a rectangle image based on input string.\nWidth is the length of the string.\nHeight is the nu...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from PIL import Image, ImageDraw\n\ndef generate_rectangle_image(input_string):\n \"\"\"\n Generates a rectangle image based on the input string.\n \n - The width of the rectangle ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011438", "row_id": 11438, "seed_ids": "['Llama-3.3-70B-Instruct_30327']" }
0.449222
Filter_11438
I
[ "count_vowels", "generate_rectangle_image" ]
2
[ [ "generate_rectangle_image", "count_vowels" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
91bd79bd5f89197a74d0ee15746aa5a5c201c1fd
4d764b147a98a5ef84e25937ddaffc5326a4567b
v1.0
instruct
Filter
Filter_11482_I
I want to create a program that takes an input from the user and determines if the input is a palindrome or not. I also want the program to be able to take a file with a list of words as an input and check each word in the file to see if it is a palindrome.
def is_palindrome(word): """ Determine if the given word is a palindrome. """ word = word.lower() return word == word[::-1] def check_palindromes_in_file(file_path): """ Check each word in the given file to see if it is a palindrome. The file should contain one word per line. """ ...
from solution import is_palindrome, check_palindromes_in_file def test_is_palindrome_single_word(): assert is_palindrome("racecar") == True assert is_palindrome("hello") == False def test_is_palindrome_case_insensitivity(): assert is_palindrome("RaceCar") == True assert is_palindrome("Hello") == False...
[ { "docstring": "Determine if the given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Check each word in the given file to see if it is a palindrome.\nThe file should contain one word...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(word):\n \"\"\"\n Returns True if the word is a palindrome, False otherwise.\n \"\"\"\n word = word.lower().replace(\" \", \"\")\n return word == word[::-1]\n\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011482", "row_id": 11482, "seed_ids": "['Llama-3.3-70B-Instruct_30405']" }
0.716443
Filter_11482
I
[ "is_palindrome", "check_palindromes_in_file" ]
2
[ [ "check_palindromes_in_file", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a818fd7f4b327241cf6ddc0da74e6e0480f07b03
7d6a3018d3847cc27e7d852073bcf74c7ff88427
v1.0
instruct
Filter
Filter_11503_I
You've been tasked with adding support for nested lists within lists in an existing XML parser. The existing parser can handle flat XML structures, but it doesn't support nested elements with the same name. How would you modify the existing parser to handle nested lists? # Development Environment * Python 3.8+ * XML fi...
import xml.etree.ElementTree as ET from collections import defaultdict def parse_xml(root): """ Parses an XML element (root) into a dictionary, handling nested elements with the same name as lists. """ def parse_element(element): parsed = defaultdict(list) for child in element: ...
from solution import xml_to_dict def test_single_node(): xml_string = '<root><child>value</child></root>' expected_output = {'child': {'text': 'value'}} assert xml_to_dict(xml_string) == expected_output def test_nested_nodes(): xml_string = ''' <root> <parent> <child>value1</ch...
[ { "docstring": "Parses an XML element (root) into a dictionary, \nhandling nested elements with the same name as lists.", "function_declaration": "def parse_xml(root):", "function_name": "parse_xml", "parameter_list": "(root)" }, { "docstring": "Converts an XML string to a dict.", "funct...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import xml.etree.ElementTree as ET\n\ndef parse_xml_with_nested_lists(xml_string):\n \"\"\"\n Parses an XML string and returns a nested dictionary to support nested lists within lists.\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00011503", "row_id": 11503, "seed_ids": "['Llama-3.3-70B-Instruct_30463']" }
0.569509
Filter_11503
I
[ "parse_xml", "xml_to_dict" ]
2
[ [ "xml_to_dict", "parse_xml" ] ]
1
[]
false
[]
false
pytest
true
[]
true
25a7d7969f6908bb1da57c4b23d75746ad84aabd
430ec04b7fb2037ba7840a223b1a5333c870bf39
v1.0
instruct
Filter
Filter_11507_I
I'm trying to write a program that will generate a random number between two values. In my case, I want to generate a number between 1 and 100. I want the user to be able to input the minimum and maximum values. Here is what I have so far: ```python import random def generate_random_number(min_value, max_value): ...
import random def generate_random_number(min_value, max_value): return random.randint(min_value, max_value) def get_integer_input(prompt): while True: try: return int(input(prompt)) except ValueError: print("Invalid input. Please enter a valid integer.") def get_min_ma...
import pytest from unittest.mock import patch from solution import generate_random_number, get_integer_input, get_min_max_values def test_generate_random_number(): random_number = generate_random_number(1, 100) assert 1 <= random_number <= 100 def test_get_integer_input_valid(): with patch('builtins.input...
[ { "docstring": null, "function_declaration": "def generate_random_number(min_value, max_value):", "function_name": "generate_random_number", "parameter_list": "(min_value, max_value)" }, { "docstring": null, "function_declaration": "def get_integer_input(prompt):", "function_name": "...
[ 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 generate_random_number(min_value, max_value):\n return random.randint(min_value, max_value)\n\ndef get_valid_integer(prompt):\n while True:\n try:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00011507", "row_id": 11507, "seed_ids": "['Llama-3.3-70B-Instruct_30471']" }
0.483549
Filter_11507
I
[ "generate_random_number", "get_integer_input", "get_min_max_values", "main" ]
4
[ [ "get_min_max_values", "get_integer_input" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7bf64c2b7cd1d3e49d43991e52ab6301b9a4778c
c830b2838a55af217c7480c8abccef7aa4a58ee7