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_63776_I
Can you provide a Python function to calculate the ground state energy of a one-dimensional Ising model with nearest neighbor interactions using the Metropolis-Hastings algorithm?
import numpy as np def ising_energy(spin_config, J=1): """ Compute the energy of a given spin configuration in a 1D Ising model. Args: spin_config (list): A list of spins (+1 or -1). J (float): Coupling constant (default is 1). Returns: float: The energy of the given spin configur...
from solution import ising_energy, metropolis_ising_1d def test_ising_energy_all_up(): # All spins up (ground state) assert ising_energy([1, 1, 1, 1]) == -4.0 assert ising_energy([1, 1, 1, 1, 1]) == -5.0 def test_ising_energy_all_down(): # All spins down (ground state) assert ising_energy([-1, -1,...
[ { "docstring": "Compute the energy of a given spin configuration in a 1D Ising model.\n\nArgs:\nspin_config (list): A list of spins (+1 or -1).\nJ (float): Coupling constant (default is 1).\n\nReturns:\nfloat: The energy of the given spin configuration.", "function_declaration": "def ising_energy(spin_confi...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef initialize_spin_chain(length):\n \"\"\"\n Initialize the spin chain with random spins of +1 or -1.\n \"\"\"\n return np.random.choice([-1, 1], size=length...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00063776", "row_id": 63776, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129055']" }
0.308367
Filter_63776
I
[ "ising_energy", "metropolis_ising_1d" ]
2
[ [ "metropolis_ising_1d", "ising_energy" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
40081057163795c678c1b412bbb49ab467819359
37368af7e844b2c8b7072e14b088b65453c341f0
v1.0
instruct
Filter
Filter_63823_I
Write a Python function to calculate the factorial of a number using recursion and another function that uses iteration. Compare the execution time of both methods for calculating the factorial of numbers from 0 to 20.
import time def factorial_recursive(n): """ Returns the factorial of n using recursion. """ if n == 0 or n == 1: return 1 return n * factorial_recursive(n - 1) def factorial_iterative(n): """ Returns the factorial of n using iteration. """ result = 1 for i in range(2, n...
from solution import factorial_recursive, factorial_iterative, compare_execution_time import pytest def test_factorial_recursive(): assert factorial_recursive(0) == 1 assert factorial_recursive(1) == 1 assert factorial_recursive(5) == 120 assert factorial_recursive(10) == 3628800 assert factorial_r...
[ { "docstring": "Returns the factorial of n using recursion.", "function_declaration": "def factorial_recursive(n):", "function_name": "factorial_recursive", "parameter_list": "(n)" }, { "docstring": "Returns the factorial of n using iteration.", "function_declaration": "def factorial_ite...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef factorial_recursive(n):\n \"\"\"\n Returns the factorial of n using recursion.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n else:\n return n * f...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00063823", "row_id": 63823, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129141']" }
0.575073
Filter_63823
I
[ "factorial_recursive", "factorial_iterative", "compare_execution_time" ]
3
[ [ "compare_execution_time", "factorial_iterative" ], [ "compare_execution_time", "factorial_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b9a00a6e2dfc32093ca00d0b16247c4552d65138
236a3da0c73f478d5138bd3f7611e7e1404cb873
v1.0
instruct
Filter
Filter_63852_I
I need a Python script that can filter and display the names of files in a directory based on a specific keyword. The script should also display the file size in a human-readable format. For example, if I search for the keyword "report" in the directory "/home/user/documents", it should list all files containing the ke...
import os def human_readable_size(size, decimal_places=1): """ Convert a file size to a human-readable format. """ for unit in ['B', 'KB', 'MB', 'GB', 'TB']: if size < 1024.0: return f"{size:.{decimal_places}f} {unit}" size /= 1024.0 def filter_files_by_keyword(directory, k...
from solution import human_readable_size, filter_files_by_keyword import os import pytest def test_human_readable_size(): assert human_readable_size(1023) == "1023.0 B" assert human_readable_size(1024) == "1.0 KB" assert human_readable_size(1048576) == "1.0 MB" assert human_readable_size(1073741824) ==...
[ { "docstring": "Convert a file size to a human-readable format.", "function_declaration": "def human_readable_size(size, decimal_places=1):", "function_name": "human_readable_size", "parameter_list": "(size, decimal_places=1)" }, { "docstring": "List files in the given directory that contain...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef human_readable_size(size, decimal_places=1):\n \"\"\"\n Convert a file size to a human-readable format.\n \"\"\"\n for unit in ['B', 'KB', 'MB', 'GB', 'TB']:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00063852", "row_id": 63852, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129196']" }
0.586613
Filter_63852
I
[ "human_readable_size", "filter_files_by_keyword" ]
2
[ [ "filter_files_by_keyword", "human_readable_size" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4419525fdb9a615f8efa0885ca16c08cba7a9d6d
a9d5c8adbb7e78ce8f3c6d10f136d3e5d08969bd
v1.0
instruct
Filter
Filter_63869_I
How can I create a Python function that calculates the sum of all prime numbers up to a given number `n`?
def is_prime(num): """Returns True if the number is prime, otherwise False.""" if num <= 1: return False if num == 2: return True if num % 2 == 0: return False p = 3 while p * p <= num: if num % p == 0: return False p += 2 return True def ...
from solution import is_prime, sum_of_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(9) == False assert is_prime(11) == True assert is_prime(1) == False assert is_prime(17) == True ...
[ { "docstring": "Returns True if the number is prime, otherwise False.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns the sum of all prime numbers up to and including n.", "function_declaration": "def sum_o...
[ 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 num is a prime number.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00063869", "row_id": 63869, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129227']" }
0.725999
Filter_63869
I
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
74bc9792269a7052db44532202e9a52b87f59ed7
c1d0e9427d88aa82d565c7c8dee1307a9d2ed652
v1.0
instruct
Filter
Filter_63880_I
How can I modify the `my_function` in Python to include an additional feature that checks if a number is a palindrome?
def is_palindrome(n): """ Returns True if n is a palindrome, False otherwise. """ str_n = str(n) return str_n == str_n[::-1] def my_function(n): """ Returns a tuple where the first element is the original number and the second element is a boolean indicating if the number is a palindrom...
from solution import is_palindrome, my_function def test_is_palindrome(): assert is_palindrome(121) == True assert is_palindrome(123) == False assert is_palindrome(1221) == True assert is_palindrome(12321) == True assert is_palindrome(123421) == False def test_my_function(): assert my_function...
[ { "docstring": "Returns True if n is a palindrome, False otherwise.", "function_declaration": "def is_palindrome(n):", "function_name": "is_palindrome", "parameter_list": "(n)" }, { "docstring": "Returns a tuple where the first element is the original number\nand the second element is a bool...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def my_function(number):\n \"\"\"\n Checks if the given number is a palindrome.\n\n Args:\n number (int): The number to check.\n\n Returns:\n bool: True if the number is a pa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00063880", "row_id": 63880, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129255']" }
0.638995
Filter_63880
I
[ "is_palindrome", "my_function" ]
2
[ [ "my_function", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a9b0c992ac10076cf90f578c6c8949c4eb6cf33
ad6a6ee62a0cf2b747183a66fc38249efa94a14b
v1.0
instruct
Filter
Filter_63912_I
Can you provide a Python script that implements the ID3 algorithm for constructing a decision tree? Certainly! Below is a simple implementation of the ID3 algorithm in Python. This script constructs a decision tree from a dataset written in a CSV file. For simplicity, the dataset is assumed to be categorical, and the t...
import pandas as pd import numpy as np class DecisionNode: def __init__(self, attribute=None, branches=None, label=None): self.attribute = attribute # Attribute tested by the node self.branches = branches if branches else {} # Children of the node self.label = label # Label if node is a ...
import pytest from solution import DecisionNode, entropy, information_gain, id3, predict, fit def test_entropy(): y_single_class = np.array([1, 1, 1, 1]) y_two_classes = np.array([0, 1, 0, 1]) assert entropy(y_single_class) == 0 assert entropy(y_two_classes) != 0 def test_information_gain(): X = p...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\n\nclass DecisionNode:\n def __init__(self, attribute=None, branches=None, label=None):\n self.attribute = attribute # Attribute tested by th...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00063912", "row_id": 63912, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129309']" }
0.368875
Filter_63912
I
[ "entropy", "information_gain", "id3", "predict", "fit" ]
5
[ [ "fit", "id3" ], [ "id3", "information_gain" ], [ "information_gain", "entropy" ] ]
3
[]
false
[ "DecisionNode" ]
true
pytest
true
[ "numpy", "pandas" ]
false
9000262762a84e38b765752db83abc80c94de809
e346348bc7a809c08b82d59a623f0ac8cfc3b2b1
v1.0
instruct
Filter
Filter_63966_I
How can I create a lazy iterator in Python that generates an infinite sequence of prime numbers?
from itertools import islice 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 ...
from solution import prime_generator import pytest def test_first_prime(): primes = prime_generator() assert next(primes) == 2 def test_second_prime(): primes = prime_generator() next(primes) # 2 assert next(primes) == 3 def test_first_five_primes(): primes = prime_generator() first_five ...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "A lazy generator for an infinite sequence of prime numbers.", "function_declaration": "def prime_generator():", "function_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00063966", "row_id": 63966, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129424']" }
0.594616
Filter_63966
I
[ "is_prime", "prime_generator" ]
2
[ [ "prime_generator", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be353753dbe9dbfa7e7f6cccf48643af5915366f
b24ddc8a00b69a226029175ca0c7d2bc31c50830
v1.0
instruct
Filter
Filter_63969_I
Hello Qwen, could you help me with a Python script to simulate a simple game of dice? In this game, two players roll a six-sided die, and the player with the higher number wins. If both players roll the same number, it's a tie. The game should allow for multiple rounds, and the player who wins the most rounds is the ov...
import random def roll_die(): """ Simulates rolling a six-sided die and returns the result. """ return random.randint(1, 6) def play_round(): """ Simulates a round of dice for two players and returns the winner. Returns 'Player 1', 'Player 2', or 'Tie'. """ player1_roll = roll_die(...
from solution import roll_die, play_round, play_game def test_roll_die(): for _ in range(100): roll = roll_die() assert roll >= 1 and roll <= 6 def test_play_round(): results = {'Player 1': 0, 'Player 2': 0, 'Tie': 0} for _ in range(100): result = play_round() assert result...
[ { "docstring": "Simulates rolling a six-sided die and returns the result.", "function_declaration": "def roll_die():", "function_name": "roll_die", "parameter_list": "()" }, { "docstring": "Simulates a round of dice for two players and returns the winner.\nReturns 'Player 1', 'Player 2', or ...
[ 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 roll_dice():\n \"\"\"\n Simulates rolling a six-sided die.\n Returns:\n int: A random integer between 1 and 6 (inclusive).\n \"\"\"\n return random.r...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00063969", "row_id": 63969, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129429']" }
0.499366
Filter_63969
I
[ "roll_die", "play_round", "play_game" ]
3
[ [ "play_game", "play_round" ], [ "play_round", "roll_die" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a153a00657019e768c3a1ffc2f9f6c822bdb71d0
5036c5dd476c540da39a761f9e9a84888597f64d
v1.0
instruct
Filter
Filter_63978_I
I'm working on a project where I need to simulate a heat equation and visualize the temperature distribution in a 2D grid. Could you guide me through the process of setting up a simple simulation and visualizing it using Python?
import numpy as np import matplotlib.pyplot as plt def initialize_grid(size, initial_temp): """ Initializes a 2D grid with a specific initial temperature. Args: size (tuple): The size of the grid as (rows, cols). initial_temp (float): The initial temperature to set for all cells. Retu...
import numpy as np from solution import initialize_grid, apply_heat_source, simulate_heat_equation def test_initialize_grid(): grid = initialize_grid((5, 5), 20.0) assert grid.shape == (5, 5) assert np.all(grid == 20.0) def test_apply_heat_source(): grid = initialize_grid((5, 5), 20.0) heat_points...
[ { "docstring": "Initializes a 2D grid with a specific initial temperature.\n\nArgs:\n size (tuple): The size of the grid as (rows, cols).\n initial_temp (float): The initial temperature to set for all cells.\n\nReturns:\n np.ndarray: Initialized grid.", "function_declaration": "def initialize_grid(...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef initialize_grid(size, initial_temp):\n \"\"\"\n Initializes a 2D grid with a specific initial temperature.\n\n Args:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00063978", "row_id": 63978, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129447']" }
0.49137
Filter_63978
I
[ "initialize_grid", "apply_heat_source", "simulate_heat_equation", "visualize_grid" ]
4
[ [ "simulate_heat_equation", "apply_heat_source" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
aa5aad9f64c0e144d7f0c02fdc4f59c4e7a97945
50221eb45b4430831532d23e0e17032cb311a9ca
v1.0
instruct
Filter
Filter_63996_I
Can you help me write a Python script to generate a sine wave with a specific amplitude and frequency?
import numpy as np import matplotlib.pyplot as plt def generate_sine_wave(amplitude, frequency, duration, sample_rate): """ Generate a sine wave based on the given amplitude, frequency, duration, and sample rate. Parameters: amplitude (float): The amplitude of the sine wave. frequency (float):...
from solution import generate_sine_wave import numpy as np def test_generate_sine_wave(): amplitude = 1.0 frequency = 5.0 duration = 1.0 sample_rate = 1000 t, y = generate_sine_wave(amplitude, frequency, duration, sample_rate) assert len(t) == len(y) assert len(t) == sample_rate *...
[ { "docstring": "Generate a sine wave based on the given amplitude, frequency,\nduration, and sample rate.\n\nParameters:\namplitude (float): The amplitude of the sine wave.\nfrequency (float): The frequency of the sine wave (Hz).\nduration (float): The duration of the sine wave (seconds).\nsample_rate (int): Th...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef generate_sine_wave(amplitude, frequency, duration, sampling_rate=44100):\n \"\"\"\n Generate a sine wave based on the given amp...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00063996", "row_id": 63996, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129487']" }
0.64962
Filter_63996
I
[ "generate_sine_wave", "plot_sine_wave" ]
2
[ [ "plot_sine_wave", "generate_sine_wave" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
7519f785b37e5bac22e067cedd5bf28681b791db
01526584dcf7e4f66b7c3662ef5859398a931a78
v1.0
instruct
Filter
Filter_64034_I
How can I create a generic problem solver in Python that can handle a variety of different types of problems, from numerical to symbolic, by leveraging libraries and techniques?
import numpy as np import sympy as sp from scipy.optimize import minimize def problem_solver(problem_type, *args): """ A generic problem solver that handles numerical and symbolic problems. Parameters: - problem_type (str): Type of the problem ['numerical', 'symbolic', or 'optimization'] - arg...
from solution import problem_solver def test_solve_numerical(): data = [1, 2, 3, 4, 5] assert problem_solver('numerical', np.array(data)) == 3.0 def test_solve_symbolic(): expr = 'x**2 + 2*x + 1' variable = 'x' expected = '2*x + 2' solution = problem_solver('symbolic', expr, variable) asse...
[ { "docstring": "A generic problem solver that handles numerical and symbolic problems.\n\nParameters:\n- problem_type (str): Type of the problem ['numerical', 'symbolic', or 'optimization']\n- args: Arguments required to solve the problem\n\nReturns:\n- Solution to the problem", "function_declaration": "def...
[ 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\nimport sympy as sp\nfrom scipy.optimize import minimize\n\nclass GenericProblemSolver:\n def solve_numerical(self, a, b, operation):\n if operation == 'add':\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064034", "row_id": 64034, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129558']" }
0.41938
Filter_64034
I
[ "problem_solver", "_solve_numerical", "_solve_symbolic", "_solve_optimization" ]
4
[ [ "problem_solver", "_solve_numerical" ], [ "problem_solver", "_solve_optimization" ], [ "problem_solver", "_solve_symbolic" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sympy" ]
false
e2f4a2e2dbb6bb4f45d26b18f0fb65d8ee1913bb
26c4dabbb2c18dd551263c5261919e978157b405
v1.0
instruct
Filter
Filter_64041_I
Write a Python function named `find_largest_prime` that takes a list of integers as input and returns the largest prime number from the list. If there are no prime numbers in the list, the function should return `None`. Additionally, include a simple test function to verify that your solution works as expected with a f...
def is_prime(n): """ Helper function to check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n ** 0.5) + 1, 2): if n % i == 0: return False return True def find_larges...
from solution import find_largest_prime def test_find_largest_prime_with_primes(): assert find_largest_prime([2, 3, 5, 7, 11, 13]) == 13 assert find_largest_prime([23, 2, 3, 17, 19]) == 23 def test_find_largest_prime_with_no_primes(): assert find_largest_prime([0, 1, 4, 6, 8, 9]) == None def test_find_la...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the largest prime number from the list. If there are no prime numbers, returns None.", "function_de...
[ 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 <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n i...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064041", "row_id": 64041, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129585']" }
0.669087
Filter_64041
I
[ "is_prime", "find_largest_prime" ]
2
[ [ "find_largest_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
471b5cb141e2b549c4d1d64d1f4399b64b26a489
c942535289c4c4046ae624c36713982123c64afe
v1.0
instruct
Filter
Filter_64046_I
Design a Python function that takes a string `s` as input and returns the number of substrings within `s` that are palindromes.
def is_palindrome(sub): """ Helper function to check if a given string is a palindrome. """ return sub == sub[::-1] def count_palindromic_substrings(s): """ Returns the number of palindromic substrings within the input string `s`. """ count = 0 n = len(s) for i in range(n):...
from solution import count_palindromic_substrings def test_empty_string(): assert count_palindromic_substrings("") == 0 def test_single_character(): assert count_palindromic_substrings("a") == 1 assert count_palindromic_substrings("z") == 1 def test_two_characters(): assert count_palindromic_substrin...
[ { "docstring": "Helper function to check if a given string is a palindrome.", "function_declaration": "def is_palindrome(sub):", "function_name": "is_palindrome", "parameter_list": "(sub)" }, { "docstring": "Returns the number of palindromic substrings within the input string `s`.", "fun...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def count_palindromic_substrings(s):\n \"\"\"\n Returns the number of palindromic substrings in the input string s.\n \"\"\"\n n = len(s)\n count = 0\n\n def expand_around_ce...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064046", "row_id": 64046, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129600']" }
0.716932
Filter_64046
I
[ "is_palindrome", "count_palindromic_substrings" ]
2
[ [ "count_palindromic_substrings", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
461f21e2f31320ce86493ccbfe65a13ca1fb474d
19065a1ae5f717cba79ab2eb746616e905045942
v1.0
instruct
Filter
Filter_64070_I
I need help with creating a Python program that processes a list of file paths and filters out those that are not formatted as valid Windows paths. A valid Windows path should start with a drive letter followed by a colon (e.g., "C:\Users\Username"), and can include directories and filenames thereafter. How can I achie...
import re def is_valid_windows_path(path): """ Checks if the given path is a valid Windows path. A valid Windows path starts with a drive letter followed by a colon (e.g., 'C:\\'). """ pattern = r'^[A-Za-z]:\\.*' return re.match(pattern, path) is not None def filter_valid_windows_paths(paths):...
from solution import is_valid_windows_path, filter_valid_windows_paths def test_is_valid_windows_path(): assert is_valid_windows_path("C:\\Users\\Username") assert is_valid_windows_path("D:\\Folder\\file.txt") assert not is_valid_windows_path("C:/incorrect/path") assert not is_valid_windows_path("\\NoD...
[ { "docstring": "Checks if the given path is a valid Windows path.\nA valid Windows path starts with a drive letter followed by a colon (e.g., 'C:\\').", "function_declaration": "def is_valid_windows_path(path):", "function_name": "is_valid_windows_path", "parameter_list": "(path)" }, { "docs...
[ 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 is_valid_windows_path(path):\n \"\"\"\n Validates if the given path is a valid Windows path.\n \n A valid Windows path starts with a drive letter followed by a col...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064070", "row_id": 64070, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129649']" }
0.631732
Filter_64070
I
[ "is_valid_windows_path", "filter_valid_windows_paths" ]
2
[ [ "filter_valid_windows_paths", "is_valid_windows_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e9dca306516f031601ec8416a7b96d2997ce01d
1c3231e44eb6dc5c7c69bdfd0ab7d2a0c89f019c
v1.0
instruct
Filter
Filter_64073_I
Hello, can you explain how to implement a simple blockchain in Python? Creating a Blockchain involves several components including blocks, the blockchain itself, and a mechanism to validate the integrity of the chain. Could you provide a basic example?
import hashlib import time class Block: def __init__(self, index, previous_hash, timestamp, data, hash): self.index = index self.previous_hash = previous_hash self.timestamp = timestamp self.data = data self.hash = hash def calculate_hash(index, previous_hash, timestamp, da...
from solution import Block, calculate_hash, create_genesis_block, create_new_block, is_chain_valid def test_calculate_hash(): hash_value = calculate_hash(0, "0", 12345, "Genesis Block") expected_hash = hashlib.sha256("0012345Genesis Block".encode('utf-8')).hexdigest() assert hash_value == expected_hash de...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport time\n\nclass Block:\n def __init__(self, index, timestamp, transactions, proof, previous_hash):\n self.index = index\n self.timestamp = timestamp\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064073", "row_id": 64073, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129654']" }
0.351063
Filter_64073
I
[ "calculate_hash", "create_genesis_block", "create_new_block", "is_chain_valid" ]
4
[ [ "create_genesis_block", "calculate_hash" ], [ "create_new_block", "calculate_hash" ], [ "is_chain_valid", "calculate_hash" ] ]
3
[]
false
[ "Block" ]
true
pytest
true
[]
true
bca41b0137a8f47cf4f20baaeb7cc79d0ff25c22
b1b333897bfed00934d9c61a82d0fc1b1cb7df16
v1.0
instruct
Filter
Filter_64080_I
I need a detailed explanation of how to implement a Convolutional Neural Network (CNN) from scratch using only NumPy in Python. This includes data preparation, model architecture, forward and backward propagation, and learning the weights. How can I achieve this?
# Data preparation import numpy as np def generate_synthetic_data(num_samples=1000, image_dim=28): """ Generates synthetic data for training the CNN. Returns: - X: Synthetic images of shape (num_samples, image_dim, image_dim) - y: Synthetic labels of shape (num_samples,) """ X = np.random.r...
import numpy as np from solution import generate_synthetic_data, conv2d, relu, max_pool, softmax, forward def test_generate_synthetic_data(): X, y = generate_synthetic_data(5, 28) assert X.shape == (5, 28, 28) assert y.shape == (5,) assert np.all(y >= 0) and np.all(y < 10) def test_conv2d(): image...
[ { "docstring": "Generates synthetic data for training the CNN.\nReturns:\n- X: Synthetic images of shape (num_samples, image_dim, image_dim)\n- y: Synthetic labels of shape (num_samples,)", "function_declaration": "def generate_synthetic_data(num_samples=1000, image_dim=28):", "function_name": "generate...
[ 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\n# Helper function: One-hot encoding\ndef one_hot_encode(labels, num_classes):\n return np.eye(num_classes)[labels]\n\n# Convolutional Layer\nclass ConvLayer:\n def ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064080", "row_id": 64080, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129680']" }
0.291748
Filter_64080
I
[ "generate_synthetic_data", "conv2d", "relu", "max_pool", "softmax", "forward" ]
6
[ [ "forward", "conv2d" ], [ "forward", "max_pool" ], [ "forward", "relu" ], [ "forward", "softmax" ] ]
4
[]
false
[]
false
pytest
true
[ "numpy" ]
false
79e2eb1778a2cc02497d8ab53717dc73130c8388
263a7b1a433c087753aaa58607df37871ef02ad0
v1.0
instruct
Filter
Filter_64090_I
Generate a Python script for a basic web crawler that can scrape data from a website and extract specific content. For this example, let's assume we want to scrape all the URLs and headings (H1, H2, H3) from the CNN homepage.
import requests from bs4 import BeautifulSoup def fetch_html(url): """ Fetches HTML content from a given URL. """ response = requests.get(url) response.raise_for_status() return response.text def extract_urls_and_headings(html_content): """ Extracts all URLs and headings (H1, H2, H3) f...
from solution import fetch_html, extract_urls_and_headings, crawl_website def test_fetch_html(): url = "https://www.cnn.com" html_content = fetch_html(url) assert "<html" in html_content.lower() def test_extract_urls_and_headings(): html_content = """ <html> <body> <h1>Heading ...
[ { "docstring": "Fetches HTML content from a given URL.", "function_declaration": "def fetch_html(url):", "function_name": "fetch_html", "parameter_list": "(url)" }, { "docstring": "Extracts all URLs and headings (H1, H2, H3) from the given HTML content.", "function_declaration": "def ext...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\n\ndef fetch_html(url):\n \"\"\"\n Fetches HTML content from a given URL.\n \"\"\"\n response = requests.get(url)\n response.raise...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064090", "row_id": 64090, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129702']" }
0.709554
Filter_64090
I
[ "fetch_html", "extract_urls_and_headings", "crawl_website" ]
3
[ [ "crawl_website", "extract_urls_and_headings" ], [ "crawl_website", "fetch_html" ] ]
2
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
c989661f4df4d1b87642272e904f630f116136a5
78bf546b291f2ea8087daa8adca72e0bf9148ad6
v1.0
instruct
Filter
Filter_64114_I
Can you provide a Python code to create a dictionary with keys as prime numbers less than 50 and values as their corresponding square values?
def is_prime(n): """ Returns True if n is a prime number, else False. """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def primes_below_50(): """ Returns a dictionary with keys as prime numbers less than ...
from solution import is_prime, primes_below_50 def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(1) == False assert is_prime(0) == False def test_primes_below_50():...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a dictionary with keys as prime numbers less than 50 and values as their square values.", "functi...
[ 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 if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064114", "row_id": 64114, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129746']" }
0.508763
Filter_64114
I
[ "is_prime", "primes_below_50" ]
2
[ [ "primes_below_50", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7feb99917927dac8bc77515f51a7c2e07722a7ef
04315bbf1704474fdae6b87f906a92b0e8f57ff7
v1.0
instruct
Filter
Filter_64123_I
Write a Python script to find prime numbers within a given range. The script should prompt the user to input the start and end of the range and then print out all prime numbers within that range.
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 find_primes(start, end): """ Find all prime numbers within a given range [start, end]. ""...
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(5) == True assert is_prime(1) == False assert is_prime(-10) == False def test_find_primes(): assert find_primes(10, 20) == [11, ...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find all prime numbers within a given range [start, end].", "function_declaration": "def find_primes(start, end):", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064123", "row_id": 64123, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129763']" }
0.640109
Filter_64123
I
[ "is_prime", "find_primes" ]
2
[ [ "find_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4a92dbc9e01d251feee663f4fa1fb29a270f9613
ffea93b46c6d9ebd548c836cde96118077483d30
v1.0
instruct
Filter
Filter_64150_I
I need help with creating a z-order curve iterator for a given range of integer values. A z-order curve, also known as a Morton code, maps multi-dimensional data to a single dimension. I want to iterate over a range of 2D integer coordinates using this curve. Could you provide a Python implementation for this?
def interleave_bits(x, y): """ Interleaves the bits of x and y. """ z = 0 for i in range(max(x.bit_length(), y.bit_length())): z |= ((x >> i) & 1) << (2 * i) z |= ((y >> i) & 1) << (2 * i + 1) return z def z_order_curve_iterator(x_range, y_range): """ Generates tuples of...
from solution import z_order_curve_iterator def test_z_order_curve_iterator_small_range(): result = list(z_order_curve_iterator((0, 2), (0, 2))) expected = [(0, 0), (1, 0), (0, 1), (1, 1)] assert result == expected def test_z_order_curve_iterator_larger_range(): result = list(z_order_curve_iterator((0...
[ { "docstring": "Interleaves the bits of x and y.", "function_declaration": "def interleave_bits(x, y):", "function_name": "interleave_bits", "parameter_list": "(x, y)" }, { "docstring": "Generates tuples of (x, y) coordinates within the specified ranges,\nordered according to the Z-order cur...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def split_by_2_bits(x):\n x = (x | (x << 16)) & 0x0000FFFF0000FFFF\n x = (x | (x << 8)) & 0x00FF00FF00FF00FF\n x = (x | (x << 4)) & 0x0F0F0F0F0F0F0F0F\n x = (x | (x << 2)) & 0x3333...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064150", "row_id": 64150, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129820']" }
0.353518
Filter_64150
I
[ "interleave_bits", "z_order_curve_iterator" ]
2
[ [ "z_order_curve_iterator", "interleave_bits" ] ]
1
[]
false
[]
false
pytest
true
[]
true
49961a85233c67bd03067e171598cdb69c6ce40a
c79215f81b4db79c9f28a4a69fa91232ec6c68b1
v1.0
instruct
Filter
Filter_64170_I
I want to create a Python program that not only generates a list of prime numbers within a given range but also calculates the sum of all prime numbers in that range. How can I achieve this?
def is_prime(n): """ Check if a number is a prime. """ if n <= 1: return False if n == 2: return True # 2 is the only even prime number if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True ...
from solution import primes_in_range, sum_of_primes_in_range def test_primes_in_range_basic(): assert primes_in_range(10, 20) == [11, 13, 17, 19] assert primes_in_range(1, 10) == [2, 3, 5, 7] def test_primes_in_range_no_primes(): assert primes_in_range(14, 16) == [] assert primes_in_range(0, 1) == [] ...
[ { "docstring": "Check if a number is a prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Return a list of prime numbers in the given range [start, end].", "function_declaration": "def primes_in_range(start, end):"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064170", "row_id": 64170, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129859']" }
0.58866
Filter_64170
I
[ "is_prime", "primes_in_range", "sum_of_primes_in_range" ]
3
[ [ "primes_in_range", "is_prime" ], [ "sum_of_primes_in_range", "primes_in_range" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f2cc1392d56406e5b4e1e44339e81d4d4869e36b
5fb32cd7167eb9764e94c59ba5fa82d8310ab3db
v1.0
instruct
Filter
Filter_64179_I
Write a Python function that calculates the area of a triangle given its base and height. The function should be named `calculate_triangle_area`, and it should take two parameters: `base` and `height`. The docstring for the function should describe what the function does, its parameters, and the return value. Additiona...
def calculate_triangle_area(base, height): """ Calculates the area of a triangle given its base and height. Parameters: - base (float): The base length of the triangle. - height (float): The height of the triangle. Returns: - float: The area of the triangle. """ return 0.5 ...
from solution import calculate_triangle_area, verify_solution def test_calculate_triangle_area_typical_case(): assert calculate_triangle_area(10, 5) == 25.0 def test_calculate_triangle_area_zero_base(): assert calculate_triangle_area(0, 5) == 0.0 def test_calculate_triangle_area_zero_height(): assert cal...
[ { "docstring": "Calculates the area of a triangle given its base and height.\n\nParameters:\n- base (float): The base length of the triangle.\n- height (float): The height of the triangle.\n\nReturns:\n- float: The area of the triangle.", "function_declaration": "def calculate_triangle_area(base, height):",...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_triangle_area(base, height):\n \"\"\"\n Calculate the area of a triangle given its base and height.\n \n Parameters:\n base (float): The base length of the triangl...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064179", "row_id": 64179, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129876']" }
0.752247
Filter_64179
I
[ "calculate_triangle_area", "verify_solution" ]
2
[ [ "verify_solution", "calculate_triangle_area" ] ]
1
[]
false
[]
false
pytest
true
[]
true
714cc8be75986f52488d725d98f5ffda013486ab
816daa41cdeefe4c0d966722caf31cc6392cef41
v1.0
instruct
Filter
Filter_64194_I
I need to create a Python decorator that can validate the input parameters of a function using a set of rules defined in a separate dictionary. How can I implement such a decorator?
def validate_params(rules): """ Decorator to validate function input parameters based on provided rules. :param rules: Dictionary containing parameter names and their validation rules (functions). """ def decorator(func): def wrapper(*args, **kwargs): # Get function argument...
import pytest from solution import register_user def test_register_user_valid_params(): assert register_user("Alice", 30) == "User Alice, aged 30, registered." def test_register_user_invalid_age(): with pytest.raises(ValueError) as excinfo: register_user("Alice", -1) assert str(excinfo.value) == "...
[ { "docstring": "Decorator to validate function input parameters based on provided rules.\n\n:param rules: Dictionary containing parameter names and their validation rules (functions).", "function_declaration": "def validate_params(rules):", "function_name": "validate_params", "parameter_list": "(rul...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def validate_params(rules):\n \"\"\"\n A decorator to validate input parameters of a function based on the provided rules.\n \n rules: dict\n A dictionary that defines the v...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064194", "row_id": 64194, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129905']" }
0.491937
Filter_64194
I
[ "validate_params", "register_user" ]
2
[ [ "register_user", "validate_params" ] ]
1
[]
false
[]
false
pytest
true
[]
true
da3b6b7a38d107a581e5da1e213569b8a1a89844
7208c5088254e11fce126832ce0d84762df063b4
v1.0
instruct
Filter
Filter_64225_I
Write a Python script to generate a report on web server performance using Apache status module. The script should fetch the status output from an Apache server and parse it to extract key performance metrics such as the number of currently processing requests, the number of idle workers, and the total number of bytes ...
import requests def fetch_apache_status(url): """ Fetch the Apache status page from the given URL. """ response = requests.get(url) response.raise_for_status() return response.text def parse_apache_status(status_text): """ Parse the given Apache status text to extract key performance m...
import pytest from solution import fetch_apache_status, parse_apache_status, generate_report # Mock data for testing mock_status_text = """ Total Accesses: 10234 Total kBytes: 123456 ReqPerSec: 5.67 BytesPerSec: 1024.67 BytesPerReq: 180.56 BusyWorkers: 10 IdleWorkers: 5 """ def test_parse_apache_status(): metrics...
[ { "docstring": "Fetch the Apache status page from the given URL.", "function_declaration": "def fetch_apache_status(url):", "function_name": "fetch_apache_status", "parameter_list": "(url)" }, { "docstring": "Parse the given Apache status text to extract key performance metrics.", "funct...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom typing import Dict\n\ndef fetch_apache_status(url: str) -> str:\n \"\"\"\n Fetches Apache status page.\n \n Args:\n url (str): The URL to the Apache status...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064225", "row_id": 64225, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_129978']" }
0.500043
Filter_64225
I
[ "fetch_apache_status", "parse_apache_status", "generate_report" ]
3
[ [ "generate_report", "fetch_apache_status" ], [ "generate_report", "parse_apache_status" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
518e9b1d1ded2309d7b4de81ed4c44c0908363af
666765a6df12b5536d99f140e0e758c0e752a9e2
v1.0
instruct
Filter
Filter_64246_I
I have a Python script that creates an Excel file with pandas. The script includes a column with values that match the pattern of email addresses, but I want to add a new column that checks if these values conform to a regular expression that defines a valid email address. I can use the `re` module in Python for regex ...
import pandas as pd import re def is_valid_email(email): """ Validates if the provided email matches the pattern of a valid email address. """ email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return re.match(email_regex, email) is not None def add_email_validation_column(df, email...
import pandas as pd from solution import is_valid_email, add_email_validation_column def test_is_valid_email(): assert is_valid_email("test@example.com") assert not is_valid_email("invalid-email") assert is_valid_email("hello@world.net") assert not is_valid_email("another.invalid-email") assert is_...
[ { "docstring": "Validates if the provided email matches the pattern of a valid email address.", "function_declaration": "def is_valid_email(email):", "function_name": "is_valid_email", "parameter_list": "(email)" }, { "docstring": "Adds a new column to the DataFrame that checks if email addr...
[ 1, 0, 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 is_valid_email(email):\n \"\"\"\n Validates if the provided email matches the pattern of a valid email address.\n \"\"\"\n email_regex = r'^[a...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064246", "row_id": 64246, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130020']" }
0.509185
Filter_64246
I
[ "is_valid_email", "add_email_validation_column" ]
2
[ [ "add_email_validation_column", "is_valid_email" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
440d35a3f3429cf54fd14a37b70dfef2002bc3e2
2757849cfeb89b2a813037e3edee0131967620e5
v1.0
instruct
Filter
Filter_64265_I
Can you create a Python function that takes a list of integers and returns a new list containing only those integers that are palindromes? A palindrome is a number that reads the same backward as forward.
def is_palindrome(n): """ Helper function to check if a number is a palindrome. """ s = str(n) return s == s[::-1] def filter_palindromes(int_list): """ Returns a new list containing only the integers that are palindromes. """ return [num for num in int_list if is_palindrome(num)]
from solution import filter_palindromes def test_filter_palindromes_all_palindromes(): assert filter_palindromes([121, 33, 44, 909]) == [121, 33, 44, 909] def test_filter_palindromes_some_palindromes(): assert filter_palindromes([123, 121, 1441, 987]) == [121, 1441] def test_filter_palindromes_no_palindromes...
[ { "docstring": "Helper function to check if a number is a palindrome.", "function_declaration": "def is_palindrome(n):", "function_name": "is_palindrome", "parameter_list": "(n)" }, { "docstring": "Returns a new list containing only the integers that are palindromes.", "function_declarat...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(number):\n \"\"\"\n Returns True if the given number is a palindrome, False otherwise.\n \"\"\"\n str_num = str(number)\n return str_num == str_num[::-1]\n\nde...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064265", "row_id": 64265, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130060']" }
0.707313
Filter_64265
I
[ "is_palindrome", "filter_palindromes" ]
2
[ [ "filter_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e5543396892873942e50777886732feaafe828d4
77fe7b68f9d12c4d4db59d3b5e336fd5c531803d
v1.0
instruct
Filter
Filter_64311_I
I want to create a Python script that takes a directory of images, processes them, and then saves the processed images back to a new directory. Can you provide a basic template for this script?
import os from PIL import Image def process_image(image_path): """ Processes the image and returns the processed image. In this example, we convert image to grayscale. """ with Image.open(image_path) as img: processed_img = img.convert("L") # Convert image to grayscale return processed...
import os from PIL import Image from solution import process_image, process_images def test_process_image(): # Create a test image img = Image.new('RGB', (10, 10), color = 'red') img_path = 'test_image.jpg' img.save(img_path) # Process the image processed_img = process_image(img_path) ...
[ { "docstring": "Processes the image and returns the processed image.\nIn this example, we convert image to grayscale.", "function_declaration": "def process_image(image_path):", "function_name": "process_image", "parameter_list": "(image_path)" }, { "docstring": "Processes images in the inpu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport cv2\n\ndef process_image(image):\n \"\"\"\n Process the image as required.\n This is a placeholder function and should be replaced with actual processing logic.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064311", "row_id": 64311, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130159']" }
0.537679
Filter_64311
I
[ "process_image", "process_images" ]
2
[ [ "process_images", "process_image" ] ]
1
[]
false
[]
false
pytest
true
[ "PIL" ]
false
f685a64d0884104ebcc302d1e318c745ec960847
ea1ddda780f3f315622ef3bcb97a15a47bb29b7d
v1.0
instruct
Filter
Filter_64381_I
I want to write a Python script that reads data from a CSV file and creates a simple web application using Flask to display this data in a table format. How can I achieve this?
from flask import Flask, render_template_string import pandas as pd app = Flask(__name__) def read_csv(file_path): """Reads data from a CSV file and returns a pandas DataFrame.""" return pd.read_csv(file_path) @app.route('/') def display_table(): """Reads data from CSV file and renders it in an HTML tabl...
import pytest from solution import read_csv import pandas as pd def test_read_csv(tmp_path): # Create a CSV file csv_content = "name,age\nAlice,30\nBob,25" csv_file = tmp_path / "data.csv" csv_file.write_text(csv_content) # Read CSV file df = read_csv(csv_file) # Expected DataFrame ex...
[ { "docstring": "Reads data from a CSV file and returns a pandas DataFrame.", "function_declaration": "def read_csv(file_path):", "function_name": "read_csv", "parameter_list": "(file_path)" }, { "docstring": "Reads data from CSV file and renders it in an HTML table.", "function_declarati...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, render_template_string\nimport pandas as pd\n\napp = Flask(__name__)\n\ndef read_csv(file_path):\n \"\"\"Reads data from a CSV file and returns a pandas DataFrame.\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064381", "row_id": 64381, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130305']" }
0.510577
Filter_64381
I
[ "read_csv", "display_table" ]
2
[ [ "display_table", "read_csv" ] ]
1
[]
false
[]
false
pytest
true
[ "flask", "pandas" ]
false
b57be8685a2fc628723e5ced0034b7979347e81f
1df3183a27562543a250092e444cda33eca2b4b3
v1.0
instruct
Filter
Filter_64395_I
Can you provide an example of how to use the `assert` statement in Python for the `sqrt` function in the `math` module?
import math def calculate_sqrt(value): """ Returns the square root of the given value. """ return math.sqrt(value) # Example usage of assert statement def example_usage(): result = calculate_sqrt(9) assert result == 3.0, f"Expected 3.0, but got {result}"
import math from solution import calculate_sqrt def test_calculate_sqrt_positive_number(): assert calculate_sqrt(9) == 3.0 def test_calculate_sqrt_zero(): assert calculate_sqrt(0) == 0.0 def test_calculate_sqrt_small_positive_number(): assert calculate_sqrt(0.25) == 0.5 def test_calculate_sqrt_large_num...
[ { "docstring": "Returns the square root of the given value.", "function_declaration": "def calculate_sqrt(value):", "function_name": "calculate_sqrt", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def example_usage():", "function_name": "example_usage",...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef sqrt_assert_example(value):\n \"\"\"\n Computes the square root of the given value.\n\n :param value: Number to compute the square root for.\n :return: Square ro...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064395", "row_id": 64395, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130336']" }
0.540222
Filter_64395
I
[ "calculate_sqrt", "example_usage" ]
2
[ [ "example_usage", "calculate_sqrt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
795e64755f3f7ed2b042525f61a8f609503972a8
61ffdf95ff7057a9de497bd34a93b064f818a58a
v1.0
instruct
Filter
Filter_64427_I
Can you provide a Python code for generating a random least common multiple (LCM) of a list of numbers within a specified range? First, generate the numbers randomly, and then calculate their LCM.
import random from math import gcd from functools import reduce def generate_random_numbers(n, lower, upper): """ Generates a list of n random numbers within the specified range [lower, upper]. """ return [random.randint(lower, upper) for _ in range(n)] def lcm(a, b): """ Returns the least com...
from solution import generate_random_numbers, lcm, lcm_of_list, generate_random_lcm import pytest def test_generate_random_numbers_length(): numbers = generate_random_numbers(5, 1, 10) assert len(numbers) == 5 def test_generate_random_numbers_range(): numbers = generate_random_numbers(5, 1, 10) assert...
[ { "docstring": "Generates a list of n random numbers within the specified range [lower, upper].", "function_declaration": "def generate_random_numbers(n, lower, upper):", "function_name": "generate_random_numbers", "parameter_list": "(n, lower, upper)" }, { "docstring": "Returns the least co...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom math import gcd\nfrom functools import reduce\n\ndef lcm(a, b):\n \"\"\"\n Return the Least Common Multiple (LCM) of two integers a and b.\n \"\"\"\n return abs...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064427", "row_id": 64427, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130414']" }
0.667665
Filter_64427
I
[ "generate_random_numbers", "lcm", "lcm_of_list", "generate_random_lcm" ]
4
[ [ "generate_random_lcm", "generate_random_numbers" ], [ "generate_random_lcm", "lcm_of_list" ], [ "lcm_of_list", "lcm" ] ]
3
[]
false
[]
false
pytest
true
[]
true
eb7840ef4ef28581e8f8b569b9995c40e217d34c
6fdf5b04e873310aa75f7843cb2dde9ffdddd4e6
v1.0
instruct
Filter
Filter_64460_I
How can I modify the given Python code to pause the execution of a loop until a specific condition is met?
import time def loop_with_pause(condition_func, pause_interval=1): """ Loops until the condition_func returns True. Pauses the loop execution at each iteration until the condition is met. :param condition_func: Function that returns a boolean value indicating whether to continue or pause. :par...
import time from solution import loop_with_pause, example_loop_execution def test_loop_with_pause(): start_time = time.time() condition_met = False def condition_func(): nonlocal condition_met return condition_met def set_condition_true(): nonlocal condition_met time.s...
[ { "docstring": "Loops until the condition_func returns True.\nPauses the loop execution at each iteration until the condition is met.\n\n:param condition_func: Function that returns a boolean value indicating whether to continue or pause.\n:param pause_interval: Number of seconds to wait before the next check."...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef loop_with_pause(condition_func, pause_interval=1):\n \"\"\"\n Loops until the condition_func returns True.\n Pauses the loop execution at each iteration until the c...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064460", "row_id": 64460, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130482']" }
0.48629
Filter_64460
I
[ "loop_with_pause", "example_loop_execution" ]
2
[ [ "example_loop_execution", "loop_with_pause" ] ]
1
[]
false
[]
false
pytest
true
[]
true
623a6ea0ffd126bd2819387808442ac4ae694ffa
5ebadd1f5d116272fc1b4c19a34b317aec4feb34
v1.0
instruct
Filter
Filter_64490_I
Create a Python code that calculates the degree of similarity between two strings using the Levenshtein distance algorithm. The function should return a similarity ratio between 0 and 1, where 1 means the strings are identical, and 0 means they are completely different.
def levenshtein_distance(s1, s2): if len(s1) == 0: return len(s2) if len(s2) == 0: return len(s1) matrix = [[0 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)] for i in range(len(s1) + 1): matrix[i][0] = i for j in range(len(s2) + 1): matrix[0][j] =...
from solution import levenshtein_distance, similarity_ratio def test_levenshtein_distance_empty_strings(): assert levenshtein_distance("", "") == 0 assert levenshtein_distance("abc", "") == 3 assert levenshtein_distance("", "def") == 3 def test_levenshtein_distance_identical_strings(): assert levensht...
[ { "docstring": null, "function_declaration": "def levenshtein_distance(s1, s2):", "function_name": "levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": null, "function_declaration": "def similarity_ratio(s1, s2):", "function_name": "similarity_ratio", "parameter...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def levenshtein_distance(s1, s2):\n \"\"\"\n Computes the Levenshtein distance between two strings.\n \"\"\"\n if len(s1) < len(s2):\n return levenshtein_distance(s2, s1)\n\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064490", "row_id": 64490, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130538']" }
0.77466
Filter_64490
I
[ "levenshtein_distance", "similarity_ratio" ]
2
[ [ "similarity_ratio", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
019d63883393bbc357529e2acd7372a316047b6f
ebf486850abc60fc77ef7b3d54fa618463a8e645
v1.0
instruct
Filter
Filter_64491_I
Hello Qwen, how can I modify the code to handle a scenario where the list of items is not directly accessible, but rather is obtained through a function call? Let's say the function is named `get_items()` and it returns the list of items. How should I adjust my code to accommodate this?
def process_items(): """ Fetches the list of items from the get_items() function and processes them. """ items = get_items() # Process the items processed_items = [item * 2 for item in items] # Example processing return processed_items def get_items(): """ Returns a list of items. ...
from solution import process_items, get_items def test_process_items_with_sample_data(): items = get_items() expected_processed_items = [item * 2 for item in items] assert process_items() == expected_processed_items def test_process_items_with_custom_data(monkeypatch): def mock_get_items(): re...
[ { "docstring": "Fetches the list of items from the get_items() function and processes them.", "function_declaration": "def process_items():", "function_name": "process_items", "parameter_list": "()" }, { "docstring": "Returns a list of items.", "function_declaration": "def get_items():",...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_items():\n \"\"\"\n Simulates a function that returns a list of items.\n \"\"\"\n return [1, 2, 3, 4, 5]\n\ndef process_items():\n \"\"\"\n Processes items obtained f...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064491", "row_id": 64491, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130539']" }
0.376301
Filter_64491
I
[ "process_items", "get_items" ]
2
[ [ "process_items", "get_items" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f76172220ca3b27cdd602096f076617e07151677
a141f2963934d1600bfea7acd666cd05b884c1b4
v1.0
instruct
Filter
Filter_64502_I
Write a Python script that takes a list of URLs, fetches each URL, and prints the title of the HTML page. You should handle exceptions and ensure the script can process multiple URLs efficiently.
import requests from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor def fetch_title(url): """ Fetches the title of the HTML page for the given URL. """ try: response = requests.get(url, timeout=5) response.raise_for_status() soup = BeautifulSoup(respo...
from solution import fetch_title, fetch_titles import pytest from unittest import mock def mock_requests_get(*args, **kwargs): class MockResponse: def __init__(self, content, status_code): self.content = content self.status_code = status_code def raise_for_status(se...
[ { "docstring": "Fetches the title of the HTML page for the given URL.", "function_declaration": "def fetch_title(url):", "function_name": "fetch_title", "parameter_list": "(url)" }, { "docstring": "Fetches the titles for a list of URLs efficiently.", "function_declaration": "def fetch_ti...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef fetch_title(url):\n \"\"\"\n Fetches the title of the HTML page at the given URL....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064502", "row_id": 64502, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130560']" }
0.717221
Filter_64502
I
[ "fetch_title", "fetch_titles" ]
2
[ [ "fetch_titles", "fetch_title" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
3d359ddcd934421b8ecfaaeb2ad6a0826c4e0441
4201cb91964acc4cbeb6c239c2e84ed5b039ddd1
v1.0
instruct
Filter
Filter_64508_I
Can you provide a Python script that dynamically generates a report based on the given data? The script should be able to handle different types of data and should be flexible enough to adapt to changes in data format and structure. The script should also include error handling and logging.
import json import logging from typing import Any, Dict, List # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def generate_report(data: Any) -> str: """ Generate a report based on the given data. The repor...
from solution import generate_report # Ensure you save the solution in a file named "solution.py" def test_generate_report_with_dict(): data = {"name": "Alice", "age": 30, "city": "New York"} expected_report = "Dictionary Report:\nname: Alice\nage: 30\ncity: New York" assert generate_report(data) == expec...
[ { "docstring": "Generate a report based on the given data.\nThe report format adapts to the data type and structure.\n\nParameters:\ndata (Any): The data to generate the report from. Can be of any type.\n\nReturns:\nstr: The generated report as a string.", "function_declaration": "def generate_report(data):...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport logging\nfrom typing import Any, Dict, List, Union\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n\nd...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064508", "row_id": 64508, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130574']" }
0.440459
Filter_64508
I
[ "generate_report", "generate_dict_report", "generate_list_report" ]
3
[ [ "generate_report", "generate_dict_report" ], [ "generate_report", "generate_list_report" ] ]
2
[]
false
[]
false
pytest
true
[]
true
01d98b443fb1316e8218c02f7621ebb79961913c
dc3f5e5f35f1c1a4907d77e64ef50a1f469fe3a3
v1.0
instruct
Filter
Filter_64565_I
Write a Python function to check if a number is an Armstrong number and a function to find all Armstrong numbers in a given range.
def is_armstrong_number(n): """ Checks if a number is an Armstrong number. An Armstrong number is an n-digit number that is equal to the sum of its own digits each raised to the power of n. """ num_str = str(n) num_length = len(num_str) sum_of_powers = sum(int(digit) ** num_length for digit ...
from solution import is_armstrong_number, find_armstrong_numbers_in_range def test_is_armstrong_number_single_digit(): for i in range(10): assert is_armstrong_number(i) == True def test_is_armstrong_number_true_cases(): assert is_armstrong_number(153) == True assert is_armstrong_number(370) == Tru...
[ { "docstring": "Checks if a number is an Armstrong number.\nAn Armstrong number is an n-digit number that is equal to the sum of its own digits each raised to the power of n.", "function_declaration": "def is_armstrong_number(n):", "function_name": "is_armstrong_number", "parameter_list": "(n)" },...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_armstrong_number(n):\n \"\"\"\n Check if the provided number n is an Armstrong number.\n \n An Armstrong number for a given number of digits is an integer such that the sum ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064565", "row_id": 64565, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130713']" }
0.524034
Filter_64565
I
[ "is_armstrong_number", "find_armstrong_numbers_in_range" ]
2
[ [ "find_armstrong_numbers_in_range", "is_armstrong_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bb7a49e68c804e36133a0e508c299177b75c24e3
369bfc62a9460906eacad810faf4d02c574f8220
v1.0
instruct
Filter
Filter_64578_I
Create a Python function that identifies all pairs of words that rhyme in a given text. A pair of words rhyme if their last two syllables are identical. For example, "moon" and "soon", "banana" and "vista". The function should return a list of tuples, where each tuple contains a pair of rhyming words. Assume the text c...
import re from collections import defaultdict from itertools import combinations def get_rhyming_part(word): # This function extracts the last two syllables for rhyming. vowels = 'aeiou' parts = re.split(f'([{vowels}]+)', word) syllables = [p for p in parts if p] if len(syllables) < 2: retu...
from solution import find_rhyming_pairs def test_no_rhymes(): assert find_rhyming_pairs("apple orange pear") == [] def test_simple_rhymes(): result = find_rhyming_pairs("moon spoon soon noon") assert result == [("moon", "spoon"), ("moon", "soon"), ("moon", "noon"), ("spoon", "soon"), ("spoon", "noon"), ("...
[ { "docstring": null, "function_declaration": "def get_rhyming_part(word):", "function_name": "get_rhyming_part", "parameter_list": "(word)" }, { "docstring": null, "function_declaration": "def find_rhyming_pairs(text):", "function_name": "find_rhyming_pairs", "parameter_list": "(...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom collections import defaultdict\nfrom itertools import combinations\n\ndef get_rhyming_part(word):\n # This function extracts the last two syllables for rhyming.\n vowels ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064578", "row_id": 64578, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130732']" }
0.550418
Filter_64578
I
[ "get_rhyming_part", "find_rhyming_pairs" ]
2
[ [ "find_rhyming_pairs", "get_rhyming_part" ] ]
1
[]
false
[]
false
pytest
true
[]
true
49c95a3605984f89880dcc530404d6b745b71435
bf9c0316ea485ef44ca5932b75be57119e0a50bf
v1.0
instruct
Filter
Filter_64610_I
Tell me how to print the first 100 prime numbers in Python?
def is_prime(n): """ Checks if a number n is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def first_100_primes(): """ ...
from solution import is_prime, first_100_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(10) == False assert is_prime(11) == True assert is_prime(0) == False assert is_prime(1) == Fa...
[ { "docstring": "Checks if a number n is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Prints the first 100 prime numbers.", "function_declaration": "def first_100_primes():", "function_name": "first_100_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 \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064610", "row_id": 64610, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130794']" }
0.614374
Filter_64610
I
[ "is_prime", "first_100_primes" ]
2
[ [ "first_100_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d671b7a2cd01622d3f2cc6dca8cf4a3390e18013
abb271e3a758a04361d928c9303275b042c66223
v1.0
instruct
Filter
Filter_64669_I
How can I modify the code to run the function `Meow` 10 times?
def Meow(): """ Prints 'meow'. """ print('meow') def run_Meow_ten_times(): """ Runs the Meow function 10 times. """ for _ in range(10): Meow()
from io import StringIO import sys from solution import Meow, run_Meow_ten_times def test_Meow_output(): captured_output = StringIO() sys.stdout = captured_output Meow() sys.stdout = sys.__stdout__ assert captured_output.getvalue() == "meow\n" def test_run_Meow_ten_times_output(): captured_out...
[ { "docstring": "Prints 'meow'.", "function_declaration": "def Meow():", "function_name": "Meow", "parameter_list": "()" }, { "docstring": "Runs the Meow function 10 times.", "function_declaration": "def run_Meow_ten_times():", "function_name": "run_Meow_ten_times", "parameter_lis...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def Meow():\n \"\"\"\n Prints 'Meow'.\n \"\"\"\n print(\"Meow\")\n\ndef run_meow_10_times():\n \"\"\"\n Runs the Meow function 10 times.\n \"\"\"\n for _ in range(10):\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064669", "row_id": 64669, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130927']" }
0.412736
Filter_64669
I
[ "Meow", "run_Meow_ten_times" ]
2
[ [ "run_Meow_ten_times", "Meow" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c9fcc5cc41946ad3bbccb076a2a06e4c00f3b269
6c4f18db124d2b05544717d0306543b7dff0f364
v1.0
instruct
Filter
Filter_64680_I
Could you provide a detailed explanation of how to implement a JPEG compression algorithm in Python, including the steps involved and any necessary libraries?
import numpy as np import imageio import scipy.fftpack def rgb_to_ycbcr(image): """ Convert an RGB image to YCbCr color space. """ transform_matrix = np.array([ [ 0.299, 0.587, 0.114], [-0.1687, -0.3313, 0.5], [ 0.5, -0.4187, -0.0813] ]) ycbcr = image @ transfor...
import numpy as np import imageio import os from solution import compress_image, decompress_image, rgb_to_ycbcr, ycbcr_to_rgb def generate_dummy_image(path, width=32, height=32): dummy_image = np.random.randint(0, 256, (width, height, 3), dtype=np.uint8) imageio.imwrite(path, dummy_image) def test_image_compr...
[ { "docstring": "Convert an RGB image to YCbCr color space.", "function_declaration": "def rgb_to_ycbcr(image):", "function_name": "rgb_to_ycbcr", "parameter_list": "(image)" }, { "docstring": "Convert a YCbCr image to RGB color space.", "function_declaration": "def ycbcr_to_rgb(ycbcr):",...
[ 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 PIL import Image\nimport scipy.fftpack\n\ndef rgb_to_ycbcr(image):\n \"\"\"\n Converts an RGB image to YCbCr color space.\n \"\"\"\n return image.convert('...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064680", "row_id": 64680, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130949']" }
0.471343
Filter_64680
I
[ "rgb_to_ycbcr", "ycbcr_to_rgb", "block_processing", "dct_2d", "idct_2d", "quantize", "dequantize", "compress_image", "decompress_image" ]
9
[ [ "compress_image", "block_processing" ], [ "compress_image", "dct_2d" ], [ "compress_image", "quantize" ], [ "compress_image", "rgb_to_ycbcr" ], [ "decompress_image", "block_processing" ], [ "decompress_image", "dequantize" ], [ "decompres...
8
[]
false
[]
false
pytest
true
[ "imageio", "numpy", "scipy" ]
false
688c91f12746cb5b56bbc06df82313355ea1d356
e38ee3192ebb6bba72cf3a7d97a286d43c64c3a7
v1.0
instruct
Filter
Filter_64691_I
Please provide a Python function that calculates the nth Fibonacci number using matrix exponentiation. This method is more efficient than the iterative or recursive approach, especially for large n.
def matrix_mult(A, B): """ Multiplies two 2x2 matrices A and B. """ return [ [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]], [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]] ] def matrix_power(matrix, n): """ Rais...
def test_matrix_mult(): A = [[1, 2], [3, 4]] B = [[2, 0], [1, 2]] assert matrix_mult(A, B) == [[4, 4], [10, 8]] def test_matrix_power(): F = [[1, 1], [1, 0]] assert matrix_power(F, 0) == [[1, 0], [0, 1]] assert matrix_power(F, 1) == [[1, 1], [1, 0]] assert matrix_power(F, 2) == [[2, 1], [1,...
[ { "docstring": "Multiplies two 2x2 matrices A and B.", "function_declaration": "def matrix_mult(A, B):", "function_name": "matrix_mult", "parameter_list": "(A, B)" }, { "docstring": "Raises the 2x2 matrix to the power of n using exponentiation by squaring.", "function_declaration": "def ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \"\"\"\n return [\n [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064691", "row_id": 64691, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_130969']" }
0.673707
Filter_64691
I
[ "matrix_mult", "matrix_power", "fibonacci" ]
3
[ [ "fibonacci", "matrix_power" ], [ "matrix_power", "matrix_mult" ] ]
2
[]
false
[]
false
pytest
false
[]
true
555f49b1f7d3e9bde1b6ed1a814c752a955b0d50
ba02096de494108317f82217923aa9cdd746179a
v1.0
instruct
Filter
Filter_64710_I
In Python, how can I determine if a word is a palindrome and if it is, find the longest palindrome in a list of words?
def is_palindrome(word): """ Checks if a given word is a palindrome. """ return word == word[::-1] def longest_palindrome(words): """ Returns the longest palindrome in a list of words. If there are multiple longest palindromes of the same length, the first one encountered in the list is...
from solution import is_palindrome, longest_palindrome def test_is_palindrome(): assert is_palindrome("madam") == True assert is_palindrome("racecar") == True assert is_palindrome("hello") == False assert is_palindrome("level") == True assert is_palindrome("world") == False def test_longest_palind...
[ { "docstring": "Checks if a given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Returns the longest palindrome in a list of words. If there are\nmultiple longest palindromes of the s...
[ 0, 1, 1 ]
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 Checks if a given word is a palindrome.\n Args:\n word (str): the word to check\n \n Returns:\n bool: True if the word is a palindrome,...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064710", "row_id": 64710, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131006']" }
0.722907
Filter_64710
I
[ "is_palindrome", "longest_palindrome" ]
2
[ [ "longest_palindrome", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d2363456cb0ec346761a4821ccd0090f1126391e
e34a687fb09f99d5fe271f1e92f449a8a0191d85
v1.0
instruct
Filter
Filter_64711_I
Write a Python code snippet that reads a list of integers from a file, calculates the average, and writes the result back to another file. The input file contains one integer per line, and the output file should contain the average as a floating-point number.
def read_integers(file_path): """ Reads a list of integers from a file, where each line contains one integer. """ with open(file_path, 'r') as file: return [int(line.strip()) for line in file] def calculate_average(integers): """ Calculates the average of a list of integers. """ ...
import os from solution import read_integers, calculate_average, write_average, process_files def test_read_integers(tmpdir): test_file = tmpdir.join("test_input.txt") test_file.write("1\n2\n3\n") assert read_integers(str(test_file)) == [1, 2, 3] def test_calculate_average(): assert calculate_average(...
[ { "docstring": "Reads a list of integers from a file, where each line contains one integer.", "function_declaration": "def read_integers(file_path):", "function_name": "read_integers", "parameter_list": "(file_path)" }, { "docstring": "Calculates the average of a list of integers.", "fun...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_average(input_file, output_file):\n \"\"\"\n Reads a list of integers from the input file, calculates the average,\n and writes the result to the output file.\n \"\"\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064711", "row_id": 64711, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131008']" }
0.676687
Filter_64711
I
[ "read_integers", "calculate_average", "write_average", "process_files" ]
4
[ [ "process_files", "calculate_average" ], [ "process_files", "read_integers" ], [ "process_files", "write_average" ] ]
3
[]
false
[]
false
pytest
true
[]
true
92c26a5096ed0310e3734b9db9d9ed4970f3692e
b9ec15b8e4d3c829490c796fbbb48475d9e246aa
v1.0
instruct
Filter
Filter_64716_I
How can I calculate the exact output of a neural network for a specific input using a forward pass in Python?
import numpy as np def sigmoid(x): """ Sigmoid activation function. """ return 1 / (1 + np.exp(-x)) def forward_pass(input_data, weights_input_hidden, bias_hidden, weights_hidden_output, bias_output): """ Perform the forward pass of the neural network. Args: - input_data (numpy array)...
import numpy as np from solution import sigmoid, forward_pass def test_sigmoid(): assert np.isclose(sigmoid(0), 0.5) assert np.isclose(sigmoid(1), 1 / (1 + np.exp(-1))) assert np.isclose(sigmoid(-1), 1 / (1 + np.exp(1))) def test_forward_pass(): input_data = np.array([1, 2]) weights_input_hidden =...
[ { "docstring": "Sigmoid activation function.", "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": "Perform the forward pass of the neural network.\n\nArgs:\n- input_data (numpy array): Input data to the network.\n- weights_input_h...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef relu(x):\n \"\"\"\n Implements the ReLU function element-wise.\n \"\"\"\n return np.maximum(0, x)\n\ndef forward_pass(input_data, weights, biases):\n \...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064716", "row_id": 64716, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131020']" }
0.525598
Filter_64716
I
[ "sigmoid", "forward_pass" ]
2
[ [ "forward_pass", "sigmoid" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
115f1db68babf14fa69c6c230149618d6084ee62
b3c12d5b3dd5f86917afffa35226cf4ce34b76af
v1.0
instruct
Filter
Filter_64731_I
I require a Python script to convert a JSON file containing nested structures into a flat CSV file. How can I achieve this?
import json import csv def flatten_json(y): """ Flatten a nested json object """ out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: ...
from solution import flatten_json, json_to_csv import os def setup_module(module): """ Setup necessary files for testing before any test functions are called. """ nested_json = [{ 'name': 'John', 'location': { 'city': 'San Francisco', 'state': 'CA' }, ...
[ { "docstring": "Flatten a nested json object", "function_declaration": "def flatten_json(y):", "function_name": "flatten_json", "parameter_list": "(y)" }, { "docstring": "Converts a nested JSON file to a flat CSV file.", "function_declaration": "def json_to_csv(json_file_path, csv_file_p...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport csv\n\ndef flatten_json(y):\n \"\"\"\n Flatten a nested json object\n \"\"\"\n out = {}\n\n def flatten(x, name=''):\n if type(x) is dict:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064731", "row_id": 64731, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131053']" }
0.639163
Filter_64731
I
[ "flatten_json", "json_to_csv" ]
2
[ [ "json_to_csv", "flatten_json" ] ]
1
[]
false
[]
false
pytest
true
[]
true
358eff67f5116141b96c65443551dae5db2afa91
5598bad7cb5cf3892f17cd440a28e3b2f25f9254
v1.0
instruct
Filter
Filter_64759_I
Can you design a Python function that can parse a JSON file and extract specific information based on a given key? For example, if I have a JSON file with nested structures, how can I retrieve all values associated with a specific key, such as "id"?
import json def extract_values(obj, key): """ Recursively find all values associated with the given key in the JSON object. Parameters: obj (dict, list, etc.): A JSON object or sub-object key (str): The key whose values are to be extracted Returns: list: A list of values associate...
from solution import extract_values, parse_json_file import tempfile import json import pytest def test_extract_values_single_level(): data = {"id": 1, "name": "Alice"} key = "id" assert extract_values(data, key) == [1] def test_extract_values_nested(): data = {"outer": {"inner": {"id": 2}}, "id": 1} ...
[ { "docstring": "Recursively find all values associated with the given key in the JSON object.\n\nParameters:\nobj (dict, list, etc.): A JSON object or sub-object\nkey (str): The key whose values are to be extracted\n\nReturns:\nlist: A list of values associated with the key", "function_declaration": "def ex...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nfrom typing import Any, List\n\ndef find_values_by_key(json_data: Any, key: str) -> List[Any]:\n \"\"\"\n Recursively find all values associated with the specified key in th...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064759", "row_id": 64759, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131106']" }
0.658385
Filter_64759
I
[ "extract_values", "parse_json_file" ]
2
[ [ "parse_json_file", "extract_values" ] ]
1
[]
false
[]
false
pytest
true
[]
true
18c4aff55fcd14f0d4acb946b8ca174e535d68bd
ae6ee28574f6a37af9446977cf5e4afa8549918a
v1.0
instruct
Filter
Filter_64764_I
Write a Python script that reads a CSV file containing a list of numbers, calculates the sum and average of these numbers, and writes the results to a new CSV file.
import csv def read_numbers_from_csv(input_file): """ Read numbers from a CSV file and return them as a list. """ numbers = [] with open(input_file, 'r') as file: reader = csv.reader(file) for row in reader: for number in row: numbers.append(float(number)...
import os from solution import calculate_sum_and_average, read_numbers_from_csv, write_results_to_csv def test_read_numbers_from_csv(tmpdir): test_file = tmpdir.join("test_input.csv") test_file.write("1,2,3\n4,5,6\n") numbers = read_numbers_from_csv(test_file) assert numbers == [1, 2, 3, 4, 5, 6] ...
[ { "docstring": "Read numbers from a CSV file and return them as a list.", "function_declaration": "def read_numbers_from_csv(input_file):", "function_name": "read_numbers_from_csv", "parameter_list": "(input_file)" }, { "docstring": "Write the sum and average of numbers to a CSV file.", ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\n\ndef read_csv_and_calculate(input_filename, output_filename):\n \"\"\"\n Reads a CSV file containing a list of numbers, calculates the sum and average of these numbers, \n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064764", "row_id": 64764, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131116']" }
0.714011
Filter_64764
I
[ "read_numbers_from_csv", "write_results_to_csv", "calculate_sum_and_average" ]
3
[ [ "calculate_sum_and_average", "read_numbers_from_csv" ], [ "calculate_sum_and_average", "write_results_to_csv" ] ]
2
[]
false
[]
false
pytest
true
[]
true
809b80dc18eb1c3b2536e839cd35c2a4810b5b0e
201d8d113eac7a209345216e970308db6ad3315b
v1.0
instruct
Filter
Filter_64775_I
How can I create a Python function to calculate the sum of all prime numbers within a given range?
def is_prime(n): """ Helper function to check if a number is a prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i...
from solution import is_prime, 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(13) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-5) == False assert is_prime(...
[ { "docstring": "Helper function to check if a number is a prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the sum of all prime numbers within the given range [start, end].", "function_declaration": "def ...
[ 1, 0, 1 ]
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 Helper function to determine if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064775", "row_id": 64775, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131143']" }
0.733313
Filter_64775
I
[ "is_prime", "sum_of_primes_in_range" ]
2
[ [ "sum_of_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8b5881c1bd5a61c26b7e5354bddd847a2f963b8a
c2ae80822c7e36271778387c10d1d9f3fda4c68d
v1.0
instruct
Filter
Filter_64832_I
How can I implement a simple event-driven framework in Python using decorators and functions to handle events?
event_handlers = {} def event(event_name): """ A decorator to register an event handler for a specific event. """ def decorator(func): if event_name not in event_handlers: event_handlers[event_name] = [] event_handlers[event_name].append(func) return func return ...
from solution import event, handle_event # Mock functions to simulate the prints import io import sys def test_on_startup(): captured_output = io.StringIO() sys.stdout = captured_output handle_event('startup') sys.stdout = sys.__stdout__ assert captured_output.getvalue().strip() == "System is star...
[ { "docstring": "A decorator to register an event handler for a specific event.", "function_declaration": "def event(event_name):", "function_name": "event", "parameter_list": "(event_name)" }, { "docstring": "Handles the given event by calling all registered handlers for that event.", "f...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class SimpleEventFramework:\n def __init__(self):\n self.event_handlers = {}\n\n def on(self, event):\n \"\"\"\n Decorator to register an event handler.\n \"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064832", "row_id": 64832, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131257']" }
0.400212
Filter_64832
I
[ "event", "handle_event", "on_startup", "on_shutdown", "on_custom_event" ]
5
[ [ "on_custom_event", "event" ], [ "on_shutdown", "event" ], [ "on_startup", "event" ] ]
3
[]
false
[]
false
pytest
true
[]
true
690b12676009952376dad85a2e2f79c7f205c05a
120da7e9f97d71c453c04a9fc33e7ca4c3ceeb55
v1.0
instruct
Filter
Filter_64879_I
Write a Python script that prints the first 20 prime numbers.
def is_prime(n): """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def first_n_primes(n): """ Returns a list of the first n prime numbers. ""...
from solution import is_prime, first_n_primes def test_is_prime(): assert is_prime(2) is True assert is_prime(3) is True assert is_prime(4) is False assert is_prime(17) is True assert is_prime(18) is False def test_first_n_primes(): assert first_n_primes(5) == [2, 3, 5, 7, 11] assert first...
[ { "docstring": "Returns True if n is a prime number, otherwise False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of the first n prime numbers.", "function_declaration": "def first_n_primes(n):", ...
[ 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 Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00064879", "row_id": 64879, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131357']" }
0.578902
Filter_64879
I
[ "is_prime", "first_n_primes" ]
2
[ [ "first_n_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f158344509cdcf8870681fb3c74a85f0b7364c0e
8ce8f54117b0a70e54d9323c6a1a86d07923d848
v1.0
instruct
Filter
Filter_64884_I
Please write a Python function that implements the heap sort algorithm on an array of integers. The function should return the array in descending order.
def heapify(arr, n, i): """ To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap. """ largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is greater ...
from solution import heap_sort def test_heap_sort_empty(): assert heap_sort([]) == [] def test_heap_sort_one_element(): assert heap_sort([1]) == [1] def test_heap_sort_sorted(): assert heap_sort([5, 4, 3, 2, 1]) == [5, 4, 3, 2, 1] def test_heap_sort_unsorted(): assert heap_sort([4, 10, 3, 5, 1]) == ...
[ { "docstring": "To heapify a subtree rooted with node i which is an index in arr[].\nn is size of heap.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Main function to sort an array of given size in descendi...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def heapify(arr, n, i):\n \"\"\"\n Helper function to maintain the heap property of a subtree rooted at index i,\n where n is the size of heap.\n \"\"\"\n largest = i\n left ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064884", "row_id": 64884, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131364']" }
0.753127
Filter_64884
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7797d61e9def1bfe65c4faa7d305520ddeba3499
ce9a1b115bb58e038f69e0efe0293f274ee019c1
v1.0
instruct
Filter
Filter_64891_I
Hey, I'm trying to generate a list of prime numbers up to 100 using a Python script. Could you help me with that?
def is_prime(n): """ Check if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n ** 0.5) + 1, 2): if n % i == 0: return False return True def generate_primes_up_to_100(): ...
from solution import is_prime, generate_primes_up_to_100 def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(97) == True assert is_prime(99) == False def test_generate_primes_up_to_100(): expected_primes = [ 2, 3, 5, 7,...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generate a list of prime numbers up to 100.", "function_declaration": "def generate_primes_up_to_100():", "function_name":...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_primes_up_to_100():\n \"\"\"\n Returns a list of prime numbers up to 100.\n \"\"\"\n primes = []\n for num in range(2, 101):\n is_prime = True\n for i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00064891", "row_id": 64891, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131375']" }
0.569447
Filter_64891
I
[ "is_prime", "generate_primes_up_to_100" ]
2
[ [ "generate_primes_up_to_100", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f9db829c7aa82cc8c791594064d776d1a5d30f0
2eebe551f85902eff206d7afa2ce275b1690c1f7
v1.0
instruct
Filter
Filter_64903_I
I have a list of numbers and I need to classify them into two categories: prime numbers and non-prime numbers. Can you provide a Python code to do that?
def is_prime(n): """ Determines if a number is prime. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def classify_numbers(numbers): ...
from solution import is_prime, classify_numbers 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(20) == False assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-5) == ...
[ { "docstring": "Determines if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Classifies a list of numbers into primes and non-primes.\n\n:param numbers: List of integers to be classified.\n:return: A tu...
[ 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 if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return Fa...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064903", "row_id": 64903, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131418']" }
0.552915
Filter_64903
I
[ "is_prime", "classify_numbers" ]
2
[ [ "classify_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c815a15b4e8d88bf031461d3652cbb24dc471015
6bc3d1ef6bfd518f2beb2a3a22b0b83df8e24174
v1.0
instruct
Filter
Filter_64908_I
Can you provide a Python script that prints the prime numbers between 1 and 100?
def is_prime(n): """ Returns True if n is a prime number, False otherwise. """ 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 pr...
from solution import is_prime, primes_between_1_and_100 def test_is_prime(): assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(1) assert not is_prime(0) assert not is_prime(-3) assert not is_prime(15) assert is_prime(17) def test_pr...
[ { "docstring": "Returns True if n is a prime number, False otherwise.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of prime numbers between 1 and 100.", "function_declaration": "def primes_between_1_a...
[ 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 Returns True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064908", "row_id": 64908, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131425']" }
0.637855
Filter_64908
I
[ "is_prime", "primes_between_1_and_100" ]
2
[ [ "primes_between_1_and_100", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
04c540cd717f5656aa7124070c73983bb92eb44b
897098c9aca3f75ee2c676f92600b682117b9615
v1.0
instruct
Filter
Filter_64992_I
How can I create a Python program that simulates a simple chat room using sockets? This chat room should allow multiple clients to connect and communicate with each other in real-time.
import socket import threading # Server code def broadcast(message, client_socket, clients): """ Send a message to all clients except the sender. """ for client in clients: if client != client_socket: try: client.send(message) except: clie...
import socket import threading import time HOST = '127.0.0.1' PORT = 12345 def start_test_server(): """ Start the chat server in a separate thread for testing. """ threading.Thread(target=start_server, args=(HOST, PORT), daemon=True).start() def test_server_accepts_client(): start_test_server() ...
[ { "docstring": "Send a message to all clients except the sender.", "function_declaration": "def broadcast(message, client_socket, clients):", "function_name": "broadcast", "parameter_list": "(message, client_socket, clients)" }, { "docstring": "Handle the individual client connection.", ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import socket\nimport threading\n\n# Server code\ndef broadcast(message, client_socket, clients):\n \"\"\"\n Send a message to all clients except the sender.\n \"\"\"\n for client ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00064992", "row_id": 64992, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131599']" }
0.556905
Filter_64992
I
[ "broadcast", "handle_client", "remove_client", "start_server" ]
4
[ [ "broadcast", "remove_client" ], [ "handle_client", "broadcast" ], [ "handle_client", "remove_client" ] ]
3
[]
false
[]
false
pytest
false
[]
true
e7ce91d1462582d51f4ba460b84993c821b562f9
22f80f60a4161550fb73f066b661e4a807e2a425
v1.0
instruct
Filter
Filter_65027_I
How can I use the `return` value in Python to handle data between functions?
def square(n): """ Returns the square of the given number. """ return n * n def add_to_square(n, add_value): """ Returns the sum of the square of n and add_value. """ squared_value = square(n) return squared_value + add_value
from solution import square, add_to_square def test_square(): assert square(2) == 4 assert square(-3) == 9 assert square(0) == 0 def test_add_to_square(): assert add_to_square(2, 3) == 7 # 2^2 + 3 = 4 + 3 assert add_to_square(-3, 4) == 13 # (-3)^2 + 4 = 9 + 4 assert add_to_square(0, 5) == 5 ...
[ { "docstring": "Returns the square of the given number.", "function_declaration": "def square(n):", "function_name": "square", "parameter_list": "(n)" }, { "docstring": "Returns the sum of the square of n and add_value.", "function_declaration": "def add_to_square(n, add_value):", "f...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def process_data(data):\n \"\"\"\n Processes the input data and returns it.\n In this example, let's assume the processing is converting the input data to uppercase.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065027", "row_id": 65027, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131684']" }
0.416642
Filter_65027
I
[ "square", "add_to_square" ]
2
[ [ "add_to_square", "square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2a650868d21d316b315b6b6ed44fe0a0e2b89979
e75fdf62b1a4ef0e8efcef3b620d887da67d18c6
v1.0
instruct
Filter
Filter_65074_I
Could you provide a Python script that simulates a simple game of rock-paper-scissors between two players?
import random def get_winner(player1, player2): """ Determines the winner of a rock-paper-scissors game between player1 and player2. Parameters: player1 (str): The choice of player 1 ('rock', 'paper' or 'scissors') player2 (str): The choice of player 2 ('rock', 'paper' or 'scissors') ...
from solution import get_winner, simulate_game import pytest def test_get_winner_tie(): assert get_winner('rock', 'rock') == 'Tie' assert get_winner('paper', 'paper') == 'Tie' assert get_winner('scissors', 'scissors') == 'Tie' def test_get_winner_player1_wins(): assert get_winner('rock', 'scissors') =...
[ { "docstring": "Determines the winner of a rock-paper-scissors game between player1 and player2.\n\nParameters:\nplayer1 (str): The choice of player 1 ('rock', 'paper' or 'scissors')\nplayer2 (str): The choice of player 2 ('rock', 'paper' or 'scissors')\n\nReturns:\nstr: 'Player 1 wins', 'Player 2 wins', or 'Ti...
[ 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(player1_choice, player2_choice):\n \"\"\"\n Determines the winner of a rock-paper-scissors game.\n \n Parameters:\n player1_choice (str): The cho...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065074", "row_id": 65074, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131766']" }
0.400273
Filter_65074
I
[ "get_winner", "simulate_game" ]
2
[ [ "simulate_game", "get_winner" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bfe7101362f7a37912619a930e388055dcc62c4e
513f30eb4307ab9eba99603fc5a2462c1c4d520d
v1.0
instruct
Filter
Filter_65103_I
Can you provide a Python example to demonstrate a simple blockchain implementation?
import hashlib import time class Block: def __init__(self, index, previous_hash, timestamp, data, hash): self.index = index self.previous_hash = previous_hash self.timestamp = timestamp self.data = data self.hash = hash def calculate_hash(index, previous_hash, timestamp, da...
from solution import Block, calculate_hash, create_genesis_block, create_block def test_create_genesis_block(): genesis_block = create_genesis_block() assert genesis_block.index == 0 assert genesis_block.previous_hash == "0" assert genesis_block.data == "Genesis Block" assert calculate_hash(0, "0",...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport time\n\nclass Block:\n def __init__(self, index, previous_hash, timestamp, data, hash):\n self.index = index\n self.previous_hash = previous_hash\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065103", "row_id": 65103, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131819']" }
0.391762
Filter_65103
I
[ "calculate_hash", "create_genesis_block", "create_block" ]
3
[ [ "create_block", "calculate_hash" ], [ "create_genesis_block", "calculate_hash" ] ]
2
[]
false
[ "Block" ]
true
pytest
true
[]
true
59f609340eb00d886f5b1527d1fbbeb4d75a855d
22739d61474fc4d8ec88ee6517b1c01e39c1c8ef
v1.0
instruct
Filter
Filter_65134_I
Construct a Python script that automates the process of downloading a zip file from a given URL and extracting it into a specified directory. The script should handle exceptions and include logging for better traceability.
import os import requests import zipfile import logging from pathlib import Path def setup_logging(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def download_and_extract_zip(url, extract_to): setup_logging() try: logging.info(f"Starting downloa...
from unittest.mock import patch, mock_open, MagicMock import pytest import os import zipfile from solution import download_and_extract_zip @patch('solution.requests.get') def test_download_and_extract_zip(mock_get): mock_response = MagicMock() mock_response.content = b'This is a test zip file' # Invalid zip ...
[ { "docstring": null, "function_declaration": "def setup_logging():", "function_name": "setup_logging", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def download_and_extract_zip(url, extract_to):", "function_name": "download_and_extract_zip", "parameter_...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport requests\nimport zipfile\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\ndef download_and_extract_zip(url, e...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065134", "row_id": 65134, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131900']" }
0.796367
Filter_65134
I
[ "setup_logging", "download_and_extract_zip" ]
2
[ [ "download_and_extract_zip", "setup_logging" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
10ddd039ec92fa5a0d9ebafc4342b2cc72888261
b8e5cf8077ec91220324e51c1f4e73385e41f585
v1.0
instruct
Filter
Filter_65156_I
Can you help me with a script to train a simple neural network using PyTorch for a classification task?
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset # Define the model class SimpleNN(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size...
import torch from solution import SimpleNN, create_and_train_model def test_model_structure(): input_size = 10 hidden_size = 5 num_classes = 3 model = SimpleNN(input_size, hidden_size, num_classes) assert isinstance(model.fc1, torch.nn.Linear), "First layer should be Linear" assert isinstance(...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "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\nfrom torch.utils.data import DataLoader, TensorDataset\n\n# Define the model\nclass SimpleNN(nn.Module):\n def __init__(sel...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065156", "row_id": 65156, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131953']" }
0.426609
Filter_65156
I
[ "train_model", "create_and_train_model" ]
2
[ [ "create_and_train_model", "train_model" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
73a8dba9e91525996a26311f6c4fa6f26ec6c9dc
1d30077948f93bfb643c02e15976a65b9d479547
v1.0
instruct
Filter
Filter_65179_I
I need help with a Python program that generates a list of random words, each word being 5 to 8 characters long, and then finds the longest common suffix among these words. How can I achieve this?
import random import string def generate_random_word(length): """ Generates a random word of given length. """ return ''.join(random.choices(string.ascii_lowercase, k=length)) def generate_random_words(n, min_length=5, max_length=8): """ Generates a list of n random words each with length betw...
from solution import generate_random_words, longest_common_suffix def test_generate_random_words(): words = generate_random_words(10) assert len(words) == 10 for word in words: assert 5 <= len(word) <= 8 def test_longest_common_suffix_with_common_suffix(): words = ["testing", "ringing", "singi...
[ { "docstring": "Generates a random word of given length.", "function_declaration": "def generate_random_word(length):", "function_name": "generate_random_word", "parameter_list": "(length)" }, { "docstring": "Generates a list of n random words each with length between min_length and max_leng...
[ 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 string\n\ndef generate_random_word(length):\n \"\"\"\n Generates a random word of given length.\n \"\"\"\n return ''.join(random.choices(string.ascii_lowercas...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065179", "row_id": 65179, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_131993']" }
0.6975
Filter_65179
I
[ "generate_random_word", "generate_random_words", "longest_common_suffix" ]
3
[ [ "generate_random_words", "generate_random_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2d3967d79dbed2a07eda22f3d13dd19dcf4b4729
1ac334af9a25ee488ec1916e5ab68c3494eda904
v1.0
instruct
Filter
Filter_65203_I
Can you help me with a Python script that creates a simple text-based adventure game? The game should have a main menu where the player can choose different paths to take, and the player's choices should lead to different outcomes. The game should be interactive and allow the player to make decisions at various points.
def main_menu(): """ Displays the main menu and prompts the player to choose a path. """ print("Welcome to the Adventure Game!") print("1. Enter the forest") print("2. Go to the village") print("3. Climb the mountain") print("4. Quit the game") choice = int(input("Choose your path (1...
import pytest from io import StringIO from unittest.mock import patch from solution import main_menu, forest_path, village_path, mountain_path def test_main_menu_choice_1(): with patch('builtins.input', return_value='1'): assert main_menu() == 1 def test_main_menu_choice_2(): with patch('builtins.inpu...
[ { "docstring": "Displays the main menu and prompts the player to choose a path.", "function_declaration": "def main_menu():", "function_name": "main_menu", "parameter_list": "()" }, { "docstring": "Simulates the forest path of the game.", "function_declaration": "def forest_path():", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def main_menu():\n print(\"Welcome to the Adventure Game!\")\n print(\"1. Enter the forest\")\n print(\"2. Cross the river\")\n print(\"3. Climb the mountain\")\n print(\"4. Exi...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065203", "row_id": 65203, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132040']" }
0.395294
Filter_65203
I
[ "main_menu", "forest_path", "village_path", "mountain_path", "adventure_game" ]
5
[ [ "adventure_game", "forest_path" ], [ "adventure_game", "main_menu" ], [ "adventure_game", "mountain_path" ], [ "adventure_game", "village_path" ] ]
4
[]
false
[]
false
pytest
true
[]
true
c6a161c9cb592e62dea640f216e5540131715049
a6aafe47806f923808eac7b2fea1cb5557bcc80e
v1.0
instruct
Filter
Filter_65206_I
Can you explain the concept of genetic algorithms and provide a simple example in Python?
import random def fitness(individual): """ Fitness function to evaluate the individual. For the example f(x) = x^2. """ x = int("".join(map(str, individual)), 2) return x ** 2 def select(population, fitnesses): """ Select an individual from the population based on their fitnesses. ...
from solution import genetic_algorithm def test_genetic_algorithm(): best_value, best_fitness = genetic_algorithm(max_generations=100, population_size=20, crossover_rate=0.8, mutation_rate=0.01) assert isinstance(best_value, int) assert isinstance(best_fitness, int) assert best_value >= 0 assert be...
[ { "docstring": "Fitness function to evaluate the individual.\nFor the example f(x) = x^2.", "function_declaration": "def fitness(individual):", "function_name": "fitness", "parameter_list": "(individual)" }, { "docstring": "Select an individual from the population based on their fitnesses.\n...
[ 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 genetic_algorithm(target, population_size, mutation_rate, generations):\n def create_individual(length):\n return [random.choice('abcdefghijklmnopqrstuvwxyz ') f...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065206", "row_id": 65206, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132046']" }
0.379968
Filter_65206
I
[ "fitness", "select", "crossover", "mutate", "genetic_algorithm" ]
5
[ [ "genetic_algorithm", "crossover" ], [ "genetic_algorithm", "fitness" ], [ "genetic_algorithm", "mutate" ], [ "genetic_algorithm", "select" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7443e340ccd0e1d79a36de77ed2d49af9ecfbedc
f6214fa702615d0308dcaeef98081b6b90e3ea44
v1.0
instruct
Filter
Filter_65228_I
How can I implement a Python program to read a CSV file using the `csv` module and handle different data types in the rows?
import csv def read_csv(file_path): """ Reads a CSV file and handles different data types in the rows. Returns a list of dictionaries with appropriate data types. """ results = [] with open(file_path, mode='r', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in ...
import os import csv import pytest from solution import read_csv def test_parse_csv_with_mixed_data_types(tmpdir): file_path = os.path.join(tmpdir, 'test.csv') with open(file_path, mode='w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['name', 'age', 'height']) ...
[ { "docstring": "Reads a CSV file and handles different data types in the rows.\nReturns a list of dictionaries with appropriate data types.", "function_declaration": "def read_csv(file_path):", "function_name": "read_csv", "parameter_list": "(file_path)" }, { "docstring": "Attempts to conver...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\n\ndef read_csv(file_path):\n \"\"\"\n Reads a CSV file and returns its contents as a list of dictionaries.\n Each row in the CSV file is converted to a dictionary where ke...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065228", "row_id": 65228, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132101']" }
0.565526
Filter_65228
I
[ "read_csv", "parse_value" ]
2
[ [ "read_csv", "parse_value" ] ]
1
[]
false
[]
false
pytest
true
[]
true
524ece6a35f8cd4c86fc7ba8c233274dc7a4134b
134e45682f46afccbe65272d419fe081e2d8fa58
v1.0
instruct
Filter
Filter_65236_I
Write a Python function that simulates a simple process termination and cleanup mechanism. The function should take a process ID (pid) and a timeout value (in seconds) as input. It should attempt to terminate the process gracefully and if it fails to terminate within the timeout period, it should forcefully kill the pr...
import os import signal import time import logging # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s') def cleanup(pid): """ Cleanup operations like removing associated temporary files and releasing resources. """ try: temp_file_path = f"/tmp/process...
import os import subprocess import pytest from solution import terminate_process def test_terminate_process_gracefully(): # Create a dummy sleep process proc = subprocess.Popen(["sleep", "10"]) pid = proc.pid assert terminate_process(pid, 5) == True assert proc.poll() is not None # Process should ...
[ { "docstring": "Cleanup operations like removing associated temporary files and releasing resources.", "function_declaration": "def cleanup(pid):", "function_name": "cleanup", "parameter_list": "(pid)" }, { "docstring": "Attempts to terminate the process with the given pid gracefully within ...
[ 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 signal\nimport time\nimport tempfile\nimport logging\n\ndef terminate_process(pid, timeout):\n \"\"\"\n Terminate the process with the given pid. Try to terminate grace...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065236", "row_id": 65236, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132122']" }
0.618813
Filter_65236
I
[ "cleanup", "terminate_process" ]
2
[ [ "terminate_process", "cleanup" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2eae891c0ed7e6b3b7cdba27dbfd1975a064323a
530b8c88ea4277beb81db9ce8149aac74ca1cdd3
v1.0
instruct
Filter
Filter_65258_I
Can you provide a Python script that simulates a dice game where two players roll a six-sided die, and the player with the higher roll wins? The game should continue until one player reaches a score of 5. The score is accumulated based on the number of wins. The script should include functions to roll the die, determin...
import random def roll_die(): """Simulates rolling a six-sided die and returns the result (1-6).""" return random.randint(1, 6) def play_round(): """Simulates a round of the dice game, returns the result for player 1 and player 2.""" player1_roll = roll_die() player2_roll = roll_die() if playe...
from solution import roll_die, play_round, play_game def test_roll_die(): result = roll_die() assert 1 <= result <= 6 def test_play_round(): player1_wins, player2_wins = play_round() assert (player1_wins == 0 and player2_wins == 0) or (player1_wins == 1 and player2_wins == 0) or (player1_wins == 0 and...
[ { "docstring": "Simulates rolling a six-sided die and returns the result (1-6).", "function_declaration": "def roll_die():", "function_name": "roll_die", "parameter_list": "()" }, { "docstring": "Simulates a round of the dice game, returns the result for player 1 and player 2.", "functio...
[ 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 roll_die():\n \"\"\"\n Simulates rolling a six-sided die and returns the result.\n \"\"\"\n return random.randint(1, 6)\n\ndef determine_winner(roll1, roll2):\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065258", "row_id": 65258, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132160']" }
0.494302
Filter_65258
I
[ "roll_die", "play_round", "play_game" ]
3
[ [ "play_game", "play_round" ], [ "play_round", "roll_die" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f7359d6c704186389fdb3c549e26c685983251a2
dee114f2b1e906567d4ea7fbbb7bb8c00a561f2e
v1.0
instruct
Filter
Filter_65291_I
Can you provide a Python program that finds the smallest palindrome greater than a given number? A palindrome is a number that reads the same backward as forward, such as 121 or 1331.
def is_palindrome(num): """ Returns True if num is a palindrome, otherwise False. """ return str(num) == str(num)[::-1] def next_palindrome(num): """ Returns the smallest palindrome greater than the given number. """ num += 1 while not is_palindrome(num): num += 1 return...
from solution import next_palindrome def test_next_palindrome_single_digit(): assert next_palindrome(5) == 6 def test_next_palindrome_direct_palindrome(): assert next_palindrome(131) == 141 def test_next_palindrome_large_gap(): assert next_palindrome(123) == 131 def test_next_palindrome_exact_palindrome...
[ { "docstring": "Returns True if num is a palindrome, otherwise False.", "function_declaration": "def is_palindrome(num):", "function_name": "is_palindrome", "parameter_list": "(num)" }, { "docstring": "Returns the smallest palindrome greater than the given number.", "function_declaration...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(num):\n \"\"\"\n Check if the given number is a palindrome.\n \"\"\"\n return str(num) == str(num)[::-1]\n\ndef next_palindrome(num):\n \"\"\"\n Find the sm...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065291", "row_id": 65291, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132213']" }
0.738164
Filter_65291
I
[ "is_palindrome", "next_palindrome" ]
2
[ [ "next_palindrome", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9af63f62a961955d89876cffbdcadb250831ea11
5c6793fa12d12eb08b8326ae8ca691e3aeb9d503
v1.0
instruct
Filter
Filter_65299_I
Write a Python script to create a web scraper that extracts data from a website's search results page. The script should handle pagination and extract product details such as name, price, and description from each page of search results. The website you will use for this example is "https://example.com/search?q=laptops...
import requests from bs4 import BeautifulSoup import csv def extract_product_details(soup): """ Extracts product details like name, price, and description from the BeautifulSoup parsed HTML. """ products = [] for product in soup.find_all('div', class_='product'): name = product.find('h2', c...
from solution import extract_product_details, scrape_search_results, save_to_csv import pytest from bs4 import BeautifulSoup def test_extract_product_details(): html = ''' <div class="product"> <h2 class="product-name">Laptop 1</h2> <span class="product-price">$1000</span> <p class="pro...
[ { "docstring": "Extracts product details like name, price, and description from the BeautifulSoup parsed HTML.", "function_declaration": "def extract_product_details(soup):", "function_name": "extract_product_details", "parameter_list": "(soup)" }, { "docstring": "Scrapes the search results ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\nfrom urllib.parse import urljoin\n\ndef scrape_search_results(base_url, query, output_file):\n \"\"\"\n Scrapes search results...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065299", "row_id": 65299, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132230']" }
0.575627
Filter_65299
I
[ "extract_product_details", "scrape_search_results", "save_to_csv", "main" ]
4
[ [ "scrape_search_results", "extract_product_details" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
520a0bb620b48f2ce78b3fda26ae62b68a6a39cf
c209d3955dd1b884be5d87e941666fbb3ac7d4b0
v1.0
instruct
Filter
Filter_65307_I
Hello, I need to write a Python script that takes a list of integers and returns the largest prime number from the list. If there are no prime numbers in the list, the script should return `None`. Can you provide a helper function to check if a number is prime and the main function to find the largest prime number in t...
def is_prime(n): """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False if n == 2: return True # 2 is the only even prime number if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False ...
from solution import is_prime, largest_prime_in_list def test_is_prime(): assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(1) assert not is_prime(0) assert not is_prime(-1) assert is_prime(13) assert not is_prime(15) def test_large...
[ { "docstring": "Returns True if n is a prime number, otherwise False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the largest prime number in the list.\nIf there is no prime number, returns None.", "functio...
[ 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 n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065307", "row_id": 65307, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132245']" }
0.681711
Filter_65307
I
[ "is_prime", "largest_prime_in_list" ]
2
[ [ "largest_prime_in_list", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0a275c7101a3c74adf9c8f67c6a3824145cbb51c
24ca581cdf0b105d91e86d507d494a38a25e1168
v1.0
instruct
Filter
Filter_65318_I
Could you provide a detailed explanation of how to implement a recurrent neural network (RNN) from scratch in Python? Implementing an RNN from scratch is quite complex. Can you provide a step-by-step guide with appropriate code examples?
import numpy as np def init_weights(input_dim, hidden_dim, output_dim): """ Initialize weights and biases. """ Whx = np.random.randn(hidden_dim, input_dim) * 0.01 # Input to hidden weights Whh = np.random.randn(hidden_dim, hidden_dim) * 0.01 # Hidden to hidden weights Why = np.random.randn(ou...
import numpy as np from solution import init_weights, rnn_step_forward, rnn_forward def test_init_weights(): Whx, Whh, Why, bh, by = init_weights(3, 2, 2) assert Whx.shape == (2, 3) assert Whh.shape == (2, 2) assert Why.shape == (2, 2) assert bh.shape == (2, 1) assert by.shape == (2, 1) def te...
[ { "docstring": "Initialize weights and biases.", "function_declaration": "def init_weights(input_dim, hidden_dim, output_dim):", "function_name": "init_weights", "parameter_list": "(input_dim, hidden_dim, output_dim)" }, { "docstring": "Perform one step of forward propagation for a single ti...
[ 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\n\ndef initialize_parameters(input_size, hidden_size, output_size):\n np.random.seed(1)\n parameters = {\n \"Wh\": np.random.randn(hidden_size, hidden_size) * 0...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065318", "row_id": 65318, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132262']" }
0.359351
Filter_65318
I
[ "init_weights", "rnn_step_forward", "rnn_forward" ]
3
[ [ "rnn_forward", "rnn_step_forward" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
a6c56c39a741762c5f98dca55925bc6d4713610c
9768b93b93f0200fa4f04bd77613f0f394abaa3a
v1.0
instruct
Filter
Filter_65330_I
Can you provide a Python function to calculate the factorial of a large number efficiently, leveraging parallel processing capabilities?
import multiprocessing import math def chunk_factorial(start, end): result = 1 for i in range(start, end + 1): result *= i return result def parallel_factorial(n, num_chunks): if n == 0: return 1 chunk_size = n // num_chunks ranges = [(i*chunk_size+1, (i+1)*chunk_size) for i in...
from solution import parallel_factorial def test_parallel_factorial_small_numbers(): assert parallel_factorial(5, 2) == 120 assert parallel_factorial(0, 2) == 1 assert parallel_factorial(1, 2) == 1 def test_parallel_factorial_medium_numbers(): assert parallel_factorial(10, 3) == 3628800 assert par...
[ { "docstring": null, "function_declaration": "def chunk_factorial(start, end):", "function_name": "chunk_factorial", "parameter_list": "(start, end)" }, { "docstring": null, "function_declaration": "def parallel_factorial(n, num_chunks):", "function_name": "parallel_factorial", "...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport math\n\ndef split_range(n, num_chunks):\n \"\"\"\n Splits the range from 1 to n into num_chunks chunks.\n \"\"\"\n step = n // num_chunks\n ran...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065330", "row_id": 65330, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132296']" }
0.598194
Filter_65330
I
[ "chunk_factorial", "parallel_factorial" ]
2
[ [ "parallel_factorial", "chunk_factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
662fa39fb54ed91cef6f9d08260b7fe028e1851f
0a0860f746a959b316c127ca8aacaad55273540c
v1.0
instruct
Filter
Filter_65336_I
Can you help me write a Python script to find duplicate files in a directory and its subdirectories?
import os import hashlib def hash_file(file_path): """Returns the SHA-1 hash of the file content.""" h = hashlib.sha1() with open(file_path, 'rb') as file: while chunk := file.read(8192): h.update(chunk) return h.hexdigest() def find_duplicate_files(directory): """Finds and ret...
import os import tempfile from solution import find_duplicate_files def create_temp_file_with_content(directory, filename, content): file_path = os.path.join(directory, filename) with open(file_path, 'w') as f: f.write(content) return file_path def test_no_duplicates(): with tempfile.Temporary...
[ { "docstring": "Returns the SHA-1 hash of the file content.", "function_declaration": "def hash_file(file_path):", "function_name": "hash_file", "parameter_list": "(file_path)" }, { "docstring": "Finds and returns a list of duplicate files in the given directory and its subdirectories.", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport hashlib\n\ndef hash_file(file_path):\n \"\"\"\n Generates a hash for a file using SHA-256.\n \"\"\"\n hasher = hashlib.sha256()\n with open(file_path, 'rb') as...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065336", "row_id": 65336, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132307']" }
0.616503
Filter_65336
I
[ "hash_file", "find_duplicate_files" ]
2
[ [ "find_duplicate_files", "hash_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bbaf423e4ff25cf2820e9723c99c23a16e30e8fc
53e316c1cac457fdae2e9685162dc02cd7734d3a
v1.0
instruct
Filter
Filter_65359_I
Can you provide a Python script to simulate a game where a player throws a ball into a basket, and the outcome depends on the player's accuracy and the wind's effect? We can assume that the player has a base accuracy of 80%, and the wind can affect the accuracy by up to 10% in either direction. The wind's effect can be...
import random def throw_ball(base_accuracy=0.8): """ Simulates a ball throw by a player, considering the wind effect. Parameters: base_accuracy (float): The player's base accuracy of throwing the ball (Default is 0.8). Returns: bool: True if the ball goes into the basket, False otherw...
from solution import throw_ball, simulate_game def test_throw_ball(): successes = 0 trials = 1000 for _ in range(trials): if throw_ball(): successes += 1 # Check if the success rate is within a reasonable range given the setup # We would expect roughly 800 successes +/...
[ { "docstring": "Simulates a ball throw by a player, considering the wind effect.\n\nParameters:\nbase_accuracy (float): The player's base accuracy of throwing the ball (Default is 0.8).\n\nReturns:\nbool: True if the ball goes into the basket, False otherwise.", "function_declaration": "def throw_ball(base_...
[ 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 throw_ball(base_accuracy=0.80, wind_effect_range=0.10):\n \"\"\"\n Simulates throwing a ball into a basket.\n \n :param base_accuracy: The base accuracy of the...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065359", "row_id": 65359, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132349']" }
0.429488
Filter_65359
I
[ "throw_ball", "simulate_game" ]
2
[ [ "simulate_game", "throw_ball" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a765d1936176d76f56fc845d80bf4de5700577e3
a717418fea9cc117d0389ae8565b8cfc89c6ddc1
v1.0
instruct
Filter
Filter_65365_I
How can I write a Python script to monitor a website's online status and generate a report every time the status changes?
import requests import time def check_website_status(url): """ Checks the status of the given website. Parameters: url (str): The URL of the website to check. Returns: bool: True if the website is accessible, False otherwise. """ try: response = requests.head(url, timeout=5) ...
from solution import check_website_status, report_status_change import pytest from unittest.mock import patch, call import requests @patch("solution.requests.head") def test_check_website_status_online(mock_head): mock_head.return_value.status_code = 200 assert check_website_status("http://example.com") == Tru...
[ { "docstring": "Checks the status of the given website.\n\nParameters:\nurl (str): The URL of the website to check.\n\nReturns:\nbool: True if the website is accessible, False otherwise.", "function_declaration": "def check_website_status(url):", "function_name": "check_website_status", "parameter_l...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom datetime import datetime\nimport time\n\ndef check_website_status(url):\n \"\"\"\n Check the status of a website.\n \n Parameters:\n url (str): The URL of ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065365", "row_id": 65365, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132363']" }
0.513546
Filter_65365
I
[ "check_website_status", "monitor_website", "report_status_change" ]
3
[ [ "monitor_website", "check_website_status" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
89948a48814b3abd8221b197661e2c64a1d9c083
816829a1af44dfc9c2999413a79b22e503da1fd8
v1.0
instruct
Filter
Filter_65376_I
How can I use the `ai_read_next_char` function to simulate typing out a sentence in Python, where it delays before reading each character?
import time def ai_read_next_char(char): """ Simulates reading a character with a delay before reading it. For demonstration, this function just prints the character with a delay. """ time.sleep(0.5) # delay for 0.5 seconds before returning the character return char def simulate_typing(s...
from solution import simulate_typing def test_simulate_typing_single_word(): sentence = "hello" expected_output = "hello" assert simulate_typing(sentence) == expected_output def test_simulate_typing_sentence(): sentence = "hello world" expected_output = "hello world" assert simulate_typing(sen...
[ { "docstring": "Simulates reading a character with a delay before reading it.\n\nFor demonstration, this function just prints the character with a delay.", "function_declaration": "def ai_read_next_char(char):", "function_name": "ai_read_next_char", "parameter_list": "(char)" }, { "docstring...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef ai_read_next_char(text, delay=0.2):\n \"\"\"\n Simulates typing out a sentence with a delay before reading each character.\n \n Parameters:\n text (str): ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065376", "row_id": 65376, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132384']" }
0.420202
Filter_65376
I
[ "ai_read_next_char", "simulate_typing" ]
2
[ [ "simulate_typing", "ai_read_next_char" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b760957b54fce45d22532d5ca23d5678a694ec13
f686bcfb05a11fbda2568f4f54fcc77d9623d7b1
v1.0
instruct
Filter
Filter_65382_I
Write a Python code to demonstrate the Caesar cipher encryption and decryption. The shift value should be 3.
def caesar_cipher_encrypt(text, shift=3): """ Encrypts the given text using a Caesar cipher with the specified shift value. """ result = "" for char in text: if char.isalpha(): stay_in_alphabet = ord('A') if char.isupper() else ord('a') result += chr((ord(char) - stay...
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("hello world") == "khoor zruog" assert caesar_cipher_encrypt("HELLO WORLD!")...
[ { "docstring": "Encrypts the given text using a Caesar cipher with the specified shift value.", "function_declaration": "def caesar_cipher_encrypt(text, shift=3):", "function_name": "caesar_cipher_encrypt", "parameter_list": "(text, shift=3)" }, { "docstring": "Decrypts the given text that w...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def caesar_encrypt(text, shift=3):\n \"\"\"\n Encrypt the text using Caesar cipher with the given shift.\n \"\"\"\n encrypted_text = []\n for char in text:\n if char.isal...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065382", "row_id": 65382, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132395']" }
0.647917
Filter_65382
I
[ "caesar_cipher_encrypt", "caesar_cipher_decrypt" ]
2
[ [ "caesar_cipher_decrypt", "caesar_cipher_encrypt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bbb5452553a93c244fc6f60d742960c1913d92f5
cad026703248762ffa90ea71cfb19896c533cb4c
v1.0
instruct
Filter
Filter_65414_I
I have a list and I want to find out which elements are prime numbers. Given a list of integers, write a Python function that identifies all the prime numbers in the list. A prime number is a number greater than 1 that has no divisors other than 1 and itself.
def is_prime(n): """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False ...
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(5) == True assert is_prime(10) == False assert is_prime(11) == True assert is_prime(1) == False assert is_prime(-7) == False ...
[ { "docstring": "Returns True if n is a prime number, otherwise False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Given a list of integers, returns a list of prime numbers from the input list.", "function_declarati...
[ 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 Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n elif n == 2:\n return True\n elif n % 2 == 0:\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065414", "row_id": 65414, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132457']" }
0.747678
Filter_65414
I
[ "is_prime", "find_primes" ]
2
[ [ "find_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2a4907ed41bbb11dd9d6fbe93e9054aea3b779d9
f2469e65c934d5cf2d4eeaecb500434a87061c61
v1.0
instruct
Filter
Filter_65427_I
Given a string `s` consisting of digits, partition the string into substrings such that each substring is a palindrome. Return all possible palindrome partitioning of `s`.
def is_palindrome(s: str) -> bool: return s == s[::-1] def partition(s: str): def dfs(start, path): if start == len(s): result.append(path) return for cut in range(start + 1, len(s) + 1): if is_palindrome(s[start:cut]): dfs(cut, path + [s[star...
from solution import partition def test_single_character(): assert partition("a") == [["a"]] def test_two_characters_palindrome(): assert partition("aa") == [["a", "a"], ["aa"]] def test_two_characters_non_palindrome(): assert partition("ab") == [["a", "b"]] def test_three_characters_palindrome(): a...
[ { "docstring": null, "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def partition(s):", "function_name": "partition", "parameter_list": "(s)" }, { "docstring": nul...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(s: str) -> bool:\n return s == s[::-1]\n\ndef partition(s: str):\n def dfs(start, path):\n if start == len(s):\n result.append(path)\n retu...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065427", "row_id": 65427, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132482']" }
0.743514
Filter_65427
I
[ "is_palindrome", "partition" ]
2
[ [ "partition", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d9013f6a15073c76e3e3faeddb5cdf5c4f57cdbe
1d69e7477d4989f33034fc215b8dc0e0e4ce0e8f
v1.0
instruct
Filter
Filter_65429_I
Could you provide a Python function that efficiently sorts a list of integers using the heap sort algorithm?
def heapify(arr, n, i): """ Helper function to convert a subtree rooted with node i into a heap. """ largest = i # Initialize largest as root left = 2 * i + 1 # left = 2*i + 1 right = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is greater than root if left ...
from solution import heap_sort def test_heap_sort_with_positive_numbers(): assert heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10] def test_heap_sort_with_negative_numbers(): assert heap_sort([-1, -10, -5, -3, 0]) == [-10, -5, -3, -1, 0] def test_heap_sort_with_mixed_numbers(): assert heap_sort([3, -2, 45...
[ { "docstring": "Helper function to convert a subtree rooted with node i into a heap.", "function_declaration": "def heapify(arr, n, i):", "function_name": "heapify", "parameter_list": "(arr, n, i)" }, { "docstring": "Main function to perform heap sort", "function_declaration": "def heap_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def heapify(arr, n, i):\n \"\"\"\n A function to heapify a subtree rooted with node i which is an index in arr.\n n is the size of the heap.\n \"\"\"\n largest = i # Initialize...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065429", "row_id": 65429, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132485']" }
0.758371
Filter_65429
I
[ "heapify", "heap_sort" ]
2
[ [ "heap_sort", "heapify" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b715edcd02449a9ed82f0d3647b6f0e1f6e51e9a
9e25fa78d3be353f18b95d9c8cc0094328a5efc7
v1.0
instruct
Filter
Filter_65458_I
Hello! I'm trying to create a Python script to implement the RSA encryption algorithm. Can you guide me through the process?
import random from sympy import mod_inverse, isprime def generate_keypair(p, q): if not (isprime(p) and isprime(q)): raise ValueError("Both numbers must be prime.") elif p == q: raise ValueError("p and q cannot be the same.") n = p * q phi = (p - 1) * (q - 1) # Choose an integer e...
from solution import generate_keypair, encrypt, decrypt def test_key_generation(): public, private = generate_keypair(17, 19) assert isinstance(public, tuple) and len(public) == 2 assert isinstance(private, tuple) and len(private) == 2 def test_encrypt_decrypt(): public, private = generate_keypair(13,...
[ { "docstring": null, "function_declaration": "def generate_keypair(p, q):", "function_name": "generate_keypair", "parameter_list": "(p, q)" }, { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nfrom sympy import mod_inverse, isprime\n\ndef generate_keypair(p, q):\n if not (isprime(p) and isprime(q)):\n raise ValueError(\"Both numbers must be prime.\")\n el...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065458", "row_id": 65458, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132555']" }
0.620466
Filter_65458
I
[ "generate_keypair", "gcd", "encrypt", "decrypt" ]
4
[ [ "generate_keypair", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
671040dfc7bc212797aca84dfad3daae2a18d99c
d3748b32bc5f5454560a3965981001a70611d7e4
v1.0
instruct
Filter
Filter_65521_I
Can you explain the concept of functions in Python and how they can be used in data manipulation?
def clean_name(name): """ Function to clean a name string by stripping extra spaces and converting it to title case. """ cleaned_name = name.strip().title() return cleaned_name def clean_names(names): """ Function to clean a list of names using the clean_name function. """ retur...
from solution import clean_name, clean_names def test_clean_name(): assert clean_name(" alice ") == "Alice" assert clean_name("BoB") == "Bob" assert clean_name(" CaroL ") == "Carol" def test_clean_names(): assert clean_names([" alice ", "BoB", " CaroL "]) == ["Alice", "Bob", "Carol"] assert clea...
[ { "docstring": "Function to clean a name string by stripping extra spaces\nand converting it to title case.", "function_declaration": "def clean_name(name):", "function_name": "clean_name", "parameter_list": "(name)" }, { "docstring": "Function to clean a list of names using the clean_name f...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def normalize_data(data):\n \"\"\"\n Normalizes a list of data values to a range between 0 and 1.\n \"\"\"\n min_val = min(data)\n max_val = max(data)\n normalized_data = [(x...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065521", "row_id": 65521, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132691']" }
0.54823
Filter_65521
I
[ "clean_name", "clean_names" ]
2
[ [ "clean_names", "clean_name" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f75e215435ff7ffcfcfc7ab1ba1406ff1f40a030
4b11816df242ceda6ee22a270962b76d3aa963ef
v1.0
instruct
Filter
Filter_65527_I
I need to create a Python function that takes two parameters, `start` and `end`, and returns a list of all prime numbers between `start` and `end` (inclusive). The function should handle cases where `start` is greater than `end` by returning an empty list. Additionally, the function should be optimized to handle large ...
def is_prime(n): """ Check if a number is a prime number. """ 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 re...
from solution import get_primes_in_range def test_primes_in_small_range(): assert get_primes_in_range(1, 10) == [2, 3, 5, 7] def test_no_primes_in_range(): assert get_primes_in_range(8, 10) == [] def test_single_prime_range(): assert get_primes_in_range(2, 2) == [2] assert get_primes_in_range(4, ...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a list of all prime numbers between 'start' and 'end' (inclusive).", "function_declaration": "def get_primes_...
[ 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 Helper function to check if a number is prime\n \"\"\"\n if n <= 1: \n return False\n if n <= 3: \n return True\n if n % 2 == 0 or n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065527", "row_id": 65527, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132704']" }
0.625549
Filter_65527
I
[ "is_prime", "get_primes_in_range" ]
2
[ [ "get_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5548f226161ba21c4cdf52ae0cca192aac197507
16ccdd3cbf9b8ea79e464caf2cb987efa5ad6ea3
v1.0
instruct
Filter
Filter_65540_I
Write a Python function that checks if any number in a provided list is a perfect cube of another number in the list. The function should return `True` if such a pair exists and `False` otherwise. Ensure your solution is self-contained, with all necessary imports included, and the code is clearly commented to explain y...
def is_perfect_cube(n): """ Checks if a number n is a perfect cube. """ if n < 0: return False cube_root = round(n ** (1/3)) return cube_root ** 3 == n def has_perfect_cube_pair(lst): """ Checks if any number in the provided list is a perfect cube of another number in the list. ...
from solution import is_perfect_cube, has_perfect_cube_pair def test_is_perfect_cube(): assert is_perfect_cube(27) == True assert is_perfect_cube(64) == True assert is_perfect_cube(26) == False assert is_perfect_cube(1) == True assert is_perfect_cube(0) == True assert is_perfect_cube(-27) == Fa...
[ { "docstring": "Checks if a number n is a perfect cube.", "function_declaration": "def is_perfect_cube(n):", "function_name": "is_perfect_cube", "parameter_list": "(n)" }, { "docstring": "Checks if any number in the provided list is a perfect cube of another number in the list.\nReturns True...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_perfect_cube(n):\n \"\"\"\n Checks if a number n is a perfect cube.\n \"\"\"\n if n < 0:\n return False\n cube_root = round(n ** (1/3))\n return cube_root ** 3 ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065540", "row_id": 65540, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132730']" }
0.74154
Filter_65540
I
[ "is_perfect_cube", "has_perfect_cube_pair" ]
2
[ [ "has_perfect_cube_pair", "is_perfect_cube" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0711abb416173afe750545eb4a707e52fe207109
cc7f50cab336c24cec0978f0428397932c09ea1b
v1.0
instruct
Filter
Filter_65606_I
Can you explain how to implement a genetic algorithm in a programming language like Python?
import random def initialize_population(pop_size, gene_length): """ Initialize a population with random integers. """ return [random.randint(0, 100) for _ in range(pop_size)] def calculate_fitness(individual): return individual ** 2 # We want to minimize this function def select_individual(popul...
from solution import initialize_population, calculate_fitness, select_individual, crossover, mutate, genetic_algorithm def test_initialize_population(): pop = initialize_population(10, 1) assert len(pop) == 10 assert all(0 <= individual <= 100 for individual in pop) def test_calculate_fitness(): asser...
[ { "docstring": "Initialize a population with random integers.", "function_declaration": "def initialize_population(pop_size, gene_length):", "function_name": "initialize_population", "parameter_list": "(pop_size, gene_length)" }, { "docstring": null, "function_declaration": "def calculat...
[ 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 initialize_population(pop_size, gene_length):\n return [[random.randint(0, 1) for _ in range(gene_length)] for _ in range(pop_size)]\n\ndef fitness(individual):\n re...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065606", "row_id": 65606, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132854']" }
0.408278
Filter_65606
I
[ "initialize_population", "calculate_fitness", "select_individual", "crossover", "mutate", "genetic_algorithm" ]
6
[ [ "genetic_algorithm", "crossover" ], [ "genetic_algorithm", "initialize_population" ], [ "genetic_algorithm", "mutate" ], [ "genetic_algorithm", "select_individual" ] ]
4
[]
false
[]
false
pytest
true
[]
true
c1e6e7beed284808f2b72f13fc67b78be3fa3ac4
46be589fe3f01b79cdfc7ff1ef805b1cdc53fb8c
v1.0
instruct
Filter
Filter_65609_I
How can I modify the given code to include a feature that calculates the average shipping cost for orders based on specific criteria, such as order weight and destination?
def calculate_shipping_cost(weight, destination): """ Calculate shipping cost based on weight and destination. """ base_cost = 5 weight_cost = weight * 0.5 if destination == 'domestic': destination_cost = 0 else: # international destination_cost = 10 total_cost = base_...
from solution import calculate_shipping_cost, average_shipping_cost def test_calculate_shipping_cost_domestic_small_weight(): assert calculate_shipping_cost(2, 'domestic') == 6 def test_calculate_shipping_cost_domestic_large_weight(): assert calculate_shipping_cost(10, 'domestic') == 10 def test_calculate_sh...
[ { "docstring": "Calculate shipping cost based on weight and destination.", "function_declaration": "def calculate_shipping_cost(weight, destination):", "function_name": "calculate_shipping_cost", "parameter_list": "(weight, destination)" }, { "docstring": "Calculate the average shipping cost...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_average_shipping_cost(orders, weight_criteria, destination_criteria):\n \"\"\"\n Calculates the average shipping cost for orders based on specific criteria: order weight an...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065609", "row_id": 65609, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132859']" }
0.379569
Filter_65609
I
[ "calculate_shipping_cost", "average_shipping_cost" ]
2
[ [ "average_shipping_cost", "calculate_shipping_cost" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5180cc5523a186100136442975d02d79ed7f8d71
836bfecf28ca5b6d3ca318175c63bee2fff94c53
v1.0
instruct
Filter
Filter_65612_I
Can you provide a Python script that lists all files in a directory along with their sizes in a human-readable format?
import os def human_readable_size(size, decimal_places=2): """ Convert a file size to a human-readable format. """ for unit in ['B', 'KB', 'MB', 'GB', 'TB']: if size < 1024: return f"{size:.{decimal_places}f} {unit}" size /= 1024 def list_files_with_sizes(directory): ""...
import pytest from solution import human_readable_size, list_files_with_sizes import os import tempfile def test_human_readable_size(): assert human_readable_size(1023) == "1023.00 B" assert human_readable_size(1024) == "1.00 KB" assert human_readable_size(1048576) == "1.00 MB" assert human_readable_si...
[ { "docstring": "Convert a file size to a human-readable format.", "function_declaration": "def human_readable_size(size, decimal_places=2):", "function_name": "human_readable_size", "parameter_list": "(size, decimal_places=2)" }, { "docstring": "List all files in the given directory along wi...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef list_files_with_sizes(directory):\n \"\"\"\n Lists all files in the given directory along with their sizes in a human-readable format.\n \n Parameters:\n direct...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065612", "row_id": 65612, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132864']" }
0.578172
Filter_65612
I
[ "human_readable_size", "list_files_with_sizes" ]
2
[ [ "list_files_with_sizes", "human_readable_size" ] ]
1
[]
false
[]
false
pytest
true
[]
true
393f04654a512b9c57188f2e09a112945536a183
e7378ce3eb37890d1a866d7c9346ab4ed24419b0
v1.0
instruct
Filter
Filter_65633_I
Is it possible to create a simple program to generate music using Python? Yes, it's possible. Can you provide a basic example of how to generate simple melodies using Python?
import numpy as np from scipy.io.wavfile import write def generate_sine_wave(frequency, duration, sample_rate=44100, amplitude=0.5): """ Generates a sine wave for given frequency, duration, and amplitude. """ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False) wave = amplitude...
import numpy as np from solution import generate_sine_wave, generate_melody, save_wave import os from scipy.io import wavfile def test_generate_sine_wave(): frequency = 440 duration = 1.0 sample_rate = 44100 amplitude = 0.5 wave = generate_sine_wave(frequency, duration, sample_rate, amplitude) ...
[ { "docstring": "Generates a sine wave for given frequency, duration, and amplitude.", "function_declaration": "def generate_sine_wave(frequency, duration, sample_rate=44100, amplitude=0.5):", "function_name": "generate_sine_wave", "parameter_list": "(frequency, duration, sample_rate=44100, amplitude...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from midiutil import MIDIFile\n\ndef create_simple_melody(filename='simple_melody.mid'):\n # Create a new MIDI file with one track\n mf = MIDIFile(1)\n\n # Define track, time, and tem...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065633", "row_id": 65633, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132896']" }
0.406579
Filter_65633
I
[ "generate_sine_wave", "generate_melody", "save_wave" ]
3
[ [ "generate_melody", "generate_sine_wave" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy" ]
false
b57eaef50b086e287c691a75c4ec8662fcfc3831
2cde8e6dc50ea1984dc79015ef1306535a62db29
v1.0
instruct
Filter
Filter_65658_I
How can I create a simple guessing game in Python that randomly selects a word and asks the user to guess letters until they can guess the word?
import random def get_random_word(words_list): """ Selects a random word from the provided list. """ return random.choice(words_list) def display_current_progress(word, guessed_letters): """ Displays the current progress of the guessed word. """ return ' '.join([letter if letter in gue...
from solution import get_random_word, display_current_progress def test_get_random_word(): words_list = ["apple", "banana", "cherry"] word = get_random_word(words_list) assert word in words_list def test_display_current_progress_initial(): assert display_current_progress("apple", set()) == "_ _ _ _ _"...
[ { "docstring": "Selects a random word from the provided list.", "function_declaration": "def get_random_word(words_list):", "function_name": "get_random_word", "parameter_list": "(words_list)" }, { "docstring": "Displays the current progress of the guessed word.", "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 random\n\ndef select_random_word(word_list):\n \"\"\"\n Selects a random word from a given list of words.\n \"\"\"\n return random.choice(word_list)\n\ndef display_word_prog...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065658", "row_id": 65658, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_132952']" }
0.542063
Filter_65658
I
[ "get_random_word", "display_current_progress", "guessing_game" ]
3
[ [ "guessing_game", "display_current_progress" ], [ "guessing_game", "get_random_word" ] ]
2
[]
false
[]
false
pytest
true
[]
true
10ed60f3d2f60ac0d8eef80d0ec63e3fe460df9d
f3b9119edcdc9ecdf530bdaf9725523a8304abf4
v1.0
instruct
Filter
Filter_65759_I
Can you assist with creating a Python script for simulating a simple dice game? The game should involve two players rolling a six-sided die and the player with the higher roll wins. If both players roll the same number, it's declared a tie. How can I implement this in Python?
import random def roll_die(): """ Simulates rolling a six-sided die. """ return random.randint(1, 6) def play_dice_game(): """ Simulates a dice game between two players. Each player rolls a die, and the player with the higher roll wins. If both players roll the same number, it is decla...
from solution import roll_die, play_dice_game def test_roll_die(): rolls = [roll_die() for _ in range(1000)] for roll in rolls: assert 1 <= roll <= 6 def test_play_dice_game(): results = [play_dice_game() for _ in range(10)] for player1_roll, player2_roll, result in results: assert 1 <...
[ { "docstring": "Simulates rolling a six-sided die.", "function_declaration": "def roll_die():", "function_name": "roll_die", "parameter_list": "()" }, { "docstring": "Simulates a dice game between two players. Each player rolls a die,\nand the player with the higher roll wins. If both player...
[ 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 roll_die():\n \"\"\"\n Simulates rolling a six-sided die and returns the result (an integer between 1 and 6).\n \"\"\"\n return random.randint(1, 6)\n\ndef dic...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065759", "row_id": 65759, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133146']" }
0.491263
Filter_65759
I
[ "roll_die", "play_dice_game" ]
2
[ [ "play_dice_game", "roll_die" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c0353f9247e55e37c374e57783b605005a738e33
3423620adb8cb539fe9caf716590dec31d2c9de9
v1.0
instruct
Filter
Filter_65766_I
Hey, can you help me with a Python function that calculates the sum of all the prime numbers within a given range [start, end]? The function should be efficient and work for relatively large ranges.
def is_prime(num): if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 return True def sum_of_primes(start, end):...
from solution import sum_of_primes def test_sum_of_primes_small_range(): assert sum_of_primes(1, 10) == 17 # primes: 2, 3, 5, 7 assert sum_of_primes(11, 19) == 60 # primes: 11, 13, 17, 19 def test_sum_of_primes_large_primes(): assert sum_of_primes(90, 100) == 97 # primes: 97 def test_sum_of_primes_lar...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def sum_of_primes(start, end):", "function_name": "sum_of_primes", "parameter_list": "(start, end)" } ]
[ 0, 1, 1 ]
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 Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065766", "row_id": 65766, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133163']" }
0.629364
Filter_65766
I
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e05ab23b5d3aef5f79f9f5b2f6ce046c8541daf
42f394527a918b14f8ce6fc47c323fe60667d3dd
v1.0
instruct
Filter
Filter_65825_I
Can you create a Python function to calculate the Mandelbrot set for a given range of complex numbers and plot it using matplotlib?
import numpy as np import matplotlib.pyplot as plt def mandelbrot(c, max_iter): """ Calculate the number of iterations for a point c in the Mandelbrot set. Args: c (complex): The complex number to check. max_iter (int): The maximum number of iterations. Returns: int: The number of...
from solution import mandelbrot, mandelbrot_set, plot_mandelbrot import numpy as np def test_mandelbrot(): assert mandelbrot(complex(0, 0), 10) == 10 assert mandelbrot(complex(1, 1), 10) < 10 assert mandelbrot(complex(-1, 0), 100) == 100 assert mandelbrot(complex(-1, 0), 1000) == 1000 def test_mandelb...
[ { "docstring": "Calculate the number of iterations for a point c in the Mandelbrot set.\n\nArgs:\nc (complex): The complex number to check.\nmax_iter (int): The maximum number of iterations.\n\nReturns:\nint: The number of iterations before the point c escapes.", "function_declaration": "def mandelbrot(c, m...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(c, max_iter):\n \"\"\"\n Determine if the given complex number c is in the Mandelbrot set.\n \n :param c: Comp...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00065825", "row_id": 65825, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133293']" }
0.470796
Filter_65825
I
[ "mandelbrot", "mandelbrot_set", "plot_mandelbrot" ]
3
[ [ "mandelbrot_set", "mandelbrot" ], [ "plot_mandelbrot", "mandelbrot_set" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
3c44e5d579e1fa4ebf84e906a2966ee1591cfde9
fffb5a3cc9b8d3f996a7d3d067c41b096bace7ce
v1.0
instruct
Filter
Filter_65836_I
Write a Python function that takes an integer `n` as input and returns a list of the first `n` prime numbers.
def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def first_n_primes(n): primes = [] num = 2 while len(primes) < n: if is_prime(num): primes.append(num) num += 1 ...
from solution import first_n_primes, is_prime def test_is_prime(): assert not is_prime(1) assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(11) def test_first_n_primes_zero(): assert first_n_primes(0) == [] def test_...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def first_n_primes(n):", "function_name": "first_n_primes", "parameter_list": "(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 if num <= 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n\ndef first_n_prim...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065836", "row_id": 65836, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133316']" }
0.736635
Filter_65836
I
[ "is_prime", "first_n_primes" ]
2
[ [ "first_n_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cb55d7778901a305c216e98722e9a91fd2cfad8c
ed48908d1eb6312f087c7725ae838ce4eac69515
v1.0
instruct
Filter
Filter_65837_I
I want to create a Python script that reads a CSV file, processes its data, and writes the results to a new CSV file. The CSV file contains columns for 'Id', 'Name', and 'Score'. The script should calculate the average score and write this information to the new file along with the original data. How can I achieve this...
import csv def read_csv(input_file_path): """ Reads the CSV file and returns the data as a list of dictionaries. """ with open(input_file_path, mode='r', newline='') as file: reader = csv.DictReader(file) data = [row for row in reader] return data def calculate_average_score(data):...
import csv import os from solution import read_csv, calculate_average_score, write_csv, process_csv def test_read_csv(tmp_path): input_csv = tmp_path / "input.csv" input_data = "Id,Name,Score\n1,John,80\n2,Jane,90\n" input_csv.write_text(input_data) expected = [ {'Id': '1', 'Name': 'John',...
[ { "docstring": "Reads the CSV file and returns the data as a list of dictionaries.", "function_declaration": "def read_csv(input_file_path):", "function_name": "read_csv", "parameter_list": "(input_file_path)" }, { "docstring": "Calculates the average score from the score data in the list of...
[ 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 process_csv(input_file, output_file):\n \"\"\"\n Reads data from 'input_file', calculates the average score, and writes the original data\n along with the average sc...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065837", "row_id": 65837, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133321']" }
0.715655
Filter_65837
I
[ "read_csv", "calculate_average_score", "write_csv", "process_csv" ]
4
[ [ "process_csv", "calculate_average_score" ], [ "process_csv", "read_csv" ], [ "process_csv", "write_csv" ] ]
3
[]
false
[]
false
pytest
true
[]
true
ef07cb6de1fce935ffb376b8e222d8e795a9c9e9
39a50032e115b8c5a4adc011aaaeb160113efe8e
v1.0
instruct
Filter
Filter_65841_I
Write a Python function that creates a binary tree and performs a post-order traversal on it. The function should take a list of integers as input where each integer represents a node value. The function should return a list of integers representing the nodes in post-order traversal. Assume the input list represents a ...
class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def create_tree_from_list(values): if not values: return None nodes = [TreeNode(value) for value in values] root = nodes[0] for i in range(len(...
from solution import post_order_from_list def test_post_order_from_list_empty(): assert post_order_from_list([]) == [] def test_post_order_from_list_single_node(): assert post_order_from_list([1]) == [1] def test_post_order_from_list_two_nodes(): assert post_order_from_list([1, 2]) == [2, 1] def test_po...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef create_complete_binary_tree(elements):\n if not elements:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065841", "row_id": 65841, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133326']" }
0.531007
Filter_65841
I
[ "create_tree_from_list", "post_order_traversal", "post_order_from_list" ]
3
[ [ "post_order_from_list", "create_tree_from_list" ], [ "post_order_from_list", "post_order_traversal" ] ]
2
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
896c69fb2b530e4837dababf0d15a5d9bb155693
e967190aaea7ffbfadc2a85062e668e52512a499
v1.0
instruct
Filter
Filter_65857_I
Write a Python script to simulate a simple dice rolling game where the user can choose to roll the dice or exit the game. The game should display the result of the dice roll and keep track of the total rolls made. If the user enters 'q' or 'quit', the game should terminate and display the total number of rolls.
import random def roll_dice(): """ Returns a randomly generated dice value between 1 and 6. """ return random.randint(1, 6) def dice_game(): """ Simulates a dice rolling game where the user can roll the dice or exit the game. Tracks and displays the total number of rolls. """ total...
from solution import roll_dice, dice_game import pytest from unittest.mock import patch, MagicMock def test_roll_dice(): roll_value = roll_dice() assert 1 <= roll_value <= 6 @patch('builtins.input', side_effect=['r', 'r', 'q']) @patch('builtins.print') def test_dice_game(mock_print, mock_input): dice_game...
[ { "docstring": "Returns a randomly generated dice value between 1 and 6.", "function_declaration": "def roll_dice():", "function_name": "roll_dice", "parameter_list": "()" }, { "docstring": "Simulates a dice rolling game where the user can roll the dice or exit the game.\nTracks and displays...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Returns a randomly generated dice value between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef dice_game():\n \"\"\"\n Si...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065857", "row_id": 65857, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133355']" }
0.557671
Filter_65857
I
[ "roll_dice", "dice_game" ]
2
[ [ "dice_game", "roll_dice" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e3db5aba793b70a46a716d70655142e3bb63ed00
f99f7adb190725e61055e856957f532ae3d2f5bd
v1.0
instruct
Filter
Filter_65884_I
How can I compare the contents of two.zip files without extracting them in Python?
import zipfile import hashlib def hash_file_content(file_obj): hash_md5 = hashlib.md5() for chunk in iter(lambda: file_obj.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def compare_zip_contents(zip_path1, zip_path2): with zipfile.ZipFile(zip_path1, 'r') as zip1, zipfile....
import zipfile import os from solution import compare_zip_contents def create_zip_file(file_name, file_contents_dict): with zipfile.ZipFile(file_name, 'w') as zip_file: for inner_file_name, content in file_contents_dict.items(): zip_file.writestr(inner_file_name, content) def test_compare_iden...
[ { "docstring": null, "function_declaration": "def hash_file_content(file_obj):", "function_name": "hash_file_content", "parameter_list": "(file_obj)" }, { "docstring": null, "function_declaration": "def compare_zip_contents(zip_path1, zip_path2):", "function_name": "compare_zip_conte...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import zipfile\n\ndef compare_zip_files(zip_file1: str, zip_file2: str) -> bool:\n \"\"\"\n Compare the contents of two zip files to check if they are identical.\n \n Parameters:\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065884", "row_id": 65884, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133408']" }
0.656588
Filter_65884
I
[ "hash_file_content", "compare_zip_contents" ]
2
[ [ "compare_zip_contents", "hash_file_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4f633fce35b118c7136563471d71fd69cebd7729
a10c08c787dab034f607ca0342c7e8201aaaf09a
v1.0
instruct
Filter
Filter_65902_I
Write a Python function to find the nth prime number. The function should handle edge cases and be efficient enough for large values of n.
def is_prime(num): """ Helper function to check if a number is prime. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while (i * i) <= num: if num % i == 0 or num % (i + 2) == 0: return...
from solution import nth_prime def test_nth_prime_first(): assert nth_prime(1) == 2 def test_nth_prime_second(): assert nth_prime(2) == 3 def test_nth_prime_sixth(): assert nth_prime(6) == 13 def test_nth_prime_invalid_input(): try: nth_prime(0) except ValueError as e: assert str...
[ { "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 nth prime number.", "function_declaration": "def nth_prime(n):", "function_name": "nth_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 ==...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00065902", "row_id": 65902, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133450']" }
0.702701
Filter_65902
I
[ "is_prime", "nth_prime" ]
2
[ [ "nth_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dac842da8f14e670609bcefd5ac2265e6702b57f
2d26505600ecc2dd725da28dc1dbead4e3a43979
v1.0
instruct
Filter
Filter_65908_I
I need to create a Python function to determine the number of prime numbers within a given range [a, b], where a <= b. How can I do this?
def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def count_primes_in_range(a, b): """ R...
from solution import is_prime, count_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(1) == False assert is_prime(0) == False assert is_prime(-1) == False assert is_prime(17)...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the count of prime numbers within the range [a, b], inclusive.", "function_declaration": "def count_primes_in_range(a, b):", "function_name...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 o...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065908", "row_id": 65908, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133467']" }
0.806936
Filter_65908
I
[ "is_prime", "count_primes_in_range" ]
2
[ [ "count_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a6a6c269f6bb3339c036521b2d2379638cc40f02
fa3dbf5752d1c9cb0957eb5d3e6e43ae23c7667b
v1.0
instruct
Filter
Filter_65909_I
How can I write a Python function to print numbers from 1 to 100 without using any loops or recursion?
def print_numbers(num=1): if num > 100: return print(num) print_numbers(num + 1) # As an alternative, here is a method using functools.partial for better function reusability from functools import partial def print_number_sequence(): print_numbers_from_1 = partial(print_numbers, 1) print_n...
from io import StringIO import sys from solution import print_number_sequence def test_print_numbers_output(): # Redirect standard output original_stdout = sys.stdout sys.stdout = StringIO() print_number_sequence() # Get standard output contents output = sys.stdout.getvalue().strip()...
[ { "docstring": null, "function_declaration": "def print_numbers(num=1):", "function_name": "print_numbers", "parameter_list": "(num=1)" }, { "docstring": null, "function_declaration": "def print_number_sequence():", "function_name": "print_number_sequence", "parameter_list": "()"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def print_numbers():\n \"\"\"\n Prints numbers from 1 to 100 without using loops or recursion.\n \"\"\"\n print((range(1, 101)))", "test_code": "import builtins\nfrom io import...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065909", "row_id": 65909, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133468']" }
0.620877
Filter_65909
I
[ "print_numbers", "print_number_sequence" ]
2
[ [ "print_number_sequence", "print_numbers" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a1108375274d4b493077f3abf5e78de6a7b5d799
611f0cc9840400e01e9ac90e26308b66082d897f
v1.0
instruct
Filter
Filter_65912_I
Can you provide a Python code snippet to extract GPS coordinates from a JPEG image file using the Exif data?
from PIL import Image from PIL.ExifTags import TAGS, GPSTAGS def get_exif_data(image): exif_data = {} info = image._getexif() if info is not None: for tag, value in info.items(): decoded = TAGS.get(tag, tag) exif_data[decoded] = value return exif_data def get_lat_lon(ex...
import pytest from PIL import Image from unittest.mock import MagicMock, patch from solution import extract_gps_coordinates, get_lat_lon, convert_to_degress def test_convert_to_degress(): value = [(100, 1), (30, 1), (15, 1)] assert convert_to_degress(value) == pytest.approx(100.504167, 0.000001) def test_get_...
[ { "docstring": null, "function_declaration": "def get_exif_data(image):", "function_name": "get_exif_data", "parameter_list": "(image)" }, { "docstring": null, "function_declaration": "def get_lat_lon(exif_data):", "function_name": "get_lat_lon", "parameter_list": "(exif_data)" ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from PIL import Image\nfrom PIL.ExifTags import TAGS, GPSTAGS\n\ndef get_exif_data(image):\n \"\"\" \n Extract the EXIF data from an image and return it as a dictionary.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00065912", "row_id": 65912, "seed_ids": "['Qwen2.5-Coder-32B-Instruct_133477']" }
0.395256
Filter_65912
I
[ "get_exif_data", "get_lat_lon", "convert_to_degress", "extract_gps_coordinates" ]
4
[ [ "extract_gps_coordinates", "get_exif_data" ], [ "extract_gps_coordinates", "get_lat_lon" ], [ "get_lat_lon", "convert_to_degress" ] ]
3
[]
false
[]
false
pytest
true
[ "PIL" ]
false
7e4e1890daf826f9f99768ecd3ba6bb56eda1e25
5738381a20bd81fd6e8eb63cbd09ef098093f235