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_67679_I | How can I use the `queue` module in Python to implement a FIFO queue for processing tasks in a multi-threaded environment? | import threading
import queue
import time
# Function that simulates processing a task
def process_task(task):
print(f"Processing task: {task}")
time.sleep(1)
print(f"Task {task} completed")
# Worker function that processes tasks from the queue
def worker(task_queue):
while True:
task = task_qu... | import threading
import queue
import time
from solution import process_task, worker, setup_queue_and_workers
def test_process_task(capsys):
output = []
def mock_print(msg):
output.append(msg)
import builtins
original_print = builtins.print
builtins.print = mock_print
try:
... | [
{
"docstring": null,
"function_declaration": "def process_task(task):",
"function_name": "process_task",
"parameter_list": "(task)"
},
{
"docstring": null,
"function_declaration": "def worker(task_queue):",
"function_name": "worker",
"parameter_list": "(task_queue)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import queue\nimport threading\nimport time\n\ndef worker(task_queue):\n while not task_queue.empty():\n task = task_queue.get()\n print(f\"Processing task: {task}\")\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067679",
"row_id": 67679,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137091']"
} | 0.511519 | Filter_67679 | I | [
"process_task",
"worker",
"setup_queue_and_workers"
] | 3 | [
[
"worker",
"process_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5810d9a4727ed906384ee45e61952f34ccf63341 | e7346fe98c27c9d52e7d9891396c1ec08d9ff1a7 | |||
v1.0 | instruct | Filter | Filter_67718_I | Write a Python function that takes an integer `n` as input and returns a list of the first `n` prime numbers. The function should be well-documented and include a docstring explaining its purpose, parameters, and return value. Additionally, include a check function that verifies the correctness of the prime number gene... | def generate_primes(n):
"""
Returns a list of the first n prime numbers.
Parameters:
n (int): The number of prime numbers to generate.
Returns:
list: A list containing the first n prime numbers.
"""
def is_prime(num):
if num <= 1:
return False
if num == 2:
... | from solution import generate_primes, check_prime_generation
def test_generate_primes():
assert generate_primes(0) == []
assert generate_primes(1) == [2]
assert generate_primes(5) == [2, 3, 5, 7, 11]
def test_check_prime_generation_correct():
known_primes_5 = [2, 3, 5, 7, 11]
assert check_prime_ge... | [
{
"docstring": "Returns a list of the first n prime numbers.\n\nParameters:\nn (int): The number of prime numbers to generate.\n\nReturns:\nlist: A list containing the first n prime numbers.",
"function_declaration": "def generate_primes(n):",
"function_name": "generate_primes",
"parameter_list": "(... | [
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 for i in range(2, int(num**0.5) + 1):\n if nu... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067718",
"row_id": 67718,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137169']"
} | 0.685949 | Filter_67718 | I | [
"generate_primes",
"check_prime_generation"
] | 2 | [
[
"check_prime_generation",
"generate_primes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c60159f44a186963e59bd811dc42e1f495055c38 | 3528aedf964db95f3ce7f2eebeef738990aa4d30 | |||
v1.0 | instruct | Filter | Filter_67727_I | I want to create a simple game where players can choose between rock, paper, and scissors. How can I implement this game in Python? | import random
def get_computer_choice():
"""
Randomly selects between 'rock', 'paper', and 'scissors'.
"""
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of the game.
Returns 'win' if... | import pytest
from solution import get_computer_choice, determine_winner, play_game
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
assert get_computer_choice() in choices
def test_determine_winner():
assert determine_winner('rock', 'scissors') == 'win'
assert determine_winner(... | [
{
"docstring": "Randomly selects between 'rock', 'paper', and 'scissors'.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of the game.\nReturns 'win' if the player wins, 'lose' if ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly returns 'rock', 'paper', or 'scissors'.\n \"\"\"\n return random.choice(['rock', 'paper', 'scissors'])\n\ndef determ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067727",
"row_id": 67727,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137188']"
} | 0.378964 | Filter_67727 | I | [
"get_computer_choice",
"determine_winner",
"play_game"
] | 3 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9f38ea9639087ff3c592db16f269553fb5b74260 | c4af35b1f01f2b0046c24903abfba955813cd79c | |||
v1.0 | instruct | Filter | Filter_67736_I | Can you provide a Python code to implement a simple genetic algorithm for solving the OneMax problem? | import random
def one_max_fitness(individual):
"""
Fitness function for the OneMax problem. Returns the sum of all bits.
"""
return sum(individual)
def generate_individual(length):
"""
Generates a random individual of given length.
"""
return [random.randint(0, 1) for _ in range(length... | from solution import one_max_fitness, generate_individual, crossover, mutate, select_parent, genetic_algorithm
def test_one_max_fitness():
assert one_max_fitness([0, 0, 0, 0]) == 0
assert one_max_fitness([1, 1, 1, 1]) == 4
assert one_max_fitness([1, 0, 1, 0]) == 2
def test_generate_individual():
indiv... | [
{
"docstring": "Fitness function for the OneMax problem. Returns the sum of all bits.",
"function_declaration": "def one_max_fitness(individual):",
"function_name": "one_max_fitness",
"parameter_list": "(individual)"
},
{
"docstring": "Generates a random individual of given length.",
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_individual(length):\n \"\"\" Generates an individual with binary genes of given length. \"\"\"\n return [random.randint(0, 1) for _ in range(length)]\n\ndef... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067736",
"row_id": 67736,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137214']"
} | 0.442988 | Filter_67736 | I | [
"one_max_fitness",
"generate_individual",
"crossover",
"mutate",
"select_parent",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"generate_individual"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"one_max_fitness"
],
[
"genetic_algorithm",
"select_parent"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 5c8a05a386c27daaace56381570d866e9bc533d0 | fa57ac8908cfc6e1845015c9ba65c0ad2f87dc1a | |||
v1.0 | instruct | Filter | Filter_67744_I | How can I generate a 2D plot of a double pendulum simulation using Python? | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
def double_pendulum_ode(t, y, L1, L2, m1, m2, g):
theta1, z1, theta2, z2 = y
c, s = np.cos(theta1 - theta2), np.sin(theta1 - theta2)
theta1dot = z1
theta2dot = z2
z1dot = (m2 * g * np.sin(theta2) * c ... | import numpy as np
from solution import simulate_double_pendulum, plot_double_pendulum
def test_simulate_double_pendulum_basic():
L1, L2, m1, m2, g = 1.0, 1.0, 1.0, 1.0, 9.81
theta1_0, theta2_0, z1_0, z2_0 = np.pi / 2, np.pi / 2, 0.0, 0.0
t_span = (0, 2)
t, y = simulate_double_pendulum(L1, L2, m1, m2, ... | [
{
"docstring": null,
"function_declaration": "def double_pendulum_ode(t, y, L1, L2, m1, m2, g):",
"function_name": "double_pendulum_ode",
"parameter_list": "(t, y, L1, L2, m1, m2, g)"
},
{
"docstring": null,
"function_declaration": "def simulate_double_pendulum(L1, L2, m1, m2, g, theta1_... | [
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\nfrom scipy.integrate import odeint\n\ndef double_pendulum_derivs(state, t, L1, L2, m1, m2, g):\n theta1, z1, theta2, z2 = state\n del... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067744",
"row_id": 67744,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137226']"
} | 0.496539 | Filter_67744 | I | [
"double_pendulum_ode",
"simulate_double_pendulum",
"plot_double_pendulum"
] | 3 | [
[
"simulate_double_pendulum",
"double_pendulum_ode"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 01e788ae50071857a6b2137eb826b636e049e769 | 268fb274fcae56bb3f483d82eb3f57c6ef760a0a | |||
v1.0 | instruct | Filter | Filter_67768_I | Hi Qwen, I have a question about Python. I'm trying to create a program that simulates a simple lottery game where a user can guess three numbers between 1 and 10, and the program then draws three winning numbers. The user wins if at least two of their guessed numbers match the winning numbers. How can I implement this... | import random
def draw_lottery_numbers():
"""
Draws three random lottery numbers between 1 and 10.
Returns a list of three integers.
"""
return random.sample(range(1, 11), 3)
def check_winning(user_numbers, lottery_numbers):
"""
Checks if at least two numbers in user_numbers match any numb... | from solution import draw_lottery_numbers, check_winning, simulate_lottery
def test_draw_lottery_numbers():
numbers = draw_lottery_numbers()
assert len(numbers) == 3
assert all(1 <= num <= 10 for num in numbers)
assert len(set(numbers)) == 3
def test_check_winning():
# Test case where user wins
... | [
{
"docstring": "Draws three random lottery numbers between 1 and 10.\nReturns a list of three integers.",
"function_declaration": "def draw_lottery_numbers():",
"function_name": "draw_lottery_numbers",
"parameter_list": "()"
},
{
"docstring": "Checks if at least two numbers in user_numbers m... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef simulate_lottery(user_guesses):\n \"\"\"\n Simulates a lottery game where user guesses three numbers between 1 and 10.\n The program draws three winning numbers. ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067768",
"row_id": 67768,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137258']"
} | 0.477414 | Filter_67768 | I | [
"draw_lottery_numbers",
"check_winning",
"simulate_lottery"
] | 3 | [
[
"simulate_lottery",
"check_winning"
],
[
"simulate_lottery",
"draw_lottery_numbers"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7dceec2bdaaa9c08466b847b4d10432ad1427d73 | ffd9752bf21308547259f47b87af014ae11a0b83 | |||
v1.0 | instruct | Filter | Filter_67782_I | How can I modify the code to allow for batch parsing of multiple files in a directory instead of processing a single file at a time? | import os
def process_file(filepath):
"""
Process a single file.
Arguments:
filepath -- the path to the file to be processed
"""
with open(filepath, 'r') as file:
data = file.read()
# Process the data here
print(f"Processed data from {filepath}: {data}")
def process_fil... | import os
import pytest
from solution import process_file, process_files_in_directory
# Helper function to create a temporary file for testing
def create_test_file(directory, filename, content):
filepath = os.path.join(directory, filename)
with open(filepath, 'w') as file:
file.write(content)
retur... | [
{
"docstring": "Process a single file.\nArguments:\nfilepath -- the path to the file to be processed",
"function_declaration": "def process_file(filepath):",
"function_name": "process_file",
"parameter_list": "(filepath)"
},
{
"docstring": "Process all files in the given directory.\nArgument... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport glob\n\ndef process_file(file_path):\n \"\"\"\n Processes a single file and returns the result.\n Replace this with the actual processing logic.\n \"\"\"\n wit... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067782",
"row_id": 67782,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137284']"
} | 0.462672 | Filter_67782 | I | [
"process_file",
"process_files_in_directory"
] | 2 | [
[
"process_files_in_directory",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c4452a5b67168659a0cb6236f90eac71329d138 | 89d78ff199d671aef21d19a6358fdc7e0f56d4f9 | |||
v1.0 | instruct | Filter | Filter_67806_I | Can you provide a detailed explanation of how to implement a neural network from scratch in Python? Implementing a neural network from scratch can be a great way to understand the workings of these models. It typically involves defining the architecture, forward propagation, loss computation, backpropagation, and optim... | import numpy as np
def sigmoid(z):
"""
Compute the sigmoid of z.
"""
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(z):
"""
Compute the derivative of the sigmoid function.
"""
return sigmoid(z) * (1 - sigmoid(z))
class NeuralNetwork:
def __init__(self, input_size, hidden_size,... | import numpy as np
from solution import NeuralNetwork
def test_forward_pass():
nn = NeuralNetwork(2, 3, 1, 0.01)
X = np.array([[0.5, 0.8]])
output = nn.forward(X)
assert output.shape == (1, 1)
def test_compute_loss():
nn = NeuralNetwork(2, 3, 1, 0.01)
Y = np.array([[1]])
Y_hat = np.array([... | [] | [
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\nclass SimpleNeuralNetwork:\n def __init__(self, input_size, hidden_size, output_size):\n # Initialize weights and biases\n self.W1 = np.random.randn(inpu... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067806",
"row_id": 67806,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137335']"
} | 0.411467 | Filter_67806 | I | [
"sigmoid",
"sigmoid_derivative"
] | 2 | [
[
"sigmoid_derivative",
"sigmoid"
]
] | 1 | [] | false | [
"NeuralNetwork"
] | true | pytest | true | [
"numpy"
] | false | f200a4fdd2df0b0b53fa2ca5224dc69c2f52893a | 6b540f40ace7765d30307878198ac782a56cecf1 | |||
v1.0 | instruct | Filter | Filter_67812_I | I have a Python dictionary with nested dictionaries, and I want to print all keys in a flattened format. For example, if my dictionary is `{'a': {'b': {'c': 1}}}`, the output should be `a.b.c`. How can I achieve this? | def flatten_dict(d, parent_key='', sep='.'):
"""
Flattens a nested dictionary, joining keys with a separator.
Args:
d (dict): Dictionary to flatten.
parent_key (str): Base key string used for recursion.
sep (str): Separator for flattening keys.
Returns:
dict: A dictionary with flattene... | from solution import get_flat_keys, flatten_dict
def test_single_level_dict():
d = {'a': 1, 'b': 2, 'c': 3}
assert get_flat_keys(d) == ['a', 'b', 'c']
def test_two_level_dict():
d = {'a': {'b': 1}}
assert get_flat_keys(d) == ['a.b']
def test_three_level_dict():
d = {'a': {'b': {'c': 1}}}
asse... | [
{
"docstring": "Flattens a nested dictionary, joining keys with a separator.\n\nArgs:\nd (dict): Dictionary to flatten.\nparent_key (str): Base key string used for recursion.\nsep (str): Separator for flattening keys.\n\nReturns:\ndict: A dictionary with flattened keys.",
"function_declaration": "def flatte... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flatten_keys(d, parent_key='', sep='.'):\n \"\"\"\n Flattens dictionary keys with nested dictionaries.\n \n Args:\n d: The dictionary to flatten.\n parent_key: The base k... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067812",
"row_id": 67812,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137347']"
} | 0.537835 | Filter_67812 | I | [
"flatten_dict",
"get_flat_keys"
] | 2 | [
[
"get_flat_keys",
"flatten_dict"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 703359860c9c8c2a29403623169e5dd371eb4b46 | 5acc1a12663ab70c52a05286949916b8d921afc3 | |||
v1.0 | instruct | Filter | Filter_67839_I | Write a Python function to convert a doubly linked list to a balanced binary search tree (BST). The number of nodes in the doubly linked list is odd. The middle element of the list should be the root of the BST, the left half of the list should form the left subtree, and the right half should form the right subtree. Th... | class ListNode:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def find_middle_and_split_list(head):
slow = head
fast = head... | from solution import ListNode, TreeNode, sorted_list_to_bst
def is_balanced(root):
def height(node):
if not node:
return 0
left_height = height(node.left)
right_height = height(node.right)
if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1:... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, prev=None, next=None):\n self.val = val\n self.prev = prev\n self.next = next\n\nclass TreeNode:\n def __init__(self, val... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067839",
"row_id": 67839,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137391']"
} | 0.643306 | Filter_67839 | I | [
"find_middle_and_split_list",
"sorted_list_to_bst"
] | 2 | [
[
"sorted_list_to_bst",
"find_middle_and_split_list"
]
] | 1 | [] | false | [
"ListNode",
"TreeNode"
] | true | pytest | true | [] | true | ee8561cf32c8a2ed92786b8bbba67100deb2a856 | f7c9173302e9ea6fb564908f3234e3762e878bc4 | |||
v1.0 | instruct | Filter | Filter_67855_I | I need help with Python programming. Can you guide me on how to create a simple program that reads numbers from a file, calculates the sum, and then writes the result to another file? | def read_numbers(file_path):
"""
Reads numbers from a file and returns them as a list of integers.
"""
with open(file_path, 'r') as file:
numbers = [int(line.strip()) for line in file]
return numbers
def write_sum(file_path, total):
"""
Writes the sum of numbers to a file.
"""
... | from solution import read_numbers, write_sum, calculate_sum, process_files
import os
def create_temp_input_file(file_path, numbers):
with open(file_path, 'w') as file:
for number in numbers:
file.write(f"{number}\n")
def test_read_numbers():
input_file_path = 'temp_input.txt'
numbers =... | [
{
"docstring": "Reads numbers from a file and returns them as a list of integers.",
"function_declaration": "def read_numbers(file_path):",
"function_name": "read_numbers",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes the sum of numbers to a file.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_numbers_from_file(file_path):\n \"\"\"\n Reads numbers from a file and returns them as a list of integers.\n :param file_path: Path to the file to read numbers from\n :ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067855",
"row_id": 67855,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137429']"
} | 0.531681 | Filter_67855 | I | [
"read_numbers",
"write_sum",
"calculate_sum",
"process_files"
] | 4 | [
[
"process_files",
"calculate_sum"
],
[
"process_files",
"read_numbers"
],
[
"process_files",
"write_sum"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c5259e5b887abf80309dfdfbab6543e7d8f04f7e | 96876de637c3694b2388937ffdb483179fab3e61 | |||
v1.0 | instruct | Filter | Filter_67886_I | How can I implement a simple game of Rock Paper Scissors using different programming paradigms? | import random
def get_computer_choice():
"""
Returns a random choice from 'rock', 'paper', 'scissors'.
"""
return random.choice(['rock', 'paper', 'scissors'])
def get_winner(player_choice, computer_choice):
"""
Determines the winner between player's choice and computer's choice.
Returns 'p... | import pytest
from solution import get_computer_choice, get_winner, rock_paper_scissors
def test_get_computer_choice():
choice = get_computer_choice()
assert choice in ['rock', 'paper', 'scissors']
def test_get_winner():
assert get_winner('rock', 'rock') == 'tie'
assert get_winner('rock', 'paper') == ... | [
{
"docstring": "Returns a random choice from 'rock', 'paper', 'scissors'.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner between player's choice and computer's choice.\nReturns 'p... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass RockPaperScissors:\n def __init__(self):\n self.choices = [\"rock\", \"paper\", \"scissors\"]\n\n def get_computer_choice(self):\n return random.choi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067886",
"row_id": 67886,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137494']"
} | 0.411844 | Filter_67886 | I | [
"get_computer_choice",
"get_winner",
"rock_paper_scissors"
] | 3 | [
[
"rock_paper_scissors",
"get_computer_choice"
],
[
"rock_paper_scissors",
"get_winner"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9ffc1b264278bf52518b034f0c46ecae02d24cd4 | 07a8ecc0eb2c2366d21359e8337061ff14cce291 | |||
v1.0 | instruct | Filter | Filter_67903_I | Can you provide a simple example of how to use the PyTorch library in Python to train a neural network on a basic dataset? | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Define a simple neural network
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(2, 3)
self.fc2 = nn.Linear(3, 1)
d... | from solution import SimpleNN, generate_data, train_model, predict
def test_model_structure():
model = SimpleNN()
assert len(list(model.parameters())) == 4
assert isinstance(model.fc1, nn.Linear)
assert isinstance(model.fc2, nn.Linear)
def test_generate_data():
X, y = generate_data()
assert X.... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"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 a simple neural network\nclass SimpleNN(nn.Module):\n de... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067903",
"row_id": 67903,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137530']"
} | 0.279834 | Filter_67903 | I | [
"generate_data",
"train_model",
"predict"
] | 3 | [
[
"train_model",
"generate_data"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 12d26d58c80420f22bc17e7f7dc491276289bebe | cd30e58a1494c850088218afd119e159c5b3f1b5 | |||
v1.0 | instruct | Filter | Filter_67908_I | Write a Python decorator that can handle functions with and without arguments, and also supports passing arguments to the decorator itself. | import functools
def decorator_with_args(decorator_arg1, decorator_arg2):
def decorator(func):
@functools.wraps(func)
def wrapped_function(*args, **kwargs):
print(f"Decorator args: {decorator_arg1}, {decorator_arg2}")
print(f"Function args: {args}, {kwargs}")
res... | from solution import greeting, add, no_arg_function
def test_greeting():
assert greeting("Alice") == "Hello, Alice!"
def test_add():
assert add(3, 4) == 7
assert add(-1, 1) == 0
def test_no_arg_function():
assert no_arg_function() == "Function with no arguments" | [
{
"docstring": null,
"function_declaration": "def decorator_with_args(decorator_arg1, decorator_arg2):",
"function_name": "decorator_with_args",
"parameter_list": "(decorator_arg1, decorator_arg2)"
},
{
"docstring": null,
"function_declaration": "def greeting(name):",
"function_name"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\ndef decorator_with_args(decorator_arg1=None, decorator_arg2=None):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067908",
"row_id": 67908,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137540']"
} | 0.564798 | Filter_67908 | I | [
"decorator_with_args",
"greeting",
"add",
"no_arg_function"
] | 4 | [
[
"add",
"decorator_with_args"
],
[
"greeting",
"decorator_with_args"
],
[
"no_arg_function",
"decorator_with_args"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 11510d03194e844df6164d541623118838fdd354 | 6c695fddbb18c6a63b5c212eecd64f6b43400403 | |||
v1.0 | instruct | Filter | Filter_67936_I | Write a Python function that takes a dictionary representing a JSON object as input and returns a new dictionary with the same key-value pairs, but with all string values converted from snake_case to camelCase. The function should handle nested dictionaries and lists as well. | def snake_to_camel(snake_str):
"""
Helper function to convert a snake_case string to camelCase.
"""
components = snake_str.split('_')
return components[0] + ''.join(x.title() for x in components[1:])
def convert_dict_key_to_camel_case(d):
"""
Function to convert all string keys in a nested ... | from solution import convert_dict_key_to_camel_case
def test_simple_conversion():
input_data = {"first_name": "John", "last_name": "Doe"}
expected_output = {"firstName": "John", "lastName": "Doe"}
assert convert_dict_key_to_camel_case(input_data) == expected_output
def test_nested_dict_conversion():
i... | [
{
"docstring": "Helper function to convert a snake_case string to camelCase.",
"function_declaration": "def snake_to_camel(snake_str):",
"function_name": "snake_to_camel",
"parameter_list": "(snake_str)"
},
{
"docstring": "Function to convert all string keys in a nested dictionary from snake... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def to_camel_case(snake_str):\n components = snake_str.split('_')\n return components[0] + ''.join(x.title() for x in components[1:])\n\ndef convert_dict_to_camel_case(d):\n if isinst... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067936",
"row_id": 67936,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137608']"
} | 0.631847 | Filter_67936 | I | [
"snake_to_camel",
"convert_dict_key_to_camel_case"
] | 2 | [
[
"convert_dict_key_to_camel_case",
"snake_to_camel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3eb33539db71a7542aef59169b87ae7c65e00026 | 701edeaa4f47caa0b32058fc4909c39d622daf12 | |||
v1.0 | instruct | Filter | Filter_68001_I | Can you provide a Python code to print the first 10 prime numbers? | def is_prime(n):
"""
Checks if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True # 2 is the only even prime number
if n % 2 == 0:
return False
max_divisor = int(n**0.5) + 1
for divisor in range(3, max_divisor, 2):
if n % divisor == 0:
... | from solution import is_prime, first_n_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(13) == True
def test_first_n_primes():
assert first_n_primes(1) == [2... | [
{
"docstring": "Checks if a number is prime.",
"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):",
"function_name": "first_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n re... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068001",
"row_id": 68001,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137726']"
} | 0.616716 | Filter_68001 | I | [
"is_prime",
"first_n_primes",
"print_first_10_primes"
] | 3 | [
[
"first_n_primes",
"is_prime"
],
[
"print_first_10_primes",
"first_n_primes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e66e82d184a1a06c25b9f3f63842b155ada80131 | 9ed22fd5000382e8644fd9ac8112241f98677abd | |||
v1.0 | instruct | Filter | Filter_68055_I | Hello! Could you help me with a programming problem? I need to create a function that takes a string and returns the longest palindromic substring in that string. Can you guide me through the solution? | def longest_palindromic_substring(s):
"""
Returns the longest palindromic substring in the given string s.
"""
if not s:
return ""
start, end = 0, 0
for i in range(len(s)):
len1 = expand_around_center(s, i, i) # Case: odd length palindrome
len2 = expand_aroun... | from solution import longest_palindromic_substring
def test_longest_palindromic_substring():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
assert longest_palindromic_substring("cbbd") == "bb"
assert longest_palindromic_substring("a") == "a"
assert longest_palindromic_substring("") == ... | [
{
"docstring": "Returns the longest palindromic substring in the given string s.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_list": "(s)"
},
{
"docstring": "Expands around center and returns the length of the... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s):\n \"\"\"\n Returns the longest palindromic substring in the given string.\n \"\"\"\n n = len(s)\n if n <= 1:\n return s\n \n s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068055",
"row_id": 68055,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137845']"
} | 0.860846 | Filter_68055 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97f12517c70e691c9537290b08ccfa10b4086a34 | 055d6a8747c4c466f3df141ca1cc75d14073fda4 | |||
v1.0 | instruct | Filter | Filter_68088_I | Can you explain the concept of "Purely Functional Programming" and provide a simple example in Python? | def add(a, b):
"""
Returns the sum of a and b. This is a purely functional function
as it does not change any state or have any side effects.
"""
return a + b
def multiply(a, b):
"""
Returns the product of a and b. This is a purely functional function
as it does not change any state or ... | from solution import add, multiply, sum_and_product
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_with_zero():
assert add(0, 5) == 5
assert add(5, 0) == 5
def test_add_negative_numbers():
assert add(-1, -1) == -2
def test_add_mixed_sign_numbers():
assert add(-1, 3) == 2
de... | [
{
"docstring": "Returns the sum of a and b. This is a purely functional function\nas it does not change any state or have any side effects.",
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the product of a and b. This i... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def purely_functional_add(a, b):\n \"\"\"\n Purely functional addition of a and b, meaning the function\n does not cause any side effects and always returns the same \n output for ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068088",
"row_id": 68088,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137902']"
} | 0.532903 | Filter_68088 | I | [
"add",
"multiply",
"sum_and_product"
] | 3 | [
[
"sum_and_product",
"add"
],
[
"sum_and_product",
"multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 701971073ffd7487be99a7ffb80fbe441ca87696 | 576db7ba9fe8f094615a5298149e6bbc2187a164 | |||
v1.0 | instruct | Filter | Filter_68150_I | Write a Python function `sum_of_primes(limit)` that calculates the sum of all prime numbers up to a given limit (inclusive). The function should take an integer `limit` as its parameter and return the sum of all prime numbers up to and including that limit. | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +... | from solution import sum_of_primes
def test_sum_of_primes_limit_10():
assert sum_of_primes(10) == 17 # Primes: 2, 3, 5, 7
def test_sum_of_primes_limit_1():
assert sum_of_primes(1) == 0 # No primes <= 1
def test_sum_of_primes_limit_20():
assert sum_of_primes(20) == 77 # Primes: 2, 3, 5, 7, 11, 13, 17, ... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers up to and including the limit.",
"function_declaration": "def sum_of_p... | [
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 determine 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:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068150",
"row_id": 68150,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138028']"
} | 0.634896 | Filter_68150 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9cf66d13ee05b2ae8be99c6b042fb904e3ecd391 | 504630f2b0ea5e8e4fcfba63824b7381d70178ca | |||
v1.0 | instruct | Filter | Filter_68152_I | Write a Python script that implements the Caesar Cipher encryption and decryption methods. The script should be able to handle both uppercase and lowercase letters, and it should ignore non-alphabetic characters. | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the given text using Caesar Cipher with the specified shift.
Parameters:
text (str): The input text to be encrypted.
shift (int): The number of positions to shift each character.
Returns:
str: The encrypted text.
"""
encr... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("Hello, World!", 3) == "Khoor, Zruog!"
assert caesar_cipher_encrypt("abcXYZ", 3) == "defABC"
assert caesar_cipher_encrypt("Python 3.8", 5) == "Udymts 3.8"
assert caesar_ciphe... | [
{
"docstring": "Encrypts the given text using Caesar Cipher with the specified shift.\n\nParameters:\ntext (str): The input text to be encrypted.\nshift (int): The number of positions to shift each character.\n\nReturns:\nstr: The encrypted text.",
"function_declaration": "def caesar_cipher_encrypt(text, sh... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encrypt(text, shift):\n \"\"\"\n Encrypts the text using Caesar Cipher with a given shift.\n \n :param text: String to be encrypted\n :param shift: Integer val... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068152",
"row_id": 68152,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138036']"
} | 0.655567 | Filter_68152 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 373cff77a8a8d1224acf53345f26b9966c14565f | 9d63bf1e39dd77317c1146fc93bd5ed9f2c439d7 | |||
v1.0 | instruct | Filter | Filter_68171_I | Could you provide a Python function that checks if a given number is a prime number and another function to find all prime numbers within a given range? | def is_prime(n):
"""
Check if the number n is a prime number.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = ... | from solution import is_prime, primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5) == F... | [
{
"docstring": "Check if the number n is a prime number.\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a l... | [
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 :param n: The number to check.\n :return: True if n is a prime number, False otherwise.\n \"\"\"\n if... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068171",
"row_id": 68171,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138078']"
} | 0.698633 | Filter_68171 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c1f6356e512d33e648d2d664b20a328299311482 | b47e69e24e0ba9426fc9fa9ea06f4217178c4431 | |||
v1.0 | instruct | Filter | Filter_68243_I | How can I implement a custom hook in my Python application to modify the behavior of specific functions based on certain conditions? | from functools import wraps
def custom_hook(hook):
"""
A decorator that applies a hook function before executing the main function.
Args:
hook (callable): A function to be called before executing the main function.
It should accept the same arguments as the main function.
... | from solution import custom_hook
# Creating a Hook function to be used in tests
def test_hook(*args, **kwargs):
test_hook.was_called = True
test_hook.arguments = args
test_hook.kwargs = kwargs
test_hook.was_called = False
@custom_hook(test_hook)
def sample_function(a, b, c=3):
return a + b + c
def te... | [
{
"docstring": "A decorator that applies a hook function before executing the main function.\n\nArgs:\nhook (callable): A function to be called before executing the main function. \n It should accept the same arguments as the main function.",
"function_declaration": "def custom_hook(hook):",... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_hook(condition):\n \"\"\"\n A custom hook decorator that modifies the behavior of the function based on the condition.\n \"\"\"\n def decorator(func):\n def wrapp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068243",
"row_id": 68243,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138221']"
} | 0.433981 | Filter_68243 | I | [
"custom_hook",
"condition_hook",
"my_function"
] | 3 | [
[
"my_function",
"condition_hook"
],
[
"my_function",
"custom_hook"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | bf7e4f63a7082b0be051ada811c8b5301bf9c977 | b0c2f0b1d8d9cbbd8f8c05f25747477b497e3278 | |||
v1.0 | instruct | Filter | Filter_68264_I | Write a comprehensive Python script that can count the frequency of words in a given text file. The script should handle common punctuation and stop words, and it should output the word frequency in descending order. Additionally, the script should be able to handle large files efficiently. | import re
from collections import Counter
import string
STOP_WORDS = set([
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'was', 'were', 'will', 'with'
])
def process_text(text):
"""
Processes the input text, remo... | from solution import process_text, count_word_frequency
def test_process_text():
text = "This is a simple example. This example is simple!"
expected_output = ['this', 'simple', 'example', 'this', 'example', 'simple']
assert process_text(text) == expected_output
def test_process_text_with_punctuation():
... | [
{
"docstring": "Processes the input text, removes punctuation, converts to lowercase, and removes stop words.",
"function_declaration": "def process_text(text):",
"function_name": "process_text",
"parameter_list": "(text)"
},
{
"docstring": "Counts the frequency of words in a given text file... | [
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 Counter\nimport string\n\nSTOP_WORDS = set([\n 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he', \n 'in', 'is', 'it', 'its',... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068264",
"row_id": 68264,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138263']"
} | 0.782494 | Filter_68264 | I | [
"process_text",
"count_word_frequency"
] | 2 | [
[
"count_word_frequency",
"process_text"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a07477960ad31353cc054c02168e3efa3073e331 | be2da0875bfd9d7ffd12d2b350cb8d25b95f6a42 | |||
v1.0 | instruct | Filter | Filter_68278_I | Write a Python code snippet to simulate a simple dice game where two players roll two dice each and the player with the highest total wins. If the totals are equal, it's a draw. | import random
def roll_dice():
return random.randint(1, 6) + random.randint(1, 6)
def dice_game():
player1_score = roll_dice()
player2_score = roll_dice()
if player1_score > player2_score:
return "Player 1 wins"
elif player2_score > player1_score:
return "Player 2 wins"
el... | from solution import dice_game, roll_dice
def test_roll_dice():
for _ in range(1000): # Test multiple times to cover range
roll = roll_dice()
assert 2 <= roll <= 12
def test_dice_game():
# Since the dice game involves randomness, we cannot assert sequential
# outcomes, but we can ... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def dice_game():",
"function_name": "dice_game",
"parameter_list": "()"
}
] | [
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 return random.randint(1, 6) + random.randint(1, 6)\n\ndef dice_game():\n player1_score = roll_dice()\n player2_score = roll_dice()\n \n if pl... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068278",
"row_id": 68278,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138294']"
} | 0.485271 | Filter_68278 | I | [
"roll_dice",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1bc4ed7502020f499b8f393c9f405634f01731b1 | 98970c01c0c15c001c7fa807b172fcdf82260705 | |||
v1.0 | instruct | Filter | Filter_68281_I | I want to balance the weights of a model using PyTorch, especially in a multi-class classification problem where some classes are heavily underrepresented. To address this issue, I can use weighted cross-entropy loss. How can I implement this in PyTorch for a multi-class classification problem? | import torch
import torch.nn as nn
def calculate_class_weights(labels, num_classes):
"""
Calculate class weights based on the frequency of labels.
Parameters:
- labels: torch.Tensor, a tensor containing the labels of the data.
- num_classes: int, the number of unique classes.
Returns:... | import torch
from solution import calculate_class_weights, get_weighted_loss_fn
def test_calculate_class_weights():
labels = torch.tensor([0, 1, 1, 2, 2, 2])
num_classes = 3
class_weights = calculate_class_weights(labels, num_classes)
assert torch.isclose(class_weights, torch.tensor([2.0, 1.0, 0.6... | [] | [
0,
1,
1
] | 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\n\ndef calculate_class_weights(labels, num_classes):\n \"\"\"\n Calculate the weights for each class based on the frequency of the labels.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068281",
"row_id": 68281,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138299']"
} | 0.283537 | Filter_68281 | I | [
"calculate_class_weights",
"get_weighted_loss_fn"
] | 2 | [
[
"get_weighted_loss_fn",
"calculate_class_weights"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 632b524a0845f8bbb286fca2127ec4e583d4926e | b365cab4932871841841749bb96138782af7f8cf | |||
v1.0 | instruct | Filter | Filter_68283_I | What is the best way to create a simple, secure, and privacy-friendly RSS feed reader in Python? | import requests
import xml.etree.ElementTree as ET
def fetch_rss_feed(url):
"""
Fetch the RSS feed from the given URL and return the parsed elements.
"""
response = requests.get(url, timeout=10)
response.raise_for_status()
return ET.fromstring(response.content)
def get_feed_titles(feed):
... | import requests
import xml.etree.ElementTree as ET
from solution import rss_reader, fetch_rss_feed, get_feed_titles
def test_fetch_rss_feed(monkeypatch):
class MockResponse:
def __init__(self, content):
self.content = content
self.status_code = 200
def raise_for_status(self... | [
{
"docstring": "Fetch the RSS feed from the given URL and return the parsed elements.",
"function_declaration": "def fetch_rss_feed(url):",
"function_name": "fetch_rss_feed",
"parameter_list": "(url)"
},
{
"docstring": "Extract and return the titles from the RSS feed.",
"function_declara... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import feedparser\n\ndef fetch_rss_feed(url):\n \"\"\"\n Fetches and parses the RSS feed from the given URL.\n \n Args:\n url (str): The URL of the RSS feed.\n \n Returns:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068283",
"row_id": 68283,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138303']"
} | 0.339708 | Filter_68283 | I | [
"fetch_rss_feed",
"get_feed_titles",
"rss_reader"
] | 3 | [
[
"rss_reader",
"fetch_rss_feed"
],
[
"rss_reader",
"get_feed_titles"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 8452a123fa716724a85968d827f72fddd14f4d39 | 53047c244ba8cba7c017c66f922e4b8d432bde08 | |||
v1.0 | instruct | Filter | Filter_68307_I | Write a Python function to solve the equation \(x^2 - 15 = 0\) using the bisection method. The function should return the root of the equation up to a precision of 1e-9. | def bisection_method(a, b, function, accuracy=1e-9):
"""
Solves for the root of the function using the bisection method.
Args:
a (float): lower boundary of the interval
b (float): upper boundary of the interval
function (callable): function for which the root is being solved
accuracy (float)... | from solution import bisection_method, equation, solve_equation_x2_minus_15
def test_bisection_method():
assert abs(bisection_method(0, 5, equation) - 3.872983346207417) < 1e-9
def test_equation():
assert equation(3.872983346207417) < 1e-9
def test_solve_equation_x2_minus_15():
root = solve_equation_x2_m... | [
{
"docstring": "Solves for the root of the function using the bisection method.\nArgs:\na (float): lower boundary of the interval\nb (float): upper boundary of the interval\nfunction (callable): function for which the root is being solved\naccuracy (float): desired accuracy, default is 1e-9\n\nReturns:\nfloat: ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bisection_method(f, a, b, tolerance=1e-9, max_iterations=1000):\n \"\"\"\n Uses the bisection method to find a root of the function f in the interval [a, b].\n \n Parameters:\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068307",
"row_id": 68307,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138352']"
} | 0.487133 | Filter_68307 | I | [
"bisection_method",
"equation",
"solve_equation_x2_minus_15"
] | 3 | [
[
"solve_equation_x2_minus_15",
"bisection_method"
],
[
"solve_equation_x2_minus_15",
"equation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e58ea58a0e4fe1a75f5fae3d96fe75decef5df61 | 6e1d7ea3bae60019d58e60c4701cff843e2778de | |||
v1.0 | instruct | Filter | Filter_68314_I | I need to create a Python script that monitors and alerts when a specific process is not running on a Windows system. How can I achieve this? | import subprocess
def is_process_running(process_name):
"""Check if there is any running process that contains the given name process_name."""
try:
# Using tasklist command to get the list of all running processes
tasks = subprocess.check_output(['tasklist'], shell=True).decode()
return... | from solution import is_process_running, alert_process_not_running
import subprocess
def test_is_process_running():
# Mocking successful process presence
subprocess.check_output = lambda cmd, shell: b"notepad.exe"
assert is_process_running("notepad.exe") == True
# Mocking process absence
subpr... | [
{
"docstring": "Check if there is any running process that contains the given name process_name.",
"function_declaration": "def is_process_running(process_name):",
"function_name": "is_process_running",
"parameter_list": "(process_name)"
},
{
"docstring": "Checks if the process is running an... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef is_process_running(process_name):\n \"\"\"\n Check if there is any running process that contains the given name... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068314",
"row_id": 68314,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138370']"
} | 0.684693 | Filter_68314 | I | [
"is_process_running",
"alert_process_not_running"
] | 2 | [
[
"alert_process_not_running",
"is_process_running"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 461e1c962e45a19ae47ac5569e0f63d1a3442585 | c323f9b3b03e8ce74f1aeb64b9982e9e7decd6b5 | |||
v1.0 | instruct | Filter | Filter_68325_I | Write a Python script to list all files in a given directory, including subdirectories, and print their sizes in a human-readable format. | import os
def list_files_with_sizes(directory):
"""
List all files in the given directory, including subdirectories,
and print their sizes in a human-readable format.
"""
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
... | import os
import pytest
from solution import list_files_with_sizes, readable_file_size
def test_readable_file_size():
assert readable_file_size(500) == "500.00 B"
assert readable_file_size(1024) == "1.00 KB"
assert readable_file_size(1048576) == "1.00 MB"
assert readable_file_size(1073741824) == "1.00 ... | [
{
"docstring": "List all files in the given directory, including subdirectories,\nand print their sizes in a human-readable format.",
"function_declaration": "def list_files_with_sizes(directory):",
"function_name": "list_files_with_sizes",
"parameter_list": "(directory)"
},
{
"docstring": "... | [
1,
0,
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 List all files in the given directory, including subdirectories,\n and print their sizes in a human-readable format.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068325",
"row_id": 68325,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138394']"
} | 0.602628 | Filter_68325 | I | [
"list_files_with_sizes",
"readable_file_size"
] | 2 | [
[
"list_files_with_sizes",
"readable_file_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cbb1dbef06de5f345cd39409997741ac514fbc31 | 40e381d4585739b42421aea976d1132e03417660 | |||
v1.0 | instruct | Filter | Filter_68339_I | Can you provide a Python code snippet that demonstrates how to convert a list of temperatures from Celsius to Fahrenheit and then apply a function to filter out temperatures above a certain threshold in Fahrenheit? Convert the following list of temperatures in Celsius: `[25, 30, 15, 10, 0, -15, -20]` and filter out tem... | def celsius_to_fahrenheit(celsius):
"""
Converts a temperature from Celsius to Fahrenheit.
"""
return celsius * 9/5 + 32
def filter_temperatures_above_threshold(temps, threshold):
"""
Filters out temperatures above the given threshold in Fahrenheit.
"""
return [temp for temp in temps if... | from solution import celsius_to_fahrenheit, filter_temperatures_above_threshold, convert_and_filter
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(25) == 77
assert celsius_to_fahrenheit(-40) == -40
assert celsius_to_fahrenheit(100) == 212
def test_... | [
{
"docstring": "Converts a temperature from Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Filters out temperatures above the given threshold in Fahrenheit.",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius_temps):\n \"\"\"\n Converts a list of temperatures from Celsius to Fahrenheit.\n \"\"\"\n return [(temp * 9/5) + 32 for temp in celsius_temps]\n\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068339",
"row_id": 68339,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138428']"
} | 0.529067 | Filter_68339 | I | [
"celsius_to_fahrenheit",
"filter_temperatures_above_threshold",
"convert_and_filter"
] | 3 | [
[
"convert_and_filter",
"celsius_to_fahrenheit"
],
[
"convert_and_filter",
"filter_temperatures_above_threshold"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | af0e37dc07aef17bff9eee2a636c52df2ddcd103 | b8d27279f3a29d13f3aa8501f6234b20146bcf0a | |||
v1.0 | instruct | Filter | Filter_68355_I | Can you explain how to create a Python function that checks if the length of a list is a prime number? | def is_prime(n):
"""
Checks if a number is prime.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def is_length_prime(lst):
"""
Checks if the length of lst is a prime number.
"""
return is_prime(... | from solution import is_prime, is_length_prime
def test_is_prime_with_prime_numbers():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(11) == True
def test_is_prime_with_non_prime_numbers():
assert is_prime(1) == False
assert is_prime(0) == Fals... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Checks if the length of lst is a prime number.",
"function_declaration": "def is_length_prime(lst):",
"function_name": "i... | [
1,
1
] | 2 | 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 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 r... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068355",
"row_id": 68355,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138463']"
} | 0.824967 | Filter_68355 | I | [
"is_prime",
"is_length_prime"
] | 2 | [
[
"is_length_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 48be349f1c194ea6ab8c31ee00a5f76075934f60 | 86591c79d8a854ffee340d2f491c69f357f3127b | |||
v1.0 | instruct | Filter | Filter_68360_I | Can you provide a Python script that checks if the user's system requirements are met before running a software application? This script should check for Python version, necessary packages, and required OS. | import sys
import platform
import importlib.util
def check_python_version(required_version=(3, 6)):
current_version = sys.version_info
if current_version >= required_version:
return True
else:
return False
def check_required_packages(packages):
missing_packages = []
for package in ... | from solution import system_requirements_check
def test_check_python_version():
result = system_requirements_check(
required_version=(3, 6)
)
assert result['python_version_ok'] == True
def test_check_missing_packages():
result = system_requirements_check(
packages=['nonexistentpackage1... | [
{
"docstring": null,
"function_declaration": "def check_python_version(required_version=(3, 6)):",
"function_name": "check_python_version",
"parameter_list": "(required_version=(3, 6))"
},
{
"docstring": null,
"function_declaration": "def check_required_packages(packages):",
"functio... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport platform\nimport pkg_resources\n\ndef check_system_requirements(required_python, required_packages, required_os):\n # Check Python version\n if sys.version_info < requ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068360",
"row_id": 68360,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138476']"
} | 0.525542 | Filter_68360 | I | [
"check_python_version",
"check_required_packages",
"check_required_os",
"system_requirements_check"
] | 4 | [
[
"system_requirements_check",
"check_python_version"
],
[
"system_requirements_check",
"check_required_os"
],
[
"system_requirements_check",
"check_required_packages"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 058e94c1cd78d5a2889ccce976428ad9d5ab6fe6 | a78d5ca1b443cb51cf1af112db0dadac50b5e0d7 | |||
v1.0 | instruct | Filter | Filter_68366_I | Can you generate a Python script that calculates the sum of all prime numbers within a given range? The script should include a function that checks if a number is prime and another function that calculates the sum of primes in the specified range. Additionally, the script should handle input validation to ensure the r... | def is_prime(n):
"""
Checks 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 sum_of_primes(start, end):
... | 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(10) == False
assert is_prime(11) == True
def test_sum_of_primes():
assert sum_of_primes(1, 10) == 1... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within the given range [start, end].",
"function_declaration": "def sum_of_primes(start,... | [
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 Check 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 False\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068366",
"row_id": 68366,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138488']"
} | 0.610708 | Filter_68366 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b4b5e8c33600c3272a5699bb94050502fe0b80c9 | 528eb0e414daad1ec478c80125ec8f17c81e858d | |||
v1.0 | instruct | Filter | Filter_68370_I | Can you provide a Python code snippet that simulates a simple dice roll game where a player can roll a dice until they reach a total score of 20 or more? The game should prompt the user to press 'Enter' to roll the dice and display the result of each roll along with the total score. The game should end when the player ... | import random
def roll_dice():
"""
Simulates rolling a dice, returns a random integer between 1 and 6.
"""
return random.randint(1, 6)
def play_game(target_score=20):
"""
Simulates a dice roll game where the player rolls a dice until they reach a total score of 20 or more.
Player is prompt... | from solution import roll_dice, play_game
def test_roll_dice_within_range():
roll = roll_dice()
assert 1 <= roll <= 6
def test_play_game_reaches_target(monkeypatch):
inputs = ['\n', '\n', '\n', '\n', '\n'] # Simulate the player pressing 'Enter'
iterator = iter(inputs)
# Simulating user input... | [
{
"docstring": "Simulates rolling a dice, returns a random integer between 1 and 6.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a dice roll game where the player rolls a dice until they reach a total score of... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a dice, returns a random integer between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_game(target_scor... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068370",
"row_id": 68370,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138494']"
} | 0.502705 | Filter_68370 | I | [
"roll_dice",
"play_game"
] | 2 | [
[
"play_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0ab6e8eaf0ad391e1322ee909aa3c7510f339e93 | 5ce33e2b449d78c308186736d54887d8c194fe4f | |||
v1.0 | instruct | Filter | Filter_68470_I | Can you provide a Python code snippet that demonstrates how to check if a number is prime and print all prime numbers less than a given number `n`? | def is_prime(num):
"""
Check if a number is prime.
:param num: an integer to check for primality.
:return: True if num is prime, False otherwise.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.... | from solution import is_prime, print_primes_less_than
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(-5) == False
def test_print_prim... | [
{
"docstring": "Check if a number is prime.\n:param num: an integer to check for primality.\n:return: True if num is prime, False otherwise.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Print all prime numbers less ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068470",
"row_id": 68470,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138720']"
} | 0.74846 | Filter_68470 | I | [
"is_prime",
"print_primes_less_than"
] | 2 | [
[
"print_primes_less_than",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8477add8db88f98f6d8a6fabfc8cd1332091548e | 3c0357d5a8df42f3c900cc89db0fd7669a815c03 | |||
v1.0 | instruct | Filter | Filter_68495_I | Write a Python program that asks the user to input a number and then checks if the number is a prime number. A prime number is a number that is only divisible by 1 and itself. The program should continue to prompt the user until a valid number is entered and then output whether the number is prime or not. | def is_prime(n):
"""
Determines if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
retu... | from solution import is_prime
def test_is_prime_prime_numbers():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(7) == True
assert is_prime(11) == True
assert is_prime(13) == True
def test_is_prime_non_prime_numbers():
assert is_prime(1) == ... | [
{
"docstring": "Determines if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Continuously prompts the user for input until a valid number is entered,\nthen checks if the number is prime and outputs th... | [
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 n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068495",
"row_id": 68495,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138780']"
} | 0.785163 | Filter_68495 | I | [
"is_prime",
"check_prime_input"
] | 2 | [
[
"check_prime_input",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 764b29dedfe5af9843a55366b419a4576bfc0cef | d42ca1d3638fc4fd66f22c11e944a6821045ae68 | |||
v1.0 | instruct | Filter | Filter_68499_I | Hello, I'm trying to implement a simple RSA encryption algorithm in Python. I've chosen two prime numbers, 17 and 23, and I want to use a public exponent of 3. However, I'm having trouble finding the correct private key. Can you help me with the steps to compute it? | def egcd(a, b):
"""
Extended Euclidean Algorithm to solve for gcd and coefficients.
"""
if a == 0:
return b, 0, 1
g, x, y = egcd(b % a, a)
return g, y - (b // a) * x, x
def modinv(a, m):
"""
Modular Inverse using Extended Euclidean Algorithm.
"""
g, x, _ = egcd(a, m)
... | def test_modinv():
p = 17
q = 23
e = 3
n = p * q
phi_n = (p - 1) * (q - 1)
# Calculate d using the provided solution code
d = modinv(e, phi_n)
# Verify that e * d % phi_n == 1
assert (e * d) % phi_n == 1
def test_egcd():
a = 3
m = 352
# Calculate gcd and coefficients... | [
{
"docstring": "Extended Euclidean Algorithm to solve for gcd and coefficients.",
"function_declaration": "def egcd(a, b):",
"function_name": "egcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Modular Inverse using Extended Euclidean Algorithm.",
"function_declaration": "def modinv(a,... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extended_gcd(a, b):\n \"\"\"\n Extended Euclidean Algorithm to find the gcd and coefficients x and y such that ax + by = gcd(a, b)\n \"\"\"\n if a == 0:\n return b, 0, 1... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068499",
"row_id": 68499,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138790']"
} | 0.557122 | Filter_68499 | I | [
"egcd",
"modinv"
] | 2 | [
[
"modinv",
"egcd"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 477f21bb5eb00fb0b65e381ee7fe5c2d7fb71f49 | 1ba0615b2ff8e7a6cebe00e3088a433954c68aec | |||
v1.0 | instruct | Filter | Filter_68532_I | Hey, I need to create a Python implementation for the Kirkpatrick and Stoll’s Algorithm. Could you provide a detailed explanation and the code for it? Kirkpatrick and Stoll’s Algorithm is used for efficient closest-pair computations in the plane. It's a classic algorithm in computational geometry. | import math
def closest_pair(points):
if len(points) < 2:
return float('inf'), None, None
points_by_x = sorted(points, key=lambda p: p[0])
points_by_y = sorted(points, key=lambda p: p[1])
return closest_pair_rec(points_by_x, points_by_y)
def closest_pair_rec(points_by_x, points_by_y)... | def test_closest_pair():
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
expected_distance = math.sqrt((3 - 2) ** 2 + (4 - 3) ** 2)
distance, p1, p2 = closest_pair(points)
assert distance == expected_distance
assert set([p1, p2]) == set([(2, 3), (3, 4)])
def test_closest_pair_single... | [
{
"docstring": null,
"function_declaration": "def closest_pair(points):",
"function_name": "closest_pair",
"parameter_list": "(points)"
},
{
"docstring": null,
"function_declaration": "def closest_pair_rec(points_by_x, points_by_y):",
"function_name": "closest_pair_rec",
"paramet... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def closest_pair(points):\n \"\"\"\n Find the closest pair of points in a 2D plane using Kirkpatrick and Stoll's Algorithm.\n \"\"\"\n \n def distance(p1, p2):\n return (... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068532",
"row_id": 68532,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138863']"
} | 0.40868 | Filter_68532 | I | [
"closest_pair",
"closest_pair_rec",
"closest_split_pair",
"brute_force_closest_pair",
"euclidean_distance"
] | 5 | [
[
"brute_force_closest_pair",
"euclidean_distance"
],
[
"closest_pair",
"closest_pair_rec"
],
[
"closest_pair_rec",
"brute_force_closest_pair"
],
[
"closest_pair_rec",
"closest_split_pair"
],
[
"closest_split_pair",
"euclidean_distance"
]
] | 5 | [] | false | [] | false | pytest | false | [] | true | 3b17f6a93c3787ecfca21f7ebbea758bb22c28ae | 6e5b90796fde6c3e1376ebeb439c52f639484d8a | |||
v1.0 | instruct | Filter | Filter_68540_I | Can you provide a Python code snippet that simulates a simple temperature monitoring system? The system should measure and print the temperature every 5 seconds for a total of 30 seconds. | import time
import random
def measure_temperature():
"""
Simulate measuring temperature. For simplicity,
this function returns a random temperature between -10 and 40 degrees Celsius.
"""
return random.uniform(-10, 40)
def temperature_monitoring_system(duration=30, interval=5):
"""
Simula... | from solution import measure_temperature, temperature_monitoring_system
def test_measure_temperature_within_range():
for _ in range(100):
temp = measure_temperature()
assert -10 <= temp <= 40
def test_temperature_monitoring_system(monkeypatch):
# Simulate a shorter duration and interval for te... | [
{
"docstring": "Simulate measuring temperature. For simplicity, \nthis function returns a random temperature between -10 and 40 degrees Celsius.",
"function_declaration": "def measure_temperature():",
"function_name": "measure_temperature",
"parameter_list": "()"
},
{
"docstring": "Simulates... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport random\n\ndef measure_temperature():\n \"\"\"\n Simulates measuring the temperature.\n \"\"\"\n return round(random.uniform(20.0, 30.0), 2)\n\ndef monitor_tempe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068540",
"row_id": 68540,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138884']"
} | 0.42887 | Filter_68540 | I | [
"measure_temperature",
"temperature_monitoring_system"
] | 2 | [
[
"temperature_monitoring_system",
"measure_temperature"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 753b209fd23ee77b19d336e6b4c91fd28e40fa4c | 8108051a5b8b139f47832a2076b7c26242483285 | |||
v1.0 | instruct | Filter | Filter_68545_I | Can you provide a simple example of an AI-powered chatbot using Python and Flask? | from flask import Flask, request, jsonify
app = Flask(__name__)
# Simple chatbot response function
def chatbot_response(message):
if "hello" in message.lower():
return "Hi there! How can I help you today?"
elif "how are you" in message.lower():
return "I'm an AI chatbot, so I don't have feelin... | from solution import app, chatbot_response
import pytest
# Define the test client for the Flask app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
# Unit test for the chatbot_response function
def test_chatbot_response():
assert chatbot_response("hello") == "Hi there! How... | [
{
"docstring": null,
"function_declaration": "def chatbot_response(message):",
"function_name": "chatbot_response",
"parameter_list": "(message)"
},
{
"docstring": null,
"function_declaration": "def chat():",
"function_name": "chat",
"parameter_list": "()"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n# Simple chatbot response function\ndef chatbot_response(message):\n if \"hello\" in message.lower():\n return \... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068545",
"row_id": 68545,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138894']"
} | 0.370773 | Filter_68545 | I | [
"chatbot_response",
"chat"
] | 2 | [
[
"chat",
"chatbot_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 26e7ccbc2b8f831173037ca51ec644cfdd54d5bb | 3c0180189a780a3a80e966b0fa537d282dc8bd5c | |||
v1.0 | instruct | Filter | Filter_68550_I | How can I create a Python program that generates a list of 100 unique random numbers between 1 and 1000? | import random
def generate_unique_random_numbers(num_numbers, min_val, max_val):
"""
Generates a list of unique random numbers within the specified range.
Args:
num_numbers (int): Number of unique random numbers to generate.
min_val (int): Minimum possible value for random numbers.
max_val (in... | from solution import generate_100_unique_random_numbers, generate_unique_random_numbers
def test_generate_100_unique_random_numbers():
numbers = generate_100_unique_random_numbers()
assert len(numbers) == 100
assert len(set(numbers)) == 100
assert all(1 <= num <= 1000 for num in numbers)
def test_gene... | [
{
"docstring": "Generates a list of unique random numbers within the specified range.\n\nArgs:\nnum_numbers (int): Number of unique random numbers to generate.\nmin_val (int): Minimum possible value for random numbers.\nmax_val (int): Maximum possible value for random numbers.\n\nReturns:\nlist: A list containi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_unique_random_numbers(n, lower_bound, upper_bound):\n \"\"\"\n Generates a list of n unique random numbers between lower_bound and upper_bound.\n \n P... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068550",
"row_id": 68550,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138902']"
} | 0.59776 | Filter_68550 | I | [
"generate_unique_random_numbers",
"generate_100_unique_random_numbers"
] | 2 | [
[
"generate_100_unique_random_numbers",
"generate_unique_random_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cae5e4ea24dad63eeabc4d043b05a2089ef34042 | a0ac0c58bcf2bc1b4997035d8b257f7627b19481 | |||
v1.0 | instruct | Filter | Filter_68552_I | Could you provide a Python code example for generating a sine wave and then applying a low-pass filter to it? | import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter
def generate_sine_wave(freq, sample_rate, duration):
"""
Generate a sine wave.
Parameters:
freq (float): Frequency of the sine wave.
sample_rate (int): Number of samples per second.
duration (float)... | from solution import generate_sine_wave, apply_lowpass_filter
import numpy as np
def test_generate_sine_wave():
sample_rate = 1000
freq = 5
duration = 1
t, x = generate_sine_wave(freq, sample_rate, duration)
assert len(t) == sample_rate * duration
assert len(x) == sample_rate * duration
... | [
{
"docstring": "Generate a sine wave.\n\nParameters:\nfreq (float): Frequency of the sine wave.\nsample_rate (int): Number of samples per second.\nduration (float): Duration in seconds.\n\nReturns:\nnp.ndarray: Time values.\nnp.ndarray: Amplitude values of the sine wave.",
"function_declaration": "def gener... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\n\ndef generate_sine_wave(freq, duration, sample_rate):\n \"\"\"\n Generates a sine wave signal.\n \... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068552",
"row_id": 68552,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138905']"
} | 0.558868 | Filter_68552 | I | [
"generate_sine_wave",
"butter_lowpass",
"apply_lowpass_filter"
] | 3 | [
[
"apply_lowpass_filter",
"butter_lowpass"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | bd0905a4f3ba746a7159d9dbbf555ca26e5828ed | 051ca6788e842502546ba926c18fa9694c407a33 | |||
v1.0 | instruct | Filter | Filter_68559_I | Given a Python list, I want to filter out all positive numbers that are not perfect squares. I need to keep all negative numbers and zero in the list. How can I achieve this? | import math
def is_perfect_square(n):
"""
Returns True if n is a perfect square, otherwise False.
"""
if n < 0:
return False
root = math.isqrt(n)
return root * root == n
def filter_list(lst):
"""
Filters the list, keeping negative numbers and zero unchanged,
and only keepin... | from solution import filter_list
def test_filter_list_all_positive():
assert filter_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16]) == [1, 4, 9, 16]
def test_filter_list_negative_and_zero():
assert filter_list([-5, -4, -3, 0, 1, 2, 4]) == [-5, -4, -3, 0, 1, 4]
def test_filter_list_with_mixed_elements():
assert... | [
{
"docstring": "Returns True if n is a perfect square, otherwise False.",
"function_declaration": "def is_perfect_square(n):",
"function_name": "is_perfect_square",
"parameter_list": "(n)"
},
{
"docstring": "Filters the list, keeping negative numbers and zero unchanged,\nand only keeping pos... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_perfect_square(n):\n \"\"\"\n Returns True if n is a perfect square, otherwise False.\n \"\"\"\n if n < 0:\n return False\n root = math.isqrt(n)\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068559",
"row_id": 68559,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138924']"
} | 0.598951 | Filter_68559 | I | [
"is_perfect_square",
"filter_list"
] | 2 | [
[
"filter_list",
"is_perfect_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f76e2765eebbaa7b01ec0acddfa4aff18e8d1581 | 1d749ad7d713e8b4589d6b1590a0270660415d7a | |||
v1.0 | instruct | Filter | Filter_68586_I | Hey Qwen, could you provide a Python code snippet that simulates a simple dice game where two players roll a six-sided die three times each and the player with the highest total wins? | import random
def roll_die():
"""
Simulates the rolling of a six-sided die.
Returns a random integer between 1 and 6 (inclusive).
"""
return random.randint(1, 6)
def play_game():
"""
Simulates a simple dice game where two players roll a six-sided die three times each.
The player with t... | from solution import roll_die, play_game
def test_roll_die():
for _ in range(100):
result = roll_die()
assert 1 <= result <= 6
def test_play_game():
outcomes = {"Player 1 wins!": 0, "Player 2 wins!": 0, "It's a tie!": 0}
for _ in range(1000):
result = play_game()
outco... | [
{
"docstring": "Simulates the rolling of a six-sided die.\nReturns a random integer between 1 and 6 (inclusive).",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a simple dice game where two players roll a six-sided... | [
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.\n Returns an integer between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_dice_game... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068586",
"row_id": 68586,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_138999']"
} | 0.517378 | Filter_68586 | I | [
"roll_die",
"play_game"
] | 2 | [
[
"play_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86dae778f2a492c080a8b273ec26c349dc77bf02 | 766fe43ba1f8c87c403c0e6bc5567afd6c62b9ba | |||
v1.0 | instruct | Filter | Filter_68666_I | Write a Python function that finds the closest prime number to a given number. The function should take an integer as input and return the closest prime number to that integer. If there are two primes equally close, the function should return the smaller prime. | def is_prime(n):
"""
Helper function to check if a number n 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
... | from solution import closest_prime
def test_prime_number_itself():
assert closest_prime(13) == 13
def test_prime_below():
assert closest_prime(10) == 11
def test_prime_above():
assert closest_prime(14) == 13
def test_equal_distance_primes():
assert closest_prime(12) == 11
def test_small_number():
... | [
{
"docstring": "Helper function to check if a number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Function to find the closest prime number to the input number.\nIf two primes are equally close, ret... | [
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 Helper function to check if a number n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068666",
"row_id": 68666,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139172']"
} | 0.629387 | Filter_68666 | I | [
"is_prime",
"closest_prime"
] | 2 | [
[
"closest_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | befa3a279c4cb60cb4525959068639ccfe8c8c1b | 936fd04c0c31df25b0f456720d8238d4f8d26a2e | |||
v1.0 | instruct | Filter | Filter_68704_I | Please write a Python script that demonstrates how to use concurrent.futures to perform a brute force attack simulation on a simple encryption algorithm. For educational purposes only, of course! Remember to include error handling and a way to stop the brute force attack gracefully if needed. | import concurrent.futures
import hashlib
import string
def simple_encrypt(password):
"""
Simple encryption using SHA-256 hash.
"""
return hashlib.sha256(password.encode()).hexdigest()
def brute_force_worker(target_hash, passwords):
"""
Worker function for brute force attack. Checks each passwo... | from solution import simple_encrypt, brute_force_attack
import string
def test_simple_encrypt():
assert simple_encrypt("password") == hashlib.sha256("password".encode()).hexdigest()
def test_brute_force_attack():
correct_password = "abc"
target_hash = simple_encrypt(correct_password)
charset = string.... | [
{
"docstring": "Simple encryption using SHA-256 hash.",
"function_declaration": "def simple_encrypt(password):",
"function_name": "simple_encrypt",
"parameter_list": "(password)"
},
{
"docstring": "Worker function for brute force attack. Checks each password in the list.",
"function_decl... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport hashlib\nimport string\n\ndef simple_encrypt(password):\n \"\"\"\n Simple encryption using SHA-256 hash.\n \"\"\"\n return hashlib.sha256(password... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068704",
"row_id": 68704,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139245']"
} | 0.403034 | Filter_68704 | I | [
"simple_encrypt",
"brute_force_worker",
"brute_force_attack"
] | 3 | [
[
"brute_force_attack",
"brute_force_worker"
],
[
"brute_force_worker",
"simple_encrypt"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 578ac482b404598ac4a049162dc78434a8561591 | d4cde583a9d5eb91344c6c15ca20bf808ad24a4b | |||
v1.0 | instruct | Filter | Filter_68707_I | Can you explain the behavior of decorators in Python with examples? | def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
def repeat(num_times):
def decorator_repeat(f... | def test_my_decorator(capfd):
say_hello()
captured = capfd.readouterr()
assert "Something is happening before the function is called." in captured.out
assert "Hello!" in captured.out
assert "Something is happening after the function is called." in captured.out
def test_repeat_decorator(capfd):
... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def my_decorator(func):\n \"\"\"\n A simple decorator that prints a message before and after calling the passed function.\n \"\"\"\n def wrapper():\n print(\"Something is ha... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068707",
"row_id": 68707,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139249']"
} | 0.427583 | Filter_68707 | I | [
"my_decorator",
"say_hello",
"repeat",
"greet",
"method_decorator"
] | 5 | [
[
"greet",
"repeat"
]
] | 1 | [] | false | [
"MyClass"
] | true | pytest | false | [] | true | e4bbd793a4be83713cff5297a7839fe4fe7777bd | ad1246d555836c016d3cad1f419b41f1b877c26a | |||
v1.0 | instruct | Filter | Filter_68742_I | Please write a Python function to delete a specific node in a binary search tree (BST). The function should handle the three cases: the node to be deleted is a leaf, has one child, or has two children. | class TreeNode:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def delete_node(root, key):
if root is None:
return root
if key < root.key:
root.left = delete_node(root.left, key)
elif key > root.key:
... | from solution import TreeNode, delete_node, inorder_traversal
def test_delete_leaf_node():
root = TreeNode(5, TreeNode(3), TreeNode(7))
root = delete_node(root, 3)
assert inorder_traversal(root) == [5, 7]
def test_delete_node_with_one_child():
root = TreeNode(5, TreeNode(3), TreeNode(7, TreeNode(6)))
... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key, left=None, right=None):\n self.key = key\n self.left = left\n self.right = right\n\ndef delete_node(root, key):\n if root i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068742",
"row_id": 68742,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139334']"
} | 0.445065 | Filter_68742 | I | [
"delete_node",
"find_min",
"inorder_traversal"
] | 3 | [
[
"delete_node",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 7c3fe6cbc156f946831500c2d3d906b0814f2253 | 5ae4e5b36462523d507c2cb25dc60ef4860a6351 | |||
v1.0 | instruct | Filter | Filter_68794_I | I need to create a simple GUI application in Python for a temperature converter that converts temperatures between Celsius, Fahrenheit, and Kelvin. Can you guide me through the process? | import tkinter as tk
from tkinter import ttk
def celsius_to_fahrenheit(celsius):
"""
Convert Celsius to Fahrenheit.
"""
return celsius * 9/5 + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Convert Fahrenheit to Celsius.
"""
return (fahrenheit - 32) * 5/9
def celsius_to_kelvin(celsius)... | from solution import (celsius_to_fahrenheit, fahrenheit_to_celsius, celsius_to_kelvin, kelvin_to_celsius,
fahrenheit_to_kelvin, kelvin_to_fahrenheit, convert_temperature)
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32.0
assert celsius_to_fahrenheit(100) == 212.0
... | [
{
"docstring": "Convert Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Convert Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius(f... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\nfrom tkinter import ttk\n\ndef celsius_to_fahrenheit(c):\n return (c * 9/5) + 32\n\ndef celsius_to_kelvin(c):\n return c + 273.15\n\ndef fahrenheit_to_celsius(f):\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068794",
"row_id": 68794,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139436']"
} | 0.367404 | Filter_68794 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"celsius_to_kelvin",
"kelvin_to_celsius",
"fahrenheit_to_kelvin",
"kelvin_to_fahrenheit",
"convert_temperature",
"create_app"
] | 8 | [
[
"convert_temperature",
"celsius_to_fahrenheit"
],
[
"convert_temperature",
"celsius_to_kelvin"
],
[
"convert_temperature",
"fahrenheit_to_celsius"
],
[
"convert_temperature",
"fahrenheit_to_kelvin"
],
[
"convert_temperature",
"kelvin_to_celsius"
],
[
... | 11 | [] | false | [] | false | pytest | true | [] | true | dc86c2cb8369d380dd70197caa6f0d9f34a68406 | 8d7703c4105bcbf6cb409f0cb584bff8097e5c6f | |||
v1.0 | instruct | Filter | Filter_68802_I | Create a Python function to calculate the sum of the prime numbers within a given range [start, end]. The function should be efficient and handle large ranges. | def is_prime(n):
"""
Helper function to determine if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import sum_of_primes_in_range
def test_sum_of_primes_in_small_range():
assert sum_of_primes_in_range(1, 10) == 17 # primes are 2, 3, 5, 7
def test_sum_of_primes_within_prime_only_range():
assert sum_of_primes_in_range(11, 13) == 24 # primes are 11, 13
def test_sum_of_primes_large_range():
... | [
{
"docstring": "Helper function to determine if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within the range [start, end].",
"function_declaration": "def su... | [
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 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 % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068802",
"row_id": 68802,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139449']"
} | 0.636765 | Filter_68802 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09f5873371a1fd98c3ec8dd1d111e5ea3ae7cdd9 | 6a1cf8aec6f2b7bb701ede175d098d13a7c7623b | |||
v1.0 | instruct | Filter | Filter_68807_I | Write a Python function to find the kth number in a sorted array that is also a Fibonacci number. The function should take a sorted array and an integer k as input and return the kth Fibonacci number present in the array. If there are less than k Fibonacci numbers in the array, the function should return -1. | def is_fibonacci(n, fib_cache={0: True, 1: True}):
"""
Check if a given number n is a Fibonacci number by using a memoized approach.
"""
if n in fib_cache:
return fib_cache[n]
a, b = 0, 1
while b < n:
a, b = b, a + b
is_fib = (b == n)
fib_cache[n] = is_fib
r... | from solution import find_kth_fibonacci_in_sorted_array
def test_find_kth_fibonacci_in_sorted_array_case_1():
assert find_kth_fibonacci_in_sorted_array([1, 4, 5, 6, 7, 8, 13], 1) == 1
def test_find_kth_fibonacci_in_sorted_array_case_2():
assert find_kth_fibonacci_in_sorted_array([1, 4, 5, 6, 7, 8, 13], 2) == ... | [
{
"docstring": "Check if a given number n is a Fibonacci number by using a memoized approach.",
"function_declaration": "def is_fibonacci(n, fib_cache={0: True, 1: True}):",
"function_name": "is_fibonacci",
"parameter_list": "(n, fib_cache={0: True, 1: True})"
},
{
"docstring": "Find the kth... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_fibonacci(n):\n \"\"\"\n Returns True if n is a Fibonacci number, else False\n \"\"\"\n if n < 0:\n return False\n a, b = 0, 1\n while a <= n:\n if a == ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068807",
"row_id": 68807,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139459']"
} | 0.678697 | Filter_68807 | I | [
"is_fibonacci",
"find_kth_fibonacci_in_sorted_array"
] | 2 | [
[
"find_kth_fibonacci_in_sorted_array",
"is_fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0bf3ace65022c1801688470ef0425dec66d5b05 | fee4c383389ec9ecb00938a5d1a704754c9729ac | |||
v1.0 | instruct | Filter | Filter_68821_I | Can you provide an example of how to implement the k-means clustering algorithm from scratch in Python without using any external libraries like NumPy or Pandas? | import random
import math
def initialize_centroids(data, k):
"""
Randomly initialize k centroids from the data.
"""
return random.sample(data, k)
def assign_clusters(data, centroids):
"""
Assigns each data point to the closest centroid.
"""
clusters = [[] for _ in centroids]
for po... | from solution import k_means, initialize_centroids, assign_clusters, update_centroids, euclidean_distance
def test_initialize_centroids():
data = [[1, 2], [3, 4], [5, 6], [7, 8]]
centroids = initialize_centroids(data, 2)
assert len(centroids) == 2
assert all(centroid in data for centroid in centroids)
... | [
{
"docstring": "Randomly initialize k centroids from the data.",
"function_declaration": "def initialize_centroids(data, k):",
"function_name": "initialize_centroids",
"parameter_list": "(data, k)"
},
{
"docstring": "Assigns each data point to the closest centroid.",
"function_declaratio... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points.\n \"\"\"\n return math.sqrt(sum([(x - y) ** 2... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068821",
"row_id": 68821,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139484']"
} | 0.615386 | Filter_68821 | I | [
"initialize_centroids",
"assign_clusters",
"update_centroids",
"euclidean_distance",
"k_means"
] | 5 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"k_means",
"assign_clusters"
],
[
"k_means",
"initialize_centroids"
],
[
"k_means",
"update_centroids"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | efaee95b07f82403252552b8acc8d65be187bd46 | 2ee89f5f6090d126d2abb6b1608f6e2d5a1407bd | |||
v1.0 | instruct | Filter | Filter_68825_I | Write a Python function that checks the availability of various services in a system, including databases, APIs, message queues, and external services. The function should use HTTP requests and custom methods to verify the health of each component. It should also log each service's status and duration of the check. | import requests
import logging
import time
# Configure logging
logging.basicConfig(level=logging.INFO)
def check_http_service(url):
"""
Check the health of an HTTP service.
"""
start_time = time.time()
try:
response = requests.get(url)
duration = time.time() - start_time
if... | from unittest.mock import patch, MagicMock
from solution import check_services, check_http_service, check_database
def test_check_http_service_up():
with patch('requests.get') as mock_get:
mock_get.return_value.status_code = 200
is_up, duration = check_http_service("http://example.com")
ass... | [
{
"docstring": "Check the health of an HTTP service.",
"function_declaration": "def check_http_service(url):",
"function_name": "check_http_service",
"parameter_list": "(url)"
},
{
"docstring": "Check the health of a database connection.",
"function_declaration": "def check_database(data... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport logging\nimport time\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\ndef check_service_status(service_name, url, check... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00068825",
"row_id": 68825,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139492']"
} | 0.568587 | Filter_68825 | I | [
"check_http_service",
"check_database",
"check_services"
] | 3 | [
[
"check_services",
"check_database"
],
[
"check_services",
"check_http_service"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | a68c8540bf19967d6ed87d60e47f7674877cae63 | b5c087822d13c7648bb31af2b14afc8aef7ca7f6 | |||
v1.0 | instruct | Filter | Filter_68846_I | Write a Python function that checks the reachability of a list of URLs and sends an email notification if any URL is unreachable. The function should be able to handle a list of URLs, check their reachability, and if any URL is found to be unreachable, it should send an email with the details to the administrator. | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import requests
def check_urls_and_notify(urls, email_config):
"""
Checks the reachability of a list of URLs and sends an email notification
if any URL is unreachable.
Parameters:
- urls: List of URL... | from unittest.mock import patch
from solution import check_urls_and_notify, send_email
def test_check_urls_and_notify():
urls = ["http://example.com", "http://invalid-url"]
email_config = {
'sender_email': "test_sender@example.com",
'receiver_email': "test_receiver@example.com",
'smtp_s... | [
{
"docstring": "Checks the reachability of a list of URLs and sends an email notification\nif any URL is unreachable.\n\nParameters:\n- urls: List of URLs to check.\n- email_config: Dictionary with email configuration:\n - 'sender_email': Email address of the sender.\n - 'receiver_email': Email address of... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport requests\n\ndef check_urls_and_notify(urls, email_config):\n \"\"\"\n Checks ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00068846",
"row_id": 68846,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139548']"
} | 0.643454 | Filter_68846 | I | [
"check_urls_and_notify",
"send_email"
] | 2 | [
[
"check_urls_and_notify",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | b2452db22a21d5063ea16a62c14e8e50360b2ddd | b7f18d661b92d83abec419b52a654c4f6c115923 | |||
v1.0 | instruct | Filter | Filter_68973_I | I want to create a Python script that can automatically download images from a list of URLs. How can I achieve this? | import os
import requests
def download_image(url, save_path):
"""
Downloads an image from the given URL and saves it to the specified path.
:param url: URL of the image to download.
:param save_path: Path to save the downloaded image.
"""
response = requests.get(url)
if response.status... | import os
import requests
from unittest import mock
from solution import download_image, download_images
def mock_requests_get(url):
class MockResponse:
def __init__(self, status_code, content):
self.status_code = status_code
self.content = content
if url == "http://example... | [
{
"docstring": "Downloads an image from the given URL and saves it to the specified path.\n\n:param url: URL of the image to download.\n:param save_path: Path to save the downloaded image.",
"function_declaration": "def download_image(url, save_path):",
"function_name": "download_image",
"parameter_... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport os\n\ndef download_image(url, save_path):\n \"\"\"\n Download an image from a URL and save it to the specified path.\n \n :param url: the URL of the image t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00068973",
"row_id": 68973,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139782']"
} | 0.55614 | Filter_68973 | I | [
"download_image",
"download_images"
] | 2 | [
[
"download_images",
"download_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | a061f476c12cc355f9b81fe22b797a51147078be | 9f7c20985ab0fccdf394408d3f6df100a372cb8c | |||
v1.0 | instruct | Filter | Filter_69003_I | Create a Python function that calculates the sum of all prime numbers within a given range, including the start and end points. The function should also handle cases where the range is negative or starts from a non-prime number. | def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def sum_primes_in_range(start, end):
if start > end:
start, end = end, start
total_sum = 0
for number in range(start, end + 1):
... | from solution import sum_primes_in_range, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(-1) == False
assert is_prime(0) == False
assert is_prime(1) == False
def test_sum_primes_in_r... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def sum_primes_in_range(start, end):",
"function_name": "sum_primes_in_range",
"parameter_list": "(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 Helper function to check if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069003",
"row_id": 69003,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139829']"
} | 0.645545 | Filter_69003 | I | [
"is_prime",
"sum_primes_in_range"
] | 2 | [
[
"sum_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 00875c1320711e03d6b614b38e9431962dc225f8 | 084e9f32f30fdc2e0cc88263e5dce5dd9d7b5257 | |||
v1.0 | instruct | Filter | Filter_69004_I | Could you provide a Python function that takes a list of strings and returns a new list containing only the strings that are palindromes? A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). | def is_palindrome(s):
"""
Returns True if s is a palindrome, False otherwise.
"""
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]
def filter_palindromes(strings):
"""
Returns a list containing only the strings that are palindromes.
"""
return [s for s in strings if i... | from solution import filter_palindromes, is_palindrome
def test_is_palindrome():
assert is_palindrome("A man a plan a canal Panama") == True
assert is_palindrome("No lemon, no melon") == True
assert is_palindrome("hello") == False
assert is_palindrome("racecar") == True
assert is_palindrome("Was it... | [
{
"docstring": "Returns True if s is a palindrome, False otherwise.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Returns a list containing only the strings that are palindromes.",
"function_declaration": "... | [
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(s):\n \"\"\"\n Helper function to check if a string is a palindrome.\n Ignores spaces, punctuation, and capitalization.\n \"\"\"\n import re\n s = re.sub(r'... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069004",
"row_id": 69004,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139831']"
} | 0.756823 | Filter_69004 | I | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f3880cc8131c1ca8ebb16810178608099fc59b6d | 7e05000cc7bc1cc07047fc9680c569e2af8e9823 | |||
v1.0 | instruct | Filter | Filter_69039_I | Could you please help me write a Python script that checks a website for broken links? This script should be able to handle relative links and convert them to absolute links before checking their status. How can I achieve this? | import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def is_broken_link(url):
"""
Returns True if the link is broken (i.e., status code is not 200).
"""
try:
response = requests.head(url, allow_redirects=True)
return response.status_code != 200
except reque... | import pytest
from unittest.mock import patch, Mock
from solution import is_broken_link, get_all_links, check_website_for_broken_links
@patch('requests.head')
def test_is_broken_link(mock_head):
mock_response = Mock()
mock_response.status_code = 200
mock_head.return_value = mock_response
assert not is_... | [
{
"docstring": "Returns True if the link is broken (i.e., status code is not 200).",
"function_declaration": "def is_broken_link(url):",
"function_name": "is_broken_link",
"parameter_list": "(url)"
},
{
"docstring": "Returns all the links found on the given website URL.",
"function_decla... | [
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\nfrom urllib.parse import urljoin\n\ndef is_broken_link(url):\n \"\"\"\n Returns True if the link is broken (i.e., status code is not 200).... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069039",
"row_id": 69039,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139911']"
} | 0.596311 | Filter_69039 | I | [
"is_broken_link",
"get_all_links",
"check_website_for_broken_links"
] | 3 | [
[
"check_website_for_broken_links",
"get_all_links"
],
[
"check_website_for_broken_links",
"is_broken_link"
]
] | 2 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | aeed07d9df9c1efbc34326c2b83ed46687e810f8 | ef6610e59274b76bf3a83282c1733ca8c92e41e2 | |||
v1.0 | instruct | Filter | Filter_69066_I | Write a Python script to check if a number is a prime number and return a list of all prime numbers up to a given number. | 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, prime_numbers_up_to
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(0) =... | [
{
"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 all prime numbers up to n (inclusive).",
"function_declaration": "def prime_number... | [
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 given number n 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 % ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069066",
"row_id": 69066,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139980']"
} | 0.751809 | Filter_69066 | I | [
"is_prime",
"prime_numbers_up_to"
] | 2 | [
[
"prime_numbers_up_to",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ab02a54597cf37a0678879f9963e8bbdb970bc8 | bafd9977eee0f4b1ac241aacab1aac194bf8e531 | |||
v1.0 | instruct | Filter | Filter_69075_I | I need to create a Python script that can batch process data cleaning tasks on multiple CSV files. The script should be able to handle missing values, remove duplicates, and normalize column names by converting them to lowercase and replacing any spaces with underscores. How can I achieve this? | import pandas as pd
import os
def clean_csv_file(file_path):
"""
Cleans a CSV file by handling missing values, removing duplicates,
and normalizing column names.
Parameters:
file_path (str): Path to the CSV file to be cleaned.
Returns:
pd.DataFrame: Cleaned DataFrame.
"""
df = pd.... | from solution import clean_csv_file, batch_process_csv_files
import pandas as pd
import os
def test_clean_csv_file(tmpdir):
test_data = pd.DataFrame({
"Column A": [1, 2, 2, None, 4],
"Column B": ["A", "B", "B", "C", None]
})
test_csv = tmpdir.join("test.csv")
test_data.to_csv(test_csv, ... | [
{
"docstring": "Cleans a CSV file by handling missing values, removing duplicates,\nand normalizing column names.\n\nParameters:\nfile_path (str): Path to the CSV file to be cleaned.\n\nReturns:\npd.DataFrame: Cleaned DataFrame.",
"function_declaration": "def clean_csv_file(file_path):",
"function_name"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport os\n\ndef clean_csv_file(file_path):\n \"\"\"\n Cleans a CSV file by handling missing values, removing duplicates,\n and normalizing column names.\n\n P... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069075",
"row_id": 69075,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_139991']"
} | 0.602371 | Filter_69075 | I | [
"clean_csv_file",
"batch_process_csv_files"
] | 2 | [
[
"batch_process_csv_files",
"clean_csv_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 6db317f92db663ab0a6ace9de81d7e8804eac9e4 | 8d08ec88696c24b2c661d732fae50366c874ec61 | |||
v1.0 | instruct | Filter | Filter_69085_I | Can you provide a Python script that can encrypt and decrypt text using a simple Caesar cipher? Certainly! Below is a Python script that implements a Caesar cipher for both encrypting and decrypting text. The Caesar cipher is a basic encryption technique where each letter in the plaintext is shifted a certain number of... | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the input text using Caesar cipher by shifting the characters by the specified number.
Parameters:
text (str): Input text to be encrypted.
shift (int): Number of positions each character is shifted.
Returns:
str: Encrypted text.
"""
... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("ABC", 3) == "DEF"
assert caesar_cipher_encrypt("abc", 3) == "def"
assert caesar_cipher_encrypt("xyz", 3) == "abc"
assert caesar_cipher_encrypt("Hello, World!", 5) == "Mjqqt,... | [
{
"docstring": "Encrypts the input text using Caesar cipher by shifting the characters by the specified number.\n\nParameters:\ntext (str): Input text to be encrypted.\nshift (int): Number of positions each character is shifted.\n\nReturns:\nstr: Encrypted text.",
"function_declaration": "def caesar_cipher_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encrypt(plain_text, shift):\n \"\"\"\n Encrypts plain_text using a Caesar cipher with the given shift.\n \n Arguments:\n plain_text -- the text to be encrypted... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069085",
"row_id": 69085,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140006']"
} | 0.581264 | Filter_69085 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 732803d0e82a6f9884a25a3c7861657988d902ae | fb047a466500a3606b11738994b4905f15ad75a8 | |||
v1.0 | instruct | Filter | Filter_69093_I | Can you provide a Python code snippet to search for duplicate files in a directory and delete them, keeping only one copy of each file? | import os
import hashlib
def calculate_hash(file_path):
"""
Calculate the MD5 hash of a file.
"""
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
buf = f.read()
hasher.update(buf)
return hasher.hexdigest()
def find_and_delete_duplicates(directory):
"""
Find and ... | import os
import shutil
from solution import find_and_delete_duplicates
def create_test_files(directory, files):
if not os.path.exists(directory):
os.makedirs(directory)
for filename, content in files.items():
with open(os.path.join(directory, filename), 'w') as f:
f.write(content)
... | [
{
"docstring": "Calculate the MD5 hash of a file.",
"function_declaration": "def calculate_hash(file_path):",
"function_name": "calculate_hash",
"parameter_list": "(file_path)"
},
{
"docstring": "Find and delete duplicate files in the specified directory, keeping only one copy of each file."... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\n\ndef file_hash(filepath):\n \"\"\"\n Generates a hash for the contents of a file.\n \"\"\"\n hasher = hashlib.md5()\n with open(filepath, 'rb') as fi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069093",
"row_id": 69093,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140020']"
} | 0.559811 | Filter_69093 | I | [
"calculate_hash",
"find_and_delete_duplicates"
] | 2 | [
[
"find_and_delete_duplicates",
"calculate_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ac28f325b9d8557351e07798772980ed413f9a8 | 78f5d277923150829185a7b7ac01046180f5975d | |||
v1.0 | instruct | Filter | Filter_69115_I | Design a Python function that calculates the sum of all prime numbers within a given range `[start, end]`. The function should handle invalid inputs, such as negative numbers or non-integer values for the range, and return appropriate error messages. Additionally, the function should include a mechanism to check if a n... | def is_prime(n):
"""
Checks if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return T... | from solution import sum_prime_numbers_in_range, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(-5) == False
def test_sum_prime_numbers_in_range_valid_range():
assert sum_prime_numbers_... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within a given range [start, end].\nHandles invalid inputs such as negative numbers or non... | [
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 n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069115",
"row_id": 69115,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140055']"
} | 0.671308 | Filter_69115 | I | [
"is_prime",
"sum_prime_numbers_in_range"
] | 2 | [
[
"sum_prime_numbers_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99388c2314ce77ea2e7f498f13501961731e6228 | 02d23c9a181dc967e0b5e6b30391dc4aa447e726 | |||
v1.0 | instruct | Filter | Filter_69176_I | Can you create a simple Python program that simulates a basic dice rolling game? The game should allow a user to roll a six-sided die and keep track of the total score. The game should continue until the user decides to stop rolling, and at the end, it should display the total score. | import random
def roll_dice():
"""
Simulates rolling a six-sided die and returns the result.
"""
return random.randint(1, 6)
def play_game():
"""
Starts the dice rolling game.
"""
total_score = 0
keep_rolling = 'y'
while keep_rolling.lower() == 'y':
roll = roll_dic... | from solution import roll_dice, play_game
import pytest
def test_roll_dice():
for _ in range(100):
result = roll_dice()
assert 1 <= result <= 6
def test_play_game(monkeypatch):
responses = iter(['y', 'y', 'n'])
def mock_input(s):
return next(responses)
monkeypatch.set... | [
{
"docstring": "Simulates rolling a six-sided die and returns the result.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Starts the dice rolling game.",
"function_declaration": "def play_game():",
"function_name":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided dice and returns the result (1-6).\n \"\"\"\n return random.randint(1, 6)\n\ndef dice_rolling_game(input_... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069176",
"row_id": 69176,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140176']"
} | 0.57009 | Filter_69176 | I | [
"roll_dice",
"play_game"
] | 2 | [
[
"play_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05d27d27b698dd820a682b9904c03f3adbc2d691 | 647e728fc768a1547bea127f486cc91e48051b24 | |||
v1.0 | instruct | Filter | Filter_69179_I | Hey there! How can I prompt a user to input a number and then check if it's a prime number using Python? | def is_prime(n):
"""
Check if a number is a prime number.
Args:
n (int): The number to check.
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i ... | from solution import is_prime
def test_is_prime_positive_numbers():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
def test_is_prime_negative_numbers():
assert is_prime(-1) == False
assert is_prime(-17) == False
def test_is_prime_... | [
{
"docstring": "Check if a number is a prime number.\n\nArgs:\nn (int): The number to check.\n\nReturns:\nbool: True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Prompt user to i... | [
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 Args:\n n (int): The number to check.\n\n Returns:\n bool: True if n is a prime number, False otherwise.\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069179",
"row_id": 69179,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140180']"
} | 0.719794 | Filter_69179 | I | [
"is_prime",
"prompt_and_check_prime"
] | 2 | [
[
"prompt_and_check_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de210118c0bc8b7054fc8b2bd1effab170621e95 | f1684a190741ecbbe1327bdc957d5a2f0b157899 | |||
v1.0 | instruct | Filter | Filter_69182_I | Write a Python script that reads a text file and counts the frequency of each word in the file. The script should ignore common stopwords (like "the", "and", "is", etc.), and it should also handle punctuation and case sensitivity. You can use any Python libraries you find useful. | import re
from collections import Counter
import string
def read_file(filepath):
with open(filepath, 'r') as file:
text = file.read()
return text
def process_text(text):
# Define a list of common stopwords
stopwords = set([
'the', 'and', 'is', 'in', 'it', 'of', 'to', 'a', 'on', 'with',... | from solution import read_file, process_text, word_frequency
import os
def test_read_file():
test_file = 'test.txt'
with open(test_file, 'w') as file:
file.write('Hello, World!')
assert read_file(test_file) == 'Hello, World!'
os.remove(test_file)
def test_process_text():
text = "Hello, Wor... | [
{
"docstring": null,
"function_declaration": "def read_file(filepath):",
"function_name": "read_file",
"parameter_list": "(filepath)"
},
{
"docstring": null,
"function_declaration": "def process_text(text):",
"function_name": "process_text",
"parameter_list": "(text)"
},
{
... | [
0,
1,
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 Counter\nfrom typing import Dict\n\n# A set of common English stopwords\nSTOPWORDS = {\n \"the\", \"and\", \"is\", \"in\", \"to\", \"with\", \"a\", \"an\"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069182",
"row_id": 69182,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140189']"
} | 0.754619 | Filter_69182 | I | [
"read_file",
"process_text",
"word_frequency"
] | 3 | [
[
"word_frequency",
"process_text"
],
[
"word_frequency",
"read_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 73a7a76e46aa1ee0af8db0178e4d2cbc3d4fb08b | dd35b44653e1a8c5f1024d0a10daaccdd2016e9f | |||
v1.0 | instruct | Filter | Filter_69197_I | Can you provide a Python function that can encode and decode a string using a simple Caesar cipher? A Caesar cipher is a type of substitution cipher where each letter in the plaintext is shifted a certain number of places down the alphabet. | def caesar_cipher_encode(text, shift):
"""
Encodes the given text using a Caesar cipher with the given shift.
Args:
text (str): the text to be encoded.
shift (int): the number of places to shift each letter.
Returns:
str: the encoded text.
"""
encoded_text = []
for char... | from solution import caesar_cipher_encode, caesar_cipher_decode
def test_caesar_cipher_encode():
assert caesar_cipher_encode("abc", 1) == "bcd"
assert caesar_cipher_encode("xyz", 2) == "zab"
assert caesar_cipher_encode("HELLO", 5) == "MJQQT"
assert caesar_cipher_encode("Hello, World!", 3) == "Khoor, Zr... | [
{
"docstring": "Encodes the given text using a Caesar cipher with the given shift.\n\nArgs:\ntext (str): the text to be encoded.\nshift (int): the number of places to shift each letter.\n\nReturns:\nstr: the encoded text.",
"function_declaration": "def caesar_cipher_encode(text, shift):",
"function_name... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encode(plaintext, shift):\n \"\"\"\n Encodes a plaintext string using the Caesar cipher with a given shift.\n \n Args:\n plaintext (str): The string to be enco... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069197",
"row_id": 69197,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140216']"
} | 0.64806 | Filter_69197 | I | [
"caesar_cipher_encode",
"caesar_cipher_decode"
] | 2 | [
[
"caesar_cipher_decode",
"caesar_cipher_encode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5fdff5fac700c3ff3b1c41c0f68a3bbcdf22a579 | e7da9eb99088bb3d4b73d9a0149de5cdaf574e2d | |||
v1.0 | instruct | Filter | Filter_69221_I | Create a simple text-based game in Python where the player chooses a path. The game should have a storyline involving a treasure hunt in a mysterious forest. The player has to make decisions that affect the outcome of the game. The game includes at least one random event and should have a forfeit option to quit the gam... | import random
def display_storyline():
"""
Displays the initial storyline.
"""
print("You find yourself at the edge of a mysterious forest.")
print("Rumor has it that a hidden treasure lies within.")
print("Will you dare to enter and seek the treasure?")
def choose_path():
"""
Prompts ... | from solution import display_storyline, choose_path, random_event, play_game
def test_display_storyline(capsys):
display_storyline()
captured = capsys.readouterr()
assert "You find yourself at the edge of a mysterious forest." in captured.out
assert "Will you dare to enter and seek the treasure?" in ca... | [
{
"docstring": "Displays the initial storyline.",
"function_declaration": "def display_storyline():",
"function_name": "display_storyline",
"parameter_list": "()"
},
{
"docstring": "Prompts the player to choose a path.\nReturns the player's choice.",
"function_declaration": "def choose_p... | [
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 start_game():\n print(\"Welcome to the Mysterious Forest Treasure Hunt!\")\n print(\"You find yourself at the entrance of a dark and mysterious forest. Legend has it... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069221",
"row_id": 69221,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140259']"
} | 0.458024 | Filter_69221 | I | [
"display_storyline",
"choose_path",
"random_event",
"play_game"
] | 4 | [
[
"play_game",
"choose_path"
],
[
"play_game",
"display_storyline"
],
[
"play_game",
"random_event"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b2c4e65b4ec658ab3fb49cc906dbf52eda383ad9 | 7306e5500286981a90789424dc64f5473e0c55fe | |||
v1.0 | instruct | Filter | Filter_69229_I | Can you provide an example of a Python function that utilizes a decorator to add a custom header to an HTTP request made using the `requests` library? | import requests
def add_custom_header(header_name, header_value):
"""
Decorator that adds a custom header to requests made by the decorated function.
"""
def decorator(func):
def wrapper(url, *args, **kwargs):
headers = kwargs.get('headers', {})
headers[header_name] = he... | import requests
from unittest.mock import patch, MagicMock
from solution import make_request, add_custom_header
@patch('requests.get')
def test_make_request_with_custom_header(mock_get):
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {'Content-Type': 'application/json'}... | [
{
"docstring": "Decorator that adds a custom header to requests made by the decorated function.",
"function_declaration": "def add_custom_header(header_name, header_value):",
"function_name": "add_custom_header",
"parameter_list": "(header_name, header_value)"
},
{
"docstring": "Makes an HTT... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\n\ndef add_custom_header(func):\n \"\"\"\n Decorator that adds a custom header to the request.\n \"\"\"\n def wrapper(url, **kwargs):\n headers = kwargs.get(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069229",
"row_id": 69229,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140270']"
} | 0.502062 | Filter_69229 | I | [
"add_custom_header",
"make_request"
] | 2 | [
[
"make_request",
"add_custom_header"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 61a45bf5bccb17ed17e3a032332015ea7b2f118a | 4ce84f9e4b7e58b549cb35230e79d0c0f68ca109 | |||
v1.0 | instruct | Filter | Filter_69267_I | How can I write a Python code to find the prime factors of a given number using the Eratosthenes Sieve method? | def sieve_erathosthenes(n):
primes = []
sieve = [True] * (n + 1)
for p in range(2, n + 1):
if sieve[p]:
primes.append(p)
for i in range(p * p, n + 1, p):
sieve[i] = False
return primes
def prime_factors(n):
primes = sieve_erathosthenes(int(n**0.5) + 1... | from solution import prime_factors
def test_prime_factors_of_2():
assert prime_factors(2) == [2]
def test_prime_factors_of_15():
assert prime_factors(15) == [3, 5]
def test_prime_factors_of_100():
assert prime_factors(100) == [2, 2, 5, 5]
def test_prime_factors_of_1():
assert prime_factors(1) == []
... | [
{
"docstring": null,
"function_declaration": "def sieve_erathosthenes(n):",
"function_name": "sieve_erathosthenes",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"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 sieve(n):\n \"\"\"\n Returns a list of primes up to n using the Sieve of Eratosthenes algorithm.\n \"\"\"\n is_prime = [True] * (n + 1)\n p = 2\n while (p * p <= n):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069267",
"row_id": 69267,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140348']"
} | 0.708747 | Filter_69267 | I | [
"sieve_erathosthenes",
"prime_factors"
] | 2 | [
[
"prime_factors",
"sieve_erathosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0561bfb4f73671cfb76503fb85b41fb3e0e4aa4b | 17140d121f6eb9c99376ce460ffe239f066d8524 | |||
v1.0 | instruct | Filter | Filter_69285_I | Write a Python function to check if two given numbers are amicable numbers. Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. For example, the smallest pair of amicable numbers is (220, 284). | def sum_of_proper_divisors(n):
"""
Returns the sum of proper divisors of a given number n.
"""
return sum([i for i in range(1, n) if n % i == 0])
def are_amicable_numbers(a, b):
"""
Returns True if a and b are amicable numbers, False otherwise.
"""
return sum_of_proper_divisors(a) == b ... | from solution import are_amicable_numbers
def test_amicable_numbers():
assert are_amicable_numbers(220, 284) == True
def test_not_amicable_numbers():
assert are_amicable_numbers(10, 20) == False
def test_amicable_numbers_non_smallest():
assert are_amicable_numbers(1184, 1210) == True
def test_same_numbe... | [
{
"docstring": "Returns the sum of proper divisors of a given number n.",
"function_declaration": "def sum_of_proper_divisors(n):",
"function_name": "sum_of_proper_divisors",
"parameter_list": "(n)"
},
{
"docstring": "Returns True if a and b are amicable numbers, False otherwise.",
"func... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sum_of_proper_divisors(n):\n \"\"\"\n Returns the sum of proper divisors of a given number n.\n \"\"\"\n divisors = [1]\n for i in range(2, int(n**0.5) + 1):\n if n %... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069285",
"row_id": 69285,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140382']"
} | 0.616939 | Filter_69285 | I | [
"sum_of_proper_divisors",
"are_amicable_numbers"
] | 2 | [
[
"are_amicable_numbers",
"sum_of_proper_divisors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfa0e5c01fe317d4e2584e3e0e94a8804eb2232b | 8bb3a94c3cfba2948896a8b89dbe55c8e3b8e67b | |||
v1.0 | instruct | Filter | Filter_69314_I | Hey, can you provide a Python function that retrieves the top N words from a list of text entries, sorted by their frequency in descending order? Additionally, it would be great if the function could handle some basic preprocessing, like converting all text to lowercase and removing punctuation. | import re
from collections import Counter
def preprocess_text(text):
"""
Converts text to lowercase and removes punctuation.
"""
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
return text
def get_top_n_words(text_entries, n):
"""
Returns the top N words from a list of text ent... | from solution import get_top_n_words
def test_get_top_n_words_single_entry():
text_entries = ["Hello world! Hello universe."]
top_words = get_top_n_words(text_entries, 2)
assert top_words == [('hello', 2), ('world', 1)]
def test_get_top_n_words_multiple_entries():
text_entries = ["Hello world!", "Worl... | [
{
"docstring": "Converts text to lowercase and removes punctuation.",
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": "Returns the top N words from a list of text entries, sorted by frequency in descending... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport string\n\ndef preprocess_text(text):\n \"\"\"\n Converts text to lowercase and removes punctuation.\n \"\"\"\n text = text.lower()\n text... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069314",
"row_id": 69314,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140439']"
} | 0.69546 | Filter_69314 | I | [
"preprocess_text",
"get_top_n_words"
] | 2 | [
[
"get_top_n_words",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca511351628d7f6bec111de6bf8b69115e806b56 | 065777d6d25846d2ac9d25837e0bf28ee31d1756 | |||
v1.0 | instruct | Filter | Filter_69319_I | I have a dataset of images, and I want to resize them to a specific width and height for a machine learning model. How can I do this efficiently in Python? | from PIL import Image
import os
def resize_image(image_path, output_path, width, height):
"""
Resizes the image at image_path to the specified width and height
and saves it to output_path.
Parameters:
image_path (str): The path to the input image.
output_path (str): The path to save the resiz... | from solution import resize_image, batch_resize_images
from PIL import Image
import os
def test_resize_image(tmp_path):
input_path = tmp_path / "test_image.jpg"
output_path = tmp_path / "resized_image.jpg"
width, height = 100, 100
# Create a sample image
image = Image.new('RGB', (200, 200), co... | [
{
"docstring": "Resizes the image at image_path to the specified width and height \nand saves it to output_path.\n\nParameters:\nimage_path (str): The path to the input image.\noutput_path (str): The path to save the resized image.\nwidth (int): The width to resize the image to.\nheight (int): The height to res... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image\nimport os\n\ndef resize_image(image_path, output_path, width, height):\n \"\"\"\n Resizes the image at image_path to the specified width and height \n and saves... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069319",
"row_id": 69319,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140448']"
} | 0.533899 | Filter_69319 | I | [
"resize_image",
"batch_resize_images"
] | 2 | [
[
"batch_resize_images",
"resize_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 2aefd1e8e224131c3cb1317997ea8370927c5475 | d8b50d89184160df330eea5c9b4c9653deaa7bee | |||
v1.0 | instruct | Filter | Filter_69349_I | Can you provide a Python code snippet to simulate a simple neural network with one hidden layer and train it on a dataset? | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def simple_neural_network(X, y, hidden_neurons=4, iterations=10000, learning_rate=0.1):
input_neurons = X.shape[1]
output_neurons = y.shape[1]
# Initialize weights
weights_input_h... | import numpy as np
from solution import simple_neural_network, predict, sigmoid
def test_simple_neural_network():
# Initialize dataset (XOR problem)
X = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
y = np.array([[0],
[1],
... | [
{
"docstring": null,
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def sigmoid_derivative(x):",
"function_name": "sigmoid_derivative",
"parameter_list": "(x)"
},
{
"docstring... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\n# Activation function and its derivative\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\n# Neural Network defin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069349",
"row_id": 69349,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140516']"
} | 0.373788 | Filter_69349 | I | [
"sigmoid",
"sigmoid_derivative",
"simple_neural_network",
"predict"
] | 4 | [
[
"predict",
"sigmoid"
],
[
"simple_neural_network",
"sigmoid"
],
[
"simple_neural_network",
"sigmoid_derivative"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b94880a8551c1db89a0617a3f9d33fd4e812bcce | f562c8ebce775bc9b451ccb537d27c1fedf326d2 | |||
v1.0 | instruct | Filter | Filter_69384_I | Write a Python function that calculates the nth Fibonacci number using recursion. Additionally, include a mechanism to count how many times the function is called during the computation. This count should be reset after each call to the Fibonacci function. | call_count = 0
def fibonacci(n):
global call_count
call_count += 1
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def fibonacci_with_count(n):
global call_count
call_count = 0
result = fibonacci(n)
return ... | from solution import fibonacci_with_count
def test_fibonacci_0():
result, count = fibonacci_with_count(0)
assert result == 0
assert count == 1
def test_fibonacci_1():
result, count = fibonacci_with_count(1)
assert result == 1
assert count == 1
def test_fibonacci_5():
result, count = fibon... | [
{
"docstring": null,
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def fibonacci_with_count(n):",
"function_name": "fibonacci_with_count",
"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": "# Global variable to count the number of function calls\ncall_count = 0\n\ndef fibonacci(n):\n \"\"\"\n Returns the nth Fibonacci number using recursion.\n Also increments and keeps t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069384",
"row_id": 69384,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140593']"
} | 0.804814 | Filter_69384 | I | [
"fibonacci",
"fibonacci_with_count"
] | 2 | [
[
"fibonacci_with_count",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 922e09dfc63a1ffeae1b02b7c56cffa6350bbaf6 | 0ac0264bac42b2e9cbea458e628f590fab602d39 | |||
v1.0 | instruct | Filter | Filter_69398_I | How can I verify the integrity of a file using a checksum in Python? | import hashlib
def generate_checksum(file_path):
"""
Generates a SHA-256 checksum for the given file.
Parameters:
file_path (str): The path to the file.
Returns:
str: The SHA-256 checksum of the file.
"""
sha256 = hashlib.sha256()
with open(file_path, 'rb') as file:
... | from solution import generate_checksum, verify_checksum
import tempfile
def test_generate_checksum():
# Create a temporary file
with tempfile.NamedTemporaryFile(delete=True) as temp_file:
# Write some data to the temporary file
data = b'This is a test file for checksum generation.'
temp... | [
{
"docstring": "Generates a SHA-256 checksum for the given file.\n\nParameters:\nfile_path (str): The path to the file.\n\nReturns:\nstr: The SHA-256 checksum of the file.",
"function_declaration": "def generate_checksum(file_path):",
"function_name": "generate_checksum",
"parameter_list": "(file_pa... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef calculate_checksum(file_path, algorithm='md5'):\n \"\"\"\n Calculate the checksum of a file.\n\n Parameters:\n file_path (str): The path to the file.\n alg... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069398",
"row_id": 69398,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140619']"
} | 0.554487 | Filter_69398 | I | [
"generate_checksum",
"verify_checksum"
] | 2 | [
[
"verify_checksum",
"generate_checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 45fd01e12acd4753621ad7c133d60965d609a9bb | d4fb0c7a9654a30b913214d2508879000aaa0faa | |||
v1.0 | instruct | Filter | Filter_69400_I | I am trying to create a Python function that can identify palindromes in a list of strings. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). How can I implement this? | import re
def is_palindrome(s):
"""
Checks if a given string is a palindrome.
"""
# Remove non-alphanumeric characters and convert to lowercase
cleaned = re.sub(r'[^A-Za-z0-9]', '', s).lower()
return cleaned == cleaned[::-1]
def identify_palindromes(strings):
"""
Identifies palindromes... | from solution import is_palindrome, identify_palindromes
def test_is_palindrome():
assert is_palindrome("A man, a plan, a canal, Panama") == True
assert is_palindrome("racecar") == True
assert is_palindrome("No lemon, no melon") == True
assert is_palindrome("Hello, World!") == False
assert is_palin... | [
{
"docstring": "Checks if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Identifies palindromes in a list of strings.",
"function_declaration": "def identify_palindromes(strin... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Check if the given string is a palindrome.\n \n A palindrome reads the same forward and backward, ignoring spaces,\n punctuation, and capitaliza... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069400",
"row_id": 69400,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140623']"
} | 0.732516 | Filter_69400 | I | [
"is_palindrome",
"identify_palindromes"
] | 2 | [
[
"identify_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb3115ca3275cba071aed3d4e63b751b1434eb30 | 55e3fe8a10f75ebaa0e2f4ada5c686537b166167 | |||
v1.0 | instruct | Filter | Filter_69412_I | I need to create a Python script for a simple calculator that performs basic arithmetic operations. The calculator should be able to add, subtract, multiply, and divide. It should also handle invalid inputs gracefully. How can I implement this? | def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def subtract(a, b):
"""
Returns the difference when b is subtracted from a.
"""
return a - b
def multiply(a, b):
"""
Returns the product of a and b.
"""
return a * b
def divide(a, b):
"""
Returns t... | from solution import add, subtract, multiply, divide, calculator
# Test for add function
def test_add():
assert add(2, 3) == 5
assert add(0, 5) == 5
assert add(5, 0) == 5
assert add(-1, -1) == -2
assert add(-1, 3) == 2
# Test for subtract function
def test_subtract():
assert subtract(5, 3) == ... | [
{
"docstring": "Returns the sum of a and b.",
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the difference when b is subtracted from a.",
"function_declaration": "def subtract(a, b):",
"function_name": "subtrac... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b.\n \"\"\"\n return a + b\n\ndef subtract(a, b):\n \"\"\"\n Returns the difference between a and ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069412",
"row_id": 69412,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140645']"
} | 0.562186 | Filter_69412 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | a1be1e4dbdf3252befe5e9353b4b152d1193254b | 4fc9ba46503deb396337789ec0791b961a4a392d | |||
v1.0 | instruct | Filter | Filter_69435_I | Could you provide a Python code snippet that demonstrates how to use the `multiprocessing` module to parallelize a simple task, such as squaring numbers in a list? | from multiprocessing import Pool
def square_number(n):
"""
Function to square a number.
"""
return n * n
def parallel_square_numbers(numbers):
"""
Uses multiprocessing to parallelize the squaring of numbers in a list.
"""
with Pool(processes=4) as pool:
result = pool.map(square... | from solution import square_number, parallel_square_numbers
def test_square_number():
assert square_number(2) == 4
assert square_number(3) == 9
assert square_number(-1) == 1
assert square_number(0) == 0
def test_parallel_square_numbers():
numbers = [1, 2, 3, 4, 5]
squared_numbers = [1, 4, 9, 1... | [
{
"docstring": "Function to square a number.",
"function_declaration": "def square_number(n):",
"function_name": "square_number",
"parameter_list": "(n)"
},
{
"docstring": "Uses multiprocessing to parallelize the squaring of numbers in a list.",
"function_declaration": "def parallel_squa... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool\n\ndef square_number(n):\n \"\"\"\n Function to square a number.\n \"\"\"\n return n * n\n\ndef parallel_square_numbers(numbers):\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069435",
"row_id": 69435,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140686']"
} | 0.614367 | Filter_69435 | I | [
"square_number",
"parallel_square_numbers"
] | 2 | [
[
"parallel_square_numbers",
"square_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26a9cb90e871f34282b067387981cd3bbbfa5f03 | 286810c30a3c386546d1416aec43c736c22b678e | |||
v1.0 | instruct | Filter | Filter_69459_I | Write a Python function that takes a string representing a binary number and returns a string representing the binary number in hexadecimal format. The function should handle both uppercase and lowercase letters in the binary string and include a check function to validate the input. The hex string should be in upperca... | def binary_to_hex(binary_str):
"""
Converts a binary string to hexadecimal string in uppercase.
Parameters:
binary_str (str): A string representing a binary number.
Returns:
str: A string representing the hexadecimal equivalent in uppercase.
"""
# Validate the binary string
if ... | from solution import binary_to_hex, is_valid_binary
def test_is_valid_binary():
assert is_valid_binary("1010") == True
assert is_valid_binary("11001100") == True
assert is_valid_binary("2") == False
assert is_valid_binary("abc") == False
assert is_valid_binary("1010201") == False
def test_binary_t... | [
{
"docstring": "Converts a binary string to hexadecimal string in uppercase.\n\nParameters:\nbinary_str (str): A string representing a binary number.\n\nReturns:\nstr: A string representing the hexadecimal equivalent in uppercase.",
"function_declaration": "def binary_to_hex(binary_str):",
"function_nam... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_to_hex(binary_string):\n \"\"\"\n Convert a binary string to a hexadecimal string in uppercase.\n This function first checks if the input string is a valid binary string.\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069459",
"row_id": 69459,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140740']"
} | 0.716269 | Filter_69459 | I | [
"binary_to_hex",
"is_valid_binary"
] | 2 | [
[
"binary_to_hex",
"is_valid_binary"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 01da7bae302e93451a6db5cd4713a22f41a13840 | 82e5b7d919ed5d2a0cc3790f7882969ee324f082 | |||
v1.0 | instruct | Filter | Filter_69476_I | Write a Python code snippet to find all the prime numbers within a given range, say from 10 to 50. | def is_prime(n):
"""
Check if a number n is prime.
"""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def primes_in_range(start, end):
"""
Return a list of all prime numbers between start and end inclusiv... | from solution import is_prime, primes_in_range
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(5) is True
assert is_prime(1) is False
assert is_prime(13) is True
assert is_prime(18) is False
def test_primes_in_range():
... | [
{
"docstring": "Check if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Return a list of all prime numbers between start and end inclusive.",
"function_declaration": "def primes_in_range(start, en... | [
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 <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069476",
"row_id": 69476,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140764']"
} | 0.64693 | Filter_69476 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39aecaf41f9f6c69cb756d9e19b1c3e19abb6720 | 650054fc27283ea52c323884d1aa9de021d04548 | |||
v1.0 | instruct | Filter | Filter_69486_I | Can you provide a Python function that takes a binary tree represented as a nested list and returns an iterator for its postorder traversal? | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(lst):
if not lst:
return None
value = lst[0]
left = build_tree(lst[1]) if len(lst) > 1 and lst[1] else None
right = build_tree(lst[2]) ... | from solution import postorder_iterator
def test_postorder_iterator_empty():
it = postorder_iterator([])
assert list(it) == []
def test_postorder_iterator_single_node():
it = postorder_iterator([1])
assert list(it) == [1]
def test_postorder_iterator_two_levels():
it = postorder_iterator([1, [2], ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef build_tree(node_list):\n if... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069486",
"row_id": 69486,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140792']"
} | 0.484544 | Filter_69486 | I | [
"build_tree",
"postorder_traversal",
"postorder_iterator"
] | 3 | [
[
"postorder_iterator",
"build_tree"
],
[
"postorder_iterator",
"postorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 8713221ab05505df3fb766e75088e14309e2623e | 11a9393865c306edb95e7727ba5f1cad8340b9cc | |||
v1.0 | instruct | Filter | Filter_69505_I | Given the code snippet below, I am trying to wrap all methods of a class `MyClass` that do not start with an underscore `_` in a logging function. The logging function should print the name of the method and its arguments before the method is called. How can I achieve this? | def log_method(func):
"""
Decorator to log the method name and its arguments.
"""
def wrapper(*args, **kwargs):
print(f"Calling method: {func.__name__}, args: {args[1:]}, kwargs: {kwargs}")
return func(*args, **kwargs)
return wrapper
def wrap_methods(cls):
"""
Wraps all meth... | import io
import pytest
from contextlib import redirect_stdout
from solution import MyClass
def test_method1_logging():
my_instance = MyClass()
f = io.StringIO()
with redirect_stdout(f):
result = my_instance.method1(1, 2)
out = f.getvalue().strip()
assert "Calling method: method1, args: (1,... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\ndef logging_decorator(fn):\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n print(f\"Calling {fn.__name__} with args: {args}, kwargs: {kwargs}\")\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069505",
"row_id": 69505,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140833']"
} | 0.397336 | Filter_69505 | I | [
"log_method",
"wrap_methods"
] | 2 | [
[
"wrap_methods",
"log_method"
]
] | 1 | [] | false | [
"MyClass"
] | true | pytest | true | [] | true | 3738ae3e6431115ba3f27e459558f28fd126d316 | 8f20104cb55b3c16fc897ac599998ff6f94b6fc4 | |||
v1.0 | instruct | Filter | Filter_69522_I | Can you provide a Python code snippet that demonstrates how to use the `minimize` function from the `scipy.optimize` library to find the minimum of the Rosenbrock function, starting from an initial guess of [0, 0]? | from scipy.optimize import minimize
def rosenbrock(x):
"""
Rosenbrock function.
The function is commonly used as a performance test problem for optimization algorithms.
"""
return sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
def minimize_rosenbrock(starting_point):
"""
Uses... | from solution import minimize_rosenbrock
def test_minimize_rosenbrock_starting_at_origins():
result = minimize_rosenbrock([0, 0])
assert result.success
def test_minimize_rosenbrock_starting_near_minimum():
result = minimize_rosenbrock([1, 1])
assert result.success
assert all(abs(val - 1) < 1e-5 fo... | [
{
"docstring": "Rosenbrock function.\nThe function is commonly used as a performance test problem for optimization algorithms. ",
"function_declaration": "def rosenbrock(x):",
"function_name": "rosenbrock",
"parameter_list": "(x)"
},
{
"docstring": "Uses the scipy.optimize.minimize function ... | [
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\nfrom scipy.optimize import minimize\n\ndef rosenbrock(x):\n \"\"\"\n The Rosenbrock function.\n \"\"\"\n return sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069522",
"row_id": 69522,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140872']"
} | 0.435689 | Filter_69522 | I | [
"rosenbrock",
"minimize_rosenbrock"
] | 2 | [
[
"minimize_rosenbrock",
"rosenbrock"
]
] | 1 | [] | false | [] | false | pytest | true | [
"scipy"
] | false | dac7d4d84a73e59b82d82456d4ac06f450f3fffb | a360c4753be9d65fe1f73efcc34cd2b728198681 | |||
v1.0 | instruct | Filter | Filter_69536_I | Write a Python function that parses an XML file and returns a nested dictionary representing the XML structure. The XML file should be located at a specified path, and the function should handle elements with attributes, nested elements, and text content. You are required to use the `xml.etree.ElementTree` library for ... | import xml.etree.ElementTree as ET
def xml_to_dict(element):
"""
Recursively converts an XML element and its children into a dictionary.
"""
node = {}
# Process attributes of the element, if any
if element.attrib:
node['@attributes'] = element.attrib
# Process element's te... | import os
import xml.etree.ElementTree as ET
from solution import parse_xml_file
# Helper function to create temporary XML file for testing
def create_temp_xml(content, file_name="temp_test.xml"):
with open(file_name, "w") as file:
file.write(content)
return file_name
def test_parse_xml_simple():
... | [
{
"docstring": "Recursively converts an XML element and its children into a dictionary.",
"function_declaration": "def xml_to_dict(element):",
"function_name": "xml_to_dict",
"parameter_list": "(element)"
},
{
"docstring": "Parses the XML file at the given file path and converts it into a ne... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\n\ndef xml_to_dict(element):\n \"\"\"\n Recursively converts an XML element (and its children) into a dictionary.\n \"\"\"\n # Initialize the dic... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069536",
"row_id": 69536,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140899']"
} | 0.763549 | Filter_69536 | I | [
"xml_to_dict",
"parse_xml_file"
] | 2 | [
[
"parse_xml_file",
"xml_to_dict"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c2efe96f3bad32e00c62de30709f6719e5f301e | 01a1f4a6beac25674241435ad3ac65aa7fcb106c | |||
v1.0 | instruct | Filter | Filter_69542_I | I want to create a simple math quiz game in Python where the user can answer addition and subtraction questions. The game should allow the user to choose the difficulty level (easy, medium, hard) and the number of questions they want to answer. Based on their answers, the game should provide feedback and show the score... | import random
def generate_question(difficulty):
if difficulty == 'easy':
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
elif difficulty == 'medium':
num1 = random.randint(10, 50)
num2 = random.randint(10, 50)
elif difficulty == 'hard':
num1 = random.randi... | from solution import generate_question
def test_generate_question_easy():
question, answer = generate_question('easy')
assert 1 <= int(question.split()[0]) <= 10
assert 1 <= int(question.split()[2]) <= 10
if question.split()[1] == '+':
assert answer == int(question.split()[0]) + int(question.sp... | [
{
"docstring": null,
"function_declaration": "def generate_question(difficulty):",
"function_name": "generate_question",
"parameter_list": "(difficulty)"
},
{
"docstring": null,
"function_declaration": "def math_quiz_game(difficulty, num_questions):",
"function_name": "math_quiz_game... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_question(difficulty):\n \"\"\"\n Generate an addition or subtraction question based on the difficulty level.\n \"\"\"\n if difficulty == 'easy':\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069542",
"row_id": 69542,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140917']"
} | 0.508793 | Filter_69542 | I | [
"generate_question",
"math_quiz_game"
] | 2 | [
[
"math_quiz_game",
"generate_question"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bfaf756f4a009b7b23c7cf008937dcc157a22264 | f6c7283c4b23e816880d799ac5018a5dacd7d989 | |||
v1.0 | instruct | Filter | Filter_69577_I | Develop a simple text-based game in Python that involves navigating through a maze. The player starts at the entrance (top-left corner) and must reach the exit (bottom-right corner). The maze is represented as a 2D list where 0 represents an open path and 1 represents a wall. The player can move up, down, left, or righ... | def is_valid_move(maze, position):
"""
Check if the move is valid.
"""
x, y = position
if x < 0 or y < 0 or x >= len(maze) or y >= len(maze[0]) or maze[x][y] == 1:
return False
return True
def find_exit(maze, position=(0, 0), path=[]):
"""
Recursive function to find the path to ... | from solution import is_valid_move, find_exit, display_maze
def test_is_valid_move():
maze = [
[0, 1, 0],
[0, 1, 0],
[0, 0, 0]
]
assert is_valid_move(maze, (0, 0)) == True
assert is_valid_move(maze, (0, 1)) == False
assert is_valid_move(maze, (1, 0)) == True
assert is_va... | [
{
"docstring": "Check if the move is valid.",
"function_declaration": "def is_valid_move(maze, position):",
"function_name": "is_valid_move",
"parameter_list": "(maze, position)"
},
{
"docstring": "Recursive function to find the path to the exit.",
"function_declaration": "def find_exit(... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid_move(maze, position):\n \"\"\"\n Check if the move is valid.\n \"\"\"\n x, y = position\n if x < 0 or y < 0 or x >= len(maze) or y >= len(maze[0]) or maze[x][y] == ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069577",
"row_id": 69577,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_140982']"
} | 0.541633 | Filter_69577 | I | [
"is_valid_move",
"find_exit",
"display_maze",
"play_maze"
] | 4 | [
[
"find_exit",
"is_valid_move"
],
[
"play_maze",
"display_maze"
],
[
"play_maze",
"find_exit"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8e9e2ad0e16cdd1b6e03c48a22f7991bf1b71a8f | a7c78a62a1c3faa8460c73fa5cf5b4bf8b13efcf | |||
v1.0 | instruct | Filter | Filter_69585_I | Hello, I'm trying to write a Python script that can simulate a simple game of rock-paper-scissors. The game should allow a user to play against the computer, and the computer's choice should be randomly generated. The game should have a simple text-based interface. Can you provide a sample code for this? | import random
def get_computer_choice():
"""
Randomly select between 'rock', 'paper', and 'scissors'.
"""
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def determine_winner(player_choice, computer_choice):
"""
Determine the winner of the rock-paper-scissors game.
... | from solution import get_computer_choice, determine_winner, play_round
def test_get_computer_choice_output():
choice = get_computer_choice()
assert choice in ['rock', 'paper', 'scissors']
def test_determine_winner_draw():
assert determine_winner('rock', 'rock') == 'draw'
assert determine_winner('paper... | [
{
"docstring": "Randomly select between 'rock', 'paper', and 'scissors'.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determine the winner of the rock-paper-scissors game.\n\nArgs:\nplayer_choice (st... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly select between 'rock', 'paper', or 'scissors' for the computer.\n \"\"\"\n choices = ['rock', 'paper', 'scissors']\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069585",
"row_id": 69585,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141006']"
} | 0.376781 | Filter_69585 | I | [
"get_computer_choice",
"determine_winner",
"play_round"
] | 3 | [
[
"play_round",
"determine_winner"
],
[
"play_round",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 735eb4c463a079adb3b4c96683aef81883c55f50 | 0f9ab610bbac16f609c7d3f3cb9ad0006d13d05d | |||
v1.0 | instruct | Filter | Filter_69641_I | Hello, I'm looking for a Python code snippet to calculate the sum of all prime numbers up to a given number `n`. | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True # 2 is the only even prime number
if n % 2 == 0:
return False # no other even number is a prime
p = 3
while p * p <= n:
if n % p == 0:
... | 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(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-3) == False
def test_sum_of_primes():
... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers up to and including n.",
"function_declaration": "def sum_of_primes(n)... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069641",
"row_id": 69641,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141113']"
} | 0.6353 | Filter_69641 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0db7f9c8304e2d9ffe334165a71327fb54882a35 | 83dddb60daca8a11bfaa41697e52a483df3c619c | |||
v1.0 | instruct | Filter | Filter_69652_I | I have a Python script that I use to process text data. It's currently set up to handle one file at a time. I want to modify it so that it can handle multiple files in a directory. How can I do that? | import os
def process_file(file_path):
"""
Process an individual file.
Insert the code that processes a single file here.
"""
with open(file_path, 'r') as file:
data = file.read()
# Process the data here
return data
def process_directory(directory_path):
"""
Process... | import os
import pytest
from solution import process_file, process_directory
def test_process_file(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("This is a test file.")
result = process_file(test_file)
assert result == "This is a test file."
def test_process_directory(tmp... | [
{
"docstring": "Process an individual file.\nInsert the code that processes a single file here.",
"function_declaration": "def process_file(file_path):",
"function_name": "process_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Process all text files in the given directory.\n\nArgs... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef process_text(file_path):\n \"\"\"\n Mock function to process a single text file.\n For the example purpose, it just reads the content and returns it.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069652",
"row_id": 69652,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141137']"
} | 0.559638 | Filter_69652 | I | [
"process_file",
"process_directory"
] | 2 | [
[
"process_directory",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2419a499800eb67118a06763a136751bcc3a9f12 | 2e5522340cd598fc994df7a1b3679ae71c644425 | |||
v1.0 | instruct | Filter | Filter_69686_I | Can you help me with a Caesar Cipher algorithm in Python? I need to encode and decode messages using a shift of 3. | def caesar_cipher_encode(text, shift):
"""
Encodes the given text using Caesar Cipher with the given shift.
"""
encoded_text = []
for char in text:
if char.isalpha():
shift_base = ord('A') if char.isupper() else ord('a')
encoded_text.append(chr((ord(char) - shift_base... | from solution import caesar_cipher_encode, caesar_cipher_decode
def test_caesar_cipher_encode():
assert caesar_cipher_encode("HELLO", 3) == "KHOOR"
assert caesar_cipher_encode("hello", 3) == "khoor"
assert caesar_cipher_encode("Hello, World!", 3) == "Khoor, Zruog!"
assert caesar_cipher_encode("xyz", 3)... | [
{
"docstring": "Encodes the given text using Caesar Cipher with the given shift.",
"function_declaration": "def caesar_cipher_encode(text, shift):",
"function_name": "caesar_cipher_encode",
"parameter_list": "(text, shift)"
},
{
"docstring": "Decodes the given text using Caesar Cipher with t... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encode(message, shift=3):\n \"\"\"\n Encodes a message using Caesar Cipher with a given shift (default is 3).\n \"\"\"\n encoded_message = []\n for char in mes... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069686",
"row_id": 69686,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141212']"
} | 0.61012 | Filter_69686 | I | [
"caesar_cipher_encode",
"caesar_cipher_decode"
] | 2 | [
[
"caesar_cipher_decode",
"caesar_cipher_encode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eff6928e77f3fbfbaecac79c965086ba8176257d | 65f0243a45c8977f1388ed5d4bfc05486dcbcf7d | |||
v1.0 | instruct | Filter | Filter_69715_I | Can you provide a Python code snippet that reads a CSV file and appends data to it based on user input? This code should handle potential errors and provide feedback to the user. | import csv
def read_csv(file_path):
"""
Reads the content of a CSV file and returns it as a list of dictionaries.
"""
try:
with open(file_path, mode='r', newline='') as file:
reader = csv.DictReader(file)
return list(reader)
except FileNotFoundError:
print(f"... | import os
import csv
from solution import read_csv, append_to_csv
def test_read_csv_file_exists():
# Create a sample csv file
test_file_path = 'test.csv'
with open(test_file_path, mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['name', 'age'])
writer.writeheader()
... | [
{
"docstring": "Reads the content of a CSV file and returns it as a list of dictionaries.",
"function_declaration": "def read_csv(file_path):",
"function_name": "read_csv",
"parameter_list": "(file_path)"
},
{
"docstring": "Appends a dictionary (data) to a CSV file.",
"function_declarati... | [
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 append_to_csv(file_path, new_data):\n \"\"\"\n Appends a row of new_data to the CSV file located at file_path.\n\n Parameters:\n - file_path (str): The path to th... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069715",
"row_id": 69715,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141275']"
} | 0.570824 | Filter_69715 | I | [
"read_csv",
"append_to_csv",
"input_and_append_data"
] | 3 | [
[
"input_and_append_data",
"append_to_csv"
],
[
"input_and_append_data",
"read_csv"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 515ffc954155908e0e3fc3d8c451d7c187bd85c0 | 07b6e4c57a5863c179e4d1e0135fd7671f79b619 | |||
v1.0 | instruct | Filter | Filter_69722_I | How can I calculate the first k prime numbers using Python? | def is_prime(n):
"""
Determine if n 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
retur... | from solution import is_prime, first_k_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(19) == True
assert is_prime(20) == False
def test_first_k_primes():
assert first_k_primes(0) ... | [
{
"docstring": "Determine if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate the first k prime numbers.",
"function_declaration": "def first_k_primes(k):",
"function_name": "first_k_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 Determine if n 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:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069722",
"row_id": 69722,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141291']"
} | 0.634558 | Filter_69722 | I | [
"is_prime",
"first_k_primes"
] | 2 | [
[
"first_k_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d29a977f284cbb11bd5410bbbe1a39c13d517d3 | f804ebc7c7ac152e0b13e15e5f2654fe9de35034 | |||
v1.0 | instruct | Filter | Filter_69727_I | I want to design a game where players can vote on which direction their character should move in a 2D grid. The grid is 10x10, and each player can vote for one of the four cardinal directions: up, down, left, or right. The character moves in the direction that receives the most votes. If there's a tie, the character do... | import pygame
from collections import Counter
# Initialize the grid size
GRID_SIZE = 10
CELL_SIZE = 40
SCREEN_SIZE = GRID_SIZE * CELL_SIZE
# Define the directions
DIRECTIONS = {
"up": (0, -1),
"down": (0, 1),
"left": (-1, 0),
"right": (1, 0),
}
def calculate_new_position(position, direction):
"""... | from solution import calculate_new_position, determine_move
def test_calculate_new_position():
assert calculate_new_position((5, 5), "up") == (5, 4)
assert calculate_new_position((5, 5), "down") == (5, 6)
assert calculate_new_position((5, 5), "left") == (4, 5)
assert calculate_new_position((5, 5), "rig... | [
{
"docstring": "Calculate the new position based on the current position and the direction.",
"function_declaration": "def calculate_new_position(position, direction):",
"function_name": "calculate_new_position",
"parameter_list": "(position, direction)"
},
{
"docstring": "Determine the move... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pygame\nfrom collections import Counter\n\n# Initialize the grid size\nGRID_SIZE = 10\nCELL_SIZE = 40\nSCREEN_SIZE = GRID_SIZE * CELL_SIZE\n\n# Define the directions\nDIRECTIONS = {\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069727",
"row_id": 69727,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141299']"
} | 0.418903 | Filter_69727 | I | [
"calculate_new_position",
"determine_move",
"game_loop"
] | 3 | [
[
"game_loop",
"calculate_new_position"
],
[
"game_loop",
"determine_move"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pygame"
] | false | 379071ec48d596b396c83f7f1625f62713f72c41 | 802884365c38537422907b5bd2689a4e7b7976da | |||
v1.0 | instruct | Filter | Filter_69756_I | Hey there! I need to create a Python function that can parse a given string and extract all the valid IP addresses embedded within it. The function should be robust enough to handle any format of text. How can I achieve this? | import re
def extract_ip_addresses(text):
"""
Extracts all valid IPv4 addresses from the given text.
"""
ip_pattern = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
ips = ip_pattern.findall(text)
valid_ips = [ip for ip in ips if is_valid_ip(ip)]
return valid_ips
def is_valid_ip(ip):
... | from solution import extract_ip_addresses, is_valid_ip
def test_extract_ip_addresses():
text = "Here are some IPs: 192.168.1.1, 10.0.0.1, and an invalid one 999.999.999.999."
assert extract_ip_addresses(text) == ["192.168.1.1", "10.0.0.1"]
def test_extract_ip_addresses_with_text():
text = "Emails: test@ex... | [
{
"docstring": "Extracts all valid IPv4 addresses from the given text.",
"function_declaration": "def extract_ip_addresses(text):",
"function_name": "extract_ip_addresses",
"parameter_list": "(text)"
},
{
"docstring": "Helper function to determine if a given IP address is valid.",
"funct... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef extract_ip_addresses(text):\n \"\"\"\n Parses a given string and extracts all valid IP addresses embedded within it.\n \n Args:\n text (str): The input text con... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069756",
"row_id": 69756,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141356']"
} | 0.730446 | Filter_69756 | I | [
"extract_ip_addresses",
"is_valid_ip"
] | 2 | [
[
"extract_ip_addresses",
"is_valid_ip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 403d9be90401f9b4130c55f74434a5720f6a6d81 | 1e4992a26a4082936381436b19851b10387cf2be | |||
v1.0 | instruct | Filter | Filter_69757_I | I am looking to implement a simple blockchain simulation to understand how blockchain works, including its cryptographic elements such as hashing and digital signatures. Can you provide a basic example in Python? | 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
def test_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 genesis_block.hash == cal... | [] | [
1,
0,
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, previous_hash, timestamp, data, hash):\n self.index = index\n self.previous_hash = previous_hash\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069757",
"row_id": 69757,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141358']"
} | 0.370367 | Filter_69757 | I | [
"calculate_hash",
"create_genesis_block",
"create_new_block"
] | 3 | [
[
"create_genesis_block",
"calculate_hash"
],
[
"create_new_block",
"calculate_hash"
]
] | 2 | [] | false | [
"Block"
] | true | pytest | true | [] | true | f700fa970c597453d248ac0b9f62454a2a021ef7 | 6f243d5d1372d82b46145f517b1d25317bfed02d | |||
v1.0 | instruct | Filter | Filter_69762_I | Write a Python code to calculate the 7th number in the Fibonacci sequence using an iterative approach. | def fibonacci(n):
"""
Returns the nth number in the Fibonacci sequence using an iterative approach.
"""
if n <= 0:
return "Invalid input"
elif n == 1:
return 0
elif n == 2:
return 1
a, b = 0, 1
for _ in range(2, n):
a, b = b, a + b
return b
# To find... | from solution import fibonacci, find_7th_fibonacci
def test_fibonacci_base_cases():
assert fibonacci(1) == 0
assert fibonacci(2) == 1
def test_fibonacci_sequential():
assert fibonacci(3) == 1
assert fibonacci(4) == 2
assert fibonacci(5) == 3
assert fibonacci(6) == 5
def test_fibonacci_7th():
... | [
{
"docstring": "Returns the nth number in the Fibonacci sequence using an iterative approach.",
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_7th_fibonacci():",
"function_na... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci(n):\n \"\"\"\n Returns the nth number in the Fibonacci sequence using an iterative approach.\n\n :param n: The position of the number in the Fibonacci sequence\n :ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069762",
"row_id": 69762,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141366']"
} | 0.662146 | Filter_69762 | I | [
"fibonacci",
"find_7th_fibonacci"
] | 2 | [
[
"find_7th_fibonacci",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de69915126815bba4b45cf129b0c6c89978ba430 | 68baaf9791130079faf3e1a19e6695a04d26b88f | |||
v1.0 | instruct | Filter | Filter_69792_I | Write a Python code snippet that calculates the sum of all prime numbers within a given range, say from 1 to 50, using a while loop. | def is_prime(n):
"""
Checks if a number n is prime.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def sum_primes_in_range(start, end):
"""
Returns the sum of all prime numbers in the given range [start... | from solution import is_prime, sum_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(19) == True
def test_sum_primes_in_r... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers in the given range [start, end].",
"function_declaration": "def sum_primes_in_range(st... | [
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 prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069792",
"row_id": 69792,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141420']"
} | 0.621421 | Filter_69792 | I | [
"is_prime",
"sum_primes_in_range"
] | 2 | [
[
"sum_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3f0f7dcdcea73b12fa035a8cf007f0f3ddabfd85 | aa96681027219f6f67ecc8f2457f29772612557c | |||
v1.0 | instruct | Filter | Filter_69820_I | How can I simulate a simple dice game in Python where two players roll a die and the player with the higher roll wins? If the rolls are equal, it's a tie. | import random
def roll_die():
"""
Simulates rolling a six-sided die.
"""
return random.randint(1, 6)
def dice_game():
"""
Simulates a dice game where two players roll a die.
The player with the higher roll wins. If the rolls are equal, it's a tie.
Returns the result as a tuple: (player... | from solution import roll_die, dice_game
import pytest
def test_roll_die_range():
# Test if roll_die returns a value between 1 and 6 inclusive
for _ in range(1000):
assert 1 <= roll_die() <= 6
def test_dice_game_player_1_wins(monkeypatch):
# Mock roll_die to force player 1 to roll a higher number ... | [
{
"docstring": "Simulates rolling a six-sided die.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a dice game where two players roll a die.\nThe player with the higher roll wins. If the rolls are equal, it's a tie... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"\n Simulates rolling a 6-sided die and returns the result (between 1 and 6).\n \"\"\"\n return random.randint(1, 6)\n\ndef play_dice_game()... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069820",
"row_id": 69820,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141479']"
} | 0.48073 | Filter_69820 | I | [
"roll_die",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04587afd43dceb873d7f77f3b5072e6696536180 | 383a5de570181357f8b2afc3e4ecb789de6d07ab | |||
v1.0 | instruct | Filter | Filter_69837_I | Please provide the code to implement a K-Nearest Neighbors (KNN) algorithm using the Euclidean distance metric in Python. You should include the code for data preprocessing, model training, and evaluation. | import numpy as np
from collections import Counter
def euclidean_distance(point1, point2):
"""
Computes the Euclidean distance between two points.
"""
return np.sqrt(np.sum((point1 - point2) ** 2))
def preprocess_data(features, labels):
"""
Preprocesses the data (e.g., normalization, handling ... | import numpy as np
from solution import euclidean_distance, preprocess_data, knn_predict, knn, evaluate
def test_euclidean_distance():
assert np.isclose(euclidean_distance(np.array([1, 1]), np.array([4, 5])), 5.0)
assert np.isclose(euclidean_distance(np.array([0, 0]), np.array([3, 4])), 5.0)
def test_preproce... | [
{
"docstring": "Computes the Euclidean distance between two points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Preprocesses the data (e.g., normalization, handling missing... | [
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\nfrom collections import Counter\n\nclass KNearestNeighbors:\n def __init__(self, k=3):\n self.k = k\n\n def fit(self, X_train, y_train):\n self.X_train ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069837",
"row_id": 69837,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141512']"
} | 0.640662 | Filter_69837 | I | [
"euclidean_distance",
"preprocess_data",
"knn_predict",
"knn",
"evaluate"
] | 5 | [
[
"knn",
"knn_predict"
],
[
"knn_predict",
"euclidean_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 290ec7aa7dd2b619f245ef42f8a5617aa6bd0892 | a71be21f8d2dc56aa8ce919c68679063130a49a8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.