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_7859_I
I have an app that stores a list of contacts and their birthdays. I want to add a feature that calculates the age of each contact. The problem is that my contacts' birthdays are stored as strings in 'YYYY-MM-DD' format. I also have a current date which is a string in 'YYYY-MM-DD' format. I want a function that calcul...
from datetime import datetime def calculate_age(birthday, current_date): """ Calculate age of a person based on the birthday and the current date. :param birthday: str, birthday in 'YYYY-MM-DD' format :param current_date: str, current date in 'YYYY-MM-DD' format :return: int, age of the person...
from solution import calculate_age, add_ages_to_contacts def test_calculate_age(): assert calculate_age("1990-02-12", "2024-09-16") == 34 assert calculate_age("1995-01-25", "2024-09-16") == 29 assert calculate_age("1980-09-15", "2024-09-16") == 44 assert calculate_age("2000-12-31", "2024-01-01") == 23 ...
[ { "docstring": "Calculate age of a person based on the birthday and the current date.\n\n:param birthday: str, birthday in 'YYYY-MM-DD' format\n:param current_date: str, current date in 'YYYY-MM-DD' format\n:return: int, age of the person", "function_declaration": "def calculate_age(birthday, current_date):...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import datetime\n\ndef calculate_age(birthday, current_date):\n \"\"\"\n Calculate age of a person based on the birthday and the current date.\n \n :param birthday: s...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007859", "row_id": 7859, "seed_ids": "['Llama-3.3-70B-Instruct_22125']" }
0.586824
Filter_7859
I
[ "calculate_age", "add_ages_to_contacts" ]
2
[ [ "add_ages_to_contacts", "calculate_age" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9056dc34e02873121451db33e4870c5ede2c2784
d89af1dfee04cdaca2a847d3309706b2640f3f19
v1.0
instruct
Filter
Filter_7862_I
In this problem, you will use Python to simulate the coin-flipping experiment. Your program will flip a coin a specified number of times, and then count how many times the coin came up heads. You will repeat this experiment many times, and keep track of how many heads came up in each repetition.
import random def flip_coin(): """ Simulates a single coin flip. Returns True for heads and False for tails. """ return random.choice([True, False]) def simulate_flips(num_flips): """ Simulates flipping a coin num_flips times. Returns the number of heads (True) that were flipped. "...
from solution import flip_coin, simulate_flips, repeat_experiment def test_flip_coin(): heads_count = sum(flip_coin() for _ in range(1000)) assert 400 < heads_count < 600 # Approximately 50% heads in a large sample size def test_simulate_flips(): num_flips = 10 heads_count = simulate_flips(num_flips)...
[ { "docstring": "Simulates a single coin flip.\nReturns True for heads and False for tails.", "function_declaration": "def flip_coin():", "function_name": "flip_coin", "parameter_list": "()" }, { "docstring": "Simulates flipping a coin num_flips times.\nReturns the number of heads (True) that...
[ 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 flip_coin():\n \"\"\"\n Simulates a single coin flip.\n Returns 'H' for heads and 'T' for tails.\n \"\"\"\n return 'H' if random.random() > 0.5 else 'T'\n\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007862", "row_id": 7862, "seed_ids": "['Llama-3.3-70B-Instruct_22137']" }
0.489513
Filter_7862
I
[ "flip_coin", "simulate_flips", "repeat_experiment" ]
3
[ [ "repeat_experiment", "simulate_flips" ], [ "simulate_flips", "flip_coin" ] ]
2
[]
false
[]
false
pytest
true
[]
true
29e8fca80e0d6c03598a94ce3dec005bb4ad4eca
9c5e926b73e1a3ca738f4f125bab884145a2c590
v1.0
instruct
Filter
Filter_7883_I
### Word Scramble Game #### Game Description The goal is to unscramble letters to form a valid English word. The game should be able to handle a collection of words and allow users to play multiple rounds. #### Game Requirements * The game should randomly select a word from the collection of words. * The game should s...
import random # Define a list of words words = ["apple", "banana", "cherry", "date", "elderberry"] def scramble_word(word): """Scramble the letters of a word.""" return "".join(random.sample(word, len(word))) def play_round(word_choice_func, get_input_func): """Play a round of the word scramble game, all...
from solution import scramble_word, play_round def test_scramble_word(): word = "banana" scrambled_word = scramble_word(word) assert sorted(scrambled_word) == sorted(word) assert scrambled_word != word # Very unlikely but possible edge case has been considered as well def test_play_round_correct_answ...
[ { "docstring": "Scramble the letters of a word.", "function_declaration": "def scramble_word(word):", "function_name": "scramble_word", "parameter_list": "(word)" }, { "docstring": "Play a round of the word scramble game, allowing for dependency injection of word choice and input functions."...
[ 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 list of words\nwords = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\"]\n\ndef scramble_word(word):\n \"\"\"Scramble the letters of a word.\"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007883", "row_id": 7883, "seed_ids": "['Llama-3.3-70B-Instruct_22180']" }
0.660341
Filter_7883
I
[ "scramble_word", "play_round", "play_game" ]
3
[ [ "play_game", "play_round" ], [ "play_round", "scramble_word" ] ]
2
[]
false
[]
false
pytest
true
[]
true
158b9df4c397300fcd9701d847bec5f6a97858e0
ad11c0afb81e346d6eb782dc088b2f815d129ffa
v1.0
instruct
Filter
Filter_7885_I
I have a function `f(x)` which depends on x and I want to calculate `f'(x)`. However, I'm not given a specific function, but rather a general form that `f(x)` can take. Given that `f(x) = x^3 + 3x^2 + 2x + 1`, calculate `f'(x)`. Note: For this specific case, I have been given the function and I know how to calculate ...
import sympy as sp def calculate_derivative(expr, variable): """ Calculate the derivative of a given sympy expression with respect to a given variable. Parameters: - expr: sympy expression, the function to differentiate. - variable: sympy symbol, the variable to differentiate with respect to. ...
from solution import calculate_derivative, derivative_from_string import sympy as sp def test_calculate_derivative(): x = sp.symbols('x') f = x**3 + 3*x**2 + 2*x + 1 expected_derivative = 3*x**2 + 6*x + 2 assert calculate_derivative(f, x) == expected_derivative def test_derivative_from_string(): e...
[ { "docstring": "Calculate the derivative of a given sympy expression with respect to a given variable.\n\nParameters:\n- expr: sympy expression, the function to differentiate.\n- variable: sympy symbol, the variable to differentiate with respect to.\n\nReturns:\n- Derivative of the expression with respect to th...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sympy as sp\n\ndef symbolic_derivative(func):\n \"\"\"\n Calculate the derivative of a given symbolic function.\n \n Parameters:\n func (sympy expression): The symbol...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007885", "row_id": 7885, "seed_ids": "['Llama-3.3-70B-Instruct_22182']" }
0.586154
Filter_7885
I
[ "calculate_derivative", "derivative_from_string" ]
2
[ [ "derivative_from_string", "calculate_derivative" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
b4313dafd1746f731edc39619d7b97afc20e0010
05efdddca66dc2286823b5f4ca8e3c94c304d396
v1.0
instruct
Filter
Filter_7899_I
I have data that has two categories only (A or B). I'm trying to classify this two-category data using Random Forest. However, I'm getting very different results with sklearn's RF and my own implementation. I've implemented RF from scratch, but I'm not sure if it's correct. Here's my code for my implementation: ``` im...
import numpy as np def entropy(y): p = np.mean(y == 1) if p == 0 or p == 1: return 0 return -p * np.log2(p) - (1 - p) * np.log2(1 - p) def gain(left, right, parent_entropy): n = len(left) + len(right) el = entropy(left) er = entropy(right) return parent_entropy - (len(left)/n)*el -...
import numpy as np from solution import entropy, gain, decision_tree, random_forest, predict_rf def test_entropy(): assert entropy(np.array([1, 1, 1, 1])) == 0 assert entropy(np.array([1, 1, 0, 0])) == 1 assert entropy(np.array([1, 0, 0, 0])) == 0.8112781244591328 def test_gain(): parent_entropy = ent...
[ { "docstring": null, "function_declaration": "def entropy(y):", "function_name": "entropy", "parameter_list": "(y)" }, { "docstring": null, "function_declaration": "def gain(left, right, parent_entropy):", "function_name": "gain", "parameter_list": "(left, right, parent_entropy)"...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.ensemble import RandomForestClassifier\nimport numpy as np\n\ndef entropy(y):\n \"\"\"\n Calculates the entropy of a binary array y.\n \"\"\"\n if len(y) == 0:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007899", "row_id": 7899, "seed_ids": "['Llama-3.3-70B-Instruct_22213']" }
0.481611
Filter_7899
I
[ "entropy", "gain", "decision_tree", "predict", "random_forest", "predict_rf" ]
6
[ [ "decision_tree", "entropy" ], [ "decision_tree", "gain" ], [ "gain", "entropy" ], [ "predict_rf", "predict" ], [ "random_forest", "decision_tree" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
34405b2fcf3b0f962b25eed8ea7fc5e31e2a1f9b
07a9185a1f708028062f4db6866444013f039c95
v1.0
instruct
Filter
Filter_7906_I
I'm trying to design a simple game of Tic Tac Toe in the console. Here's what I have so far: ```python def print_board(board): for row in board: print(" | ".join(row)) print("---------") def check_win(board): for row in board: if row[0] == row[1] == row[2] != " ": return row...
def print_board(board): for row in board: print(" | ".join(row)) print("---------") def check_win(board): for row in board: if row[0] == row[1] == row[2] != " ": return row[0] for col in range(3): check = [] for row in board: check.append(row[...
from solution import check_win, is_board_full def test_check_win_row(): board = [["X", "X", "X"], [" ", "O", " "], [" ", " ", "O"]] assert check_win(board) == "X" def test_check_win_col(): board = [["X", " ", "O"], ["X", "O", " "], ["X", " ", " "]] a...
[ { "docstring": null, "function_declaration": "def print_board(board):", "function_name": "print_board", "parameter_list": "(board)" }, { "docstring": null, "function_declaration": "def check_win(board):", "function_name": "check_win", "parameter_list": "(board)" }, { "doc...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def print_board(board):\n for row in board:\n print(\" | \".join(row))\n print(\"---------\")\n\ndef check_win(board):\n for row in board:\n if row[0] == row[1] == r...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007906", "row_id": 7906, "seed_ids": "['Llama-3.3-70B-Instruct_22229']" }
0.496461
Filter_7906
I
[ "print_board", "check_win", "is_board_full", "play_game" ]
4
[ [ "play_game", "check_win" ], [ "play_game", "is_board_full" ], [ "play_game", "print_board" ] ]
3
[]
false
[]
false
pytest
true
[]
true
0b692cfc1d39983b1732e6ca357ce0a941c78cbb
d38596fae9e1666cb39e2c98a590cd096af1b85b
v1.0
instruct
Filter
Filter_7938_I
I think there may be an issue with the implementation of my Python script. It's designed to find the closest pair of points. The closest pair of points is a pair of points that are closest to each other. I've implemented the brute force solution, but I would like to implement the divide and conquer solution using div...
import math def distance(point1, point2): return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y): num_points = len(points_sorted_by_x) # Base case when there's few points to compare if num_points <= 3: r...
from solution import divide_and_conquer_closest_pair, brute_force_closest_pair, distance def test_example_case(): points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] closest_pair, min_distance = divide_and_conquer_closest_pair(points) assert closest_pair == ((2, 3), (3, 4)) assert math.iscl...
[ { "docstring": null, "function_declaration": "def distance(point1, point2):", "function_name": "distance", "parameter_list": "(point1, point2)" }, { "docstring": null, "function_declaration": "def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y):", "function_name": "clo...
[ 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 distance(point1, point2):\n return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)\n\ndef brute_force_closest_pair(points):\n min_distance = float('...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007938", "row_id": 7938, "seed_ids": "['Llama-3.3-70B-Instruct_22308']" }
0.579337
Filter_7938
I
[ "distance", "closest_pair_recursive", "closest_in_strip", "divide_and_conquer_closest_pair", "brute_force_closest_pair" ]
5
[ [ "brute_force_closest_pair", "distance" ], [ "closest_in_strip", "distance" ], [ "closest_pair_recursive", "brute_force_closest_pair" ], [ "closest_pair_recursive", "closest_in_strip" ], [ "divide_and_conquer_closest_pair", "closest_pair_recursive" ] ]
5
[]
false
[]
false
pytest
true
[]
true
4f084f39e093135517a0d59fdc6c70def4911ebd
755ff66dc13c094734c585a0f0775ed99816a088
v1.0
instruct
Filter
Filter_7944_I
Given the following Python code: ```python import random import math def rand_list(): return [random.randint(1, 100) for _ in range(10)] def rand_matrix(): return [[random.randint(1, 100) for _ in range(10)] for _ in range(10)] def dist(p1, p2): return math.sqrt(sum([(a - b) ** 2 for a, b in zip(p1, p2)]...
import random import math def rand_list(): return [[random.randint(1, 100) for _ in range(10)] for _ in range(10)] def rand_matrix(): return [[random.randint(1, 100) for _ in range(10)] for _ in range(10)] def dist(p1, p2): return math.sqrt(sum([(a - b) ** 2 for a, b in zip(p1, p2)])) def min_dist(matri...
from solution import rand_list, rand_matrix, dist, min_dist def test_rand_list_dimensions(): result = rand_list() assert len(result) == 10 assert all(len(point) == 10 for point in result) def test_rand_matrix_dimensions(): result = rand_matrix() assert len(result) == 10 assert all(len(row)...
[ { "docstring": null, "function_declaration": "def rand_list():", "function_name": "rand_list", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def rand_matrix():", "function_name": "rand_matrix", "parameter_list": "()" }, { "docstring": null, "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport math\n\ndef rand_point():\n return [random.randint(1, 100) for _ in range(10)]\n\ndef rand_list():\n return [rand_point() for _ in range(10)]\n\ndef rand_matrix():\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007944", "row_id": 7944, "seed_ids": "['Llama-3.3-70B-Instruct_22317']" }
0.667915
Filter_7944
I
[ "rand_list", "rand_matrix", "dist", "min_dist" ]
4
[ [ "min_dist", "dist" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4ba0c657f78dd3fb48ecc3cbfffbcbc852644539
adb24936e05f5ea7f6f9de1faa0305cee3077ed8
v1.0
instruct
Filter
Filter_7950_I
I've been trying to write a program that can find all the duplicate files in a directory. A program that will identify duplicate files based on their content, not their name. I've been having trouble writing this program. Here are the details of the program you should write: 1. The program will take a directory path a...
import os import sys import hashlib def calculate_checksum(file_path): """ Calculate the SHA-256 checksum of a file. """ sha256 = hashlib.sha256() try: with open(file_path, 'rb') as file: while chunk := file.read(8192): sha256.update(chunk) except OSError: ...
import os import pytest from tempfile import TemporaryDirectory from solution import calculate_checksum, find_duplicates def create_test_file(directory, filename, content): """ Helper function to create a test file with given content. """ file_path = os.path.join(directory, filename) with open(file...
[ { "docstring": "Calculate the SHA-256 checksum of a file.", "function_declaration": "def calculate_checksum(file_path):", "function_name": "calculate_checksum", "parameter_list": "(file_path)" }, { "docstring": "Find all duplicate files in the given directory.", "function_declaration": "...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport sys\nimport hashlib\n\ndef calculate_checksum(file_path):\n \"\"\"\n Calculate the SHA256 checksum of a file.\n \"\"\"\n sha256 = hashlib.sha256()\n try:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007950", "row_id": 7950, "seed_ids": "['Llama-3.3-70B-Instruct_22329']" }
0.621165
Filter_7950
I
[ "calculate_checksum", "find_duplicates", "main" ]
3
[ [ "find_duplicates", "calculate_checksum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
53b1fbce03c185e7e67d8dfa27d8b1ba69816deb
95a714f7cf2d065df444b774d9325919c7ee4c8f
v1.0
instruct
Filter
Filter_7951_I
Create a code that reads an integer from the user, then checks if the integer is within a specified range (for example, 1-100). If it is, the program will proceed to check if the integer is a prime number. If the integer is not within the specified range or is not a prime number, the program will display an error messa...
def is_prime(n): """ Check if a number is a prime number. """ if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def validate_integer_in_range(n, lower=1, upper=100): """ Validate if the integer n is within ...
from solution import is_prime, validate_integer_in_range def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(11) == True assert is_prime(1) == False assert is_prime(-1) == False assert is_prime...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Validate if the integer n is within the specified range [lower, upper].", "function_declaration": "def validate_integ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"Check if a number is a prime number.\"\"\"\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007951", "row_id": 7951, "seed_ids": "['Llama-3.3-70B-Instruct_22331']" }
0.611281
Filter_7951
I
[ "is_prime", "validate_integer_in_range", "get_valid_prime_in_range" ]
3
[ [ "get_valid_prime_in_range", "is_prime" ], [ "get_valid_prime_in_range", "validate_integer_in_range" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9c65ba5f84268d90bef43d67962dad2d1e44476c
a7fd1936fae692b071f8caa014980efd15de3406
v1.0
instruct
Filter
Filter_7959_I
I've got a little trio of ordinary differential equations, three first-order ODEs. I'm looking to solve them using Python's `scipy.integrate` module. Here's the lot: dx/dt = cos(y) * sin(z) dy/dt = sin(x) * cos(z) dz/dt = cos(x) * sin(y) Can you show me a simplified example of how you'd tackle this?
import numpy as np from scipy.integrate import solve_ivp def odes(t, y): """ Defines the system of ordinary differential equations. Parameters: t : float Independent variable (time) y : array_like, shape (3,) Dependent variables [x, y, z] Returns: dydt : array,...
import numpy as np from solution import odes, solve_odes def test_odes(): # Test the derivative function at a specific point t = 0 y = [1, 1, 1] dydt = odes(t, y) assert np.allclose(dydt, [np.cos(1) * np.sin(1), np.sin(1) * np.cos(1), np.cos(1) * np.sin(1)], rtol=1e-5) def test_solve_odes(): #...
[ { "docstring": "Defines the system of ordinary differential equations.\n\nParameters:\nt : float\n Independent variable (time)\ny : array_like, shape (3,)\n Dependent variables [x, y, z]\n \nReturns:\ndydt : array, shape (3,)\n Derivatives [dx/dt, dy/dt, dz/dt]", "function_declaration": "def ode...
[ 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 solve_ivp\n\ndef odes(t, y):\n x, y, z = y\n dxdt = np.cos(y) * np.sin(z)\n dydt = np.sin(x) * np.cos(z)\n dzdt = np.cos(x) * np.sin...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007959", "row_id": 7959, "seed_ids": "['Llama-3.3-70B-Instruct_22352']" }
0.278965
Filter_7959
I
[ "odes", "solve_odes" ]
2
[ [ "solve_odes", "odes" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
6cec748bffb351461a05510c09371409fcac375d
bb2fd9e75586faed2aa74a465b45eb5c43d654d0
v1.0
instruct
Filter
Filter_7974_I
I'll give you a task. Write a Python program to find the sum of all the prime numbers within a given range (m, n). ## Step-by-step analysis of the problem: 1. **Define a helper function to check if a number is prime**: This function will take an integer as input and return True if it's prime, False otherwise. 2. **Ite...
def is_prime(number): """ Checks if a number is prime. """ if number <= 1: return False for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def sum_of_primes_in_range(m, n): """ Returns the sum of all prime numbers in the r...
from solution import is_prime, sum_of_primes_in_range def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(17) == True assert is_prime(18) == False assert is_prime(19) == True assert is_prime(1)...
[ { "docstring": "Checks if a number is prime.", "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": "Returns the sum of all prime numbers in the range (m, n).", "function_declaration": "def sum_of_primes_in_range(m, ...
[ 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(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007974", "row_id": 7974, "seed_ids": "['Llama-3.3-70B-Instruct_22375']" }
0.602966
Filter_7974
I
[ "is_prime", "sum_of_primes_in_range" ]
2
[ [ "sum_of_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b45236134546aba2e459d7700896010966a27b64
b25215c61028b891a24605db591e313f4a0817cb
v1.0
instruct
Filter
Filter_7985_I
Can you explain how to write a recursive function in Python to solve the "Maximum Subarray" problem?
def max_crossing_sum(arr, left, mid, right): # Include elements on left of mid sm = 0 left_sum = float('-inf') for i in range(mid, left-1, -1): sm = sm + arr[i] if (sm > left_sum): left_sum = sm # Include elements on right of mid sm = 0 ...
from solution import find_maximum_subarray def test_all_positive_numbers(): assert find_maximum_subarray([1, 2, 3, 4, 5]) == 15 def test_all_negative_numbers(): assert find_maximum_subarray([-1, -2, -3, -4, -5]) == -1 def test_mixed_positive_and_negative_numbers(): assert find_maximum_subarray([-2, 1, -3...
[ { "docstring": null, "function_declaration": "def max_crossing_sum(arr, left, mid, right):", "function_name": "max_crossing_sum", "parameter_list": "(arr, left, mid, right)" }, { "docstring": null, "function_declaration": "def max_subarray_sum(arr, left, right):", "function_name": "m...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_crossing_sum(arr, left, mid, right):\n \"\"\"\n Helper function to find the maximum possible sum of a subarray crossing the midpoint.\n \"\"\"\n left_sum = float('-inf')\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007985", "row_id": 7985, "seed_ids": "['Llama-3.3-70B-Instruct_22397']" }
0.681384
Filter_7985
I
[ "max_crossing_sum", "max_subarray_sum", "find_maximum_subarray" ]
3
[ [ "find_maximum_subarray", "max_subarray_sum" ], [ "max_subarray_sum", "max_crossing_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
721e424415ec7e491a97f2991d3989c8ff48bdc4
101026bcc4df6deefd74a1ca6e155c92cf22d326
v1.0
instruct
Filter
Filter_8011_I
### Initialization Before we start, I want to make sure you understand the context and the task at hand. I have a project where I need to read data from a file, then transform it and finally write the transformed data to another file. ### Task The task is to take the input file, read it line by line, transform each li...
def transform_line(line): """ Transforms a line from the input file to the required output format. Example of input line: 'John 25' Expected output: 'Name: John, Age: 25' """ name, age = line.strip().split() return f"Name: {name}, Age: {age}" def process_files(input_filename, output_fi...
import pytest import os from solution import transform_line, process_files # Test transform_line function def test_transform_line(): assert transform_line("John 25") == "Name: John, Age: 25" assert transform_line("Alice 30") == "Name: Alice, Age: 30" assert transform_line("Bob 35") == "Name: Bob, Age: 35"...
[ { "docstring": "Transforms a line from the input file to the required output format.\n\nExample of input line: 'John 25'\nExpected output: 'Name: John, Age: 25'", "function_declaration": "def transform_line(line):", "function_name": "transform_line", "parameter_list": "(line)" }, { "docstrin...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def transform_line(line):\n \"\"\"\n Transform a single line from the input format to the output format.\n \n Args:\n line (str): A line from the input file, e.g., 'John 25'.\n\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008011", "row_id": 8011, "seed_ids": "['Llama-3.3-70B-Instruct_22448']" }
0.514069
Filter_8011
I
[ "transform_line", "process_files" ]
2
[ [ "process_files", "transform_line" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3c30b86080d174bed00ea4abf7cb12b39fb2d7e2
0fbe55a9dfb7dac542eb4ecc4e88e221bb7dbac5
v1.0
instruct
Filter
Filter_8023_I
I have been trying to implement a function that can return all the prime numbers within a given range [a, b] (assuming a and b are integers). However, I am having trouble achieving this. Could you please provide me with a Python function that accomplishes this task efficiently?
def is_prime(n): """ Check if a number is prime """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True ...
from solution import is_prime, find_primes_in_range def test_is_prime(): assert is_prime(0) == False assert is_prime(1) == False assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False def test_find_primes_i...
[ { "docstring": "Check if a number is prime", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers within the range [a, b] inclusive", "function_declaration": "def find_primes_in_range(a, b)...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n in (2, 3):\n return True\n if n % 2 == 0 or n % 3 == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008023", "row_id": 8023, "seed_ids": "['Llama-3.3-70B-Instruct_22473']" }
0.630752
Filter_8023
I
[ "is_prime", "find_primes_in_range" ]
2
[ [ "find_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0fc86d92fcc447103dba2150458484a77e58d671
b9745c01ce5a6734bbdf7a3a6776ab8d47f3368d
v1.0
instruct
Filter
Filter_8042_I
I have a dataset of exam results where students are assigned grades based on their scores. The grades are assigned based on the following rules: - 'A' if the score is 90 or above - 'B' if the score is between 80 and 89 - 'C' if the score is between 70 and 79 - 'D' if the score is between 60 and 69 - 'F' if the score is...
def get_grade(score): """ Returns the letter grade for a given score based on the defined grading criteria. Handles scores from 0 to 100. """ if not isinstance(score, (int, float)): raise ValueError("Score must be a number.") if not 0 <= score <= 100: raise ValueError("Score must...
from solution import get_grade, get_grades def test_get_grade(): assert get_grade(95) == 'A' assert get_grade(85) == 'B' assert get_grade(75) == 'C' assert get_grade(65) == 'D' assert get_grade(55) == 'F' def test_get_grade_edge_cases(): assert get_grade(90) == 'A' assert get_grade(80) == ...
[ { "docstring": "Returns the letter grade for a given score based on the defined grading criteria.\nHandles scores from 0 to 100.", "function_declaration": "def get_grade(score):", "function_name": "get_grade", "parameter_list": "(score)" }, { "docstring": "Returns a list of letter grades for...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_grade(score):\n if not isinstance(score, (int, float)):\n raise ValueError(\"Score must be a number.\")\n if score < 0 or score > 100:\n raise ValueError(\"Score mu...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008042", "row_id": 8042, "seed_ids": "['Llama-3.3-70B-Instruct_22511']" }
0.749801
Filter_8042
I
[ "get_grade", "get_grades" ]
2
[ [ "get_grades", "get_grade" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dbc0b0321c001518aec90f272373b1d7b62845bd
f76ccfa28f1557a39eb389009942cb9d771fde28
v1.0
instruct
Filter
Filter_8059_I
Based on the information below, write a program in Python to read in the following commands from a text file named "input.txt" and then execute them. The commands defined are: - add <number1> <number2> - sub <number1> <number2> - mul <number1> <number2> - div <number1> <number2> - power <number1> <number2> Where <numb...
def process_command(command): parts = command.split() if len(parts) != 3: raise ValueError("Invalid command format") operation, number1, number2 = parts[0], float(parts[1]), float(parts[2]) if operation == 'add': return number1 + number2 elif operation == 'sub': ret...
import pytest from solution import process_command, execute_commands_from_file def test_process_command_add(): assert process_command('add 2 3') == 5 def test_process_command_sub(): assert process_command('sub 5 3') == 2 def test_process_command_mul(): assert process_command('mul 2 3') == 6 def test_pro...
[ { "docstring": null, "function_declaration": "def process_command(command):", "function_name": "process_command", "parameter_list": "(command)" }, { "docstring": null, "function_declaration": "def execute_commands_from_file(filename):", "function_name": "execute_commands_from_file", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def add(number1, number2):\n return number1 + number2\n\ndef sub(number1, number2):\n return number1 - number2\n\ndef mul(number1, number2):\n return number1 * number2\n\ndef div(numb...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008059", "row_id": 8059, "seed_ids": "['Llama-3.3-70B-Instruct_22539']" }
0.474796
Filter_8059
I
[ "process_command", "execute_commands_from_file" ]
2
[ [ "execute_commands_from_file", "process_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3dcb0ad74fc49fa54a079c524da69621ce2aa23b
2ee98e57861494838ba42fbdb938023c0ea9a42b
v1.0
instruct
Filter
Filter_8060_I
I have a function that draws a circle using the parametric equation for a circle: `x = r*cos(t) + x0` and `y = r*sin(t) + y0`. The function takes `r`, `x0`, `y0` and a list of `t` values as input, and returns a list of `(x, y)` coordinates. The function is written in Python and uses NumPy. Here is the function: ```py...
import numpy as np import matplotlib.pyplot as plt def draw_circle(r, x0, y0, t): x = r * np.cos(t) + x0 y = r * np.sin(t) + y0 return np.column_stack((x, y)) def plot_circle(r, x0, y0, t): coordinates = draw_circle(r, x0, y0, t) plt.figure() plt.plot(coordinates[:, 0], coordinates[:, 1], labe...
import numpy as np from solution import draw_circle, plot_circle def test_draw_circle(): r = 1.0 x0 = 0.0 y0 = 0.0 t = np.linspace(0, 2 * np.pi, 100) coordinates = draw_circle(r, x0, y0, t) assert coordinates.shape == (100, 2), "The shape of the returned coordinates array is incorrect" asse...
[ { "docstring": null, "function_declaration": "def draw_circle(r, x0, y0, t):", "function_name": "draw_circle", "parameter_list": "(r, x0, y0, t)" }, { "docstring": null, "function_declaration": "def plot_circle(r, x0, y0, t):", "function_name": "plot_circle", "parameter_list": "(...
[ 1, 1, 0 ]
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 numpy as np\n\ndef draw_circle(r, x0, y0, t):\n x = r * np.cos(t) + x0\n y = r * np.sin(t) + y0\n return np.column_stack((x, y))\n\ndef plot_ci...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008060", "row_id": 8060, "seed_ids": "['Llama-3.3-70B-Instruct_22541']" }
0.627665
Filter_8060
I
[ "draw_circle", "plot_circle" ]
2
[ [ "plot_circle", "draw_circle" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
c074fd173d7f6811a60479c02af4698ee7d3df72
2cf9545faed852632b93cd49c8a80da892c4da41
v1.0
instruct
Filter
Filter_8063_I
Here is the code to generate the first 100 prime numbers: ```python def is_prime(num): if num < 2: return False for i in range(2, num): if num % i == 0: return False return True def get_primes(n): primes = [] num = 2 while len(primes) < n: if is_prime(num): ...
def is_prime(num): """ Check if a number is prime. """ if num < 2: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True def get_primes_until(limit): """ Generate all prime numbers up to a given limit. """ primes...
from solution import is_prime, get_primes_until def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-1) == False def test_get_primes_until(...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Generate all prime numbers up to a given limit.", "function_declaration": "def get_primes_until(limit):", "function_na...
[ 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 Check if a number is prime.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008063", "row_id": 8063, "seed_ids": "['Llama-3.3-70B-Instruct_22546']" }
0.628491
Filter_8063
I
[ "is_prime", "get_primes_until" ]
2
[ [ "get_primes_until", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7b9d14a5f5184c7f081552f38baeb5862cc1023e
1ed5c8f54110e78d4f7b5e95ab772911defccbdf
v1.0
instruct
Filter
Filter_8069_I
To determine if a number is prime, we can use the fact that a larger factor of the number would be a multiple of smaller factor that has already been checked. Write a code that implements the above idea and returns all the prime numbers in a given range of numbers.
def is_prime(n): """ Determines if the given number n is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 ...
from solution import is_prime, primes_in_range def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(10) == False assert is_prime(11) == True assert is_prime(-1) == False assert is_prime(0) == Fa...
[ { "docstring": "Determines if the given number n is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers in the specified range [start, end).", "function_declaration": "def primes_in_r...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Determines if a number is prime.\n \n Args:\n n (int): The number to check.\n \n Returns:\n bool: True if the number is prime, else False.\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008069", "row_id": 8069, "seed_ids": "['Llama-3.3-70B-Instruct_22556']" }
0.683946
Filter_8069
I
[ "is_prime", "primes_in_range" ]
2
[ [ "primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
36172aeba9d21b92ac9f2f1ccb48ec8c2e32ab77
09745a8efe8fee5bd70927009fe57cbf0773517a
v1.0
instruct
Filter
Filter_8084_I
I have a list of words, and for each word, I want to find the nearest neighbor in a given set of words. The nearest neighbor is defined as the word with the minimum Levenshtein distance. How can I do this in Python?
def levenshtein_distance(s1, s2): """ Compute the Levenshtein distance between two strings. """ if len(s1) < len(s2): return levenshtein_distance(s2, s1) if len(s2) == 0: return len(s1) previous_row = list(range(len(s2) + 1)) for i, c1 in enumerate(s1): current_row ...
from solution import levenshtein_distance, find_nearest_neighbor, get_nearest_neighbors def test_levenshtein_distance(): assert levenshtein_distance("kitten", "sitting") == 3 assert levenshtein_distance("flaw", "lawn") == 2 assert levenshtein_distance("intention", "execution") == 5 assert levenshtein_d...
[ { "docstring": "Compute the Levenshtein distance between two strings.", "function_declaration": "def levenshtein_distance(s1, s2):", "function_name": "levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": "Find the nearest neighbor of the given word in the words_set.", "f...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def levenshtein_distance(s1, s2):\n \"\"\"\n Compute the Levenshtein distance between two strings.\n \"\"\"\n if len(s1) < len(s2):\n return levenshtein_distance(s2, s1)\n\n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008084", "row_id": 8084, "seed_ids": "['Llama-3.3-70B-Instruct_22591']" }
0.571694
Filter_8084
I
[ "levenshtein_distance", "find_nearest_neighbor", "get_nearest_neighbors" ]
3
[ [ "find_nearest_neighbor", "levenshtein_distance" ], [ "get_nearest_neighbors", "find_nearest_neighbor" ] ]
2
[]
false
[]
false
pytest
true
[]
true
213ef4cc6be7d53aaff89ebf42a95f56e3f5643b
574ca45bb41010e8c33584bda9ae0b778727f29f
v1.0
instruct
Filter
Filter_8118_I
### Assignment 6.2: Rock, Paper, Scissors For this assignment, you will implement a Rock, Paper, Scissors game in Python. The game should allow the user to choose one of Rock, Paper, or Scissors, and then the computer will randomly select one of the options. The game will keep track of the score and display it after ea...
import random def get_computer_choice(): choices = ['Rock', 'Paper', 'Scissors'] return random.choice(choices) def determine_winner(user_choice, computer_choice): if user_choice == computer_choice: return 'Draw' elif (user_choice == 'Rock' and computer_choice == 'Scissors') or \ (user...
from solution import get_computer_choice, determine_winner def test_get_computer_choice(): choices = ['Rock', 'Paper', 'Scissors'] assert get_computer_choice() in choices def test_determine_winner(): assert determine_winner('Rock', 'Scissors') == 'User' assert determine_winner('Scissors', 'Paper') == ...
[ { "docstring": null, "function_declaration": "def get_computer_choice():", "function_name": "get_computer_choice", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def determine_winner(user_choice, computer_choice):", "function_name": "determine_winner", "p...
[ 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 get_computer_choice():\n choices = ['Rock', 'Paper', 'Scissors']\n return random.choice(choices)\n\ndef determine_winner(user_choice, computer_choice):\n if user_...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008118", "row_id": 8118, "seed_ids": "['Llama-3.3-70B-Instruct_22655']" }
0.59811
Filter_8118
I
[ "get_computer_choice", "determine_winner", "rock_paper_scissors_game" ]
3
[ [ "rock_paper_scissors_game", "determine_winner" ], [ "rock_paper_scissors_game", "get_computer_choice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
95173220e237563c7896d90dc5df723a9b279c47
df8e189b17abebc6286e20d9f25936959ce4516f
v1.0
instruct
Filter
Filter_8156_I
I will give you a set of distances between cities. Can you create a Python program to calculate the shortest path that visits each city exactly once and then returns to the first city?
import itertools def calculate_total_distance(route, distance_matrix): total_distance = 0 for i in range(len(route) - 1): total_distance += distance_matrix[route[i]][route[i + 1]] total_distance += distance_matrix[route[-1]][route[0]] # To return to the start city return total_distance def sh...
from solution import shortest_path_tsp def test_shortest_path_tsp_single_city(): distance_matrix = [ [0] ] route, distance = shortest_path_tsp(distance_matrix) assert route == (0,) assert distance == 0 def test_shortest_path_tsp_two_cities(): distance_matrix = [ [0, 10], ...
[ { "docstring": null, "function_declaration": "def calculate_total_distance(route, distance_matrix):", "function_name": "calculate_total_distance", "parameter_list": "(route, distance_matrix)" }, { "docstring": null, "function_declaration": "def shortest_path_tsp(distance_matrix):", "...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def tsp(distances):\n \"\"\"\n Solves the Traveling Salesman Problem for a given distance matrix.\n \n Parameters:\n distances (list of list of ints): 2D list representing dista...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008156", "row_id": 8156, "seed_ids": "['Llama-3.3-70B-Instruct_22749']" }
0.649112
Filter_8156
I
[ "calculate_total_distance", "shortest_path_tsp" ]
2
[ [ "shortest_path_tsp", "calculate_total_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a2a4a371789db2d254d7b828c2d0eb07635ba222
41102278f88ce7826cb8a6ca22de94c41ee04c1d
v1.0
instruct
Filter
Filter_8175_I
I have been given an assignment to create a Python script that can encrypt and decrypt messages using the Caesar Cipher algorithm. The task is to write a Python function that will take in a string input and shift each letter in the string by 3 places to the right, wrapping around to the beginning of the alphabet when n...
def caesar_cipher_encrypt(message, shift=3): """ Encrypts the given message using Caesar Cipher with a shift of 3. Args: message (str): The input string to be encrypted. shift (int): The number of positions each letter should be shifted. Returns: str: The encrypted message. """...
from solution import caesar_cipher_encrypt, caesar_cipher_decrypt def test_caesar_cipher_encrypt(): assert caesar_cipher_encrypt("HELLO") == "KHOOR" assert caesar_cipher_encrypt("hello") == "khoor" assert caesar_cipher_encrypt("abc") == "def" assert caesar_cipher_encrypt("xyz") == "abc" assert caes...
[ { "docstring": "Encrypts the given message using Caesar Cipher with a shift of 3.\n\nArgs:\nmessage (str): The input string to be encrypted.\nshift (int): The number of positions each letter should be shifted.\n\nReturns:\nstr: The encrypted message.", "function_declaration": "def caesar_cipher_encrypt(mess...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def caesar_cipher_encrypt(message, shift=3):\n \"\"\"\n Encrypts a message using the Caesar Cipher algorithm with a default shift of 3.\n \"\"\"\n encrypted_message = []\n for c...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008175", "row_id": 8175, "seed_ids": "['Llama-3.3-70B-Instruct_22798']" }
0.731585
Filter_8175
I
[ "caesar_cipher_encrypt", "caesar_cipher_decrypt" ]
2
[ [ "caesar_cipher_decrypt", "caesar_cipher_encrypt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cdfba779d8b235d1588c8eb48aee5513bd75e29a
16dc184608bdeb6e11920b12c0d83ff6a10c9991
v1.0
instruct
Filter
Filter_8208_I
I've been working on a project that involves a lot of files and folders. After some time, I noticed that I had many duplicate files with the same content. I'd like to find and delete these duplicates to free up some space on my disk. Is there a way to achieve this programmatically, perhaps with Python?
import os import hashlib def get_file_hash(file_path, algorithm=hashlib.md5, chunk_size=4096): """ Computes the hash of a file using the specified hashing algorithm. :param file_path: Path to the file that needs to be hashed. :param algorithm: Hashing algorithm from hashlib module. Defaults to has...
import os import tempfile from solution import find_duplicate_files, get_file_hash def test_get_file_hash(): with tempfile.NamedTemporaryFile(delete=False) as tmp_file: tmp_file.write(b"Test content") tmp_file_path = tmp_file.name assert get_file_hash(tmp_file_path) == get_file_hash(tmp_fi...
[ { "docstring": "Computes the hash of a file using the specified hashing algorithm.\n\n:param file_path: Path to the file that needs to be hashed.\n:param algorithm: Hashing algorithm from hashlib module. Defaults to hashlib.md5.\n:param chunk_size: Size of chunks to read from the file. Defaults to 4096 bytes.\n...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport hashlib\n\ndef get_file_hash(file_path):\n \"\"\"\n Calculates the SHA-256 hash of the given file.\n \"\"\"\n hash_obj = hashlib.sha256()\n with open(file_path...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008208", "row_id": 8208, "seed_ids": "['Llama-3.3-70B-Instruct_22904']" }
0.535517
Filter_8208
I
[ "get_file_hash", "find_duplicate_files" ]
2
[ [ "find_duplicate_files", "get_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0d9d8d44809a3d3bdf63764da9a1a657544932a3
5c16481a2bf468e1f8a4a4b773c792c0a52e748c
v1.0
instruct
Filter
Filter_8239_I
I've been given a large range of integers from a to b (inclusive) and need to find all the prime numbers within this range. Write me a code that accomplishes that. ### Range of Integers The range is defined by two integers, `a` and `b`, where `a` and `b` are the start and end of the range, respectively. ### Prime Num...
def is_prime(n): """Check if a number is prime.""" # Check if n is less than 2 if n < 2: return False # Check if n is 2 if n == 2: return True # Check if n is an even number if n % 2 == 0: return False # Check odd divisors up to the square root of n...
from solution import is_prime, find_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(19) == True assert is_prime(20) == False assert is_prime(1) == False assert is_prime(0) == False ...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find all prime numbers within a given range.", "function_declaration": "def find_primes(a, b):", "function_name": "find_pr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008239", "row_id": 8239, "seed_ids": "['Llama-3.3-70B-Instruct_22972']" }
0.602869
Filter_8239
I
[ "is_prime", "find_primes" ]
2
[ [ "find_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5b3c3362cf11ea284260ab46c507347157331898
f91efb58c2273b41ed83a419d76380b0b54a7ca1
v1.0
instruct
Filter
Filter_8296_I
Can you suggest a way to add conditional logic to a Python function to check if a user has permission to perform an operation?
def permission_required(permission): """ Decorator to check if a user has a specific permission. """ def decorator(func): def wrapper(user, *args, **kwargs): if permission in user.get('permissions', []): return func(user, *args, **kwargs) else: ...
from solution import edit_document, user_with_permission, user_without_permission def test_edit_document_with_permission(): result = edit_document(user_with_permission, "MyDocument") assert result == "Document 'MyDocument' edited by Alice." def test_edit_document_without_permission(): result = edit_docume...
[ { "docstring": "Decorator to check if a user has a specific permission.", "function_declaration": "def permission_required(permission):", "function_name": "permission_required", "parameter_list": "(permission)" }, { "docstring": "Function to edit a document. Requires 'edit' permission.", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_permission(user, permission):\n \"\"\"\n Checks if a user has a specific permission.\n\n :param user: dict, a dictionary representing a user containing at least a 'permissio...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008296", "row_id": 8296, "seed_ids": "['Llama-3.3-70B-Instruct_23108']" }
0.425308
Filter_8296
I
[ "permission_required", "edit_document" ]
2
[ [ "edit_document", "permission_required" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9ed9211c751511ee72501946befe896e08ee62bb
6e93a83c04caf8eec48b9095af4155dc2e47daab
v1.0
instruct
Filter
Filter_8341_I
I have developed a mobile app. I want to send each user a custom message including their name and their number of years since they joined. The list of users is in a CSV file with their details. How do I go about doing this? Here from the csv file name,joinedOn John,2018 Mary,2019 Joe,2017 Katy,2020 You can assum...
import csv from datetime import datetime def calculate_years_since_joined(joined_year): """ Calculate the number of years since the user joined. """ current_year = datetime.now().year return current_year - joined_year def generate_custom_messages(csv_filename): """ Read user details from a...
import csv from datetime import datetime from solution import calculate_years_since_joined, generate_custom_messages import pytest def test_calculate_years_since_joined(): current_year = datetime.now().year assert calculate_years_since_joined(2018) == current_year - 2018 assert calculate_years_since_joined...
[ { "docstring": "Calculate the number of years since the user joined.", "function_declaration": "def calculate_years_since_joined(joined_year):", "function_name": "calculate_years_since_joined", "parameter_list": "(joined_year)" }, { "docstring": "Read user details from a CSV file and generat...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nfrom datetime import datetime\n\ndef generate_custom_messages(csv_filename):\n current_year = datetime.now().year\n messages = []\n \n with open(csv_filename, mode='r')...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008341", "row_id": 8341, "seed_ids": "['Llama-3.3-70B-Instruct_23219']" }
0.443681
Filter_8341
I
[ "calculate_years_since_joined", "generate_custom_messages" ]
2
[ [ "generate_custom_messages", "calculate_years_since_joined" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd0bdcd015927930d4a538f94837a31a5ac6f3c8
e4d106eb800effe2efbcd09d5d4fd9a8c4dfa68d
v1.0
instruct
Filter
Filter_8348_I
Here is a problem: Given an undirected graph with n nodes, find the shortest path between all pairs of nodes. Solution: Use Floyd-Warshall algorithm. Floyd-Warshall algorithm is a dynamic programming algorithm for finding the shortest paths in a weighted graph with positive or negative edge weights. The algorithm wor...
import sys def floyd_warshall(graph): """ This function receives a graph as input and returns the shortest path matrix. :param graph: A 2D list representing the graph :return: The shortest path matrix """ n = len(graph) dist = [[sys.maxsize] * n for _ in range(n)] for i in ran...
from solution import floyd_warshall, print_shortest_path def test_floyd_warshall_simple(): graph = [ [0, 3, sys.maxsize, 7], [8, 0, 2, sys.maxsize], [5, sys.maxsize, 0, 1], [2, sys.maxsize, sys.maxsize, 0] ] result = floyd_warshall(graph) expected = [ [0, 3, 5, 6...
[ { "docstring": "This function receives a graph as input and returns the shortest path matrix.\n\n:param graph: A 2D list representing the graph\n:return: The shortest path matrix", "function_declaration": "def floyd_warshall(graph):", "function_name": "floyd_warshall", "parameter_list": "(graph)" ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\ndef floyd_warshall(graph):\n \"\"\"\n This function receives a graph as input and returns the shortest path matrix.\n \n :param graph: A 2D list representing the grap...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008348", "row_id": 8348, "seed_ids": "['Llama-3.3-70B-Instruct_23239']" }
0.607943
Filter_8348
I
[ "floyd_warshall", "print_shortest_path" ]
2
[ [ "print_shortest_path", "floyd_warshall" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b1f413cf2b26425f28602fd3f986e1a8070e4f20
9579ebe346c3b56b69020f8750720b3989bb8d3f
v1.0
instruct
Filter
Filter_8356_I
### Sorting Algorithm Comparison #### Overview Three sorting algorithms (Bubble Sort, Selection Sort, and Insertion Sort) are compared in terms of their time complexity. #### Time Complexity | Algorithm | Best Case | Average Case | Worst Case | | --- | --- | --- | --- | | Bubble Sort | O(n) | O(n^2) | O(n^2) | | Select...
def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right) def sort_array(arr): """ Sorts the...
from solution import sort_array def test_insertion_sort_on_small_array(): assert sort_array([3, 1, 2]) == [1, 2, 3] assert sort_array([9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_quick_sort_on_large_array(): assert sort_array([3, 1, 2, 5, 4, 7, 6, 9, 8, 10]) == [1, 2, 3, 4, 5, 6, 7...
[ { "docstring": null, "function_declaration": "def quick_sort(arr):", "function_name": "quick_sort", "parameter_list": "(arr)" }, { "docstring": "Sorts the array based on its size.\nUses Insertion Sort for arrays with less than 10 elements.\nUses Quick Sort for arrays with 10 or more elements...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def quick_sort(arr):\n \"\"\"\n Quick Sort implementation.\n \"\"\"\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008356", "row_id": 8356, "seed_ids": "['Llama-3.3-70B-Instruct_23252']" }
0.546291
Filter_8356
I
[ "quick_sort", "sort_array", "insertion_sort" ]
3
[ [ "sort_array", "insertion_sort" ], [ "sort_array", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c603af2290cc405dbf6e4ad009c7c38ad418fa87
42b8dc39e3c0fbe81e4c99c50730144b64d67ecc
v1.0
instruct
Filter
Filter_8360_I
You'll be asked to create a function `nearest_common_ancestor` that takes two nodes and a list of nodes as input and returns the nearest common ancestor of the two nodes in the list of nodes. The nodes are represented as dictionaries with the following structure: ```python node = { 'id': unique identifier, 'v...
def find_path_to_node(root, target_id, path): """ Recursive helper function to find the path from root to the target node. """ path.append(root) if root['id'] == target_id: return True for child in root['children']: if find_path_to_node(child, target_id, path): return...
import pytest from solution import nearest_common_ancestor def test_nearest_common_ancestor_simple(): node1 = {'id': 1, 'value': 'A', 'children': []} node2 = {'id': 2, 'value': 'B', 'children': []} node3 = {'id': 3, 'value': 'C', 'children': [node1, node2]} node4 = {'id': 4, 'value': 'D', 'children': [...
[ { "docstring": "Recursive helper function to find the path from root to the target node.", "function_declaration": "def find_path_to_node(root, target_id, path):", "function_name": "find_path_to_node", "parameter_list": "(root, target_id, path)" }, { "docstring": "Returns the nearest common ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def nearest_common_ancestor(node1, node2, nodes):\n \"\"\"\n Returns the nearest common ancestor of node1 and node2 in the list of nodes.\n \"\"\"\n def path_to_root(node, nodes):\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008360", "row_id": 8360, "seed_ids": "['Llama-3.3-70B-Instruct_23262']" }
0.528223
Filter_8360
I
[ "find_path_to_node", "nearest_common_ancestor" ]
2
[ [ "nearest_common_ancestor", "find_path_to_node" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b0aacf75cf2193dbe68f6595d192e57875e18f66
2c590f10170210bafa59728b69f16a5e6f680f7b
v1.0
instruct
Filter
Filter_8391_I
You can use this URL to check the availability of the books: https://example.com/check-book-availability You can also use this API endpoint to reserve the book: https://example.com/reserve-book You should follow these steps to reserve a book: 1. Check if the book is available using the first URL. 2. If the book is a...
import requests def check_book_availability(book_id): try: response = requests.get(f"https://example.com/check-book-availability/{book_id}") response.raise_for_status() # Raise an error on a bad status code return response.json() except requests.RequestException as e: print(f"E...
import pytest from unittest.mock import patch, Mock from solution import check_book_availability, reserve_book, reserve_book_if_available @patch('solution.requests.get') def test_check_book_availability_success(mock_get): mock_response = Mock() mock_response.json.return_value = {"available": True} mock_ge...
[ { "docstring": null, "function_declaration": "def check_book_availability(book_id):", "function_name": "check_book_availability", "parameter_list": "(book_id)" }, { "docstring": null, "function_declaration": "def reserve_book(book_id):", "function_name": "reserve_book", "paramete...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\n\ndef check_book_availability(book_id):\n try:\n response = requests.get(f\"https://example.com/check-book-availability/{book_id}\")\n response.raise_for_stat...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008391", "row_id": 8391, "seed_ids": "['Llama-3.3-70B-Instruct_23331']" }
0.535355
Filter_8391
I
[ "check_book_availability", "reserve_book", "reserve_book_if_available" ]
3
[ [ "reserve_book_if_available", "check_book_availability" ], [ "reserve_book_if_available", "reserve_book" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
e3942cf5ecb665d2bf63f60aa71ccc27276029f8
f3501359d98c097dc87b65354b2e55ce2610a39a
v1.0
instruct
Filter
Filter_8400_I
I have 1200 images to apply a custom style transfer to. I have a pre-trained model and have written code in Python to apply the style transfer. However, I'd like to leverage GPU acceleration for this process to speed it up. Can you provide me with a code template that I can use as a starting point?
import torch from torchvision import transforms from PIL import Image import os def load_image(image_path, transform=None): """ Load an image from the specified path and apply the given transformation. """ image = Image.open(image_path).convert('RGB') if transform: image = transform(image)....
import torch from PIL import Image import os import shutil from solution import load_image, save_image, style_transfer, process_images def setup_function(): # Create necessary folders for testing os.makedirs("test_input", exist_ok=True) os.makedirs("test_output", exist_ok=True) # Create a dummy image ...
[ { "docstring": "Load an image from the specified path and apply the given transformation.", "function_declaration": "def load_image(image_path, transform=None):", "function_name": "load_image", "parameter_list": "(image_path, transform=None)" }, { "docstring": "Save a tensor as an image to t...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nimport os\n\ndef load_image(image_path, max_size=400, shape=None):\n image = Image.open(image_path).convert...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008400", "row_id": 8400, "seed_ids": "['Llama-3.3-70B-Instruct_23351']" }
0.254701
Filter_8400
I
[ "load_image", "save_image", "style_transfer", "process_images" ]
4
[ [ "process_images", "load_image" ], [ "process_images", "save_image" ], [ "process_images", "style_transfer" ] ]
3
[]
false
[]
false
pytest
true
[ "PIL", "torch", "torchvision" ]
false
676d3ab18853bc618be1a98a330d88da2dc037e6
4e4a0b6ef1ab1c58d62621d681fbacbf07fb81d6
v1.0
instruct
Filter
Filter_8442_I
Here is the problem I am trying to solve: https://projecteuler.net/problem=145 I am trying to solve this using Python. I have written the following code: ```python import itertools def is_reversible(num): if num < 10: return False str_num = str(num) rev = int(str_num[::-1]) if rev != num and...
def is_reversible(num): """ Check if a number is a reversible number. A reversible number is one that when reversed and added to the original results in a sum with all odd digits. """ str_num = str(num) rev_str_num = str_num[::-1] if str_num[-1] == '0': return False # The numbe...
import pytest from solution import is_reversible, count_reversible_numbers def test_is_reversible(): # Test cases where we expect True assert is_reversible(36) == True # 36 + 63 = 99 -> all odd assert is_reversible(409) == True # 409 + 904 = 1313 -> all odd # Test cases where we expect False ...
[ { "docstring": "Check if a number is a reversible number. A reversible number is one that when reversed and\nadded to the original results in a sum with all odd digits.", "function_declaration": "def is_reversible(num):", "function_name": "is_reversible", "parameter_list": "(num)" }, { "docs...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_reversible(num):\n \"\"\"\n Checks if a number is reversible.\n A reversible number is defined as a number that, when added to its reverse,\n results in a number where all d...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008442", "row_id": 8442, "seed_ids": "['Llama-3.3-70B-Instruct_23420']" }
0.712042
Filter_8442
I
[ "is_reversible", "count_reversible_numbers" ]
2
[ [ "count_reversible_numbers", "is_reversible" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a08f9642e747e0322ac5e2e6834355b5f4dc58b9
12a394360ce14ad4a12377ca9e329e507b80c879
v1.0
instruct
Filter
Filter_8449_I
I have been trying to solve a problem where I have a set of data where each data point is a pair of floating point numbers (x, y) and I want to calculate the convex hull of this set. I have been using the following code to calculate the convex hull using the Graham's scan algorithm: ``` def orientation(p, q, r): v...
import matplotlib.pyplot as plt def orientation(p, q, r): """ Determine the orientation of the triplet (p, q, r). Returns: 0 : if p, q, r are collinear 1 : if Clockwise 2 : if Counterclockwise """ val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) if val == 0: ...
from solution import convex_hull def test_convex_hull_square(): points = [(0, 0), (1, 0), (1, 1), (0, 1)] result = convex_hull(points) expected = [(0, 0), (1, 0), (1, 1), (0, 1)] assert sorted(result) == sorted(expected) def test_convex_hull_collinear_line(): points = [(0, 0), (1, 1), (2, 2)] ...
[ { "docstring": "Determine the orientation of the triplet (p, q, r).\n\nReturns:\n0 : if p, q, r are collinear\n1 : if Clockwise\n2 : if Counterclockwise", "function_declaration": "def orientation(p, q, r):", "function_name": "orientation", "parameter_list": "(p, q, r)" }, { "docstring": "Com...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# The function for orientation is correctly implemented\ndef orientation(p, q, r):\n val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])\n if val == 0:\n return 0 ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008449", "row_id": 8449, "seed_ids": "['Llama-3.3-70B-Instruct_23444']" }
0.424947
Filter_8449
I
[ "orientation", "convex_hull", "plot_convex_hull" ]
3
[ [ "convex_hull", "orientation" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
b87f556800e2cdf7f6c8af11983af217c3024760
29dc11b8c65517b65578970dec9d6c2c3a49127e
v1.0
instruct
Filter
Filter_8473_I
This is a follow-up to a problem I asked about parsing a string and I have figured out how to parse it. However, I now need to call a function based on the parsed value. To give an example, let's say the string is in the format of "start:command:parameter", and I have parsed the string into `start`, `command`, and `p...
def add_function(): print("add_function called") def subtract_function(): print("subtract_function called") def multiply_function(): print("multiply_function called") def divide_function(): print("divide_function called") def unknown_command(): print("Unknown command") command_map = { 'add'...
from solution import execute_command def test_add_command(capfd): execute_command('add') out, err = capfd.readouterr() assert out == "add_function called\n" def test_subtract_command(capfd): execute_command('subtract') out, err = capfd.readouterr() assert out == "subtract_function called\n" d...
[ { "docstring": null, "function_declaration": "def add_function():", "function_name": "add_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def subtract_function():", "function_name": "subtract_function", "parameter_list": "()" }, { "docst...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Define the functions corresponding to each command\ndef add_function():\n return \"Executing add function\"\n\ndef subtract_function():\n return \"Executing subtract function\"\n\ndef ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008473", "row_id": 8473, "seed_ids": "['Llama-3.3-70B-Instruct_23483']" }
0.465312
Filter_8473
I
[ "add_function", "subtract_function", "multiply_function", "divide_function", "unknown_command", "execute_command" ]
6
[ [ "execute_command", "unknown_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b34e13bc32453198b5e8a0b7aaf7d48d91392d65
c4a85a839936420a1cdb767ca5eb8fc61290f628
v1.0
instruct
Filter
Filter_8497_I
### Creating a Simple Game with Python Python is a popular language for game development. In this example, we'll create a simple game where the player has to guess a randomly chosen number. #### Game Requirements The game should: * Ask the player for their name * Generate a random number between 1 and 100 * Ask the pl...
import random def get_player_name(): """Asks the player for their name.""" player_name = input("What is your name? ") return player_name def generate_random_number(): """Generates a random number between 1 and 100.""" return random.randint(1, 100) def get_player_guess(): """Asks the player fo...
from solution import get_player_name, generate_random_number, get_player_guess, play_game import builtins import random def test_get_player_name(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: "Alice") assert get_player_name() == "Alice" def test_generate_random_number(monkeypatch): monkeypa...
[ { "docstring": "Asks the player for their name.", "function_declaration": "def get_player_name():", "function_name": "get_player_name", "parameter_list": "()" }, { "docstring": "Generates a random number between 1 and 100.", "function_declaration": "def generate_random_number():", "f...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_player_name():\n \"\"\"Asks the player for their name.\"\"\"\n player_name = input(\"What is your name? \")\n return player_name\n\ndef generate_random_number...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008497", "row_id": 8497, "seed_ids": "['Llama-3.3-70B-Instruct_23545']" }
0.596535
Filter_8497
I
[ "get_player_name", "generate_random_number", "get_player_guess", "play_game" ]
4
[ [ "play_game", "generate_random_number" ], [ "play_game", "get_player_guess" ], [ "play_game", "get_player_name" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6e83116bf32b0e3a961577d466bf5842fadd3212
4b3e4c6b29bee5fb0f7799a4baabb857a94182ca
v1.0
instruct
Filter
Filter_8499_I
This is my code for sorting a list of integers using sorting algorithm of quicksort. Here's my code: ```python def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[0] left = [x for x in arr[1:] if x < pivot] right = [x for x in arr[1:] if x >= pivot] return quicksort(left) + [pivot]...
def quicksort(arr, low=0, high=None): if high is None: high = len(arr) - 1 if low < high: pivot_index = (low + high) // 2 pivot_new_index = partition(arr, low, high, pivot_index) quicksort(arr, low, pivot_new_index - 1) quicksort(arr, pivot_new_index + 1, high) ...
def test_quicksort(): assert quicksort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10] assert quicksort([35, 2, 1, 45, 5, 3]) == [1, 2, 3, 5, 35, 45] assert quicksort([]) == [] assert quicksort([1]) == [1] assert quicksort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert quicksort([5, -1, 3, 2, 6, 0...
[ { "docstring": null, "function_declaration": "def quicksort(arr, low=0, high=None):", "function_name": "quicksort", "parameter_list": "(arr, low=0, high=None)" }, { "docstring": null, "function_declaration": "def partition(arr, low, high, pivot_index):", "function_name": "partition",...
[ 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, low=0, high=None):\n if high is None:\n high = len(arr) - 1\n\n def partition(arr, low, high):\n pivot = arr[high]\n i = low - 1\n for j in...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008499", "row_id": 8499, "seed_ids": "['Llama-3.3-70B-Instruct_23552']" }
0.539554
Filter_8499
I
[ "quicksort", "partition" ]
2
[ [ "quicksort", "partition" ] ]
1
[]
false
[]
false
pytest
false
[]
true
618de71f2ab8146c0d782531bf248d1ff605693b
56fa4b35499a8e23a7d056c23dfd92197b21231d
v1.0
instruct
Filter
Filter_8516_I
I have a JSON object that represents a list of items, where each item has a unique ID. I need to determine the shortest path between two nodes in this list using a specific algorithm. I can use any algorithm and data structure, but the items should be modeled as nodes of a directed graph, and the edges should represe...
import heapq import json def create_graph(json_data): graph = {} for item in json_data: graph[item["id"]] = {} for neighbor in json_data: if item["id"] != neighbor["id"]: weight = abs(item["id"] - neighbor["id"]) graph[item["id"]][neighbor["id"]] = we...
from solution import shortest_path def test_shortest_path(): test_data = [ {"id": 1, "name": "item1"}, {"id": 2, "name": "item2"}, {"id": 3, "name": "item3"}, {"id": 4, "name": "item4"}, {"id": 5, "name": "item5"} ] assert shortest_path(test_data, 1, 5) == (4, [1, 5]...
[ { "docstring": null, "function_declaration": "def create_graph(json_data):", "function_name": "create_graph", "parameter_list": "(json_data)" }, { "docstring": null, "function_declaration": "def dijkstra(graph, start, end):", "function_name": "dijkstra", "parameter_list": "(graph...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nimport json\n\ndef create_graph(json_data):\n \"\"\"\n Create a graph from JSON data.\n \"\"\"\n graph = {}\n for item in json_data:\n id_ = item[\"id\"]\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008516", "row_id": 8516, "seed_ids": "['Llama-3.3-70B-Instruct_23585']" }
0.53767
Filter_8516
I
[ "create_graph", "dijkstra", "shortest_path" ]
3
[ [ "shortest_path", "create_graph" ], [ "shortest_path", "dijkstra" ] ]
2
[]
false
[]
false
pytest
true
[]
true
feb7bc50c3aaabf0069550a343052e15e0c0a970
6a5ae6f74f6c6dd069f2e99dec94f7d4b553262d
v1.0
instruct
Filter
Filter_8524_I
I have two functions, `function1` and `function2`, which are already implemented and work correctly. Now I need to combine them into one function, `combined_function`, that takes three arguments: `arg1`, `arg2`, and `arg3`. `function1` takes `arg1` and `arg2` as arguments, and `function2` takes the result of `function1...
def function1(arg1, arg2): """ Mock implementation of function1. For example purposes, let's assume it sums the two arguments. """ return arg1 + arg2 def function2(result, arg3): """ Mock implementation of function2. For example purposes, let's assume it multiplies the result by arg3. ...
from solution import combined_function def test_combined_function_basic(): assert combined_function(1, 2, 3) == 9 # (1 + 2) * 3 = 9 def test_combined_function_zero(): assert combined_function(0, 0, 10) == 0 # (0 + 0) * 10 = 0 assert combined_function(0, 0, 0) == 0 # (0 + 0) * 0 = 0 assert combined...
[ { "docstring": "Mock implementation of function1.\nFor example purposes, let's assume it sums the two arguments.", "function_declaration": "def function1(arg1, arg2):", "function_name": "function1", "parameter_list": "(arg1, arg2)" }, { "docstring": "Mock implementation of function2.\nFor ex...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from unittest.mock import patch\n\ndef combined_function(arg1, arg2, arg3):\n result = function1(arg1, arg2)\n return function2(result, arg3)", "test_code": "from solution import com...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008524", "row_id": 8524, "seed_ids": "['Llama-3.3-70B-Instruct_23618']" }
0.538687
Filter_8524
I
[ "function1", "function2", "combined_function" ]
3
[ [ "combined_function", "function1" ], [ "combined_function", "function2" ] ]
2
[]
false
[]
false
pytest
true
[]
true
78e832010444710d04f8ea033ce5c4868eb5957c
3d8586ceea27703c9500028d0dede482778806d5
v1.0
instruct
Filter
Filter_8536_I
### Introduction to Task The following is a step-by-step guide to solving a coding problem. The goal is to write a Python function `sum_of_primes(n)` that takes an integer `n` as input and returns the sum of all prime numbers less than `n`.
def is_prime(num): """ Helper function to check if a number is prime. """ if num <= 1: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(num**0.5) + 1, 2): if num % i == 0: return False return True def s...
from solution import sum_of_primes def test_sum_of_primes_below_10(): assert sum_of_primes(10) == 17 # primes are 2, 3, 5, 7 def test_sum_of_primes_below_20(): assert sum_of_primes(20) == 77 # primes are 2, 3, 5, 7, 11, 13, 17, 19 def test_sum_of_primes_below_2(): assert sum_of_primes(2) == 0 # no pri...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns the sum of all prime numbers less than n.", "function_declaration": "def sum_of_primes(n):", ...
[ 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 == 2:\n return True\n if num % 2 ==...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008536", "row_id": 8536, "seed_ids": "['Llama-3.3-70B-Instruct_23646']" }
0.702123
Filter_8536
I
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
854a8cae16b1191450f09747beee67642cb3a233
d9a9b8e1d17a326da516f8579bbb9857b454586e
v1.0
instruct
Filter
Filter_8629_I
I have two files: `base.json` and `config.json`. I want to merge them into a new file, `merged.json`. The `base.json` contains the base configuration, and the `config.json` contains the overrides. I want to merge the two in that order (i.e., start with the base configuration and then apply the overrides). Here is a...
import json def deep_merge(base, override): """ Recursively merges two dictionaries. The values in override will overwrite those in base. :param base: Base dictionary :param override: Dictionary with override values :return: Merged dictionary """ for key in override: if key...
import json import os from solution import deep_merge, merge_json_files def test_deep_merge(): base = { "name": "John", "age": 30, "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } } overr...
[ { "docstring": "Recursively merges two dictionaries. The values in override will\noverwrite those in base.\n\n:param base: Base dictionary\n:param override: Dictionary with override values\n:return: Merged dictionary", "function_declaration": "def deep_merge(base, override):", "function_name": "deep_mer...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\n\ndef merge_dicts(base, overrides):\n \"\"\"\n Recursively merges two dictionaries. Values from overrides take precedence.\n \"\"\"\n for key, value in overrides.items...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008629", "row_id": 8629, "seed_ids": "['Llama-3.3-70B-Instruct_23882']" }
0.560376
Filter_8629
I
[ "deep_merge", "merge_json_files" ]
2
[ [ "merge_json_files", "deep_merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9a3948763fe8efc74e2a55e82c346893da8b7834
dfb14c3787601b8996122d51d2c924061aebdf6f
v1.0
instruct
Filter
Filter_8640_I
I want to create a program in Python for solving the famous "8-Queens Problem". The goal of the 8-Queens Problem is to place 8 queens on a chessboard such that no two queens attack each other. So can you provide me with the code?
def is_safe(board, row, col): """ Check if it's safe to place a queen at board[row][col]. This is checked by ensuring no other queens are placed on the same row, column, or diagonals. """ for i in range(row): if board[i] == col or board[i] - i == col - row or board[i] + i == col + row: ...
from solution import is_safe, solve_n_queens, format_solution def test_is_safe(): board = [-1, -1, -1, -1, -1, -1, -1, -1] assert is_safe(board, 0, 0) board[0] = 0 assert not is_safe(board, 1, 0) assert not is_safe(board, 1, 1) assert is_safe(board, 1, 2) def test_solve_n_queens(): solutio...
[ { "docstring": "Check if it's safe to place a queen at board[row][col].\nThis is checked by ensuring no other queens are placed \non the same row, column, or diagonals.", "function_declaration": "def is_safe(board, row, col):", "function_name": "is_safe", "parameter_list": "(board, row, col)" }, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_safe(board, row, col):\n # Check this row on the left side\n for i in range(col):\n if board[row][i] == 1:\n return False\n\n # Check upper diagonal on the le...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008640", "row_id": 8640, "seed_ids": "['Llama-3.3-70B-Instruct_23911']" }
0.450559
Filter_8640
I
[ "is_safe", "solve_n_queens_util", "solve_n_queens", "format_solution" ]
4
[ [ "solve_n_queens", "solve_n_queens_util" ], [ "solve_n_queens_util", "is_safe" ] ]
2
[]
false
[]
false
pytest
true
[]
true
73384359460bdbffe3ca2297d81b30dda1e44d6a
56a04789f3a7434aa8a5863ce677b278473dafde
v1.0
instruct
Filter
Filter_8645_I
### Overview Build a Python program that allows users to create, read, update and delete (CRUD) entries for books in a library. ### Requirements - The library can store information about books (such as title, author, publication date and whether the book is borrowed or not). - Each book will have a unique identifier. ...
import json import uuid LIBRARY_FILE = 'library.json' def load_library(): try: with open(LIBRARY_FILE, 'r') as file: return json.load(file) except FileNotFoundError: return [] def save_library(library): with open(LIBRARY_FILE, 'w') as file: json.dump(library, file, ind...
import os import pytest from solution import create_book, read_books, update_book, delete_book, LIBRARY_FILE @pytest.fixture(autouse=True) def setup_and_teardown(): # Setup: Reset the library.json file before each test if os.path.exists(LIBRARY_FILE): os.remove(LIBRARY_FILE) yield # Teardown: R...
[ { "docstring": null, "function_declaration": "def load_library():", "function_name": "load_library", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def save_library(library):", "function_name": "save_library", "parameter_list": "(library)" }, { "d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport uuid\n\nFILE_NAME = \"library.json\"\n\n\ndef load_books():\n try:\n with open(FILE_NAME, \"r\") as file:\n return json.load(file)\n except FileNotF...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008645", "row_id": 8645, "seed_ids": "['Llama-3.3-70B-Instruct_23920']" }
0.43305
Filter_8645
I
[ "load_library", "save_library", "create_book", "read_books", "update_book", "delete_book" ]
6
[ [ "create_book", "load_library" ], [ "create_book", "save_library" ], [ "delete_book", "load_library" ], [ "delete_book", "save_library" ], [ "read_books", "load_library" ], [ "update_book", "load_library" ], [ "update_book", "save_libr...
7
[]
false
[]
false
pytest
true
[]
true
caf4fc8b3c8f263cc1bc30f13d59faf09351f1bd
973dd3252864b16c456185d659e3b725343e1f4c
v1.0
instruct
Filter
Filter_8655_I
I have a 2D array of size N x M where each cell contains a unique integer. I want to find the maximum sum of a subarray (submatrix) within the 2D array. For example, given the following 2D array: ``` [[-1, -2, -3, -4], [-5, -6, -7, -8], [-9, -10, -11, -12], [-13, -14, -15, -16]] ``` The maximum sum of a subarray i...
def max_subarray_sum_2D(arr): """ Finds the maximum sum of a subarray (submatrix) within the 2D array 'arr'. """ N = len(arr) M = len(arr[0]) max_sum = float('-inf') for left in range(M): temp = [0] * N for right in range(left, M): # Calculate sum of ele...
# Assuming the above method is defined in a module named 'solution' from solution import max_subarray_sum_2D def test_max_subarray_sum_2D_all_negative(): arr = [ [-1, -2, -3, -4], [-5, -6, -7, -8], [-9, -10, -11, -12], [-13, -14, -15, -16] ] assert max_subarray_sum_2D(arr) =...
[ { "docstring": "Finds the maximum sum of a subarray (submatrix) within the 2D array 'arr'.", "function_declaration": "def max_subarray_sum_2D(arr):", "function_name": "max_subarray_sum_2D", "parameter_list": "(arr)" }, { "docstring": "Kadane's algorithm to find the maximum sum subarray in a ...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_subarray_sum_2D(arr):\n \"\"\"\n Finds the maximum sum of a subarray (submatrix) within the 2D array 'arr'.\n \"\"\"\n N = len(arr)\n M = len(arr[0])\n max_sum = floa...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008655", "row_id": 8655, "seed_ids": "['Llama-3.3-70B-Instruct_23935']" }
0.590518
Filter_8655
I
[ "max_subarray_sum_2D", "kadane" ]
2
[ [ "max_subarray_sum_2D", "kadane" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7851100169c086252d9b2eeac423e6027af19dd
2e283f48a2c97c7a5fa13559a4c03a997b23abea
v1.0
instruct
Filter
Filter_8656_I
Here is a simple code that prints the first 100 prime numbers: ```python def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def print_primes(n): count = 0 num = 2 while count < n: if is_prime(nu...
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def get_primes(n): primes = [] for num in range(2, 10000): # Arbitrary large number to ensure we get 100 primes if is_prime(num): prim...
from solution import is_prime, get_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(16) == False assert is_prime(17) == True def test_get_primes(): primes = get_primes(10) expected_p...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def get_primes(n):", "function_name": "get_primes", "parameter_list": "(n)" }, { "docstring": null, "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef get_primes(n):\n pri...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008656", "row_id": 8656, "seed_ids": "['Llama-3.3-70B-Instruct_23936']" }
0.571484
Filter_8656
I
[ "is_prime", "get_primes", "print_primes" ]
3
[ [ "get_primes", "is_prime" ], [ "print_primes", "get_primes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
92514714c1d43eb275b82f762568591f033aca6a
256ba3773e35f1599fdbcc35bed7bbaa6a27cd8d
v1.0
instruct
Filter
Filter_8691_I
In this problem, we will create a program that prints out the number of "prime" numbers that are in a given range. A prime number is a number greater than 1 that is only divisible by 1 and itself. For example, the prime numbers between 5 and 10 are 5 and 7. Write a function that takes in a range of two integers, and ...
def is_prime(n): """ Returns True if n is a prime number, else False. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def count_p...
from solution import count_primes_in_range def test_count_primes_single_prime(): assert count_primes_in_range(5, 5) == 1 def test_count_primes_no_prime(): assert count_primes_in_range(8, 10) == 0 def test_count_primes_multiple_primes(): assert count_primes_in_range(5, 10) == 2 def test_count_primes_larg...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the number of prime numbers in the given range [start, end].", "function_declaration": "def count...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if the number n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n i...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008691", "row_id": 8691, "seed_ids": "['Llama-3.3-70B-Instruct_24025']" }
0.685917
Filter_8691
I
[ "is_prime", "count_primes_in_range" ]
2
[ [ "count_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1b7e2bfd1e0456ec10d7d0f06592ed947399724c
1766ac5bbf2dcb960662fee66375c2a7514840c1
v1.0
instruct
Filter
Filter_8692_I
I have a table of data in a CSV file that includes a column of text data. I would like to use Python to perform some basic text preprocessing on the text data in this column. Specifically, I would like to remove punctuation, convert all text to lowercase, and remove any non-alphanumeric characters. What is the best w...
import pandas as pd import re import string def preprocess_text(text): """ Perform basic text preprocessing by removing punctuation, converting to lowercase, and removing non-alphanumeric characters (except spaces). """ text = text.lower() # Convert to lowercase text = re.sub(f"[{string.punctu...
from solution import preprocess_text, preprocess_csv_column import pandas as pd from io import StringIO def test_preprocess_text(): assert preprocess_text("Hello, World! How's it going?") == "hello world hows it going" assert preprocess_text("This is another row of text.") == "this is another row of text" ...
[ { "docstring": "Perform basic text preprocessing by removing punctuation, converting to lowercase,\nand removing non-alphanumeric characters (except spaces).", "function_declaration": "def preprocess_text(text):", "function_name": "preprocess_text", "parameter_list": "(text)" }, { "docstring...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport re\n\ndef preprocess_text(text):\n \"\"\"\n Preprocess a text string by removing punctuation, converting to lowercase,\n and removing any non-alphanumeric ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008692", "row_id": 8692, "seed_ids": "['Llama-3.3-70B-Instruct_24027']" }
0.627559
Filter_8692
I
[ "preprocess_text", "preprocess_csv_column" ]
2
[ [ "preprocess_csv_column", "preprocess_text" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
af4a507a52636e1296967c0f22d9b7e419747942
13eb60cb542aa69390fa75c15859694f7ff04a75
v1.0
instruct
Filter
Filter_8698_I
I have been searching for an inexpensive way to evolve my Pokémon. I've written code to do so but it requires a significant amount of manual data entry. Can I get some code that will automatically extract the Pokémon from a csv file and then evolve them?
import csv from typing import List, Dict def load_pokemon_data(filename: str) -> List[Dict[str, str]]: """ Loads Pokémon data from a CSV file. Args: - filename (str): The path to the CSV file containing Pokémon data. Returns: - List[Dict[str, str]]: List of dictionaries where each dic...
import pytest from solution import load_pokemon_data, evolve_pokemon, evolve_pokemons_from_csv import os def test_load_pokemon_data(): test_csv_content = "Name,Type\nPikachu,Electric\nCharmander,Fire\n" with open("test_pokemon.csv", "w") as f: f.write(test_csv_content) result = load_pokemon_data("t...
[ { "docstring": "Loads Pokémon data from a CSV file.\n\nArgs:\n- filename (str): The path to the CSV file containing Pokémon data.\n\nReturns:\n- List[Dict[str, str]]: List of dictionaries where each dictionary contains Pokémon data.", "function_declaration": "def load_pokemon_data(filename):", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\n\ndef evolve_pokemon(csv_file_path):\n \"\"\"\n Extracts Pokémon data from a CSV file and evolves them.\n\n Parameters:\n csv_file_path (str): The path to the CSV file ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008698", "row_id": 8698, "seed_ids": "['Llama-3.3-70B-Instruct_24051']" }
0.408773
Filter_8698
I
[ "load_pokemon_data", "evolve_pokemon", "evolve_pokemons_from_csv" ]
3
[ [ "evolve_pokemons_from_csv", "evolve_pokemon" ], [ "evolve_pokemons_from_csv", "load_pokemon_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e645abd8b55930ed874bacbab892ac67fa80ac9b
cd1136bb47070b3a0beaacf37f581413a691e0c8
v1.0
instruct
Filter
Filter_8700_I
### Homework 1: Python Basics #### Problem 1: Calculate the sum of all integers from 1 to n Write a Python function `calculate_sum(n)` that calculates the sum of all integers from 1 to n (inclusive) using a for loop. ```python def calculate_sum(n): # Initialize the sum variable to 0 total = 0 # Loop t...
def calculate_sum(n): """ Calculate the sum of all integers from 1 to n using a for loop. """ if n < 0: raise ValueError("n must be a non-negative integer") total = 0 for i in range(1, n + 1): total += i return total def calculate_sum_formula(n): """ Calculate t...
from solution import calculate_sum, calculate_sum_formula, compare_results import pytest def test_calculate_sum(): assert calculate_sum(0) == 0 assert calculate_sum(1) == 1 assert calculate_sum(2) == 3 assert calculate_sum(10) == 55 assert calculate_sum(100) == 5050 with pytest.raises(ValueErro...
[ { "docstring": "Calculate the sum of all integers from 1 to n using a for loop.", "function_declaration": "def calculate_sum(n):", "function_name": "calculate_sum", "parameter_list": "(n)" }, { "docstring": "Calculate the sum of all integers from 1 to n using the formula.", "function_dec...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_sum(n):\n \"\"\"\n Calculate the sum of all integers from 1 to n using a for loop.\n \"\"\"\n if n < 0:\n raise ValueError(\"n must be a non-negative integer\"...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008700", "row_id": 8700, "seed_ids": "['Llama-3.3-70B-Instruct_24054']" }
0.668615
Filter_8700
I
[ "calculate_sum", "calculate_sum_formula", "compare_results" ]
3
[ [ "compare_results", "calculate_sum" ], [ "compare_results", "calculate_sum_formula" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d58b72c209f31c5c07542183c988c07f1f572158
da4cad062c0bc8b045299b6a53656b703523eb5b
v1.0
instruct
Filter
Filter_8706_I
I have two functions, `validate_username` and `parse_username`, that I want to combine into one function, `parse_and_validate_username`. I'd like this new function to first call `parse_username` and then call `validate_username` with the result of the previous function. Here's how the `parse_username` function looks: ...
def parse_username(username: str) -> str: """ Parse the username from the input string. This function takes an input string, removes any leading/trailing whitespace, and returns the parsed username. Args: username (str): The username to parse. Returns: str: The parsed username...
import pytest from solution import parse_and_validate_username def test_parse_and_validate_username_valid(): assert parse_and_validate_username(" validUser123 ") == True def test_parse_and_validate_username_too_short(): assert parse_and_validate_username(" a ") == False def test_parse_and_validate_username_i...
[ { "docstring": "Parse the username from the input string.\n\nThis function takes an input string, removes any leading/trailing whitespace,\nand returns the parsed username.\n\nArgs:\n username (str): The username to parse.\n\nReturns:\n str: The parsed username.", "function_declaration": "def parse_us...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def parse_username(username: str) -> str:\n \"\"\"\n Parse the username from the input string.\n\n This function takes an input string, removes any leading/trailing whitespace,\n a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008706", "row_id": 8706, "seed_ids": "['Llama-3.3-70B-Instruct_24061']" }
0.468387
Filter_8706
I
[ "parse_username", "validate_username", "parse_and_validate_username" ]
3
[ [ "parse_and_validate_username", "parse_username" ], [ "parse_and_validate_username", "validate_username" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5f6c831a6aadbd59ff467dd24246d9357872571b
129a03e947948e03d835d7c87f4ad5fea0bd7545
v1.0
instruct
Filter
Filter_8711_I
I've been tasked with writing a Python code snippet to perform the following operations: - Check if a given list of integers is sorted in ascending order. - If the list is sorted, calculate the sum of all the prime numbers in the list. - If the list is not sorted, sort the list first, then calculate the sum of all the ...
def is_sorted(lst): return lst == sorted(lst) def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_of_primes(lst): if not is_sorted(lst): lst.sort() return sum(num for num in lst if is_pr...
def test_is_sorted(): assert is_sorted([1, 2, 3, 4, 5]) == True assert is_sorted([5, 4, 3, 2, 1]) == False assert is_sorted([2, 2, 3, 4, 5]) == True assert is_sorted([3, 1, 4, 1, 5]) == False def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == Fa...
[ { "docstring": null, "function_declaration": "def is_sorted(lst):", "function_name": "is_sorted", "parameter_list": "(lst)" }, { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_sorted(lst):\n return lst == sorted(lst)\n\ndef is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008711", "row_id": 8711, "seed_ids": "['Llama-3.3-70B-Instruct_24072']" }
0.62337
Filter_8711
I
[ "is_sorted", "is_prime", "sum_of_primes" ]
3
[ [ "sum_of_primes", "is_prime" ], [ "sum_of_primes", "is_sorted" ] ]
2
[]
false
[]
false
pytest
false
[]
true
810ea9ea8446a0f354892eeeebba095a7c38967e
98e999a1e16978ed101afe93c784d7cdf59fd717
v1.0
instruct
Filter
Filter_8748_I
Here is the code that I am using to create a binary search tree from a sorted array. ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None def sorted_array_to_bst(array): if not array: return None mid = len(array) // 2 r...
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def _sorted_array_to_bst(array): if not array: return None mid = len(array) // 2 root = Node(array[mid]) root.left = _sorted_array_to_bst(array[:mid]) root.right = _sor...
from solution import array_to_bst, Node def in_order_traversal(root): """ Helper function to perform in-order traversal and return the list of node values. """ return in_order_traversal(root.left) + [root.value] + in_order_traversal(root.right) if root else [] def test_sorted_array_to_bst(): a...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef sorted_array_to_bst_helper(array):\n if not array:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008748", "row_id": 8748, "seed_ids": "['Llama-3.3-70B-Instruct_24160']" }
0.573286
Filter_8748
I
[ "_sorted_array_to_bst", "array_to_bst" ]
2
[ [ "array_to_bst", "_sorted_array_to_bst" ] ]
1
[]
false
[ "Node" ]
true
pytest
true
[]
true
49e15066c1c3ec04645fcb4263edcc6dbe61d627
a2c4dbd4460ba82583bc6535fd302a0fc93c6c3e
v1.0
instruct
Filter
Filter_8755_I
I've been trying to write a program that can solve a Sudoku puzzle and I've hit a roadblock. The Sudoku puzzle is represented as a 2D list in Python where zeros represent empty cells and non-zero numbers represent filled-in cells. I've written the code to check if a number can be placed in a cell, but I'm having troubl...
def is_valid(board, row, col, num): """ Check if it's valid to place `num` in the position (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 F...
import pytest 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], ...
[ { "docstring": "Check if it's valid to place `num` in the position (row, col).", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Solves the given Sudoku puzzle in-place using backtrackin...
[ 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(board, row, col, num):\n \"\"\"\n Check if it's valid to place `num` at `board[row][col]`.\n \"\"\"\n # Check the row\n for x in range(9):\n if board[row][x]...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008755", "row_id": 8755, "seed_ids": "['Llama-3.3-70B-Instruct_24172']" }
0.444602
Filter_8755
I
[ "is_valid", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cd632f7346cab70b50b66dc2ded3a0a26a19f6a8
c9d648df01fda60cfa6ec46dbc1a8aa8a60b0783
v1.0
instruct
Filter
Filter_8778_I
I wrote a Python script that I would like to add more functionality to. The script calculates the median of a given array of numbers. Here is my Python script: ``` import statistics def calculate_median(numbers): return statistics.median(numbers) numbers = [12, 4, 21, 7] print("Median: ", calculate_median(numbers...
import statistics def calculate_average(numbers): """ Returns the average of a list of numbers. """ return statistics.mean(numbers) def calculate_statistic(numbers, stat_type): """ Returns either the median or the average of a list of numbers based on stat_type. stat_type: str, should...
from solution import calculate_average, calculate_statistic def test_calculate_average_non_empty_list(): assert calculate_average([12, 4, 21, 7]) == 11 assert calculate_average([1, 2, 3, 4, 5]) == 3 def test_calculate_average_single_element(): assert calculate_average([10]) == 10 def test_calculate_stati...
[ { "docstring": "Returns the average of a list of numbers.", "function_declaration": "def calculate_average(numbers):", "function_name": "calculate_average", "parameter_list": "(numbers)" }, { "docstring": "Returns either the median or the average of a list of numbers based on stat_type.\n\ns...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import statistics\n\ndef calculate_average(numbers):\n \"\"\"\n Returns the average (mean) of a list of numbers.\n \"\"\"\n return statistics.mean(numbers)\n\ndef calculate_median_...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008778", "row_id": 8778, "seed_ids": "['Llama-3.3-70B-Instruct_24219']" }
0.642464
Filter_8778
I
[ "calculate_average", "calculate_statistic" ]
2
[ [ "calculate_statistic", "calculate_average" ] ]
1
[]
false
[]
false
pytest
true
[]
true
91f0c0157f7ec3c59fea883d76d179aab426faed
5b0dcf7b4c950b7a8cd63d321798d7e4a08cafcb
v1.0
instruct
Filter
Filter_8789_I
I have a set of coordinates in the format `(x, y)` and I want to find the `k` nearest neighbors for each point. I'm using Python and was wondering if you could provide an example code snippet to achieve this.
import heapq import math def calculate_distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) def k_nearest_neighbors(points, k): """ Return the k nearest neighbors for each point in t...
from solution import calculate_distance, k_nearest_neighbors def test_calculate_distance(): assert math.isclose(calculate_distance((0, 0), (3, 4)), 5.0, rel_tol=1e-9) assert math.isclose(calculate_distance((1, 1), (4, 5)), 5.0, rel_tol=1e-9) def test_k_nearest_neighbors_simple(): points = [(0, 0), (1, 1),...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def calculate_distance(point1, point2):", "function_name": "calculate_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Return the k nearest neighbors for each point in the list.\...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nimport math\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return math.sqrt((point1[0] - point2...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008789", "row_id": 8789, "seed_ids": "['Llama-3.3-70B-Instruct_24237']" }
0.718473
Filter_8789
I
[ "calculate_distance", "k_nearest_neighbors" ]
2
[ [ "k_nearest_neighbors", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
87dc5454385641641b36d6c645573ab0f0bc2cf8
82361519d005438f919c352f34eee23b4c1ef771
v1.0
instruct
Filter
Filter_8823_I
I've been tasked with writing a program to create a wide range of simulations for a game. One of the types of simulations I need to create is a simple "orbital simulator". The idea is to take in a set of celestial bodies, each with a position, velocity, and mass, and then to simulate their motion over time according ...
import numpy as np class CelestialBody: def __init__(self, mass, position, velocity): self.mass = mass self.position = np.array(position, dtype=np.float64) self.velocity = np.array(velocity, dtype=np.float64) self.acc = np.zeros_like(self.position) def compute_gravitational_acceler...
from solution import CelestialBody, compute_gravitational_acceleration, simulate import numpy as np def test_compute_gravitational_acceleration(): G = 6.67430e-11 body1 = CelestialBody(mass=1.0, position=[0, 0, 0], velocity=[0, 0, 0]) body2 = CelestialBody(mass=1.0, position=[1, 0, 0], velocity=[0, 0, 0]) ...
[]
[ 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 calculate_accelerations(positions, masses, G):\n num_bodies = len(masses)\n accelerations = np.zeros_like(positions)\n for i in range(num_bodies):\n f...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008823", "row_id": 8823, "seed_ids": "['Llama-3.3-70B-Instruct_24336']" }
0.274757
Filter_8823
I
[ "compute_gravitational_acceleration", "simulate_step", "simulate" ]
3
[ [ "simulate", "compute_gravitational_acceleration" ], [ "simulate", "simulate_step" ] ]
2
[]
false
[ "CelestialBody" ]
true
pytest
true
[ "numpy" ]
false
ed489453442c4442a172684bba24dafd8d46bf24
98286e3cc0b242c0dda2c38e6ba87cd21827527e
v1.0
instruct
Filter
Filter_8837_I
I have a long list of words, and I need to check how many of them are palindromes. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). I want to write a function in Python to do this, but I'm not sure how t...
def is_palindrome(word): """ Checks if a given word is a palindrome. """ sanitized_word = ''.join(e for e in word if e.isalnum()).lower() return sanitized_word == sanitized_word[::-1] def count_palindromes(words): """ Counts the number of palindromes in the given list of words. """ ...
from solution import is_palindrome, count_palindromes def test_is_palindrome_with_palindromes(): assert is_palindrome("racecar") == True assert is_palindrome("madam") == True assert is_palindrome("A man, a plan, a canal, Panama") == True # Considering punctuation and capitalization def test_is_palindrome...
[ { "docstring": "Checks if a given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Counts the number of palindromes in the given list of words.", "function_declaration": "def count_...
[ 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 Check if a given word is a palindrome.\n \n A palindrome reads the same forward and backward, ignoring spaces, punctuation,\n and capitalizat...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008837", "row_id": 8837, "seed_ids": "['Llama-3.3-70B-Instruct_24364']" }
0.744536
Filter_8837
I
[ "is_palindrome", "count_palindromes" ]
2
[ [ "count_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d8efb5c6f90139e93d2544603893616398171abc
5c388a1e1814e9fb2ad9b34cb312a169df6f6cb4
v1.0
instruct
Filter
Filter_8885_I
### Simulating a Casino Game #### Problem Statement You are a game developer who has been tasked with simulating a casino game. The game has the following rules: * The game is played with a standard deck of 52 cards, without jokers. * Each round, the player starts with a bankroll of $100. * The player is initiall...
import random # Define card ranks and suits ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] # Define card values values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11} # Funct...
from solution import create_deck, calculate_hand_value, deal_card, play_round def test_create_deck(): deck = create_deck() assert len(deck) == 52 assert isinstance(deck, list) assert all(isinstance(card, dict) for card in deck) def test_calculate_hand_value(): hand = [{'rank': '2', 'suit': 'Hearts...
[ { "docstring": null, "function_declaration": "def create_deck():", "function_name": "create_deck", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def calculate_hand_value(hand):", "function_name": "calculate_hand_value", "parameter_list": "(hand)" }, ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\n# Define card ranks and suits\nranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nsuits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n\n# Define card v...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008885", "row_id": 8885, "seed_ids": "['Llama-3.3-70B-Instruct_24476']" }
0.619142
Filter_8885
I
[ "create_deck", "calculate_hand_value", "deal_card", "play_round", "play_game" ]
5
[ [ "play_game", "create_deck" ], [ "play_game", "play_round" ], [ "play_round", "calculate_hand_value" ], [ "play_round", "deal_card" ] ]
4
[]
false
[]
false
pytest
true
[]
true
884076f3af73f0c8a44431965118473662053b28
3767970c5e38cec73a477b8c0e200227e307accf
v1.0
instruct
Filter
Filter_8890_I
I have a web application where users can login and create content. I want to implement a functionality such that whenever a user's profile is viewed by another user, it should send a notification to the profile owner saying that "your profile has been viewed by XYZ user". How can I achieve this functionality?
def send_profile_view_notification(profile_owner_id, viewer_username): """ Send a notification to the profile owner when their profile is viewed. Parameters: profile_owner_id: str - The unique identifier of the profile owner. viewer_username: str - The username of the viewer. Returns: ...
from solution import send_profile_view_notification, send_notification def test_send_profile_view_notification(): owner_id = "user123" viewer_username = "viewerXYZ" # Expected notification message expected_message = "Your profile has been viewed by viewerXYZ." # Capture the print output o...
[ { "docstring": "Send a notification to the profile owner when their profile is viewed.\n\nParameters:\nprofile_owner_id: str - The unique identifier of the profile owner.\nviewer_username: str - The username of the viewer.\n\nReturns:\nstr - A notification message.", "function_declaration": "def send_profil...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Function to send a notification when a user's profile is viewed by another user\n\ndef send_notification(profile_owner, viewer):\n \"\"\"\n Sends a notification to the profile owner wh...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008890", "row_id": 8890, "seed_ids": "['Llama-3.3-70B-Instruct_24486']" }
0.156816
Filter_8890
I
[ "send_profile_view_notification", "send_notification" ]
2
[ [ "send_profile_view_notification", "send_notification" ] ]
1
[]
false
[]
false
pytest
true
[]
true
200071d8b4c1b77e23165400ad98e337c17f957d
c987d801af33b5ae86322a4d1ee9080693f0a7a1
v1.0
instruct
Filter
Filter_8892_I
### Background and Context In the United States, students at the K-12 level typically take a variety of courses in different subjects. One of the most widely taken courses is mathematics. In mathematics education, students are taught various topics such as algebra, geometry, and calculus. ### Problem Statement You are...
import random import operator from typing import Tuple # Define the math operations math_operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } def generate_problem() -> Tuple[str, float]: """ Generates a random simple math problem and the correct answe...
import pytest from solution import generate_problem def test_generate_problem_format(): problem, answer = generate_problem() assert isinstance(problem, str) assert isinstance(answer, (int, float)) def test_generate_problem_addition(): problem, answer = generate_problem() if '+' in problem: ...
[ { "docstring": "Generates a random simple math problem and the correct answer.\n\nReturns:\n Tuple containing the problem string and its correct answer.", "function_declaration": "def generate_problem():", "function_name": "generate_problem", "parameter_list": "()" }, { "docstring": "Runs...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport operator\nfrom typing import Tuple\n\n# Define the math operations\nmath_operations = {\n '+': operator.add,\n '-': operator.sub,\n '*': operator.mul,\n '/': ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008892", "row_id": 8892, "seed_ids": "['Llama-3.3-70B-Instruct_24489']" }
0.547384
Filter_8892
I
[ "generate_problem", "run_math_practice" ]
2
[ [ "run_math_practice", "generate_problem" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1a1299144956cc029177386c09b3ea029af5dbd
0d6c79129995f8464ef1e890ef4267f0fe2a182d
v1.0
instruct
Filter
Filter_8910_I
Here's my code. I'm using Python to generate a fractal image using the Mandelbrot set. ```python import numpy as np import matplotlib.pyplot as plt def mandelbrot(c, max_iter): z = c for n in range(max_iter): if abs(z) > 2: return n z = z*z + c return max_iter def draw_mandelb...
import numpy as np import matplotlib.pyplot as plt def mandelbrot(c, max_iter): z = c for n in range(max_iter): if abs(z) > 2: return n z = z*z + c return max_iter def draw_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter): r1 = np.linspace(xmin, xmax, width) ...
from solution import draw_mandelbrot, draw_image import numpy as np def test_mandelbrot_basic(): # Basic test to check if function handles simple case correctly c = complex(0, 0) assert mandelbrot(c, 10) == 10 def test_mandelbrot_escape(): # Test to check if a point that escapes early is detected ...
[ { "docstring": null, "function_declaration": "def mandelbrot(c, max_iter):", "function_name": "mandelbrot", "parameter_list": "(c, max_iter)" }, { "docstring": null, "function_declaration": "def draw_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):", "function_name": "dra...
[ 0, 1, 0 ]
1
medium
0.333
{ "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 mandelbrot(c, max_iter):\n z = c\n for n in range(max_iter):\n if abs(z) > 2:\n return n\n z = z*z + c...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008910", "row_id": 8910, "seed_ids": "['Llama-3.3-70B-Instruct_24520']" }
0.499466
Filter_8910
I
[ "mandelbrot", "draw_mandelbrot", "draw_image" ]
3
[ [ "draw_image", "draw_mandelbrot" ], [ "draw_mandelbrot", "mandelbrot" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
9660c1cf084f8c8962844d1ac74e76cf668d04d3
f36574fdc2285eeb8b8b1cfa68ae10e0e4fb39f5
v1.0
instruct
Filter
Filter_9017_I
Here are the functions: ``` def parse_arg(arg): return arg.split(',') def enumerate_values(some_list): return list(enumerate(some_list)) def process_data(data): return [x * 2 for x in data] ``` How would you use these functions to create a list of tuples, where each tuple contains the index and value of t...
def parse_arg(arg): """ Splits the input string by commas and returns a list of values. """ return arg.split(',') def enumerate_values(some_list): """ Returns a list of tuples, where each tuple contains an index and the value from the input list. """ return list(enumerate(some_list...
from solution import parse_arg, enumerate_values, process_data, create_doubled_enumerated_list def test_parse_arg(): assert parse_arg("1,2,3") == ["1", "2", "3"] assert parse_arg("a,b,c") == ["a", "b", "c"] def test_enumerate_values(): assert enumerate_values(["a", "b", "c"]) == [(0, "a"), (1, "b"), (2, "...
[ { "docstring": "Splits the input string by commas and returns a list of values.", "function_declaration": "def parse_arg(arg):", "function_name": "parse_arg", "parameter_list": "(arg)" }, { "docstring": "Returns a list of tuples, where each tuple contains an index and the value \nfrom the in...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def parse_arg(arg):\n return arg.split(',')\n\ndef enumerate_values(some_list):\n return list(enumerate(some_list))\n\ndef process_data(data):\n return [x * 2 for x in data]\n\ndef cr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009017", "row_id": 9017, "seed_ids": "['Llama-3.3-70B-Instruct_24761']" }
0.665245
Filter_9017
I
[ "parse_arg", "enumerate_values", "process_data", "create_doubled_enumerated_list" ]
4
[ [ "create_doubled_enumerated_list", "enumerate_values" ], [ "create_doubled_enumerated_list", "parse_arg" ], [ "create_doubled_enumerated_list", "process_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
444e9c7ccda29cfeb1be4e28e80bf4800ebfcc72
f393f5433d2380290d51fb34fee27e45e057919c
v1.0
instruct
Filter
Filter_9019_I
Here is the code that defines the `edit_mode` function. You can use this function to turn edit mode on or off. ```python def edit_mode(edit): if edit == 'on': return True elif edit == 'off': return False else: raise ValueError("Invalid input. Use 'on' or 'off'.") ``` You can use t...
def edit_mode(edit): if edit == 'on': return True elif edit == 'off': return False else: raise ValueError("Invalid input. Use 'on' or 'off'.") def toggle_edit_mode(current_edit_mode): # You can use the edit_mode function here if current_edit_mode: return edit_mode('o...
from solution import edit_mode, toggle_edit_mode, change_edit_mode def test_edit_mode_on(): assert edit_mode('on') == True def test_edit_mode_off(): assert edit_mode('off') == False def test_edit_mode_invalid(): try: edit_mode('invalid') except ValueError as e: assert str(e) == "Inval...
[ { "docstring": null, "function_declaration": "def edit_mode(edit):", "function_name": "edit_mode", "parameter_list": "(edit)" }, { "docstring": null, "function_declaration": "def toggle_edit_mode(current_edit_mode):", "function_name": "toggle_edit_mode", "parameter_list": "(curre...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def edit_mode(edit):\n if edit == 'on':\n return True\n elif edit == 'off':\n return False\n else:\n raise ValueError(\"Invalid input. Use 'on' or 'off'.\")\n\nde...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009019", "row_id": 9019, "seed_ids": "['Llama-3.3-70B-Instruct_24767']" }
0.387089
Filter_9019
I
[ "edit_mode", "toggle_edit_mode", "change_edit_mode" ]
3
[ [ "change_edit_mode", "edit_mode" ], [ "change_edit_mode", "toggle_edit_mode" ], [ "toggle_edit_mode", "edit_mode" ] ]
3
[]
false
[]
false
pytest
true
[]
true
28e9630e0bdcc83e763ecf12f51815043f848b69
dfe2a96cdf6ccc088335ea44080483ef11a4f951
v1.0
instruct
Filter
Filter_9025_I
I have a question about back-propagation in neural networks. I am implementing a neural network using the back-propagation algorithm, but I am having trouble with the computation of the output error gradient. To clarify, I am using a sigmoid activation function for the hidden and output layers. I am using the follo...
import numpy as np def sigmoid(z): """ Compute the sigmoid of z. """ return 1 / (1 + np.exp(-z)) def sigmoid_derivative(z): """ Compute the derivative of the sigmoid function. Since sigmoid(z) = 1 / (1 + exp(-z)), the derivative is sigmoid(z) * (1 - sigmoid(z)). """ sig = sigm...
from solution import sigmoid, sigmoid_derivative, error_gradient import numpy as np def test_sigmoid(): assert sigmoid(0) == 0.5 assert np.isclose(sigmoid(2), 0.8807970779778823) assert np.isclose(sigmoid(-2), 0.11920292202211755) def test_sigmoid_derivative(): assert np.isclose(sigmoid_derivative(0),...
[ { "docstring": "Compute the sigmoid of z.", "function_declaration": "def sigmoid(z):", "function_name": "sigmoid", "parameter_list": "(z)" }, { "docstring": "Compute the derivative of the sigmoid function.\nSince sigmoid(z) = 1 / (1 + exp(-z)), the derivative is \nsigmoid(z) * (1 - sigmoid(z...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef sigmoid(z):\n \"\"\"\n Compute the sigmoid of z\n \"\"\"\n return 1 / (1 + np.exp(-z))\n\ndef sigmoid_derivative(z):\n \"\"\"\n Compute the derivati...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009025", "row_id": 9025, "seed_ids": "['Llama-3.3-70B-Instruct_24786']" }
0.375663
Filter_9025
I
[ "sigmoid", "sigmoid_derivative", "error_gradient" ]
3
[ [ "error_gradient", "sigmoid_derivative" ], [ "sigmoid_derivative", "sigmoid" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
bef8b5245daeb5add3a3bdb2f158599a64873da3
4c5d3df0892f26de91fb1cd8841bab4214f46488
v1.0
instruct
Filter
Filter_9094_I
### Using Python, create a simple rock, paper, scissors game that you can play against the computer. #### The game should: * Allow the user to choose rock, paper, or scissors * Generate the computer's choice randomly * Determine the winner based on the game's rules * Ask the user if they want to play again * ...
import random def get_computer_choice(): return random.choice(["rock", "paper", "scissors"]) def determine_winner(user, computer): if user == computer: return "tie" elif (user == "rock" and computer == "scissors") or \ (user == "paper" and computer == "rock") or \ (user == "sciss...
from solution import get_computer_choice, determine_winner def test_get_computer_choice(): choices = ["rock", "paper", "scissors"] assert get_computer_choice() in choices def test_determine_winner_tie(): assert determine_winner("rock", "rock") == "tie" assert determine_winner("paper", "paper") == "tie...
[ { "docstring": null, "function_declaration": "def get_computer_choice():", "function_name": "get_computer_choice", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def determine_winner(user, computer):", "function_name": "determine_winner", "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 \"\"\"\n Get the winner of the rock-paper-scissors game.\n \n Parameters:\n - user_choice (str): User's choice, ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009094", "row_id": 9094, "seed_ids": "['Llama-3.3-70B-Instruct_24921']" }
0.558809
Filter_9094
I
[ "get_computer_choice", "determine_winner", "play_game" ]
3
[ [ "play_game", "determine_winner" ], [ "play_game", "get_computer_choice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6d6fc78ae04f8de249164247a55cb03c522eca74
7695fe39778612535789da46910929ee141c0a8d
v1.0
instruct
Filter
Filter_9109_I
So, I would like to create a box that can be used to store items. It would have 6 faces, and each face would have a different number of holes, and each hole would have a different diameter. I'd like to use a Python script to help me determine the dimensions for each hole. For example, the first face would have 10 hol...
def calculate_hole_dimensions(face_num, num_holes): """ Calculate the dimensions for each hole on a given face. Parameters: face_num (int): The face number. num_holes (int): The number of holes on the face. Returns: list: A list of diameters for each hole. """ return [face_num + i ...
from solution import calculate_hole_dimensions, get_all_hole_dimensions def test_calculate_hole_dimensions(): assert calculate_hole_dimensions(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] assert calculate_hole_dimensions(2, 8) == [2, 3, 4, 5, 6, 7, 8, 9] assert calculate_hole_dimensions(3, 6) == [3, 4, 5, 6, ...
[ { "docstring": "Calculate the dimensions for each hole on a given face.\n\nParameters:\nface_num (int): The face number.\nnum_holes (int): The number of holes on the face.\n\nReturns:\nlist: A list of diameters for each hole.", "function_declaration": "def calculate_hole_dimensions(face_num, num_holes):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_hole_dimensions(face_num, num_holes):\n \"\"\"\n Calculate the dimensions for each hole on a given face.\n\n Parameters:\n face_num (int): The face number.\n num_h...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009109", "row_id": 9109, "seed_ids": "['Llama-3.3-70B-Instruct_24957']" }
0.495988
Filter_9109
I
[ "calculate_hole_dimensions", "get_all_hole_dimensions" ]
2
[ [ "get_all_hole_dimensions", "calculate_hole_dimensions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb418333ad0c0e5ece9ec19b59d5482b0ebc0c32
32ea6138b426e13e5b499dc22fa7b7a4fd949a95
v1.0
instruct
Filter
Filter_9125_I
Here is the problem for which I need a solution: I'm a software engineer. I'm using Python, and I have a text file that contains a list of URLs separated by a newline character. The task is to write a function that reads the text file, takes each URL, and converts it into a domain name. Please provide a solution to ...
from urllib.parse import urlparse def extract_domain(url): """ Extracts the domain name from a given URL. """ parsed_url = urlparse(url) return parsed_url.hostname.replace('www.', '') def convert_urls_to_domains(file_path): """ Reads a file containing URLs and converts each to its domain n...
import pytest from solution import extract_domain, convert_urls_to_domains # Mocking file reading using StringIO from io import StringIO import tempfile def test_extract_domain(): assert extract_domain("https://example.com") == "example.com" assert extract_domain("https://www.example.com") == "example.com" ...
[ { "docstring": "Extracts the domain name from a given URL.", "function_declaration": "def extract_domain(url):", "function_name": "extract_domain", "parameter_list": "(url)" }, { "docstring": "Reads a file containing URLs and converts each to its domain name.\n\nParameters:\n- file_path: pat...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef extract_domain(url):\n \"\"\"\n Extracts and returns the domain name from a given URL.\n \"\"\"\n pattern = re.compile(r'https?://(www\\.)?')\n domain = pattern...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009125", "row_id": 9125, "seed_ids": "['Llama-3.3-70B-Instruct_24981']" }
0.611349
Filter_9125
I
[ "extract_domain", "convert_urls_to_domains" ]
2
[ [ "convert_urls_to_domains", "extract_domain" ] ]
1
[]
false
[]
false
pytest
true
[]
true
118501079ec64e2339676bf02d095293e87f5797
0ae6322dd16976735a82746390f86372cd0e4c6b
v1.0
instruct
Filter
Filter_9139_I
I have a single neuron with two inputs, x1 and x2, and I want to perform gradient descent to optimize its weights. The neuron's output is calculated using the sigmoid function. I've already implemented the neuron and the sigmoid function, but I want to calculate the derivative of the cost function with respect to each ...
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1 - x) def neuron_output(weights, inputs): return sigmoid(np.dot(weights, inputs)) def cost_function(weights, inputs, target): output = neuron_output(weights, inputs) return 0.5 * (target - outp...
from solution import sigmoid, sigmoid_derivative, neuron_output, cost_function, cost_derivative 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_neuron_output(): weights = np.array([0.5, 0.4]) inputs = np.a...
[ { "docstring": null, "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def sigmoid_derivative(x):", "function_name": "sigmoid_derivative", "parameter_list": "(x)" }, { "docstring...
[ 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 return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\ndef neuron_output(weights, inputs):\n return sigmoid(np.dot(w...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009139", "row_id": 9139, "seed_ids": "['Llama-3.3-70B-Instruct_25018']" }
0.410055
Filter_9139
I
[ "sigmoid", "sigmoid_derivative", "neuron_output", "cost_function", "cost_derivative", "main" ]
6
[ [ "cost_derivative", "neuron_output" ], [ "cost_derivative", "sigmoid_derivative" ], [ "cost_function", "neuron_output" ], [ "neuron_output", "sigmoid" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy" ]
false
5fa9be053ea415509870efeccf6b7d7f5f4b9468
dc30415a57bd733acc06a0bd5229dba2060363f4
v1.0
instruct
Filter
Filter_9142_I
I'm trying to write a program that can play Blackjack. I want to write it in Python, as it seems to be the best language for a beginner. I also want the game to be double deck, meaning that it uses two standard decks of cards. Here is the starting code: ``` import random suits = ['Hearts', 'Diamonds', 'Clubs', 'Spad...
import random suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} # Create a double deck deck = [(ran...
from solution import draw_card, calculate_hand_value, initial_deal, determine_winner, deck def test_draw_card(): before_len = len(deck) card = draw_card(deck) after_len = len(deck) assert before_len - after_len == 1 assert card is not None def test_calculate_hand_value(): assert calculate_hand...
[ { "docstring": null, "function_declaration": "def draw_card(deck):", "function_name": "draw_card", "parameter_list": "(deck)" }, { "docstring": null, "function_declaration": "def calculate_hand_value(hand):", "function_name": "calculate_hand_value", "parameter_list": "(hand)" }...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nsuits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\nranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']\nvalues = {'2': 2, '3': 3, '4': 4, '5...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009142", "row_id": 9142, "seed_ids": "['Llama-3.3-70B-Instruct_25032']" }
0.539584
Filter_9142
I
[ "draw_card", "calculate_hand_value", "initial_deal", "determine_winner" ]
4
[ [ "determine_winner", "calculate_hand_value" ], [ "initial_deal", "draw_card" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2cebc011c934e358d8472c289af84a83e9d0ee67
80fe8bd4a45782c88ce3b529d626b44f93ce6a29
v1.0
instruct
Filter
Filter_9175_I
I asked for a program that can extract and display the data from a json file, what I got was a program that assumes that I know the keys in the json file beforehand, which defeats the purpose of the program. Can you please make a program that will extract and display the data from a json file without needing to know th...
import json def display_json_data(json_data, indent=0): """ Recursively display the contents of a JSON object without needing to know the keys beforehand. """ if isinstance(json_data, dict): for key, value in json_data.items(): print(' ' * indent + str(key) + ':') displa...
import json import tempfile from solution import extract_and_display_json def test_display_json_data(capfd): json_content = { "name": "John", "age": 30, "children": [ {"name": "Jane", "age": 10}, {"name": "Doe", "age": 5} ], "address": { "...
[ { "docstring": "Recursively display the contents of a JSON object without needing to know the keys beforehand.", "function_declaration": "def display_json_data(json_data, indent=0):", "function_name": "display_json_data", "parameter_list": "(json_data, indent=0)" }, { "docstring": "Extracts ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\n\ndef display_json_data(file_path):\n \"\"\"\n Reads a JSON file and prints its data recursively.\n \"\"\"\n def print_data(data, indent=0):\n if isinstance(dat...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009175", "row_id": 9175, "seed_ids": "['Llama-3.3-70B-Instruct_25096']" }
0.472475
Filter_9175
I
[ "display_json_data", "extract_and_display_json" ]
2
[ [ "extract_and_display_json", "display_json_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dd5b833e7ffc1317d11c5044613bfce814061ee3
da7f54b706dcc7bedfeeb638e85afa733f43c9fd
v1.0
instruct
Filter
Filter_9194_I
This is the code to create the options menu: ```python options = [ ("Search and Destroy", "Search for and destroy the enemy", "s", 0), ("Search and Capture", "Search for and capture the enemy", "c", 1), ("Search and Replace", "Search for and replace the enemy", "r", 2), ("Quit", "Exit the game", "q", 3)...
def draw_menu(options): print("\n-------------------------") for i, (name, description, shortcut, index) in enumerate(options, start=1): print(f"{i}. {name} - {description} ({shortcut})") print("-------------------------\n") def get_user_choice(options): while True: draw_menu(options) ...
from solution import draw_menu, get_user_choice, main import pytest from unittest.mock import patch def test_draw_menu(capsys): options = [ ("Option1", "Description1", "o1", 0), ("Option2", "Description2", "o2", 1) ] draw_menu(options) captured = capsys.readouterr() assert "1. Optio...
[ { "docstring": null, "function_declaration": "def draw_menu(options):", "function_name": "draw_menu", "parameter_list": "(options)" }, { "docstring": null, "function_declaration": "def get_user_choice(options):", "function_name": "get_user_choice", "parameter_list": "(options)" ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def draw_menu(options):\n \"\"\"\n Draws the options menu.\n \"\"\"\n print(\"\\n-------------------------\")\n for i, (name, description, shortcut, index) in enumerate(options,...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009194", "row_id": 9194, "seed_ids": "['Llama-3.3-70B-Instruct_25153']" }
0.451761
Filter_9194
I
[ "draw_menu", "get_user_choice", "main" ]
3
[ [ "get_user_choice", "draw_menu" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bc038932cb594f41a8a806bec9a1a2e7c8fac76b
28594463511c3e4a81a9f5768b790fc8e06cc896
v1.0
instruct
Filter
Filter_9209_I
### Task 1: Write a function to convert a binary number to a decimal number #### Function Name: binary_to_decimal #### Parameters: binary_number (str) #### Returns: int ```python def binary_to_decimal(binary_number: str) -> int: """ This function converts a binary number to a decimal number. Parameters: ...
def binary_to_decimal(binary_number: str) -> int: """ This function converts a binary number to a decimal number. Parameters: binary_number (str): A string representing a binary number. Returns: int: The decimal equivalent of the binary number. """ decimal_number = 0 for i, bit in ...
import pytest from solution import binary_to_decimal, decimal_to_binary, binary_decimal_converter def test_binary_to_decimal(): assert binary_to_decimal('1010') == 10 assert binary_to_decimal('1101') == 13 assert binary_to_decimal('1001') == 9 assert binary_to_decimal('0') == 0 assert binary_to_dec...
[ { "docstring": "This function converts a binary number to a decimal number.\n\nParameters:\nbinary_number (str): A string representing a binary number.\n\nReturns:\nint: The decimal equivalent of the binary number.", "function_declaration": "def binary_to_decimal(binary_number):", "function_name": "bina...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_to_decimal(binary_number: str) -> int:\n \"\"\"\n Converts a binary number to a decimal number.\n\n Parameters:\n binary_number (str): A string representing a binary num...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009209", "row_id": 9209, "seed_ids": "['Llama-3.3-70B-Instruct_25183']" }
0.821422
Filter_9209
I
[ "binary_to_decimal", "decimal_to_binary", "binary_decimal_converter" ]
3
[ [ "binary_decimal_converter", "binary_to_decimal" ], [ "binary_decimal_converter", "decimal_to_binary" ] ]
2
[]
false
[]
false
pytest
true
[]
true
28be00a12717e4570502a075da13de260bc3a2df
e519d2edbabffa9534fecd5bb73ba863046bf530
v1.0
instruct
Filter
Filter_9222_I
I would like to create a simple game in Python where the user is presented with a menu and can choose to either roll a dice, check the current time, or exit the program.
import random import time def roll_dice(): """ Simulate rolling a dice by returning a random integer between 1 and 6. """ return random.randint(1, 6) def check_time(): """ Returns the current time as a formatted string. """ return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) d...
import time from solution import roll_dice, check_time def test_roll_dice(): for _ in range(100): result = roll_dice() assert 1 <= result <= 6 def test_check_time(): current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) assert check_time() == current_time
[ { "docstring": "Simulate rolling a dice by returning a random integer between 1 and 6.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Returns the current time as a formatted string.", "function_declaration": "def chec...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport time\n\ndef roll_dice():\n \"\"\"\n Simulate rolling a dice by returning a random integer between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef check...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009222", "row_id": 9222, "seed_ids": "['Llama-3.3-70B-Instruct_25213']" }
0.430271
Filter_9222
I
[ "roll_dice", "check_time", "menu" ]
3
[ [ "menu", "check_time" ], [ "menu", "roll_dice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5744c6f7c6024977c21476a47e049fc826c43c61
eb456be082b4c57c23992ac977167e32333234e3
v1.0
instruct
Filter
Filter_9234_I
Here's an example of how I'd like my code to behave: ```python import random def roll_dice(): """Simulate rolling 2 six-sided dice.""" return random.randint(1, 6), random.randint(1, 6) def calculate_score(dice1, dice2): """Calculate the score based on the rolls.""" if dice1 == dice2: return di...
import random def roll_dice(): """Simulate rolling 2 six-sided dice.""" return random.randint(1, 6), random.randint(1, 6) def calculate_score(dice1, dice2): """Calculate the score based on the rolls.""" if dice1 == dice2: return dice1 * 2 else: return max(dice1, dice2) def play_ga...
from solution import roll_dice, calculate_score def test_roll_dice(): dice1, dice2 = roll_dice() assert 1 <= dice1 <= 6 assert 1 <= dice2 <= 6 def test_calculate_score_doubles(): assert calculate_score(3, 3) == 6 assert calculate_score(6, 6) == 12 def test_calculate_score_non_doubles(): asser...
[ { "docstring": "Simulate rolling 2 six-sided dice.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Calculate the score based on the rolls.", "function_declaration": "def calculate_score(dice1, dice2):", "function_n...
[ 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 roll_dice():\n \"\"\"Simulate rolling 2 six-sided dice.\"\"\"\n return random.randint(1, 6), random.randint(1, 6)\n\ndef calculate_score(dice1, dice2):\n \"\"\"Ca...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009234", "row_id": 9234, "seed_ids": "['Llama-3.3-70B-Instruct_25242']" }
0.49577
Filter_9234
I
[ "roll_dice", "calculate_score", "play_game" ]
3
[ [ "play_game", "calculate_score" ], [ "play_game", "roll_dice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
16a844d220154ffac34eb78a22813f19861e7aac
b45d20a6d842e329dd47a9ebbef2c380f3bdea91
v1.0
instruct
Filter
Filter_9244_I
I have a .csv file with a specific format like so: ``` "username","email","password" "user1","user1@example.com","password1" "user2","user2@example.com","password2" "user3","user3@example.com","password3" ``` I would like to write a Python script that can read this file, add a new column for the password hash, and t...
import csv import hashlib def hash_password(password): """ Hashes the given password using SHA256 and returns the hexadecimal format of the hash. """ sha256 = hashlib.sha256() sha256.update(password.encode('utf-8')) return sha256.hexdigest() def process_csv(input_filepath, output_filepath): ...
import os import csv import hashlib from solution import hash_password, process_csv def test_hash_password(): assert hash_password('password1') == hashlib.sha256('password1'.encode('utf-8')).hexdigest() def create_test_csv(filename, rows): with open(filename, 'w', newline='') as file: writer = csv.wri...
[ { "docstring": "Hashes the given password using SHA256 and returns the hexadecimal format of the hash.", "function_declaration": "def hash_password(password):", "function_name": "hash_password", "parameter_list": "(password)" }, { "docstring": "Reads a CSV file, hashes the passwords, and wri...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nimport hashlib\n\ndef hash_password(password):\n \"\"\"\n Returns the SHA-256 hash of the given password in hexadecimal format.\n \"\"\"\n hashed = hashlib.sha256(passw...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009244", "row_id": 9244, "seed_ids": "['Llama-3.3-70B-Instruct_25277']" }
0.561647
Filter_9244
I
[ "hash_password", "process_csv" ]
2
[ [ "process_csv", "hash_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
31ecfe5285b9759d51e092d34795a92579d59954
dea91bef4f0d181fd1c1560ffeb6e8f2ec505340
v1.0
instruct
Filter
Filter_9249_I
### Overview This is a simple game written in Python. The goal of the game is to roll virtual dice and score points according to the following rules: 1. The game consists of multiple rounds. 2. Each round, the player rolls five virtual dice. 3. After each roll, the player can choose which dice to keep and which to re-r...
import random def roll_dice(num_dice): """Rolls num_dice virtual dice.""" return [random.randint(1, 6) for _ in range(num_dice)] def calculate_score(dice): """Calculates the score based on the dice.""" # Check for five of a kind if len(set(dice)) == 1: return 30 # Check for a run (1,2...
from solution import roll_dice, calculate_score def test_roll_dice(): dice = roll_dice(5) assert len(dice) == 5 assert all(1 <= x <= 6 for x in dice) def test_calculate_score_five_of_a_kind(): assert calculate_score([4, 4, 4, 4, 4]) == 30 def test_calculate_score_run(): assert calculate_score([1,...
[ { "docstring": "Rolls num_dice virtual dice.", "function_declaration": "def roll_dice(num_dice):", "function_name": "roll_dice", "parameter_list": "(num_dice)" }, { "docstring": "Calculates the score based on the dice.", "function_declaration": "def calculate_score(dice):", "function...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef roll_dice(num_dice):\n \"\"\"Rolls num_dice virtual dice.\"\"\"\n return [random.randint(1, 6) for _ in range(num_dice)]\n\ndef calculate_score(dice):\n \"\"\"Cal...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009249", "row_id": 9249, "seed_ids": "['Llama-3.3-70B-Instruct_25287']" }
0.563613
Filter_9249
I
[ "roll_dice", "calculate_score", "game_round" ]
3
[ [ "game_round", "calculate_score" ], [ "game_round", "roll_dice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3b503160467d5ef510f10454fab80727174b6985
06d6739fbf180484d64dc13acc3d2cca144c6709
v1.0
instruct
Filter
Filter_9253_I
I have a list of items in a csv file. Each item in the list has an id, name, and rating. The id is unique for each item. I want to create a function that will allow me to add, remove, and edit an item in my list based on its id. Here is an example of what my csv file looks like: ``` id,name,rating 1,Item 1,4.5 2,Item...
import csv def read_csv(file_path): items = [] with open(file_path, mode='r') as file: csv_reader = csv.DictReader(file) for row in csv_reader: items.append(row) return items def write_csv(file_path, items): fieldnames = ['id', 'name', 'rating'] with open(file_path, mod...
import os import pytest from solution import add_item, remove_item, edit_item, read_csv TEST_CSV = 'test_items.csv' @pytest.fixture(autouse=True) def setup_and_teardown(): # Setup if os.path.exists(TEST_CSV): os.remove(TEST_CSV) with open(TEST_CSV, mode='w', newline='') as file: csv_writer...
[ { "docstring": null, "function_declaration": "def read_csv(file_path):", "function_name": "read_csv", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def write_csv(file_path, items):", "function_name": "write_csv", "parameter_list": "(file_path, i...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\n\ndef read_csv(filepath):\n items = []\n with open(filepath, mode='r', newline='') as file:\n reader = csv.DictReader(file)\n for row in reader:\n ro...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009253", "row_id": 9253, "seed_ids": "['Llama-3.3-70B-Instruct_25294']" }
0.559341
Filter_9253
I
[ "read_csv", "write_csv", "add_item", "remove_item", "edit_item" ]
5
[ [ "add_item", "read_csv" ], [ "add_item", "write_csv" ], [ "edit_item", "read_csv" ], [ "edit_item", "write_csv" ], [ "remove_item", "read_csv" ], [ "remove_item", "write_csv" ] ]
6
[]
false
[]
false
pytest
true
[]
true
8d08e99d37a23704cae2485bb1f5972952a54e32
e6a273594e647f14cbe6ab5c7fa9450fdf59b337
v1.0
instruct
Filter
Filter_9266_I
I have a project in which I need to iterate over a large number of files, and for each file, I need to check if a specific string is present. If the string is found, I need to perform some action, for example, copy the file. How can I efficiently do this in Python?
import os import shutil def find_string_in_file(file_path, target_string): """ Searches for a target string in a given file. :param file_path: Path to the file to be searched. :param target_string: String to search for. :return: Boolean indicating whether the string was found. """ with...
import os import pytest import shutil from solution import find_string_in_file, process_files, copy_file @pytest.fixture def setup_files(tmp_path): # Setup temporary directory and files for testing files = [ ("file1.txt", "This is a test file. Contains target_string."), ("file2.txt", "Another f...
[ { "docstring": "Searches for a target string in a given file.\n\n:param file_path: Path to the file to be searched.\n:param target_string: String to search for.\n:return: Boolean indicating whether the string was found.", "function_declaration": "def find_string_in_file(file_path, target_string):", "fun...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport shutil\n\ndef find_and_copy_files(src_dir, dst_dir, search_string):\n \"\"\"\n Iterates over all files in src_dir, checks if search_string is present in each file.\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009266", "row_id": 9266, "seed_ids": "['Llama-3.3-70B-Instruct_25325']" }
0.59051
Filter_9266
I
[ "find_string_in_file", "process_files", "copy_file" ]
3
[ [ "process_files", "find_string_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
58e0a3810cc50371c6202d4f89c71503221b7a50
86de70739cff6bdff70a1b7ed70721cdbaaa563b
v1.0
instruct
Filter
Filter_9268_I
### Message Encryption and Decryption #### Problem Statement Write a simple encryption technique program that takes a message as input, applies a Caesar cipher to it, and prints out the encrypted message. The Caesar cipher is one of the simplest (and easiest) encryption methods. It is a type of substitution cipher in w...
def caesar_cipher(message, shift): """ Encrypts a message using the Caesar cipher technique. Args: message (str): The message to be encrypted or decrypted. shift (int): The shift value for the Caesar cipher. Returns: str: The encrypted or decrypted message. """ encrypted_message = ...
from solution import caesar_cipher, decrypt_caesar_cipher def test_caesar_cipher(): assert caesar_cipher("HELLO", 3) == "KHOOR" assert caesar_cipher("WORLD", 1) == "XPSME" assert caesar_cipher("hello", 2) == "jgnnq" assert caesar_cipher("Python-123!", 5) == "Udymts-123!" def test_decrypt_caesar_cipher...
[ { "docstring": "Encrypts a message using the Caesar cipher technique.\n\nArgs:\nmessage (str): The message to be encrypted or decrypted.\nshift (int): The shift value for the Caesar cipher.\n\nReturns:\nstr: The encrypted or decrypted message.", "function_declaration": "def caesar_cipher(message, shift):", ...
[ 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(message, shift):\n \"\"\"\n Encrypts a message using the Caesar cipher technique.\n\n Args:\n message (str): The message to be encrypted.\n shift (int): The sh...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009268", "row_id": 9268, "seed_ids": "['Llama-3.3-70B-Instruct_25328']" }
0.697175
Filter_9268
I
[ "caesar_cipher", "decrypt_caesar_cipher" ]
2
[ [ "decrypt_caesar_cipher", "caesar_cipher" ] ]
1
[]
false
[]
false
pytest
true
[]
true
307fcfa3b83d98dffc3f76e5650c1800e0bd72d9
f3ec6a92d50661a3c56d281090fc745d9ea4cb15
v1.0
instruct
Filter
Filter_9271_I
### Dice Game #### Problem Statement In this problem, we will implement a simple dice game. The game will have two players. The game will continue until one player reaches 100 points. Players will take turns rolling a dice. For each roll, the player scores the number on the dice. If the player rolls a 6, their turn con...
import random def roll_dice(): """Simulates the roll of a dice.""" return random.randint(1, 6) def player_turn(): """Simulates a player's turn.""" turn_score = 0 while True: roll = roll_dice() if roll == 1: return 0 turn_score += roll if roll != 6: ...
from solution import roll_dice, player_turn, dice_game def test_roll_dice(): for _ in range(100): roll = roll_dice() assert 1 <= roll <= 6 def test_player_turn(): for _ in range(100): score = player_turn() assert score >= 0 def test_dice_game(): player1_score, player2_scor...
[ { "docstring": "Simulates the roll of a dice.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Simulates a player's turn.", "function_declaration": "def player_turn():", "function_name": "player_turn", "paramete...
[ 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\nclass DiceGame:\n def __init__(self, seed=None):\n self.player1_score = 0\n self.player2_score = 0\n self.current_player = 1 # 1 for player 1, 2 for p...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009271", "row_id": 9271, "seed_ids": "['Llama-3.3-70B-Instruct_25333']" }
0.627008
Filter_9271
I
[ "roll_dice", "player_turn", "dice_game" ]
3
[ [ "dice_game", "player_turn" ], [ "player_turn", "roll_dice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
713baff43044e6d6e7004f598b911d090efa6362
017a14d73e0fcdf7858164a442d1f9353ce547eb
v1.0
instruct
Filter
Filter_9276_I
Here is a JSON object with some data about a fictional company: ```json { "name": "TechCorp", "revenue": 1000000, "expenses": [ { "name": "Salaries", "amount": 500000 }, { "name": "Rent", "amount": 200000 }, { "name": "Marketing", "amount": 100000 }, ...
import json # Example JSON object data = ''' { "name": "TechCorp", "revenue": 1000000, "expenses": [ { "name": "Salaries", "amount": 500000 }, { "name": "Rent", "amount": 200000 }, { "name": "Marketing", "amount": 100000 }, { "name": "Equipmen...
from solution import get_total_expenses, get_net_profit, get_employee_salaries def test_get_total_expenses(): data = json.loads(''' { "name": "TechCorp", "revenue": 1000000, "expenses": [ { "name": "Salaries", "amount": 500000 }, { "name":...
[ { "docstring": "Returns the total expenses from the JSON data.", "function_declaration": "def get_total_expenses(data):", "function_name": "get_total_expenses", "parameter_list": "(data)" }, { "docstring": "Returns the net profit after subtracting expenses from the revenue.", "function_d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\n\n# JSON object in string format\ncompany_json = '''\n{\n \"name\": \"TechCorp\",\n \"revenue\": 1000000,\n \"expenses\": [\n {\n \"name\": \"Salaries\",\n \"amoun...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009276", "row_id": 9276, "seed_ids": "['Llama-3.3-70B-Instruct_25344']" }
0.584616
Filter_9276
I
[ "get_total_expenses", "get_net_profit", "get_employee_salaries" ]
3
[ [ "get_net_profit", "get_total_expenses" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb3b614fe8a66aba8582c0f07115b472aceb7492
0f4dcfcb8ecc74b8a588bfffd5339977e04c0d10
v1.0
instruct
Filter
Filter_9315_I
Consider the following code: ``` def function(param1, param2): result = param1 + param2 print("The result is:", result) return result ``` How do you use this function in another function? Please provide an example of using this function in a different function. Also, please provide an example of using t...
# The original function def function(param1, param2): result = param1 + param2 print("The result is:", result) return result # Using function in another function def another_function(x, y, z): intermediate_result = function(x, y) final_result = function(intermediate_result, z) return final_resu...
from solution import function, another_function def test_function(): assert function(1, 1) == 2 assert function(2, 3) == 5 assert function(-1, 1) == 0 def test_another_function(): assert another_function(1, 2, 3) == 6 assert another_function(0, 0, 0) == 0 assert another_function(5, 5, 10) == 2...
[ { "docstring": null, "function_declaration": "def function(param1, param2):", "function_name": "function", "parameter_list": "(param1, param2)" }, { "docstring": null, "function_declaration": "def another_function(x, y, z):", "function_name": "another_function", "parameter_list":...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def function(param1, param2):\n result = param1 + param2\n print(\"The result is:\", result)\n return result\n\ndef use_function_in_another_function(arg1, arg2):\n \"\"\"\n This...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009315", "row_id": 9315, "seed_ids": "['Llama-3.3-70B-Instruct_25418']" }
0.561458
Filter_9315
I
[ "function", "another_function" ]
2
[ [ "another_function", "function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ae05fdc5fb3c9a55ec3cb1859b676ec351f51988
6893e164aa2895d7ba95c1c2996651038aae6924
v1.0
instruct
Filter
Filter_9326_I
Here is a code to generate a maze: ```python import turtle def draw_square(t, length, color): t.fillcolor(color) t.begin_fill() for _ in range(4): t.forward(length) t.right(90) t.end_fill() def draw_maze(t, maze): for y, row in enumerate(maze): for x, cell in enumerate(row)...
import turtle import random def draw_square(t, length, color): t.fillcolor(color) t.begin_fill() for _ in range(4): t.forward(length) t.right(90) t.end_fill() def draw_maze(t, maze): for y, row in enumerate(maze): for x, cell in enumerate(row): if cell == 1: ...
from solution import generate_maze def test_generate_maze_size(): maze = generate_maze(11, 11) assert len(maze) == 11 assert all(len(row) == 11 for row in maze) def test_generate_maze_walls(): maze = generate_maze(15, 15) # Check outer walls assert all(cell == 1 for cell in maze[0]) assert...
[ { "docstring": null, "function_declaration": "def draw_square(t, length, color):", "function_name": "draw_square", "parameter_list": "(t, length, color)" }, { "docstring": null, "function_declaration": "def draw_maze(t, maze):", "function_name": "draw_maze", "parameter_list": "(t...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\nimport random\n\ndef draw_square(t, length, color):\n t.fillcolor(color)\n t.begin_fill()\n for _ in range(4):\n t.forward(length)\n t.right(90)\n t.en...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009326", "row_id": 9326, "seed_ids": "['Llama-3.3-70B-Instruct_25442']" }
0.657933
Filter_9326
I
[ "draw_square", "draw_maze", "generate_maze", "main" ]
4
[ [ "draw_maze", "draw_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b192107da3733409f49bcd6989d848255eaeda3d
2e84dc3a9b6e1b96554a498f3a82f6f82a4198c4
v1.0
instruct
Filter
Filter_9327_I
Here are some functions for a population growth model that uses the Lotka-Volterra equations to simulate the growth of two interacting species, such as rabbits and foxes. The functions you have are: ``` def get_rabbit_growth_rate(rabbit_population, fox_population, rabbit_growth_rate, rabbit_death_rate): return rabb...
def get_rabbit_growth_rate(rabbit_population, fox_population, rabbit_growth_rate, rabbit_death_rate): return rabbit_growth_rate * rabbit_population - rabbit_death_rate * rabbit_population * fox_population def get_fox_growth_rate(rabbit_population, fox_population, fox_birth_rate, fox_death_rate): return fox_bir...
from solution import get_rabbit_growth_rate, get_fox_growth_rate, calculate_new_populations def test_get_rabbit_growth_rate(): result = get_rabbit_growth_rate(500, 30, 0.1, 0.01) expected = 500 * 0.1 - 500 * 0.01 * 30 assert result == expected def test_get_fox_growth_rate(): result = get_fox_growth_ra...
[ { "docstring": null, "function_declaration": "def get_rabbit_growth_rate(rabbit_population, fox_population, rabbit_growth_rate, rabbit_death_rate):", "function_name": "get_rabbit_growth_rate", "parameter_list": "(rabbit_population, fox_population, rabbit_growth_rate, rabbit_death_rate)" }, { ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_rabbit_growth_rate(rabbit_population, fox_population, rabbit_growth_rate, rabbit_death_rate):\n return rabbit_growth_rate * rabbit_population - rabbit_death_rate * rabbit_population...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009327", "row_id": 9327, "seed_ids": "['Llama-3.3-70B-Instruct_25444']" }
0.389078
Filter_9327
I
[ "get_rabbit_growth_rate", "get_fox_growth_rate", "calculate_new_populations" ]
3
[ [ "calculate_new_populations", "get_fox_growth_rate" ], [ "calculate_new_populations", "get_rabbit_growth_rate" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3b25e7ad3805cfb4b57652948f3e7390ed1fa871
c554f34d714bf683e4f8dc91192b2e5a0e35f349
v1.0
instruct
Filter
Filter_9328_I
I have a dataset which contains a large number of cells in the format of: [(x1, y1), (x2, y2), (x3, y3), ..., (xn, yn)]. Each cell represents a point in 2D space. I want to find a rectangle that best encloses all these points. Can you guide me through the process of implementing the solution in Python? Also, I ne...
from functools import cmp_to_key import math def find_lowest_point(points): """ Finds the point with the lowest y-coordinate. In case of a tie, the point with the lowest x-coordinate is chosen. """ return min(points, key=lambda p: (p[1], p[0])) def polar_angle(p0, p1): """ Calculates the ...
from solution import find_bounding_rectangle, find_lowest_point, polar_angle, distance, orientation, graham_scan, bounding_rectangle def test_find_lowest_point(): assert find_lowest_point([(1, 3), (3, 4), (2, 2), (5, 1)]) == (5, 1) assert find_lowest_point([(1, 2), (3, 4), (2, 2), (5, 2)]) == (1, 2) def test_...
[ { "docstring": "Finds the point with the lowest y-coordinate. \nIn case of a tie, the point with the lowest x-coordinate is chosen.", "function_declaration": "def find_lowest_point(points):", "function_name": "find_lowest_point", "parameter_list": "(points)" }, { "docstring": "Calculates the...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import atan2\n\ndef orientation(p, q, r):\n \"\"\"Return the orientation of the triplet (p, q, r).\n 0 --> p, q and r are collinear\n 1 --> Clockwise\n 2 --> Counterclock...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009328", "row_id": 9328, "seed_ids": "['Llama-3.3-70B-Instruct_25445']" }
0.538963
Filter_9328
I
[ "find_lowest_point", "polar_angle", "distance", "orientation", "graham_scan", "bounding_rectangle", "find_bounding_rectangle" ]
7
[ [ "find_bounding_rectangle", "bounding_rectangle" ], [ "find_bounding_rectangle", "graham_scan" ], [ "graham_scan", "distance" ], [ "graham_scan", "find_lowest_point" ], [ "graham_scan", "orientation" ], [ "graham_scan", "polar_angle" ] ]
6
[]
false
[]
false
pytest
true
[]
true
580c41e50781575e53be1e375f591f3428b887ca
e9350575fb27c5184a887a57c7b2e50a77581a0f
v1.0
instruct
Filter
Filter_9336_I
### Introduction You are a security consultant hired to improve the security of an office building. As part of your assessment, you need to evaluate the existing security measures and identify potential vulnerabilities. You have been provided with a set of architectural plans for the building, which include the layout ...
from collections import defaultdict def dfs_graph_paths(graph, start, path, paths): """Helper function to perform DFS and find all paths from start node.""" path = path + [start] if not graph[start]: # If there's no connection from 'start' node paths.append(path) else: for node in grap...
import pytest from solution import find_all_paths_from_entrance, dfs_graph_paths def test_dfs_graph_paths(): graph = { 'E': ['R1', 'R2'], 'R1': ['R3', 'R4'], 'R2': ['R4', 'R5'], 'R3': ['R6'], 'R4': ['R7'], 'R5': [], 'R6': [], 'R7': [] } paths ...
[ { "docstring": "Helper function to perform DFS and find all paths from start node.", "function_declaration": "def dfs_graph_paths(graph, start, path, paths):", "function_name": "dfs_graph_paths", "parameter_list": "(graph, start, path, paths)" }, { "docstring": "Find all possible paths from ...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict\n\ndef dfs_graph_paths(graph, start, path, paths):\n \"\"\"Helper function to perform DFS and find all paths from start node.\"\"\"\n path = path + [s...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009336", "row_id": 9336, "seed_ids": "['Llama-3.3-70B-Instruct_25461']" }
0.56667
Filter_9336
I
[ "dfs_graph_paths", "find_all_paths_from_entrance", "print_all_paths" ]
3
[ [ "find_all_paths_from_entrance", "dfs_graph_paths" ] ]
1
[]
false
[]
false
pytest
true
[]
true
94cb38a8a13323f9cb29075ccf078becf4f3d0d3
136e2bab9cd533f81e765d4b84350bf094ccdaf6
v1.0
instruct
Filter
Filter_9337_I
I have an algorithm that I'm working on which I'll describe below. I want to come up with the best possible implementation of it in Python, following best practices and professional guidelines for code quality, readability, and performance. Here's the algorithm: 1. Read a text file and read its content. 2. Split the ...
import re from collections import defaultdict def read_file(filename): """ Reads a text file and returns its content as a string. """ with open(filename, 'r') as file: content = file.read() return content def split_into_sentences(content): """ Splits the content into sentences. Sen...
import os import tempfile from solution import read_file, split_into_sentences, split_into_words, word_frequency, sort_by_frequency, write_to_file, process_text_file def test_read_file(): with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.write(b"Hello world. This is a test.") tmp.seek(0) ...
[ { "docstring": "Reads a text file and returns its content as a string.", "function_declaration": "def read_file(filename):", "function_name": "read_file", "parameter_list": "(filename)" }, { "docstring": "Splits the content into sentences. Sentences are assumed to end with '.', '!', or '?'."...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom collections import defaultdict\n\ndef read_file(filename):\n \"\"\"\n Reads the content from a file.\n \"\"\"\n with open(filename, 'r') as file:\n return fi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009337", "row_id": 9337, "seed_ids": "['Llama-3.3-70B-Instruct_25471']" }
0.633261
Filter_9337
I
[ "read_file", "split_into_sentences", "split_into_words", "word_frequency", "sort_by_frequency", "write_to_file", "process_text_file" ]
7
[ [ "process_text_file", "read_file" ], [ "process_text_file", "sort_by_frequency" ], [ "process_text_file", "split_into_sentences" ], [ "process_text_file", "word_frequency" ], [ "process_text_file", "write_to_file" ], [ "word_frequency", "split_int...
6
[]
false
[]
false
pytest
true
[]
true
d3c18da66c2caf24f97c937c951455fc272ded35
62af4320e4c5f0687f93f6c333c510f8c0e73fb8
v1.0
instruct
Filter
Filter_9360_I
### Overview Create a simple, single-player dice game where the player rolls two six-sided dice. The player wins if the total of the two dice is 7 or 11. The game continues until the player decides to quit. ### Requirements * The game must be able to roll two six-sided dice. * The game must determine if the playe...
import random def roll_dice(): """Rolls two six-sided dice and returns the total.""" dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) return dice1, dice2 def check_win(dice_total): """Checks if the player has won based on the dice total.""" return dice_total in [7, 11] def play_game(...
import random from solution import roll_dice, check_win def test_roll_dice(): random.seed(0) # Setting seed for reproducibility dice1, dice2 = roll_dice() assert 1 <= dice1 <= 6 assert 1 <= dice2 <= 6 def test_check_win(): assert check_win(7) == True assert check_win(11) == True assert che...
[ { "docstring": "Rolls two six-sided dice and returns the total.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Checks if the player has won based on the dice total.", "function_declaration": "def check_win(dice_total)...
[ 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 roll_dice():\n \"\"\"Rolls two six-sided dice and returns the result as a tuple.\"\"\"\n dice1 = random.randint(1, 6)\n dice2 = random.randint(1, 6)\n return d...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009360", "row_id": 9360, "seed_ids": "['Llama-3.3-70B-Instruct_25514']" }
0.529763
Filter_9360
I
[ "roll_dice", "check_win", "play_game" ]
3
[ [ "play_game", "check_win" ], [ "play_game", "roll_dice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4e07bdbffc89ff1f455a67672d94c23ab86b8bc3
d4a7bae69e192b1ff688310ffdccf45068abf915
v1.0
instruct
Filter
Filter_9381_I
I've been tasked with creating an alarm system that uses Phillips Hue lights to act as a siren. To start, I can control the Philips Hue bridge via HTTP requests and I have a list of light names and their corresponding IDs. Here's a basic example of a GET request to retrieve information about a light: ``` GET /api/<u...
import aiohttp import asyncio async def set_light_state(session, ip_address, username, light_id, state): url = f'http://{ip_address}/api/{username}/lights/{light_id}/state' async with session.put(url, json=state) as response: return await response.json() async def flash_light(light_id, interval, num_f...
import pytest from unittest.mock import patch, AsyncMock from solution import flash_light @pytest.mark.asyncio @patch('solution.aiohttp.ClientSession') async def test_flash_light(mock_session): mock_response = AsyncMock() mock_response.json.return_value = {} mock_session.return_value.__aenter__.return_valu...
[ { "docstring": null, "function_declaration": "def flash(light_id, interval, num_flashes, ip_address, username):", "function_name": "flash", "parameter_list": "(light_id, interval, num_flashes, ip_address, username)" } ]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\n\nasync def turn_light_on(session, ip_address, username, light_id):\n url = f\"http://{ip_address}/api/{username}/lights/{light_id}/state\"\n async with s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009381", "row_id": 9381, "seed_ids": "['Llama-3.3-70B-Instruct_25559']" }
0.486757
Filter_9381
I
[ "set_light_state", "flash_light", "flash" ]
3
[ [ "flash", "flash_light" ], [ "flash_light", "set_light_state" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
8343a54150f6ebb86e023fe1971190d1e85adcd7
d11a63fda76c72646a6c68ad6fee7baea6f38289
v1.0
instruct
Filter
Filter_9455_I
Can you write a code for a simple game that lets a player choose to either play a game of Tic Tac Toe or Rock Paper Scissors?
def tic_tac_toe(): """ Function to simulate a game of Tic Tac Toe. (Simplified version: No actual gameplay, just a placeholder) """ return "Starting Tic Tac Toe game..." def rock_paper_scissors(): """ Function to simulate a game of Rock Paper Scissors. (Simplified version: No actual gam...
from solution import tic_tac_toe, rock_paper_scissors, choose_game import pytest def test_tic_tac_toe(): assert tic_tac_toe() == "Starting Tic Tac Toe game..." def test_rock_paper_scissors(): assert rock_paper_scissors() == "Starting Rock Paper Scissors game..." def test_choose_game_tic_tac_toe(monkeypatch):...
[ { "docstring": "Function to simulate a game of Tic Tac Toe.\n(Simplified version: No actual gameplay, just a placeholder)", "function_declaration": "def tic_tac_toe():", "function_name": "tic_tac_toe", "parameter_list": "()" }, { "docstring": "Function to simulate a game of Rock Paper Scisso...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def tic_tac_toe():\n \"\"\"\n Function to simulate a game of Tic Tac Toe.\n (Simplified version: No actual gameplay, just a placeholder)\n \"\"\"\n return \"Starting Tic Tac Toe...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009455", "row_id": 9455, "seed_ids": "['Llama-3.3-70B-Instruct_25732']" }
0.421342
Filter_9455
I
[ "tic_tac_toe", "rock_paper_scissors", "choose_game" ]
3
[ [ "choose_game", "rock_paper_scissors" ], [ "choose_game", "tic_tac_toe" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7ce23114da6b4c3aede6bdf8f0bb2eb52580d79f
830cf21d1389053082352b4924357f602ef05341
v1.0
instruct
Filter
Filter_9471_I
### Making a Game of Hangman Hangman is a guessing game where one player thinks of a word, and the other player tries to guess the word by suggesting letters. For each incorrect guess, a part of a hanging figure is drawn. The game continues until the word is guessed or the hanging figure is complete and the player who ...
import random HANGMAN_PICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O ...
from solution import getRandomWord, displayBoard def test_getRandomWord(): wordList = ['cat', 'dog', 'fish'] word = getRandomWord(wordList) assert word in wordList, "The word must be from the provided wordList." def test_displayBoard_initial(): HANGMAN_PICS = ['0'] missedLetters = '' correctLe...
[ { "docstring": null, "function_declaration": "def getRandomWord(wordList):", "function_name": "getRandomWord", "parameter_list": "(wordList)" }, { "docstring": null, "function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):", "function_name":...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009471", "row_id": 9471, "seed_ids": "['Llama-3.3-70B-Instruct_25774']" }
0.449341
Filter_9471
I
[ "getRandomWord", "displayBoard", "getGuess", "playAgain", "hangman" ]
5
[ [ "hangman", "displayBoard" ], [ "hangman", "getGuess" ], [ "hangman", "getRandomWord" ], [ "hangman", "playAgain" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ec0e03f2ba5950ea37d16535134b1f1fb10e4c39
4fd64e0399833d7ccaf3a5422d746b8431bf3d4a
v1.0
instruct
Filter
Filter_9510_I
Here is a problem that I have been unable to solve. I am not even sure where to begin. I am given 10 random points and I need to determine if any two of them are within a certain distance of each other. Here is an example of what I have tried so far: ```python import random def distance(p1, p2): # calculate eu...
import random from itertools import product def distance(p1, p2): """ Calculate euclidean distance between two points. """ return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5 def generate_random_points(n): """ Generate n random points in a 100x100 grid. """ points = [(random.randin...
from solution import generate_random_points, check_proximity def test_no_proximity(): points = [(0, 0), (100, 100)] assert not check_proximity(points, 10) def test_some_proximity(): points = [(0, 0), (8, 6), (15, 5), (25, 15)] assert check_proximity(points, 10) def test_all_proximity(): points = ...
[ { "docstring": "Calculate euclidean distance between two points.", "function_declaration": "def distance(p1, p2):", "function_name": "distance", "parameter_list": "(p1, p2)" }, { "docstring": "Generate n random points in a 100x100 grid.", "function_declaration": "def generate_random_poin...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def distance(p1, p2):\n # calculate euclidean distance between two points\n return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5\n\ndef generate_random_points(n):\n # generate n ra...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009510", "row_id": 9510, "seed_ids": "['Llama-3.3-70B-Instruct_25861']" }
0.593854
Filter_9510
I
[ "distance", "generate_random_points", "check_proximity" ]
3
[ [ "check_proximity", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e9e3b770c7aba5a273eaa2e2876ed5061ebf661
bcf2b3d7cd799ac3ee5bf29e371dc82fa1e922b2
v1.0
instruct
Filter
Filter_9514_I
### Task 1: Generate a Python function `validate_and_send_email` to validate an email address and then send a welcome email if it's valid.
import re def validate_email(email): """ Validate email using a regular expression """ pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' return re.match(pattern, email) is not None def send_email(email): """ Mock send email function """ print(f"Sending welcome email to ...
from solution import validate_and_send_email, validate_email def test_validate_email(): assert validate_email("test@example.com") == True assert validate_email("invalid-email") == False assert validate_email("another.test@domain.co") == True assert validate_email("wrong@domain") == False def test_vali...
[ { "docstring": "Validate email using a regular expression", "function_declaration": "def validate_email(email):", "function_name": "validate_email", "parameter_list": "(email)" }, { "docstring": "Mock send email function", "function_declaration": "def send_email(email):", "function_n...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef validate_and_send_email(email):\n \"\"\"\n Validate the email address and send a welcome email if it's valid.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009514", "row_id": 9514, "seed_ids": "['Llama-3.3-70B-Instruct_25873']" }
0.619314
Filter_9514
I
[ "validate_email", "send_email", "validate_and_send_email" ]
3
[ [ "validate_and_send_email", "send_email" ], [ "validate_and_send_email", "validate_email" ] ]
2
[]
false
[]
false
pytest
true
[]
true
11ef49c3bbaa0fb8dc7e06b73c325307d656fc8d
79ffea7c2483836eb73b1e91340a168e5cbe13c7
v1.0
instruct
Filter
Filter_9519_I
I have a set of records in a text file, one record per line. Each record consists of a date in ISO 8601 format (e.g., 2022-01-01T12:00:00Z), followed by a space, followed by a name, followed by a space, followed by a value. An example is: 2022-01-01T12:00:00Z John 123 I've written a Python script that reads this fil...
import re def parse_record(record): """Parse a record into its constituent parts.""" match = re.match(r'(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z) (\w+) (\d+)', record) if match: return { 'date': match.group(1), 'name': match.group(2), 'value': int(match.group(3)) ...
import pytest from solution import parse_record, read_records def test_parse_record_valid(): record = "2022-01-01T12:00:00Z John 123" expected = {'date': '2022-01-01T12:00:00Z', 'name': 'John', 'value': 123} assert parse_record(record) == expected def test_parse_record_invalid(): invalid_record = "inv...
[ { "docstring": "Parse a record into its constituent parts.", "function_declaration": "def parse_record(record):", "function_name": "parse_record", "parameter_list": "(record)" }, { "docstring": "Read records from a file and parse them.", "function_declaration": "def read_records(filename...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef parse_record(record):\n \"\"\"Parse a record into its constituent parts.\"\"\"\n match = re.match(r'(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z) (\\w+) (\\d+)', record)\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009519", "row_id": 9519, "seed_ids": "['Llama-3.3-70B-Instruct_25891']" }
0.613918
Filter_9519
I
[ "parse_record", "read_records" ]
2
[ [ "read_records", "parse_record" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b9dab98775ffad2b6d138feb613a1234d5c6b3c2
fd617ccb45f6939750e5941bf047afdcd9de53b6
v1.0
instruct
Filter
Filter_9525_I
Here is a Python script that generates a random number and asks the user to guess it. If the user guesses lower than the number, the script should tell the user to guess higher. If the user guesses higher than the number, the script should tell the user to guess lower. The script should keep running until the user gues...
import random def guess_the_number(): number = random.randint(1, 100) user_guess = None while True: user_guess = int(input("Guess the number: ")) if user_guess == number: print("You're right! The number was {}.".format(number)) break elif user_guess < number...
import pytest from unittest.mock import patch from solution import play_game, guess_the_number def test_guess_the_number_low(): with patch('builtins.input', side_effect=['50', '75', '88', '90']): with patch('random.randint', return_value=90): with patch('builtins.print') as mock_print: ...
[ { "docstring": null, "function_declaration": "def guess_the_number():", "function_name": "guess_the_number", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def play_game():", "function_name": "play_game", "parameter_list": "()" } ]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef guess_number_game():\n \"\"\"\n A function to play the guessing number game with option to play again.\n \"\"\"\n while True:\n number = random.randint(...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009525", "row_id": 9525, "seed_ids": "['Llama-3.3-70B-Instruct_25906']" }
0.440286
Filter_9525
I
[ "guess_the_number", "play_game" ]
2
[ [ "play_game", "guess_the_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ca5f87f340b7a92ec9c7b2fadfba45ffa99a1d7f
a4c6fc2f1d7bd36fe49094b591e8be67fcad65c9
v1.0
instruct
Filter
Filter_9531_I
Create a simple rock, paper, scissors game in Python. ```python def get_computer_choice(): import random choices = ["rock", "paper", "scissors"] return random.choice(choices) def get_user_choice(): user_choice = input("Enter a choice (rock, paper, scissors): ") return user_choice def game(): ...
def get_computer_choice(): import random choices = ["rock", "paper", "scissors"] return random.choice(choices) def get_user_choice(): while True: user_choice = input("Enter a choice (rock, paper, scissors): ").lower() if user_choice in ["rock", "paper", "scissors"]: return u...
from solution import get_computer_choice, get_user_choice, game def test_get_computer_choice(): choices = ["rock", "paper", "scissors"] assert get_computer_choice() in choices def test_game_tie(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: "rock") assert game() == "Both players selecte...
[ { "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": "()" }, { ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_computer_choice():\n import random\n choices = [\"rock\", \"paper\", \"scissors\"]\n return random.choice(choices)\n\ndef get_user_choice():\n while True:\n user_cho...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009531", "row_id": 9531, "seed_ids": "['Llama-3.3-70B-Instruct_25927']" }
0.452379
Filter_9531
I
[ "get_computer_choice", "get_user_choice", "game", "main" ]
4
[ [ "game", "get_computer_choice" ], [ "game", "get_user_choice" ] ]
2
[]
false
[]
false
pytest
true
[]
true
53487067fcdd6fda08bb05a242559dcc8688453f
413b58bbd954aae883eab696774a62e352ebe63b
v1.0
instruct
Filter
Filter_9533_I
I am trying to understand how to use an encoder-decoder architecture for sequence-to-sequence tasks. Can you provide a general overview? The main issue I am trying to solve is understanding how to incorporate user input into the network such that it generates relevant results. Sequence-to-sequence models have an enc...
import torch import torch.nn as nn import torch.optim as optim # Sample Data input_sequences = [[1, 2, 3], [2, 1, 4], [1, 3, 2], [4, 2, 1]] output_sequences = ["one two three", "two one four", "one three two", "four two one"] # Vocabulary vocab = ["<pad>", "<sos>", "<eos>", "one", "two", "three", "four", "five", "six...
import pytest from solution import train, predict, prepare_data, word2idx, idx2word, encoder, decoder, Seq2Seq import torch import torch.nn as nn import torch.optim as optim def test_sequence_to_indices(): assert sequence_to_indices("one two three", word2idx) == [3, 4, 5] def test_indices_to_sequence(): asser...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Define the encoder\nclass Encoder(nn.Module):\n def __init__(self, input_dim, emb_dim, hid_dim):\n super().__ini...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009533", "row_id": 9533, "seed_ids": "['Llama-3.3-70B-Instruct_25932']" }
0.372627
Filter_9533
I
[ "sequence_to_indices", "indices_to_sequence", "prepare_data", "train", "predict" ]
5
[ [ "predict", "indices_to_sequence" ], [ "prepare_data", "sequence_to_indices" ] ]
2
[]
false
[ "Encoder", "Decoder", "Seq2Seq" ]
true
pytest
true
[ "torch" ]
false
2fecf893f2b0998ebd16770ca948c13cf175f6a5
1c864444813844469bb8334fade966efa00e11a1
v1.0
instruct
Filter
Filter_9544_I
Here is the code I have written so far: ```python import random def roll_dice(): """Simulates the roll of a six-sided dice.""" return random.randint(1, 6) def calculate_total_rolls(rolls): """Calculates the total of all the rolls in a list.""" return sum(rolls) def get_rolls(num_rolls): """Simula...
import random def roll_dice(num_sides): """ Simulates the roll of a dice with `num_sides` sides. """ return random.randint(1, num_sides) def calculate_total_rolls(rolls): """ Calculates the total of all the rolls in a list. """ return sum(rolls) def get_rolls(num_rolls, num_sides): ...
from solution import roll_dice, calculate_total_rolls, get_rolls def test_roll_dice(): # Test that roll_dice returns a value between 1 and num_sides (inclusive) num_sides = 10 roll = roll_dice(num_sides) assert 1 <= roll <= num_sides def test_calculate_total_rolls(): # Test that calculate_total_ro...
[ { "docstring": "Simulates the roll of a dice with `num_sides` sides.", "function_declaration": "def roll_dice(num_sides):", "function_name": "roll_dice", "parameter_list": "(num_sides)" }, { "docstring": "Calculates the total of all the rolls in a list.", "function_declaration": "def cal...
[ 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 roll_dice(sides=6):\n \"\"\"\n Simulates the roll of a dice with a given number of sides.\n :param sides: Number of sides on the dice, defaults to 6.\n :return...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009544", "row_id": 9544, "seed_ids": "['Llama-3.3-70B-Instruct_25965']" }
0.61109
Filter_9544
I
[ "roll_dice", "calculate_total_rolls", "get_rolls", "main" ]
4
[ [ "get_rolls", "roll_dice" ] ]
1
[]
false
[]
false
pytest
true
[]
true
672d6c6b742a608ade9fe454d9fb47e9b92fd687
6049001a7eba623263236c38db2b5d163adc3a2b
v1.0
instruct
Filter
Filter_9588_I
### Processing Encryption #### Overview The goal of this exercise is to create an encryption program that will take user input, encrypt it, and then decrypt the encrypted text. The encryption method is a simple substitution cipher that replaces each letter with the letter three positions ahead in the alphabet. #### Spe...
def encrypt(text, shift): """ Encrypts or decrypts the input text using a substitution cipher with the given shift. Handles only alphabetic characters and preserves the case. Non-alphabetic characters remain unchanged. """ result = "" for char in text: if char.isalpha(): ...
import pytest from solution import encrypt, verify_decryption def test_encrypt_with_shift_3(): assert encrypt("abc", 3) == "def" assert encrypt("ABC", 3) == "DEF" assert encrypt("xyz", 3) == "abc" assert encrypt("XYZ", 3) == "ABC" assert encrypt("Hello, World!", 3) == "Khoor, Zruog!" def test_decr...
[ { "docstring": "Encrypts or decrypts the input text using a substitution cipher \nwith the given shift. Handles only alphabetic characters and \npreserves the case. Non-alphabetic characters remain unchanged.", "function_declaration": "def encrypt(text, shift):", "function_name": "encrypt", "paramet...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def encrypt(text, shift):\n \"\"\"\n Encrypts the input text using a simple substitution cipher that shifts each letter by 'shift' positions.\n \"\"\"\n result = \"\"\n for char...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009588", "row_id": 9588, "seed_ids": "['Llama-3.3-70B-Instruct_26055']" }
0.722425
Filter_9588
I
[ "encrypt", "verify_decryption" ]
2
[ [ "verify_decryption", "encrypt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
57d83bdf19b2ef12a40489d852bfb5aae58fa2e6
d672eb48fc7b7fa264941e2fc7c008009ef4d344