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_65913_I | How can I create a Python script to simulate a basic game where a player solves a maze by moving through it? The maze should be represented as a grid, and the player can move in four directions: up, down, left, and right. The player starts at the top-left corner and wins by reaching the bottom-right corner. The player ... | def is_valid_move(maze, position):
rows = len(maze)
cols = len(maze[0])
row, col = position
if 0 <= row < rows and 0 <= col < cols and maze[row][col] == 0:
return True
return False
def move_player(maze, position, direction):
row, col = position
if direction == "up":
new_posi... | from solution import is_valid_move, move_player, solve_maze
def test_is_valid_move():
maze = [
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]
]
assert is_valid_move(maze, (0, 0)) == True
assert is_valid_move(maze, (0, 1)) == False
assert is_valid_move(maze, (2, 2)) == True
assert is_va... | [
{
"docstring": null,
"function_declaration": "def is_valid_move(maze, position):",
"function_name": "is_valid_move",
"parameter_list": "(maze, position)"
},
{
"docstring": null,
"function_declaration": "def move_player(maze, position, direction):",
"function_name": "move_player",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class MazeGame:\n def __init__(self, maze):\n self.maze = maze\n self.player_pos = (0, 0)\n self.end_pos = (len(maze) - 1, len(maze[0]) - 1)\n\n def move_up(self):\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00065913",
"row_id": 65913,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133479']"
} | 0.451623 | Filter_65913 | I | [
"is_valid_move",
"move_player",
"solve_maze"
] | 3 | [
[
"move_player",
"is_valid_move"
],
[
"solve_maze",
"move_player"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | aa10ecf070b42883c386845986dc76475e9c2c2a | 92823964ea0b5276cd025c13c25312e2e3c5e22c | |||
v1.0 | instruct | Filter | Filter_65946_I | Create a Python script to implement a basic calculator that can perform addition, subtraction, multiplication, and division. The script should be user-friendly and allow the user to input values and choose the operation they wish to perform. It should also handle invalid inputs gracefully. | 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... | import pytest
from solution import add, subtract, multiply, divide
def test_add():
assert add(4, 5) == 9
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(-1, -1) == 0
assert subtract(5, 10) == -5
def test_multiply():
assert mult... | [
{
"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,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_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 when b is subtracted from a.\n \"\"\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00065946",
"row_id": 65946,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133544']"
} | 0.617744 | Filter_65946 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9251e66e9e13c0b7b0725b92d81de08637cadcf4 | 317506eebe07be8201537af8a2f795205f5c9f60 | |||
v1.0 | instruct | Filter | Filter_65952_I | I need to generate a Python function that calculates the sum of all prime numbers within a given range. The function should take two parameters, `start` and `end`, and return the sum of all prime numbers between these two numbers, inclusive. How can I implement this? | def is_prime(n):
"""
Helper function to determine if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import sum_of_primes_in_range
def test_sum_of_primes_in_range_basic():
assert sum_of_primes_in_range(10, 20) == 60 # primes: 11, 13, 17, 19
def test_sum_of_primes_in_range_single_prime():
assert sum_of_primes_in_range(17, 17) == 17 # single prime is 17
def test_sum_of_primes_in_range_no_prime... | [
{
"docstring": "Helper function to determine 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 in the range [start, end].",
"function_declaration": "def sum_of_p... | [
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 determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 o... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00065952",
"row_id": 65952,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133557']"
} | 0.623536 | Filter_65952 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f4535924bd057db8a7d2d56b65ba95169eddc668 | e47bb17063901d2e06dd4c6f39a90aa3f0f50b45 | |||
v1.0 | instruct | Filter | Filter_65972_I | Could you provide a detailed explanation of how to set up a custom training loop for a neural network from scratch in Python, including defining the model, loss function, optimizer, and the training process? | import numpy as np
# Define the Model
class SimpleNeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.weights1 = np.random.randn(input_size, hidden_size)
self... | import numpy as np
from solution import SimpleNeuralNetwork, SGDOptimizer, train
def test_forward_pass_dimensions():
model = SimpleNeuralNetwork(input_size=3, hidden_size=5, output_size=1)
X = np.random.rand(2, 3)
y_pred = model.forward(X)
assert y_pred.shape == (2, 1)
def test_loss_function():
y_... | [] | [
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\n# Define a simple neural network model\nclass SimpleNN:\n def __init__(self, input_size, hidden_size, output_size):\n self.W1 = np.random.randn(input_size, hidd... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00065972",
"row_id": 65972,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133584']"
} | 0.36112 | Filter_65972 | I | [
"mse_loss",
"train"
] | 2 | [
[
"train",
"mse_loss"
]
] | 1 | [] | false | [
"SimpleNeuralNetwork",
"SGDOptimizer"
] | true | pytest | true | [
"numpy"
] | false | 5df0418519e0c772ee09dc1b7fb8c8316a70f6aa | 3490dd584caff2661922a9e7140218824dfa340d | |||
v1.0 | instruct | Filter | Filter_65995_I | Write a Python function to filter out all prime numbers from a given list of integers. The function should return a new list containing only the non-prime numbers from the original list. | def is_prime(n):
"""
Helper function to determine if a given number n is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def f... | from solution import filter_non_prime_numbers
def test_filter_non_prime_numbers_mixed():
assert filter_non_prime_numbers([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [4, 6, 8, 9, 10]
def test_filter_non_prime_numbers_all_non_prime():
assert filter_non_prime_numbers([4, 6, 8, 9, 10, 12]) == [4, 6, 8, 9, 10, 12]
def test_... | [
{
"docstring": "Helper function to determine if a given number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filters out the prime numbers from a list of integers.\n\nParameters:\nnumbers (list): A list of in... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00065995",
"row_id": 65995,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133635']"
} | 0.643279 | Filter_65995 | I | [
"is_prime",
"filter_non_prime_numbers"
] | 2 | [
[
"filter_non_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e92676aab6efbf4729258e7fe7b5e7fc03eb1920 | 707977aacd80e430a3eaa3c819b82af7347e80d7 | |||
v1.0 | instruct | Filter | Filter_66013_I | Can you provide me with a Python code to implement a simple encryption and decryption using the Caesar Cipher technique? | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the input `text` using the Caesar Cipher technique with the given `shift`.
Parameters:
text (str): The plaintext to be encrypted.
shift (int): The number of characters to shift.
Returns:
str: The encrypted ciphertext.
"""
... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("HELLO", 3) == "KHOOR"
assert caesar_cipher_encrypt("hello", 3) == "khoor"
assert caesar_cipher_encrypt("HELLO, WORLD!", 5) == "MJQQT, BTWQI!"
assert caesar_cipher_encrypt("a... | [
{
"docstring": "Encrypts the input `text` using the Caesar Cipher technique with the given `shift`.\n\nParameters:\ntext (str): The plaintext to be encrypted.\nshift (int): The number of characters to shift.\n\nReturns:\nstr: The encrypted ciphertext.",
"function_declaration": "def caesar_cipher_encrypt(tex... | [
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(text, shift):\n \"\"\"\n Encrypts the input text using Caesar Cipher technique with the given shift.\n \n Args:\n text (str): The string to be encrypte... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066013",
"row_id": 66013,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133673']"
} | 0.618734 | Filter_66013 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1b454b265d498f84f5cd5b6ddd12836995dc4abb | e95299b5857772998678662679322fd17faad6dd | |||
v1.0 | instruct | Filter | Filter_66014_I | Hello! How can I get a Python program to output the first 10 prime numbers? | def is_prime(num):
"""
Check if a number is prime.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def first_n_primes(n):
"""
Return the first n prime numbers.
"""
primes = []
num = 2
... | from solution import is_prime, first_n_primes, first_10_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
def test_fir... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Return the first n prime numbers.",
"function_declaration": "def first_n_primes(n):",
"function_name": "first_n_primes... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066014",
"row_id": 66014,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133675']"
} | 0.612041 | Filter_66014 | I | [
"is_prime",
"first_n_primes",
"first_10_primes"
] | 3 | [
[
"first_10_primes",
"first_n_primes"
],
[
"first_n_primes",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8a2681ea2e505ac05b13fe0f2a638a3b54877bc3 | 73ae945f301bfa5c9dbfe66ab18b477de4d9adee | |||
v1.0 | instruct | Filter | Filter_66015_I | What is the best way to create a dynamic URL shortener service using Python? | from flask import Flask, request, redirect, jsonify
import string
import random
app = Flask(__name__)
# A dictionary to store the long and short URL mappings
url_map = {}
# Base URL for the short URLs
BASE_URL = "http://short.url/"
SHORT_URL_LENGTH = 6
def generate_short_url():
"""
Generates a random string... | import pytest
from solution import app, url_map, generate_short_url
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_shorten_url(client):
response = client.post('/shorten', json={'long_url': 'https://example.com'})
assert response.status_code == 200
data = ... | [
{
"docstring": "Generates a random string of fixed length to be used as a short URL.",
"function_declaration": "def generate_short_url():",
"function_name": "generate_short_url",
"parameter_list": "()"
},
{
"docstring": "Endpoint to shorten a given long URL.",
"function_declaration": "de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport random\nimport string\n\nclass URLShortener:\n def __init__(self):\n self.url_mapping = {}\n self.short_url_prefix = \"http://short.url/\"\n \n de... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066015",
"row_id": 66015,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133680']"
} | 0.501197 | Filter_66015 | I | [
"generate_short_url",
"shorten_url",
"redirect_url"
] | 3 | [
[
"shorten_url",
"generate_short_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 20f87633847069b5992ab1f3e6c66fe2209517be | decf9b159fc1abc9ddc2439b70c09e5e5dde73eb | |||
v1.0 | instruct | Filter | Filter_66027_I | How can I create a simple web application using Flask that calculates the factorial of a number? | from flask import Flask, request, jsonify
app = Flask(__name__)
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
@app.route('/factorial', methods=['GET'])
def calculate_factorial():
try:
number = int(request.args.get('number'))
if number < 0:
... | import pytest
from solution import factorial
def test_factorial_positive_number():
assert factorial(5) == 120
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_one():
assert factorial(1) == 1
def test_factorial_large_number():
assert factorial(10) == 3628800
def test_factorial_... | [
{
"docstring": null,
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def calculate_factorial():",
"function_name": "calculate_factorial",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nimport math\n\napp = Flask(__name__)\n\n@app.route('/factorial', methods=[\"GET\"])\ndef factorial():\n try:\n number = int(request.args.ge... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066027",
"row_id": 66027,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133707']"
} | 0.510637 | Filter_66027 | I | [
"factorial",
"calculate_factorial"
] | 2 | [
[
"calculate_factorial",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | d225df2fcf9afed632ecaec6f13537c8f0568eeb | a3471f568baa305810bf12b892fbeac64c5fa280 | |||
v1.0 | instruct | Filter | Filter_66074_I | How can I create a Python script to calculate the total distance traveled by a drone based on its flight log data, assuming the drone starts from the origin (0,0)? The flight log includes GPS coordinates in latitude and longitude, and a function to convert these to distances in meters would be helpful. The data is in C... | import csv
from math import radians, sin, cos, sqrt, atan2
def haversine(lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance in meters between two points (specified in decimal degrees).
"""
R = 6371000 # Radius of Earth in meters
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2... | import pytest
from solution import haversine, calculate_total_distance
def test_haversine_same_point():
assert haversine(0, 0, 0, 0) == 0
def test_haversine_known_distance():
# Distance between (50.06638889, -5.71472222) and (58.64388889, -3.07) is approximately 968853.5 meters
result = haversine(50.06638... | [
{
"docstring": "Calculate the great circle distance in meters between two points (specified in decimal degrees).",
"function_declaration": "def haversine(lat1, lon1, lat2, lon2):",
"function_name": "haversine",
"parameter_list": "(lat1, lon1, lat2, lon2)"
},
{
"docstring": "Calculate the tot... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nfrom math import radians, sin, cos, sqrt, atan2\n\ndef haversine(lat1, lon1, lat2, lon2):\n \"\"\"\n Calculate the great circle distance between two points \n on the earth... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066074",
"row_id": 66074,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133797']"
} | 0.422341 | Filter_66074 | I | [
"haversine",
"calculate_total_distance"
] | 2 | [
[
"calculate_total_distance",
"haversine"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 125f23394722f8d7adda5ebe93af45039e350771 | b63b4ff78d3710678e26f1d857525ccec54a0feb | |||
v1.0 | instruct | Filter | Filter_66083_I | I want to create a Python program to simulate the motion of a simple pendulum. How can I do that? | import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
def pendulum_ode(t, y, g, L):
"""
Defines the ODEs for the simple pendulum.
Parameters:
t : float
The current time.
y : array_like
The current values of the dependent variables [theta, omeg... | import numpy as np
from solution import pendulum_ode, simulate_pendulum
from scipy.integrate import solve_ivp
def test_pendulum_ode():
t = 0
y = [np.pi / 4, 0]
g = 9.81
L = 1.0
dydt = pendulum_ode(t, y, g, L)
assert len(dydt) == 2
assert isinstance(dydt, list)
assert np.isclose(dydt[0],... | [
{
"docstring": "Defines the ODEs for the simple pendulum.\n\nParameters:\nt : float\n The current time.\ny : array_like\n The current values of the dependent variables [theta, omega].\ng : float\n The acceleration due to gravity.\nL : float\n The length of the pendulum.\n \nReturns:\ndydt : array... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef simulate_simple_pendulum(theta_0, length, g, dt, total_time):\n \"\"\"\n Simulates the motion of a simple pendulum using Euler's method.\n \n Args:\n t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066083",
"row_id": 66083,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133813']"
} | 0.372814 | Filter_66083 | I | [
"pendulum_ode",
"simulate_pendulum"
] | 2 | [
[
"simulate_pendulum",
"pendulum_ode"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | cb35739d03d23a1cd682ffec060b2e1f652d10e7 | de2224dbc9e75570338952c4d7b341863ccc0768 | |||
v1.0 | instruct | Filter | Filter_66113_I | Given a binary tree, write a Python function to print the boundary nodes of the binary tree. The boundary of a binary tree includes the nodes on the left boundary, the leaf nodes (excluding the left boundary nodes that are also leaf nodes), and the nodes on the right boundary in a clockwise direction. | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_leaf(node):
return node is not None and node.left is None and node.right is None
def add_left_boundary(node, boundary):
while node:
if not is_le... | from solution import TreeNode, boundary_of_binary_tree
def test_boundary_of_binary_tree_empty():
assert boundary_of_binary_tree(None) == []
def test_boundary_of_binary_tree_single_node():
root = TreeNode(1)
assert boundary_of_binary_tree(root) == [1]
def test_boundary_of_binary_tree_perfect_binary_tree()... | [] | [
0,
1,
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):\n self.left = None\n self.right = None\n self.data = key\n\ndef print_boundary_nodes(root):\n \"\"\"\n Returns the boun... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066113",
"row_id": 66113,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133873']"
} | 0.560333 | Filter_66113 | I | [
"is_leaf",
"add_left_boundary",
"add_leaves",
"add_right_boundary",
"boundary_of_binary_tree"
] | 5 | [
[
"add_leaves",
"is_leaf"
],
[
"add_left_boundary",
"is_leaf"
],
[
"add_right_boundary",
"is_leaf"
],
[
"boundary_of_binary_tree",
"add_leaves"
],
[
"boundary_of_binary_tree",
"add_left_boundary"
],
[
"boundary_of_binary_tree",
"add_right_boundary"... | 7 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 7488726fff83d6fa1a003fd843feb3d96e92dfb6 | ab421969669708ee8cdf87d9b8a231bead4a71e7 | |||
v1.0 | instruct | Filter | Filter_66152_I | I need to implement a traveling salesperson problem (TSP) solver in Python. The TSP is a classic optimization problem where the goal is to find the shortest possible route that visits a set of cities and returns to the origin city. How can I implement a simple version of this using a brute force approach? | import itertools
def calculate_distance(route, distance_matrix):
"""
Given a route and a distance matrix, calculates the total distance of the route.
"""
total_distance = 0
for i in range(len(route) - 1):
total_distance += distance_matrix[route[i]][route[i + 1]]
# Return to the origin c... | from solution import calculate_distance, solve_tsp
def test_calculate_distance():
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
route = (0, 1, 2, 3)
assert calculate_distance(route, distance_matrix) == 95
def test_solve_tsp_wit... | [
{
"docstring": "Given a route and a distance matrix, calculates the total distance of the route.",
"function_declaration": "def calculate_distance(route, distance_matrix):",
"function_name": "calculate_distance",
"parameter_list": "(route, distance_matrix)"
},
{
"docstring": "Solves the TSP ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef calculate_total_distance(distance_matrix, tour):\n \"\"\"\n Calculate the total distance of a given tour based on the distance matrix.\n\n Args:\n distance_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066152",
"row_id": 66152,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133959']"
} | 0.540108 | Filter_66152 | I | [
"calculate_distance",
"solve_tsp"
] | 2 | [
[
"solve_tsp",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ba5c9bfffaadd9b162055873e4d997da06fba7b | 559351efaca00aabd74a7904c581d2fafe125c14 | |||
v1.0 | instruct | Filter | Filter_66164_I | I need help generating code for a simple calculator in Python that can perform basic arithmetic operations like addition, subtraction, multiplication, and division. The calculator should take input from the user to choose the operation and then input two numbers to perform the operation on. It should also handle divisi... | def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero"
return a / b
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
... | from solution import add, subtract, multiply, divide
def test_add():
assert add(10, 5) == 15
assert add(-1, -1) == -2
assert add(0, 0) == 0
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(0, 5) == -5
assert subtract(-1, -1) == 0
def test_multiply():
assert multiply(10, 5)... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n return \"Error: Division by zer... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066164",
"row_id": 66164,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_133975']"
} | 0.630821 | Filter_66164 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 71509632ea180a6aa1fb5c57e90ee1145468422f | d23cd9c6175f424c492dded805767dbf1a75cec8 | |||
v1.0 | instruct | Filter | Filter_66177_I | Can you provide a detailed explanation of the PyTorch DataLoader class, including its creation, configuration options, and usage in a training loop? | import torch
from torch.utils.data import DataLoader, Dataset
class MyDataset(Dataset):
def __init__(self):
# Initialization code here
self.data = [i for i in range(100)]
def __len__(self):
return len(self.data)
def __getitem__(self, index):
# Return a data sample given an... | from solution import MyDataset, create_data_loader, train_model, SimpleModel
def test_my_dataset():
dataset = MyDataset()
assert len(dataset) == 100
assert dataset[0] == 0
assert dataset[99] == 99
def test_data_loader_creation():
data_loader = create_data_loader()
first_batch = next(iter(data_... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.utils.data import Dataset, DataLoader\n\nclass MyDataset(Dataset):\n def __init__(self, data, labels):\n self.data = data\n self.labels = labels\n\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066177",
"row_id": 66177,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134012']"
} | 0.287583 | Filter_66177 | I | [
"create_data_loader",
"train_model"
] | 2 | [
[
"train_model",
"create_data_loader"
]
] | 1 | [] | false | [
"MyDataset",
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 08947278df4074234193800fce640522708f2def | e62a671e7c2ae78d2e95c73da550d43dda48d8b2 | |||
v1.0 | instruct | Filter | Filter_66189_I | Using the Python programming language, could you provide a code snippet that calculates the factorial of a number and saves the result to a text file? | def factorial(n):
"""
Returns the factorial of a given number n.
If n is 0, the function returns 1.
"""
if n == 0:
return 1
result = 1
for i in range(1, n + 1):
result *= i
return result
def save_factorial_to_file(n, file_path):
"""
Calculates the factorial of n ... | from solution import factorial, save_factorial_to_file
def test_factorial():
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(5) == 120
assert factorial(10) == 3628800
def test_save_factorial_to_file(tmpdir):
file_path = tmpdir.join("factorial_result.txt")
save_factorial_to_f... | [
{
"docstring": "Returns the factorial of a given number n.\nIf n is 0, the function returns 1.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Calculates the factorial of n and saves the result to a specified text file."... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n Calculate the factorial of a given number n.\n \"\"\"\n if n < 0:\n raise ValueError(\"Factorial is not defined for negative numbers.\")\n if... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066189",
"row_id": 66189,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134037']"
} | 0.579232 | Filter_66189 | I | [
"factorial",
"save_factorial_to_file"
] | 2 | [
[
"save_factorial_to_file",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a74ed89a245a81f30320075969d1e680ccee05d | eda05dddbca79060f065683eabaef93b07289aed | |||
v1.0 | instruct | Filter | Filter_66191_I | Write a Python code to simulate a simple blockchain network using pandas for data manipulation. This code should include the creation of blocks and adding them to the blockchain, with each block containing a timestamp, the hash of the previous block, and a simple data payload. | import pandas as pd
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... | from solution import (Block, calculate_hash, create_genesis_block, create_new_block, create_blockchain, add_block_to_blockchain, blockchain_to_dataframe)
import time
import pandas as pd
def test_genesis_block():
genesis_block = create_genesis_block()
assert genesis_block.index == 0
assert genesis_block.pre... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport time\nimport pandas as pd\n\nclass Block:\n def __init__(self, index, data, previous_hash):\n self.index = index\n self.timestamp = time.time()\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066191",
"row_id": 66191,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134040']"
} | 0.43075 | Filter_66191 | I | [
"calculate_hash",
"create_genesis_block",
"create_new_block",
"create_blockchain",
"add_block_to_blockchain",
"blockchain_to_dataframe"
] | 6 | [
[
"add_block_to_blockchain",
"create_new_block"
],
[
"create_blockchain",
"create_genesis_block"
],
[
"create_genesis_block",
"calculate_hash"
],
[
"create_new_block",
"calculate_hash"
]
] | 4 | [] | false | [
"Block"
] | true | pytest | true | [
"pandas"
] | false | a54542826f0074733333cbb48b016d1943b922ac | 6383bc9aa62ffb4cc2bfbd533c681a507a29be54 | |||
v1.0 | instruct | Filter | Filter_66195_I | How can I create a function in Python to dynamically generate SQL queries based on user input for filtering data in a database? | import sqlite3
def generate_query(table, filters):
"""
Generates an SQL query for retrieving data from a given table with specified filters.
Parameters:
- table (str): The name of the table.
- filters (dict): A dictionary of column-value pairs for filtering the data.
Returns:
- str: A par... | import sqlite3
import pytest
from solution import generate_query, fetch_data
def setup_database(conn):
"""
Sets up a sample database for testing purposes.
Parameters:
- conn (sqlite3.Connection): The SQLite connection object.
"""
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF N... | [
{
"docstring": "Generates an SQL query for retrieving data from a given table with specified filters.\n\nParameters:\n- table (str): The name of the table.\n- filters (dict): A dictionary of column-value pairs for filtering the data.\n\nReturns:\n- str: A parameterized SQL query string.\n- tuple: A tuple of val... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_sql_query(table, filters):\n \"\"\"\n Generate a SQL query based on the table name and a dictionary of filters.\n\n Args:\n table (str): The name of the table to query... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066195",
"row_id": 66195,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134046']"
} | 0.519704 | Filter_66195 | I | [
"generate_query",
"fetch_data"
] | 2 | [
[
"fetch_data",
"generate_query"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b7ba0ccaf763ff97b246e9b51abb2ee7026bd17a | 83abeef93d392bae0abc2419b1cd48d05c2e7ce3 | |||
v1.0 | instruct | Filter | Filter_66219_I | Can you explain how the heap sort algorithm works and provide a Python implementation? | def heapify(arr, n, i):
"""
Converts a subtree rooted with node i into a max heap, assuming the subtrees are already heaps.
"""
largest = i # Initialize largest as root
left = 2 * i + 1 # left = 2*i + 1
right = 2 * i + 2 # right = 2*i + 2
if left < n and arr[i] < arr[left]:
... | from solution import heap_sort
def test_heap_sort_with_positive_numbers():
assert heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
def test_heap_sort_with_negative_numbers():
assert heap_sort([0, -1, -9, -4, -8]) == [-9, -8, -4, -1, 0]
def test_heap_sort_with_mixed_numbers():
assert heap_sort([-3, 4, 0, -... | [
{
"docstring": "Converts a subtree rooted with node i into a max heap, assuming the subtrees are already heaps.",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Main function that sorts an array using heap sor... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i):\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < n and arr[i] < arr[left]:\n largest = left\n\n if right < n and arr[largest] < ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066219",
"row_id": 66219,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134094']"
} | 0.707989 | Filter_66219 | I | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d52f1efe76887ae437c2a627a862a0e9e3041b6a | 3f31ba0fca035ed50472b290696fa278eae25d70 | |||
v1.0 | instruct | Filter | Filter_66247_I | How can I create a Python program to automate the process of validating multiple email addresses in a CSV file using regular expressions? | import re
import csv
def validate_email(email):
"""
Returns True if the email is valid, False otherwise.
"""
# Define the regular expression for a valid email
email_regex = re.compile(
r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
)
return re.match(email_regex, email) is not... | import re
from solution import validate_email, validate_emails_in_csv
def test_validate_email_valid():
assert validate_email('test@example.com') == True
assert validate_email('user.name+tag+sorting@example.com') == True
assert validate_email('user.name@example.co.uk') == True
def test_validate_email_inval... | [
{
"docstring": "Returns True if the email is valid, False otherwise.",
"function_declaration": "def validate_email(email):",
"function_name": "validate_email",
"parameter_list": "(email)"
},
{
"docstring": "Reads emails from a CSV file and returns a list of tuples\ncontaining the email and i... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nimport csv\n\ndef validate_email(email):\n \"\"\"\n Validates if the given email address matches the standard email pattern.\n \"\"\"\n email_regex = re.compile(\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066247",
"row_id": 66247,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134137']"
} | 0.637206 | Filter_66247 | I | [
"validate_email",
"validate_emails_in_csv"
] | 2 | [
[
"validate_emails_in_csv",
"validate_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 289ccdc2249bec1669119e8affb9dd791b307cbd | d3d530bdc8172532211bb549bb1f23c5dfa6334f | |||
v1.0 | instruct | Filter | Filter_66306_I | Can you provide a simple code snippet to demonstrate how to use the PyTorch framework to train a neural network with a custom dataset in PyTorch? | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
# Define a simple custom dataset
class CustomDataset(Dataset):
def __init__(self):
# Generate some random data for example purposes
self.data = torch.randn(100, 10)
self.labels = ... | import torch
from solution import get_trained_model, CustomDataset, SimpleNN
def test_model_structure():
model = SimpleNN()
assert isinstance(model, nn.Module)
assert hasattr(model, 'fc1')
assert hasattr(model, 'fc2')
def test_model_output():
model = SimpleNN()
sample_input = torch.randn(1, 10... | [] | [
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, Dataset\n\n# Define a simple dataset\nclass CustomDataset(Dataset):\n def __init__... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066306",
"row_id": 66306,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134260']"
} | 0.290768 | Filter_66306 | I | [
"train_model",
"get_trained_model"
] | 2 | [
[
"get_trained_model",
"train_model"
]
] | 1 | [] | false | [
"CustomDataset",
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 8a395fec5a8a493f2a2255b0073ce077c707aec0 | 0dd1da43b1f4142a8278a3a5b9665861907b7e95 | |||
v1.0 | instruct | Filter | Filter_66315_I | Hello Qwen, can you generate a Python script that reads a list of email addresses from a CSV file, checks each email for proper formatting using regular expressions, and then writes the valid emails to a new CSV file? | import csv
import re
def is_valid_email(email):
"""
Checks if the provided email is in a valid format.
"""
email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(email_regex, email) is not None
def filter_valid_emails(input_csv, output_csv):
"""
Reads a list of e... | import os
from solution import is_valid_email, filter_valid_emails
def test_is_valid_email():
assert is_valid_email("test@example.com")
assert is_valid_email("user.name+tag+sorting@example.com")
assert not is_valid_email("plainaddress")
assert not is_valid_email("@missingusername.com")
assert not i... | [
{
"docstring": "Checks if the provided email is in a valid format.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "Reads a list of email addresses from input_csv, checks each for proper formatting,\nand... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport re\n\ndef validate_email(email):\n \"\"\"\n Validates the email address using a regular expression.\n \"\"\"\n # Define a regular expression for validating an em... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066315",
"row_id": 66315,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134272']"
} | 0.69237 | Filter_66315 | I | [
"is_valid_email",
"filter_valid_emails"
] | 2 | [
[
"filter_valid_emails",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a85d14cf48dd64ff0dd4d00bbcce1aaa4ef8ed8 | 3ac9678432747b66e28d187f27f3fe912d5d1e81 | |||
v1.0 | instruct | Filter | Filter_66353_I | Generate a set of Python functions that perform various operations on vectors, including vector addition, subtraction, dot product, and normalization. Ensure that all functions handle vectors of arbitrary dimensions and include proper error handling. | import math
def vector_add(v1, v2):
"""
Adds two vectors element-wise.
"""
if len(v1) != len(v2):
raise ValueError("Vectors must be of the same length")
return [a + b for a, b in zip(v1, v2)]
def vector_subtract(v1, v2):
"""
Subtracts the second vector from the first vector element... | from solution import vector_add, vector_subtract, vector_dot, vector_normalize, vector_magnitude
def test_vector_add():
assert vector_add([1, 2], [3, 4]) == [4, 6]
assert vector_add([-1, -2], [-3, -4]) == [-4, -6]
def test_vector_subtract():
assert vector_subtract([1, 2], [3, 4]) == [-2, -2]
assert ve... | [
{
"docstring": "Adds two vectors element-wise.",
"function_declaration": "def vector_add(v1, v2):",
"function_name": "vector_add",
"parameter_list": "(v1, v2)"
},
{
"docstring": "Subtracts the second vector from the first vector element-wise.",
"function_declaration": "def vector_subtrac... | [
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 vector_add(v1, v2):\n \"\"\"Returns the element-wise addition of two vectors.\"\"\"\n if len(v1) != len(v2):\n raise ValueError(\"Vectors must be of the same le... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066353",
"row_id": 66353,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134348']"
} | 0.491802 | Filter_66353 | I | [
"vector_add",
"vector_subtract",
"vector_dot",
"vector_magnitude",
"vector_normalize"
] | 5 | [
[
"vector_normalize",
"vector_magnitude"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9981bd19060b963ee898861df2a1770b04f22c6 | 198fa1090968d2acec039b1445b0bfd7c694db76 | |||
v1.0 | instruct | Filter | Filter_66380_I | Can you provide a detailed explanation of the implementation of the merge sort algorithm in Python? | def merge_sort(arr):
"""
Sorts an array of integers using the merge sort algorithm.
:param arr: List of integers to sort.
:return: A new list containing sorted integers.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge... | from solution import merge_sort
def test_merge_sort_with_unsorted_list():
assert merge_sort([4, 2, 7, 1, 3]) == [1, 2, 3, 4, 7]
def test_merge_sort_with_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_with_reverse_sorted_list():
assert merge_sort([5, 4, 3, 2, 1]) ... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.\n:param arr: List of integers to sort.\n:return: A new list containing sorted integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Mer... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array using the merge sort algorithm.\n \"\"\"\n if len(arr) > 1:\n # Find the middle point and divide the array\n mid = len(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066380",
"row_id": 66380,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134401']"
} | 0.529278 | Filter_66380 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | beddaacdb45cfe53e54f031cbfef85c66b499c8d | 36745ec6598f4db82ad0cc9d1c0781679f0cc659 | |||
v1.0 | instruct | Filter | Filter_66404_I | Can you provide a Python code snippet that adds timestamps to a list of strings and prints them? | from datetime import datetime
def add_timestamps(messages):
"""
Adds current timestamp to each message in the list and returns the list of timestamped messages.
:param messages: List of strings.
:return: List of strings with timestamps.
"""
timestamped_messages = []
current_time = date... | from solution import add_timestamps
def test_add_timestamps():
messages = ["Hello", "World"]
timestamped_messages = add_timestamps(messages)
assert len(timestamped_messages) == 2
assert timestamped_messages[0].startswith("[")
assert timestamped_messages[0].endswith("] Hello")
assert timest... | [
{
"docstring": "Adds current timestamp to each message in the list and returns the list of timestamped messages.\n\n:param messages: List of strings.\n:return: List of strings with timestamps.",
"function_declaration": "def add_timestamps(messages):",
"function_name": "add_timestamps",
"parameter_li... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef add_timestamps(strings):\n \"\"\"\n Adds a timestamp to each string in the list of strings.\n\n Args:\n strings (list): A list of strings.\n\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066404",
"row_id": 66404,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134450']"
} | 0.575296 | Filter_66404 | I | [
"add_timestamps",
"print_timestamped_messages"
] | 2 | [
[
"print_timestamped_messages",
"add_timestamps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6501a2b80ef64bb7c68c50a930862a8b403a7cac | 227ccf283525138d5767b26ec72e110ef2787402 | |||
v1.0 | instruct | Filter | Filter_66429_I | Can you provide a Python program that can sort a list of integers using the merge sort algorithm? | def merge_sort(arr):
"""
Sorts an array of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, right):
... | from solution import merge_sort
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_merge_sort_unsorted_list():
assert merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two halves in sorted order.",
"function_declaration": "def merge(left, right):",... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts a list of integers using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_h... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066429",
"row_id": 66429,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134502']"
} | 0.599417 | Filter_66429 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1dee1320312190f1f1b9c307245c64e928babf87 | 0e276ce96e8610217b28f6164466a0dd180b9b09 | |||
v1.0 | instruct | Filter | Filter_66436_I | I have a JSON file with mixed data types, including numbers, strings, and arrays. How can I parse this JSON file in Python and print out each key-value pair? Traverse the JSON content recursively if it contains nested objects or arrays. | import json
def parse_json_recursively(data, indent=0):
"""
Recursively parse JSON data and print out each key-value pair.
:param data: JSON data as a dictionary or list
:param indent: Current level of indentation (used for nested objects/arrays)
"""
indent_str = ' ' * indent
if isinst... | import json
import pytest
from io import StringIO
from unittest.mock import mock_open, patch
from solution import parse_json_recursively, read_and_parse_json_file
def test_parse_json_recursively_dict(capsys):
data = {
"name": "John",
"age": 30,
"city": "New York",
"details": {
... | [
{
"docstring": "Recursively parse JSON data and print out each key-value pair.\n\n:param data: JSON data as a dictionary or list\n:param indent: Current level of indentation (used for nested objects/arrays)",
"function_declaration": "def parse_json_recursively(data, indent=0):",
"function_name": "parse_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef parse_and_print_json(data, indent=0):\n \"\"\"\n Recursively parse the JSON data and print key-value pairs.\n \"\"\"\n spaces = ' ' * indent\n if isinstance(d... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066436",
"row_id": 66436,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134521']"
} | 0.570352 | Filter_66436 | I | [
"parse_json_recursively",
"read_and_parse_json_file"
] | 2 | [
[
"read_and_parse_json_file",
"parse_json_recursively"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 931f13bd68399ed619bb32d13962e4e989f58739 | a0ced3e9beb815464fc8cd120b7bfe045e7a0932 | |||
v1.0 | instruct | Filter | Filter_66532_I | Can you provide a Python script that takes a list of integers and returns a list of the prime numbers within that list? | def is_prime(n):
"""
Returns 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 = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import is_prime, primes_in_list
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(0) == False
assert is_prime(1) == False
assert is_prime(17) == True
assert is_prime(18) == Fals... | [
{
"docstring": "Returns True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers from the given list of integers.",
"function_declaration": "def prim... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is a prime number.\n \n Args:\n n (int): The number to check.\n \n Returns:\n bool: True if the number is prime, False ot... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066532",
"row_id": 66532,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134700']"
} | 0.631706 | Filter_66532 | I | [
"is_prime",
"primes_in_list"
] | 2 | [
[
"primes_in_list",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31aeab5f7215dd7eb63658bf44362cc230f21d06 | 703cb1b8db22b95fa809e9755a19c187bf6ca211 | |||
v1.0 | instruct | Filter | Filter_66556_I | How can I modify a Python code to handle both JSON and XML data formats? | import json
import xml.etree.ElementTree as ET
def parse_json(data):
"""
Parses the input data as JSON.
Parameters:
data (str): The JSON data as a string.
Returns:
dict: The parsed data.
"""
try:
return json.loads(data)
except json.JSONDecodeError as e:
rai... | import pytest
from solution import parse_json, parse_xml, process_data
def test_parse_json_valid():
json_data = '{"name": "John", "age": 30}'
result = parse_json(json_data)
assert result == {"name": "John", "age": 30}
def test_parse_json_invalid():
json_data = '{"name": "John", "age": 30'
with pyt... | [
{
"docstring": "Parses the input data as JSON.\n\nParameters:\ndata (str): The JSON data as a string.\n\nReturns:\ndict: The parsed data.",
"function_declaration": "def parse_json(data):",
"function_name": "parse_json",
"parameter_list": "(data)"
},
{
"docstring": "Parses the input data as X... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport xml.etree.ElementTree as ET\n\ndef parse_json(data):\n \"\"\"\n Parse JSON data and return the dictionary\n \"\"\"\n return json.loads(data)\n\ndef parse_xml(da... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066556",
"row_id": 66556,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134753']"
} | 0.63614 | Filter_66556 | I | [
"parse_json",
"parse_xml",
"process_data"
] | 3 | [
[
"process_data",
"parse_json"
],
[
"process_data",
"parse_xml"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 981fabb6d12ec98b43b3b1c88bda6f60729be395 | 1710560c8764be92635800795bd9d8eb43f47d68 | |||
v1.0 | instruct | Filter | Filter_66567_I | Write a Python code to solve word jumble puzzle where you are given a set of shuffled letters as a string and you have to find all possible words that can be formed from those letters. The code should use recursion to generate all permutations of the string and then check each permutation to see if it is a valid word i... | from typing import List
def is_valid_word(word: str, dictionary: List[str]) -> bool:
"""
Check if a word is valid by comparing it with the dictionary.
"""
return word in dictionary
def word_jumble(word: str, dictionary: List[str]) -> List[str]:
"""
Solve word jumble puzzle by finding all possi... | from solution import word_jumble
def test_word_jumble_with_simple_word():
dictionary = ["cat", "dog", "tac", "god", "act", "odg"]
word = "cat"
result = word_jumble(word, dictionary)
assert set(result) == {"cat", "tac", "act"}
def test_word_jumble_with_non_dictionary_word():
dictionary = ["hello", ... | [
{
"docstring": "Check if a word is valid by comparing it with the dictionary.",
"function_declaration": "def is_valid_word(word, dictionary):",
"function_name": "is_valid_word",
"parameter_list": "(word, dictionary)"
},
{
"docstring": "Solve word jumble puzzle by finding all possible words t... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef is_valid_word(word, dictionary):\n \"\"\"\n Check if the word is in the dictionary.\n \"\"\"\n return word in dictionary\n\ndef find_valid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066567",
"row_id": 66567,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134781']"
} | 0.609259 | Filter_66567 | I | [
"is_valid_word",
"word_jumble"
] | 2 | [
[
"word_jumble",
"is_valid_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b6bb1a4811bf05aceb32143050d272f748d308d3 | 1779ac439329e40f94cd8197ccecb67cd90393f1 | |||
v1.0 | instruct | Filter | Filter_66578_I | How can I create a custom event handler for a specific message in EventBridge, which listens to messages of type "order.placed" and processes them accordingly? | import json
import boto3
def process_order_placed_event(event):
"""
Processes the 'order.placed' event.
"""
# Implement your logic to process the event here
order_id = event['detail']['order_id']
customer_id = event['detail']['customer_id']
order_amount = event['detail']['order_amount']
... | from solution import lambda_handler, process_order_placed_event
def test_process_order_placed_event():
event = {
"detail": {
"order_id": "123456",
"customer_id": "cust789",
"order_amount": 250.0
}
}
result = process_order_placed_event(event)
assert re... | [
{
"docstring": "Processes the 'order.placed' event.",
"function_declaration": "def process_order_placed_event(event):",
"function_name": "process_order_placed_event",
"parameter_list": "(event)"
},
{
"docstring": "AWS Lambda handler to process EventBridge events.",
"function_declaration"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport boto3\n\ndef create_eventbridge_rule(event_bus_name, rule_name, event_pattern):\n \"\"\"\n Creates an EventBridge rule with the specified pattern.\n \"\"\"\n cl... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066578",
"row_id": 66578,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134802']"
} | 0.187238 | Filter_66578 | I | [
"process_order_placed_event",
"lambda_handler"
] | 2 | [
[
"lambda_handler",
"process_order_placed_event"
]
] | 1 | [] | false | [] | false | pytest | true | [
"boto3"
] | false | d69f16fe2c2bc02a2a882a7d97f0161e17caaa30 | 4e9e641b2429becd5e3540f5003520f91e3de147 | |||
v1.0 | instruct | Filter | Filter_66595_I | describe a Python program that reads a centroid file, processes the coordinates, and calculates the distance between each pair of points to identify the closest pair of centroids. | import math
def read_centroids(file_path):
"""
Reads centroids from a file and returns a list of tuples containing coordinates.
"""
centroids = []
with open(file_path, 'r') as file:
for line in file:
coordinates = line.strip().split(',')
# Add a check for valid coord... | import pytest
from solution import read_centroids, calculate_distance, closest_pair
@pytest.fixture
def centroid_file(tmp_path):
data = "0,0\n1,1\n2,2\n3,3"
file = tmp_path / "centroids.txt"
file.write_text(data)
return file
def test_read_centroids(centroid_file):
centroids = read_centroids(centro... | [
{
"docstring": "Reads centroids from a file and returns a list of tuples containing coordinates.",
"function_declaration": "def read_centroids(file_path):",
"function_name": "read_centroids",
"parameter_list": "(file_path)"
},
{
"docstring": "Returns the Euclidean distance between two points... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef read_centroids(filename):\n \"\"\"\n Reads a file containing centroid coordinates and returns a list of tuples.\n Each line in the file should be formatted as: x y ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066595",
"row_id": 66595,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134847']"
} | 0.502554 | Filter_66595 | I | [
"read_centroids",
"calculate_distance",
"closest_pair"
] | 3 | [
[
"closest_pair",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e4ffa459ef743b99a0649be7f8385791e55545aa | 8619d239639d50714bafc3cc1e735f344681444f | |||
v1.0 | instruct | Filter | Filter_66618_I | Please provide a Python function to calculate the total time required to sort a list of numbers using the quicksort algorithm. This function should take a list of numbers as input and return the time taken to sort the list. | import time
import random
def quicksort(arr):
"""
QuickSort algorithm implementation.
"""
if len(arr) <= 1:
return arr
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
def ... | from solution import time_to_sort, quicksort
import time
def test_time_to_sort_small_list():
lst = [3, 1, 2]
time_taken = time_to_sort(lst)
assert isinstance(time_taken, float)
assert time_taken >= 0 # time taken should be non-negative
def test_quicksort_small_list():
lst = [3, 1, 2]
sorted_l... | [
{
"docstring": "QuickSort algorithm implementation.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": "Returns the time taken to sort the list using quicksort algorithm.",
"function_declaration": "def time_to_sort(l... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066618",
"row_id": 66618,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134890']"
} | 0.540574 | Filter_66618 | I | [
"quicksort",
"time_to_sort"
] | 2 | [
[
"time_to_sort",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee58d72fca8d1c6ac64c6e849476a232d5a62cde | b6c4137cee1cb8e8d0d3bceaf23aa097d4914234 | |||
v1.0 | instruct | Filter | Filter_66630_I | Can you provide a Python code snippet to compare two JSON files to check for differences? | import json
def compare_json_files(file_path1, file_path2):
"""
Compares two JSON files and returns the differences.
Args:
file_path1 (str): the path to the first JSON file.
file_path2 (str): the path to the second JSON file.
Returns:
dict: A dictionary containing the differences ... | import json
import tempfile
from solution import compare_json_files
def test_compare_json_files_identical():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as tmp1, \
tempfile.NamedTemporaryFile(mode='w+', delete=False) as tmp2:
json.dump({"key1": "value1", "key2": "value2"}, tmp1)
... | [
{
"docstring": "Compares two JSON files and returns the differences.\n\nArgs:\nfile_path1 (str): the path to the first JSON file.\nfile_path2 (str): the path to the second JSON file.\n\nReturns:\ndict: A dictionary containing the differences between the two JSON files.",
"function_declaration": "def compare... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef compare_json_files(file1_path, file2_path):\n \"\"\"\n Compares two JSON files and returns the differences.\n \n Args:\n file1_path (str): Path to the first J... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066630",
"row_id": 66630,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134907']"
} | 0.616898 | Filter_66630 | I | [
"compare_json_files",
"find_differences"
] | 2 | [
[
"compare_json_files",
"find_differences"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 80972899a6efffb6b6102c8045767aa28d52ff7e | c5d2d79ce0c95fc7fa9a0cd3db6b7adb77d98c53 | |||
v1.0 | instruct | Filter | Filter_66638_I | Write a Python function that reads data from the OpenWeatherMap API, extracts specific weather information for a given city, and appends this data to a CSV file. The weather information to extract includes temperature, humidity, and weather description. The function should also handle API rate limits and potential erro... | import requests
import csv
from time import sleep
API_KEY = 'your_api_key_here' # Replace with your actual OpenWeatherMap API key
def get_weather_data(city):
"""
Fetch the weather data for a given city from the OpenWeatherMap API.
Returns a dictionary with temperature, humidity, weather description ... | import pytest
import os
import csv
from unittest.mock import patch, Mock
from solution import get_weather_data, append_to_csv, fetch_and_write_weather
@patch("solution.requests.get")
def test_get_weather_data_success(mock_get):
mock_response = Mock()
mock_response.json.return_value = {
"cod": 200,
... | [
{
"docstring": "Fetch the weather data for a given city from the OpenWeatherMap API.\n\nReturns a dictionary with temperature, humidity, weather description or an error message.",
"function_declaration": "def get_weather_data(city):",
"function_name": "get_weather_data",
"parameter_list": "(city)"
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport csv\nimport time\n\ndef fetch_weather_data(city, api_key):\n \"\"\"\n Fetches weather data from OpenWeatherMap API for a given city.\n\n Args:\n - city (str... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066638",
"row_id": 66638,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134928']"
} | 0.577228 | Filter_66638 | I | [
"get_weather_data",
"append_to_csv",
"fetch_and_write_weather"
] | 3 | [
[
"fetch_and_write_weather",
"append_to_csv"
],
[
"fetch_and_write_weather",
"get_weather_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 0a00c40bcd94d5cad305ec5fe6c29c05c33be755 | 5b0544a008330d4e7660bc0b7959fc090c5fe439 | |||
v1.0 | instruct | Filter | Filter_66647_I | Can you provide an example of how to implement a Brute Force Routing algorithm in Python? | from itertools import permutations
def total_distance(route, distance_matrix):
"""
Calculate the total distance of a given route using the provided distance matrix.
"""
distance = 0
for i in range(len(route) - 1):
distance += distance_matrix[route[i]][route[i+1]]
distance += distance_ma... | from solution import total_distance, brute_force_routing
def test_total_distance():
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
route = [0, 1, 2, 3]
assert total_distance(route, distance_matrix) == 95 # 10 + 35 + 30 + 20
def... | [
{
"docstring": "Calculate the total distance of a given route using the provided distance matrix.",
"function_declaration": "def total_distance(route, distance_matrix):",
"function_name": "total_distance",
"parameter_list": "(route, distance_matrix)"
},
{
"docstring": "Given a set of nodes a... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef brute_force_routing(distances, start):\n \"\"\"\n Returns the shortest path found using brute force routing.\n \n :param distances: A 2D list with distances... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066647",
"row_id": 66647,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_134953']"
} | 0.421893 | Filter_66647 | I | [
"total_distance",
"brute_force_routing"
] | 2 | [
[
"brute_force_routing",
"total_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 722c763dcf71ae18d4ff620c90b9bab0f887b2b8 | e9fda0565bbfba31f9ac48fb635e847619b90f2b | |||
v1.0 | instruct | Filter | Filter_66672_I | I want to create a Python script to simulate a game where a player can choose to draw cards from a deck until they decide to stop or exceed 21 points. This is similar to the basic rules of Blackjack. Let's call it a simple Blackjack simulation. The deck consists of 52 cards, with Ace valued at 11, and face cards (Jack,... | import random
def create_deck():
"""
Creates a standard 52-card deck.
Aces are valued at 11, face cards (Jack, Queen, King) are valued at 10, and other cards are valued at their face value.
"""
deck = []
card_values = {
'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10... | import pytest
from solution import create_deck, draw_card, blackjack_simulation
def test_create_deck():
deck = create_deck()
assert len(deck) == 52
values = [card[2] for card in deck]
assert values.count(11) == 4 # 4 Aces
assert values.count(10) == 16 # 4 Jacks, 4 Queens, 4 Kings, 4 Tens
asse... | [
{
"docstring": "Creates a standard 52-card deck.\nAces are valued at 11, face cards (Jack, Queen, King) are valued at 10, and other cards are valued at their face value.",
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": "... | [
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 create_deck():\n \"\"\"\n Creates a standard 52-card deck.\n Aces are valued at 11, face cards (Jack, Queen, King) are valued at 10, and other cards are valued at... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066672",
"row_id": 66672,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135005']"
} | 0.531408 | Filter_66672 | I | [
"create_deck",
"draw_card",
"blackjack_simulation"
] | 3 | [
[
"blackjack_simulation",
"create_deck"
],
[
"blackjack_simulation",
"draw_card"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8d28bcddbcd7b77a5f88b5ea3bedacd5b2ef06a5 | 450150bdc41e18220c84c35f1a6606619c8cfff7 | |||
v1.0 | instruct | Filter | Filter_66682_I | Write a Python code to simulate a simple traffic light system using Pygame. The traffic light should have red, yellow, and green lights that change in a cyclical pattern (red -> green -> yellow -> red). The system should display the traffic light on a window with a fixed size and update the colors according to a specif... | import pygame
import sys
import time
# Initialize pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 200, 500
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Traffic Light Simulation')
# Define colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
# D... | import pytest
import pygame
from solution import draw_traffic_light, traffic_light_loop
def test_draw_traffic_light_red():
window = pygame.display.set_mode((200, 500))
draw_traffic_light('red')
assert window.get_at((100, 125)) == pygame.Color(255, 0, 0, 255)
def test_draw_traffic_light_green():
window... | [
{
"docstring": null,
"function_declaration": "def draw_traffic_light(color):",
"function_name": "draw_traffic_light",
"parameter_list": "(color)"
},
{
"docstring": null,
"function_declaration": "def traffic_light_loop():",
"function_name": "traffic_light_loop",
"parameter_list": ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pygame\nimport sys\nimport time\n\n# Initialize pygame\npygame.init()\n\n# Set up display\nWIDTH, HEIGHT = 200, 500\nwindow = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.se... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066682",
"row_id": 66682,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135023']"
} | 0.481657 | Filter_66682 | I | [
"draw_traffic_light",
"traffic_light_loop"
] | 2 | [
[
"traffic_light_loop",
"draw_traffic_light"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pygame"
] | false | 898e42dc06c82d15d037a6ea050d4de454cbc833 | 924dab51f7ea8fcb8032fd0594e683c1a2def88f | |||
v1.0 | instruct | Filter | Filter_66688_I | Can you generate a Python function to simulate a simple dice roll game? The function should allow a player to roll a dice and keep track of the score over several rounds. The game should continue until the player decides to stop or reaches a score of 20 or more. The player can choose to roll the dice again or stop afte... | import random
def roll_dice():
"""
Simulates rolling a six-sided dice.
Returns an integer between 1 and 6.
"""
return random.randint(1, 6)
def dice_game(choice_func):
"""
Simulates a dice game where a player can roll the dice and accumulate score.
The game continues until the player re... | from solution import roll_dice, dice_game
import random
def mock_choice_func_yes(score):
return True
def mock_choice_func_no(score):
return False
def test_roll_dice():
for _ in range(1000):
result = roll_dice()
assert 1 <= result <= 6, f"Roll result {result} is out of range"
def test_dic... | [
{
"docstring": "Simulates rolling a six-sided dice.\nReturns an integer between 1 and 6.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a dice game where a player can roll the dice and accumulate score.\nThe gam... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided dice.\n Returns an integer between 1 and 6 (inclusive).\n \"\"\"\n return random.randint(1, 6)\n\ndef ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066688",
"row_id": 66688,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135033']"
} | 0.553781 | Filter_66688 | I | [
"roll_dice",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0ab78d205284b8a9ada4e0629b7c6b000f05ba8 | ff67b7bf5fd823872fe724e8ede474dafff9b47a | |||
v1.0 | instruct | Filter | Filter_66699_I | Can you provide a Python script to simulate a simple dice game where two players roll two dice and the player with the higher sum wins? If the sums are equal, it's a tie. The game should simulate 1000 rounds and keep track of the wins, losses, and ties for each player. | import random
def roll_dice():
"""Simulates rolling two dice and returns the sum of their values."""
return random.randint(1, 6) + random.randint(1, 6)
def simulate_game(rounds=1000):
"""
Simulate a dice game between two players for a given number of rounds.
Returns the results as a dictionary con... | from solution import roll_dice, simulate_game
def test_roll_dice():
for _ in range(100):
roll = roll_dice()
assert 2 <= roll <= 12
def test_simulate_game():
results = simulate_game(1000)
total_rounds = results["Player 1 Wins"] + results["Player 2 Wins"] + results["Ties"]
assert total_r... | [
{
"docstring": "Simulates rolling two dice and returns the sum of their values.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulate a dice game between two players for a given number of rounds.\nReturns the results as... | [
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 Simulate rolling two six-sided dice and return the sum.\n \"\"\"\n return random.randint(1, 6) + random.randint(1, 6)\n\ndef simulate_g... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066699",
"row_id": 66699,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135057']"
} | 0.488564 | Filter_66699 | I | [
"roll_dice",
"simulate_game"
] | 2 | [
[
"simulate_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf7e5cff3e0dfb5cf29d0299b4455805ce983357 | 8d642248e5f65a299885daa21c17ce9b464711e6 | |||
v1.0 | instruct | Filter | Filter_66702_I | How do I create a simple live video streaming application using Python? | from flask import Flask, Response
import cv2
app = Flask(__name__)
def gen_frames():
cap = cv2.VideoCapture(0) # Capture video from the first webcam
while True:
ret, frame = cap.read()
if not ret:
break
else:
ret, buffer = cv2.imencode('.jpg', frame)
... | import pytest
from flask import Flask
from flask.testing import FlaskClient
@pytest.fixture
def client():
# Arrange
import solution
solution.app.config['TESTING'] = True
with solution.app.test_client() as client:
yield client
def test_index_route(client: FlaskClient):
# Act
response = ... | [
{
"docstring": null,
"function_declaration": "def gen_frames():",
"function_name": "gen_frames",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def video_feed():",
"function_name": "video_feed",
"parameter_list": "()"
},
{
"docstring": null,
"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, Response\nimport cv2\n\napp = Flask(__name__)\n\ndef gen_frames():\n cap = cv2.VideoCapture(0) # Capture video from the first webcam\n while True:\n ret,... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066702",
"row_id": 66702,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135062']"
} | 0.387664 | Filter_66702 | I | [
"gen_frames",
"video_feed",
"index"
] | 3 | [
[
"video_feed",
"gen_frames"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"flask"
] | false | ba612ff6c1c649efd5e690986b9f5ee7cb0cd149 | 9108d72eb3d9ff8ef040db8d7292f60b4687d764 | |||
v1.0 | instruct | Filter | Filter_66710_I | Can you provide a Python code to simulate and visualize the relationship between the learning rate and the loss function in a simple linear regression model? | import numpy as np
import matplotlib.pyplot as plt
# Create a simple linear regression dataset
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
def compute_loss(theta, X, y):
"""
Compute the Mean Squared Error loss.
"""
m = len(y)
predictions = X.dot(theta)
... | import pytest
from solution import compute_loss, gradient_descent
def test_compute_loss_zero_loss():
X_test = np.array([[1, 2], [1, 3], [1, 4]])
y_test = np.array([[2], [3], [4]])
theta_test = np.array([[0], [1]])
assert compute_loss(theta_test, X_test, y_test) == 0
def test_compute_loss_nonzero_loss(... | [
{
"docstring": "Compute the Mean Squared Error loss.",
"function_declaration": "def compute_loss(theta, X, y):",
"function_name": "compute_loss",
"parameter_list": "(theta, X, y)"
},
{
"docstring": "Perform gradient descent to learn theta.",
"function_declaration": "def gradient_descent(... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef simulate_learning_rate_vs_loss(learning_rates, iterations=100, seed=42):\n \"\"\"\n Simulates and visualizes the relationship b... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066710",
"row_id": 66710,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135075']"
} | 0.466776 | Filter_66710 | I | [
"compute_loss",
"gradient_descent"
] | 2 | [
[
"gradient_descent",
"compute_loss"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 28ec3e3f106faaa5a2ead8944f6492812d9eae22 | 786f9cbd8c4cab1b02ddfac0bfe0e93bb7a88d88 | |||
v1.0 | instruct | Filter | Filter_66721_I | Hello! I'm trying to understand how the `reduce` function in Python works, especially when used with a custom function. Can you explain it with an example? | from functools import reduce
def multiply(x, y):
return x * y
def reduce_example(numbers):
"""
Applies the "multiply" function cumulatively to the items of "numbers",
from left to right, so as to reduce the sequence to a single value.
"""
return reduce(multiply, numbers) | from solution import reduce_example
def test_reduce_example_with_positive_numbers():
numbers = [1, 2, 3, 4]
assert reduce_example(numbers) == 24 # 1*2*3*4 = 24
def test_reduce_example_with_zero():
numbers = [1, 0, 3, 4]
assert reduce_example(numbers) == 0 # multiplication with 0 results in 0
def te... | [
{
"docstring": null,
"function_declaration": "def multiply(x, y):",
"function_name": "multiply",
"parameter_list": "(x, y)"
},
{
"docstring": "Applies the \"multiply\" function cumulatively to the items of \"numbers\",\nfrom left to right, so as to reduce the sequence to a single value.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import reduce\n\ndef multiply(x, y):\n \"\"\"\n Returns the product of x and y.\n \"\"\"\n return x * y\n\ndef product_of_list(numbers):\n \"\"\"\n Returns the... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066721",
"row_id": 66721,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135098']"
} | 0.471338 | Filter_66721 | I | [
"multiply",
"reduce_example"
] | 2 | [
[
"reduce_example",
"multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 262b5ac4ba73a3e7b7fc69088902b29f6a2958ac | fc6b171abbb2f76add8b6ca5d788ea8d159ff738 | |||
v1.0 | instruct | Filter | Filter_66730_I | Can you explain how to implement a real-time chat application using WebSockets in Python? | # Python code to implement a real-time chat application using WebSockets
import asyncio
import websockets
from websockets.exceptions import ConnectionClosedOK
# A set to store connected clients
connected_clients = set()
async def register_client(websocket):
connected_clients.add(websocket)
async def unregister_... | import asyncio
import websockets
import pytest
from solution import client_handler, connected_clients, broadcast_message
# pytest fixtures to simulate WebSocket connections
@pytest.fixture
async def mock_websocket():
return await websockets.connect('ws://localhost:6789')
async def connect_and_send_message(message... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Python code to implement a real-time chat application using WebSockets\n\nimport asyncio\nimport websockets\nfrom websockets.exceptions import ConnectionClosedOK\n\n# A set to store connecte... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066730",
"row_id": 66730,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135116']"
} | 0.526403 | Filter_66730 | I | [
"register_client",
"unregister_client",
"broadcast_message",
"client_handler",
"main"
] | 5 | [
[
"client_handler",
"broadcast_message"
],
[
"client_handler",
"register_client"
],
[
"client_handler",
"unregister_client"
]
] | 3 | [] | false | [] | false | pytest | true | [
"websockets"
] | false | 70ffd43c5f96983a6c0e1dfa0cd1b4692ec53ae8 | d61918361b2e4b37797517ef671494e77ebdfcf0 | |||
v1.0 | instruct | Filter | Filter_66755_I | Can you provide a detailed explanation of how to implement a deep neural network (DNN) from scratch using only NumPy? This would include data preparation, model architecture, training process, and evaluation? | import numpy as np
# Sigmoid activation function and its derivative for backpropagation
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
# Data preparation (dummy dataset for XOR problem)
def create_xor_dataset():
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
... | import pytest
def test_sigmoid():
assert np.allclose(sigmoid(0), 0.5)
assert np.allclose(sigmoid(np.array([0, 2])), np.array([0.5, 0.88079708]))
def test_create_xor_dataset():
X, y = create_xor_dataset()
assert X.shape == (4, 2)
assert y.shape == (4, 1)
def test_initialize_parameters():
W1, b... | [
{
"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... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef sigmoid_derivative(z):\n return sigmoid(z) * (1 - sigmoid(z))\n\ndef relu(z):\n return np.maximum(0, z)\n\nd... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066755",
"row_id": 66755,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135166']"
} | 0.257311 | Filter_66755 | I | [
"sigmoid",
"sigmoid_derivative",
"create_xor_dataset",
"initialize_parameters",
"forward_propagation",
"compute_cost",
"backward_propagation",
"update_parameters",
"train_model",
"predict"
] | 10 | [
[
"backward_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"predict",
"forward_propagation"
],
[
"train_model",
"backward_propagation"
],
[
"train_model",
"compute_cost"
],
[
"train_model",
"forward_propagation"
],
... | 8 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | a33b7fea7611364096ce8207cbfbfe3841faf84b | a2628343693e215de6205ea15d1258be0e47f039 | |||
v1.0 | instruct | Filter | Filter_66767_I | Write a Python function that calculates the maximum sum of any contiguous subarray within a given list of integers. The function should use a divide-and-conquer approach to achieve a time complexity of O(log n * n). | def max_crossing_sum(arr, left, mid, right):
"""
Helper function to find the maximum sum crossing the midpoint.
"""
# Include elements on the left of mid.
left_sum = float('-inf')
total = 0
for i in range(mid, left - 1, -1):
total += arr[i]
if total > left_sum:
le... | from solution import find_maximum_subarray_sum
def test_find_maximum_subarray_sum_all_positive():
assert find_maximum_subarray_sum([1, 2, 3, 4, 5]) == 15
def test_find_maximum_subarray_sum_mixed_numbers():
assert find_maximum_subarray_sum([2, -1, 2, 3, 4, -5]) == 10
def test_find_maximum_subarray_sum_all_neg... | [
{
"docstring": "Helper function to find the maximum sum crossing the midpoint.",
"function_declaration": "def max_crossing_sum(arr, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(arr, left, mid, right)"
},
{
"docstring": "Helper function to find the maximum sub... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(arr, left, mid, right):\n # Include elements on the left of mid.\n sum_left = float('-inf')\n sum_temp = 0\n for i in range(mid, left - 1, -1):\n sum_te... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066767",
"row_id": 66767,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135186']"
} | 0.705772 | Filter_66767 | I | [
"max_crossing_sum",
"max_subarray_sum",
"find_maximum_subarray_sum"
] | 3 | [
[
"find_maximum_subarray_sum",
"max_subarray_sum"
],
[
"max_subarray_sum",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2cad26361fa0d70691565a8b782ede3715eea1fe | c993149c9668f34caf4c5a21aca00e1bde496e8f | |||
v1.0 | instruct | Filter | Filter_66777_I | How can I create a segment classifier using token embeddings in PyTorch? | import torch
from torch import nn, optim
from transformers import BertTokenizer, BertModel
class SegmentClassifier(nn.Module):
def __init__(self, bert_model_name='bert-base-uncased', num_classes=2):
super(SegmentClassifier, self).__init__()
self.bert = BertModel.from_pretrained(bert_model_name)
... | from solution import SegmentClassifier, train
from transformers import BertTokenizer
def test_segment_classifier_initialization():
model = SegmentClassifier()
assert isinstance(model, SegmentClassifier), "Model should be an instance of SegmentClassifier"
assert isinstance(model.classifier, nn.Linear), "Cla... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch import nn, optim\nfrom transformers import BertTokenizer, BertModel\n\nclass SegmentClassifier(nn.Module):\n def __init__(self, bert_model_name='bert-base-uncased',... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066777",
"row_id": 66777,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135200']"
} | 0.375127 | Filter_66777 | I | [
"prepare_data",
"train"
] | 2 | [
[
"train",
"prepare_data"
]
] | 1 | [] | false | [
"SegmentClassifier"
] | true | pytest | true | [
"torch",
"transformers"
] | false | 8088d8ca6927e00f6d76427cb977d2e231b4a22a | 49e173d3ef5d7a28ede303b71e259098b576de97 | |||
v1.0 | instruct | Filter | Filter_66794_I | Write a Python program that prints the first 10 Fibonacci numbers using recursion. | def fibonacci(n):
"""
Returns the nth Fibonacci number.
"""
if n <= 0:
raise ValueError("Input should be a positive integer.")
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def fibonacci_sequence(count):
"""
... | from solution import fibonacci, fibonacci_sequence
def test_fibonacci():
assert fibonacci(1) == 0
assert fibonacci(2) == 1
assert fibonacci(3) == 1
assert fibonacci(4) == 2
assert fibonacci(5) == 3
assert fibonacci(6) == 5
assert fibonacci(7) == 8
assert fibonacci(8) == 13
assert fi... | [
{
"docstring": "Returns the nth Fibonacci number.",
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Returns the first 'count' Fibonacci numbers.",
"function_declaration": "def fibonacci_sequence(count):",
"function... | [
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 Fibonacci number.\n \"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n - ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066794",
"row_id": 66794,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135229']"
} | 0.728283 | Filter_66794 | I | [
"fibonacci",
"fibonacci_sequence"
] | 2 | [
[
"fibonacci_sequence",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e49b97434080d17121368c417635f577b76f5107 | 1b32753853862eab63ba2a1804a7df9b55abea04 | |||
v1.0 | instruct | Filter | Filter_66803_I | You are tasked with creating a Python script that automates the process of sending multiple HTML emails using smtplib and email libraries. The script should be able to read recipient email addresses from a CSV file, send personalized emails to each recipient, and handle errors gracefully. The script should include a cu... | import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import csv
import os
def send_html_email(smtp_server, port, login, password, sender_email, recipient_email, subject, body, attachment_path=None):
try:
# Crea... | from solution import send_html_email, send_emails_from_csv
def test_send_html_email_success():
smtp_server = "smtp.example.com"
port = 465
login = "user@example.com"
password = "password"
sender_email = "sender@example.com"
recipient_email = "recipient@example.com"
subject = "Test Email"
... | [
{
"docstring": null,
"function_declaration": "def send_html_email(smtp_server, port, login, password, sender_email, recipient_email, subject, body, attachment_path=None):",
"function_name": "send_html_email",
"parameter_list": "(smtp_server, port, login, password, sender_email, recipient_email, subj... | [
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.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\nimport csv\nimport os\n\ndef send_html... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066803",
"row_id": 66803,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135249']"
} | 0.632378 | Filter_66803 | I | [
"send_html_email",
"send_emails_from_csv"
] | 2 | [
[
"send_emails_from_csv",
"send_html_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6265dbd8b879de5d274e6191a242f51cfc2750e5 | 6029b6dafa3aeaba94631ef99f00b0e76d906215 | |||
v1.0 | instruct | Filter | Filter_66812_I | Write a Python function to generate all possible palindromic partitions of a given string. A palindromic partition is a way to partition the string into substrings where each substring is a palindrome. For example, for the input string 'aab', the function should return [['a', 'a', 'b'], ['aa', 'b']]. | def is_palindrome(s):
return s == s[::-1]
def palindromic_partitions(s):
def dfs(start, path, result):
if start == len(s):
result.append(path[:])
return
for end in range(start + 1, len(s) + 1):
substring = s[start:end]
if is_palindrome(substring):... | from solution import palindromic_partitions
def test_palindromic_partitions_simple_case():
assert palindromic_partitions("aab") == [['a', 'a', 'b'], ['aa', 'b']]
def test_palindromic_partitions_single_char():
assert palindromic_partitions("a") == [['a']]
def test_palindromic_partitions_no_palindrome():
a... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def palindromic_partitions(s):",
"function_name": "palindromic_partitions",
"parameter_list": "(s)"
}... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n return s == s[::-1]\n\ndef palindromic_partitions(s):\n def backtrack(start, path):\n if start == len(s):\n partitions.append(path)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066812",
"row_id": 66812,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135276']"
} | 0.68395 | Filter_66812 | I | [
"is_palindrome",
"palindromic_partitions"
] | 2 | [
[
"palindromic_partitions",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99ba2178bea71ead3d7fa815a40c1c61db59e952 | bd7ff8d39c0be93031f1cd3857aad7d1a01a7b3b | |||
v1.0 | instruct | Filter | Filter_66822_I | Write a Python program that reads words from a file, counts the frequency of each word, and then sorts the words by their frequency in descending order. The program should handle potential errors like file not found or invalid file content. Additionally, it should provide an option to sort the words alphabetically if t... | import os
from collections import Counter
def read_words_from_file(filename):
"""
Reads words from the specified file and returns a list of words.
"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"The file {filename} does not exist.")
try:
with open(filename, 'r') as f... | import pytest
from solution import read_words_from_file, count_word_frequency, sort_words_by_frequency, word_frequency_from_file
def test_read_words_from_file(tmpdir):
# Testing a file read with valid contents
file = tmpdir.join("test.txt")
file.write("word1 word2 word3 word2 word1")
words = read_words... | [
{
"docstring": "Reads words from the specified file and returns a list of words.",
"function_declaration": "def read_words_from_file(filename):",
"function_name": "read_words_from_file",
"parameter_list": "(filename)"
},
{
"docstring": "Counts the frequency of each word in the list.",
"f... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_words_from_file(file_path):\n try:\n with open(file_path, 'r') as file:\n words = file.read().split()\n return words\n except FileNotFoundError:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066822",
"row_id": 66822,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135301']"
} | 0.690144 | Filter_66822 | I | [
"read_words_from_file",
"count_word_frequency",
"sort_words_by_frequency",
"word_frequency_from_file"
] | 4 | [
[
"word_frequency_from_file",
"count_word_frequency"
],
[
"word_frequency_from_file",
"read_words_from_file"
],
[
"word_frequency_from_file",
"sort_words_by_frequency"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e2de09eb248b9f5b85a90a03344a2f9d24ecdab2 | 482e18b4a8c75a0a604cf9b90beb91bf472319b1 | |||
v1.0 | instruct | Filter | Filter_66829_I | Hi, I'm trying to write a program in Python to solve the Traveling Salesman Problem (TSP) using Genetic Algorithms (GA). Can you provide a basic outline of the steps I should follow to implement a GA for TSP in Python? | import random
# Step 1: Helper function to calculate the total distance of a tour
def calculate_total_distance(tour, distance_matrix):
return sum(distance_matrix[tour[i]][tour[i-1]] for i in range(len(tour)))
# Step 2: Initialize a population of random tours
def initialize_population(population_size, cities):
... | import pytest
from solution import calculate_total_distance, initialize_population, evaluate_population, \
selection, crossover, mutate, create_new_population, genetic_algorithm
def test_calculate_total_distance():
distance_matrix = [
[0, 1, 2],
[1, 0, 3],
[2, 3, 0]
... | [
{
"docstring": null,
"function_declaration": "def calculate_total_distance(tour, distance_matrix):",
"function_name": "calculate_total_distance",
"parameter_list": "(tour, distance_matrix)"
},
{
"docstring": null,
"function_declaration": "def initialize_population(population_size, cities... | [
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 create_route(city_list):\n \"\"\"\n Creates a random route by shuffling the city_list.\n \"\"\"\n route = random.sample(city_list, len(city_list))\n return ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066829",
"row_id": 66829,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135315']"
} | 0.290185 | Filter_66829 | I | [
"calculate_total_distance",
"initialize_population",
"evaluate_population",
"selection",
"crossover",
"mutate",
"create_new_population",
"genetic_algorithm"
] | 8 | [
[
"create_new_population",
"crossover"
],
[
"create_new_population",
"mutate"
],
[
"evaluate_population",
"calculate_total_distance"
],
[
"genetic_algorithm",
"calculate_total_distance"
],
[
"genetic_algorithm",
"create_new_population"
],
[
"genetic_al... | 8 | [] | false | [] | false | pytest | true | [] | true | ff693edad1579c6a787c2e13bce36bac4a12309d | 2944f41992608a1b080607da9f4d532f1a4bdd6d | |||
v1.0 | instruct | Filter | Filter_66833_I | I'm looking for a simple Python script that can monitor the CPU temperature and display it in real-time. I'm using a Linux system. To achieve this, I need to use the `psutil` library, but I found out that `psutil` does not directly provide CPU temperature readings. Instead, I should use the `sensors` command from the `... | import subprocess
import time
def get_cpu_temperature():
"""
Uses the sensors command to get the CPU temperature.
Returns the CPU temperature in degrees Celsius.
"""
try:
result = subprocess.run(['sensors'], capture_output=True, text=True)
if result.returncode != 0:
rais... | from solution import get_cpu_temperature
import subprocess
def mock_sensors_output_valid():
return subprocess.CompletedProcess(args=['sensors'], returncode=0, stdout="""
coretemp-isa-0000
Adapter: ISA adapter
Package id 0: +53.0°C (high = +95.0°C, crit = +105.0°C)
Core 0: +52.0°C (high = ... | [
{
"docstring": "Uses the sensors command to get the CPU temperature.\nReturns the CPU temperature in degrees Celsius.",
"function_declaration": "def get_cpu_temperature():",
"function_name": "get_cpu_temperature",
"parameter_list": "()"
},
{
"docstring": "Monitors the CPU temperature and pri... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import subprocess\nimport time\n\ndef get_cpu_temperature():\n \"\"\"\n Uses the `sensors` command to get the CPU temperature.\n Returns the temperature as a float.\n \"\"\"\n t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066833",
"row_id": 66833,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135326']"
} | 0.458057 | Filter_66833 | I | [
"get_cpu_temperature",
"monitor_cpu_temperature"
] | 2 | [
[
"monitor_cpu_temperature",
"get_cpu_temperature"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1669c83f6e6e7c4e931a34e12ec2f336b12513fd | b65a062d604eac1ac78e90ec415a9ff497511b4c | |||
v1.0 | instruct | Filter | Filter_66841_I | Could you provide an example of a Python code that uses a genetic algorithm to solve the 0/1 knapsack problem? | import random
def generate_individual(length):
return [random.randint(0, 1) for _ in range(length)]
def calculate_fitness(individual, values, weights, max_weight):
weight_sum = sum(individual[i] * weights[i] for i in range(len(individual)))
value_sum = sum(individual[i] * values[i] for i in range(len(indi... | from solution import generate_individual, calculate_fitness, mutation, crossover, genetic_algorithm
def test_generate_individual():
individual = generate_individual(5)
assert len(individual) == 5
assert all(gene in [0, 1] for gene in individual)
def test_calculate_fitness():
values = [60, 100, 120]
... | [
{
"docstring": null,
"function_declaration": "def generate_individual(length):",
"function_name": "generate_individual",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def calculate_fitness(individual, values, weights, max_weight):",
"function_name": "c... | [
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_individual(length):\n \"\"\"Generates an individual with random 0/1 values.\"\"\"\n return [random.randint(0, 1) for _ in range(length)]\n\ndef fitness(indi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066841",
"row_id": 66841,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135341']"
} | 0.359421 | Filter_66841 | I | [
"generate_individual",
"calculate_fitness",
"mutation",
"crossover",
"genetic_algorithm"
] | 5 | [
[
"genetic_algorithm",
"calculate_fitness"
],
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"generate_individual"
],
[
"genetic_algorithm",
"mutation"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c0c07d263b01c6c788873a5064362d3e133c65c2 | c0520f0c4f3cd7155001a917804d70aee60f7806 | |||
v1.0 | instruct | Filter | Filter_66863_I | How can I create a Python script that generates a sequence of numbers based on user input and saves this sequence to a file? | def generate_sequence(start, end, step):
"""
Generates a sequence of numbers from start to end with a specified step.
"""
return list(range(start, end, step))
def save_sequence_to_file(sequence, filename):
"""
Saves a sequence of numbers to a file.
"""
with open(filename, 'w') as file:
... | from solution import generate_sequence, save_sequence_to_file, generate_and_save_sequence
import os
def test_generate_sequence_positive_step():
assert generate_sequence(0, 10, 2) == [0, 2, 4, 6, 8]
def test_generate_sequence_negative_step():
assert generate_sequence(10, 0, -2) == [10, 8, 6, 4, 2]
def test_ge... | [
{
"docstring": "Generates a sequence of numbers from start to end with a specified step.",
"function_declaration": "def generate_sequence(start, end, step):",
"function_name": "generate_sequence",
"parameter_list": "(start, end, step)"
},
{
"docstring": "Saves a sequence of numbers to a file... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_sequence_and_save(n, filename):\n \"\"\"\n Generates a sequence of numbers from 1 to n and saves it to a file.\n \n :param n: The end of the sequence.\n :param file... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066863",
"row_id": 66863,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135400']"
} | 0.51168 | Filter_66863 | I | [
"generate_sequence",
"save_sequence_to_file",
"generate_and_save_sequence"
] | 3 | [
[
"generate_and_save_sequence",
"generate_sequence"
],
[
"generate_and_save_sequence",
"save_sequence_to_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 96ea715ec38fd3886a14b43b7a2395fb41eed3ca | 02b4f021c9938a7e8c398319801f3610718620f1 | |||
v1.0 | instruct | Filter | Filter_66877_I | Could you provide a Python function to generate a list of all prime numbers within a given range [n, m]? Please include a brief explanation of how the function works. | def is_prime(num):
"""
Determines whether a given number is prime.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
return True
def prim... | from solution import is_prime, primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(11) == True
def test_primes_in_range_empty():
assert primes_in_range... | [
{
"docstring": "Determines whether a given number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers within the range [n, m].",
"function_declaration": "def primes_in_rang... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 ==... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066877",
"row_id": 66877,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135444']"
} | 0.65654 | Filter_66877 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 25dd7c10442a09d03dd052922ed94b14cac0abf6 | d91fcf166ef8c74fbcc7242c7f54fca7813d736f | |||
v1.0 | instruct | Filter | Filter_66888_I | Can you explain how to create and use functions in Python? How do they differ from loops? And could you provide an example of how to use a function within a loop? | # Functions in Python are defined using the 'def' keyword followed by the function name and parentheses, which may include parameters. A function typically performs a specific task and may return a result using the 'return' keyword. Here’s an example:
def greet(name):
"""
Returns a greeting message for the giv... | from solution import greet, greet_multiple_names
def test_greet():
assert greet("Alice") == "Hello, Alice!"
assert greet("Bob") == "Hello, Bob!"
def test_greet_multiple_names():
names = ["Alice", "Bob", "Charlie"]
expected = ["Hello, Alice!", "Hello, Bob!", "Hello, Charlie!"]
assert greet_multiple... | [
{
"docstring": "Returns a greeting message for the given name.",
"function_declaration": "def greet(name):",
"function_name": "greet",
"parameter_list": "(name)"
},
{
"docstring": "Prints a greeting message for each name in the provided list of names.",
"function_declaration": "def greet... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greet(name):\n \"\"\"\n Prints a greeting to the provided name.\n \"\"\"\n return f\"Hello, {name}!\"\n\ndef greet_multiple(names):\n \"\"\"\n Takes a list of names and u... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066888",
"row_id": 66888,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135468']"
} | 0.498834 | Filter_66888 | I | [
"greet",
"greet_multiple_names"
] | 2 | [
[
"greet_multiple_names",
"greet"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e582723f866b181beda18bb1b57283248a4b8934 | 66c49bcdd262587dc3f15baece7364eb1c6797ed | |||
v1.0 | instruct | Filter | Filter_66931_I | Can you provide a detailed explanation of how to fit a linear regression model using PyTorch, including data preparation, model definition, loss function, optimizer setup, and training loop? | import torch
import torch.nn as nn
import torch.optim as optim
# Step 1: Data Preparation
def prepare_data():
# Dummy data for simple linear regression (y = 2x + 1)
X = torch.tensor([[1.0], [2.0], [3.0], [4.0], [5.0]])
y = torch.tensor([[3.0], [5.0], [7.0], [9.0], [11.0]])
return X, y
# Step 2: Model ... | def test_prepare_data():
X, y = prepare_data()
assert X.shape == (5, 1)
assert y.shape == (5, 1)
def test_model_initialization():
model = LinearRegressionModel(1, 1)
assert isinstance(model, nn.Module)
assert hasattr(model, 'linear')
assert hasattr(model.linear, 'weight')
assert hasattr... | [] | [
1,
0,
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\nimport torch.optim as optim\n\n# Step 1: Data Preparation\ndef prepare_data():\n # Dummy data for simple linear regression (y = 2x + 1)\n X = torch.t... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00066931",
"row_id": 66931,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135552']"
} | 0.482054 | Filter_66931 | I | [
"prepare_data",
"get_loss_function",
"get_optimizer",
"train_model",
"fit_linear_regression_model"
] | 5 | [
[
"fit_linear_regression_model",
"get_loss_function"
],
[
"fit_linear_regression_model",
"get_optimizer"
],
[
"fit_linear_regression_model",
"prepare_data"
],
[
"fit_linear_regression_model",
"train_model"
]
] | 4 | [] | false | [
"LinearRegressionModel"
] | true | pytest | false | [
"torch"
] | false | b217561b16e6c925371ede9cc3c55bae979b6c8a | 8cda35b27c1690e89a0ac8e4728ae6f0e7842b1b | |||
v1.0 | instruct | Filter | Filter_66942_I | Can you explain how to create a Python program that checks for prime numbers within a given range? | def is_prime(n):
"""
Check 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 Tr... | from solution import is_prime, primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(11) == True
assert is_prime(-1) == False
assert is_prime(0) == Fa... | [
{
"docstring": "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 prime numbers in the given range [start, end).",
"function_declaration": "def primes_in_range(start, end):"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00066942",
"row_id": 66942,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135579']"
} | 0.717379 | Filter_66942 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ab72f33c556223a0acd19806c73caef3aa4af58 | 6ed8adedd9052840822c49fe2a374b1e83795543 | |||
v1.0 | instruct | Filter | Filter_66961_I | I'm trying to create a Python program that simulates a simple dice game. The game involves rolling two six-sided dice, and the player wins if the sum of the numbers on the dice is 7 or 11. If the sum is 2, 3, or 12, the player loses immediately. For any other sum, the game continues on a new roll until the player eithe... | import random
def roll_dice():
"""
Simulates rolling two six-sided dice and returns their sum.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def play_game():
"""
Simulates the dice game.
Returns 'win' if the player wins, and 'lose' if the player los... | from unittest.mock import patch
from solution import roll_dice, play_game
def test_roll_dice():
for _ in range(100):
roll = roll_dice()
assert 2 <= roll <= 12
@patch('solution.roll_dice', side_effect=[7, 0])
def test_play_game_initial_win(_: list):
result = play_game()
assert result == 'wi... | [
{
"docstring": "Simulates rolling two six-sided dice and returns their sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates the dice game.\nReturns 'win' if the player wins, and 'lose' if the player loses.",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling two six-sided dice.\n Returns a tuple containing the result of each die.\n \"\"\"\n die1 = random.randint(1, 6)\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066961",
"row_id": 66961,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135609']"
} | 0.579215 | Filter_66961 | I | [
"roll_dice",
"play_game"
] | 2 | [
[
"play_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 917dc314afe8b415f067a37b44ee18a6e3701f10 | dae988e5f0a9ac0e17061f1174aa72fa70ba3f26 | |||
v1.0 | instruct | Filter | Filter_66978_I | Can you provide a Python script that generates a list of the first 100 prime numbers? | def is_prime(n):
"""
Determines if a number n is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def generate_primes(n):
"... | from solution import is_prime, generate_primes
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert is_prime(13)
assert not is_prime(15)
assert not is_prime(-1)
assert not is_prime(0)
assert not is_prime(1)
def test_generate_pr... | [
{
"docstring": "Determines if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generates a list of the first n prime numbers.",
"function_declaration": "def generate_primes(n):",
"function_name"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00066978",
"row_id": 66978,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135636']"
} | 0.548164 | Filter_66978 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a9911334b2db499e9d994ca1bc9b1a29460cc4e5 | 062e5c2d43e441481a0da779e315e85426c55b21 | |||
v1.0 | instruct | Filter | Filter_67017_I | How can I write a Python script to solve a Sudoku puzzle using the backtracking algorithm? | def is_valid(board, row, col, num):
"""
Checks whether it will be legal to assign num to the given row, col.
"""
# Check if the number exists in the current row or column
for x in range(9):
if board[row][x] == num or board[x][col] == num:
return False
# Check if the numb... | from solution import solve_sudoku
def test_solve_sudoku():
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, ... | [
{
"docstring": "Checks whether it will be legal to assign num to the given row, col.",
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": "Solves the Sudoku puzzle using the backtracking alg... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if placing the num in the specified row and column is valid.\n \"\"\"\n # Check if num is in the row\n for i in range(9):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067017",
"row_id": 67017,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135715']"
} | 0.436379 | Filter_67017 | I | [
"is_valid",
"solve_sudoku"
] | 2 | [
[
"solve_sudoku",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5119c34740ce1aec36a53e32a7fa24f2fb889b6c | 7c754ffb0d0743e6a621fbf70b2095afe94f663d | |||
v1.0 | instruct | Filter | Filter_67029_I | I need to generate some test data for a SQL database with columns for ID, ProductName, Price, and Quantity. How can I do this programmatically in Python? | import random
import string
def generate_random_string(length=10):
"""
Generates a random string of uppercase letters with specified length.
"""
letters = string.ascii_uppercase
return ''.join(random.choice(letters) for i in range(length))
def generate_test_data(num_records=10):
"""
Genera... | from solution import generate_test_data, generate_random_string
def test_generate_random_string_length():
assert len(generate_random_string(10)) == 10
assert len(generate_random_string(15)) == 15
def test_generate_random_string_content():
random_string = generate_random_string(10)
assert all(char in s... | [
{
"docstring": "Generates a random string of uppercase letters with specified length.",
"function_declaration": "def generate_random_string(length=10):",
"function_name": "generate_random_string",
"parameter_list": "(length=10)"
},
{
"docstring": "Generates test data for a SQL database with ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\nimport sqlite3\n\ndef generate_random_string(length=10):\n \"\"\"\n Generate a random string of fixed length\n \"\"\"\n letters = string.ascii_letters... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067029",
"row_id": 67029,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135744']"
} | 0.469479 | Filter_67029 | I | [
"generate_random_string",
"generate_test_data"
] | 2 | [
[
"generate_test_data",
"generate_random_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 440ccd3dfecd1ee4e6cba0b38a331a43e9ebdcde | a70d6d11b23dba62656a9e272e9336d62812c8a0 | |||
v1.0 | instruct | Filter | Filter_67040_I | Can you provide an example of how to solve a system of equations using Python's `scipy.optimize.fsolve` function? | from scipy.optimize import fsolve
def equations(vars):
x, y = vars
eq1 = x ** 2 + y ** 2 - 1
eq2 = x ** 2 - y
return [eq1, eq2]
def solve_system_of_equations():
# Initial guess
initial_guess = [1, 1]
# Solve using fsolve
solution = fsolve(equations, initial_guess)
return solution | from solution import solve_system_of_equations
def test_solve_system_of_equations():
solution = solve_system_of_equations()
# Verify the solution
x, y = solution
assert abs(x ** 2 + y ** 2 - 1) < 1e-6
assert abs(x ** 2 - y) < 1e-6 | [
{
"docstring": null,
"function_declaration": "def equations(vars):",
"function_name": "equations",
"parameter_list": "(vars)"
},
{
"docstring": null,
"function_declaration": "def solve_system_of_equations():",
"function_name": "solve_system_of_equations",
"parameter_list": "()"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from scipy.optimize import fsolve\n\ndef equations(vars):\n \"\"\"\n Represents the system of equations:\n x^2 + y^2 = 1\n x - y = 0\n \"\"\"\n x, y = vars\n eq1 =... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067040",
"row_id": 67040,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135775']"
} | 0.449882 | Filter_67040 | I | [
"equations",
"solve_system_of_equations"
] | 2 | [
[
"solve_system_of_equations",
"equations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"scipy"
] | false | de1cb75a386df2df23108914f36938e28f0d3b08 | a1a1bcd75777aa2e2a19f4466972e15f555fc93c | |||
v1.0 | instruct | Filter | Filter_67128_I | Write a Python function that simulates a simple dice rolling game. The player can choose to roll a standard six-sided die or a custom die with a different number of sides. The function should take the number of sides as an input and return the result of the roll. Additionally, provide a mechanism to allow the player to... | import random
def roll_dice(sides=6):
"""
Roll a dice with the specified number of sides and return the result.
"""
return random.randint(1, sides)
def roll_multiple_times(sides=6, rolls=1):
"""
Roll a dice with the specified number of sides the specified number of times.
Calculate and ret... | from solution import roll_dice, roll_multiple_times
def test_roll_dice_six_sided():
result = roll_dice()
assert 1 <= result <= 6
def test_roll_dice_custom_sided():
result = roll_dice(8)
assert 1 <= result <= 8
def test_roll_multiple_times_average():
average_result = roll_multiple_times(6, 10)
... | [
{
"docstring": "Roll a dice with the specified number of sides and return the result.",
"function_declaration": "def roll_dice(sides=6):",
"function_name": "roll_dice",
"parameter_list": "(sides=6)"
},
{
"docstring": "Roll a dice with the specified number of sides the specified number of tim... | [
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(num_sides=6):\n \"\"\"\n Simulates rolling a die with a specified number of sides.\n Arguments:\n num_sides -- the number of sides on the die (default... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067128",
"row_id": 67128,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135952']"
} | 0.617425 | Filter_67128 | I | [
"roll_dice",
"roll_multiple_times"
] | 2 | [
[
"roll_multiple_times",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 25b222bbd6f8a18ed654a3b3d39b6c111e2b48ed | 7479ecfa7ef0cddd85326aeb99129b0646af050d | |||
v1.0 | instruct | Filter | Filter_67132_I | Can you give me a Python code example that demonstrates buffering of a stream of data using a buffer object? | import io
# Demonstration of buffering using a buffer object
def buffer_stream(input_stream, buffer_size=1024):
"""
Buffers the input stream data into chunks of buffer_size and yields each chunk.
Parameters:
input_stream: An input stream to buffer.
buffer_size: Size of each buffer chunk in byt... | from solution import buffered_read
def test_buffered_read_with_small_data():
data = "Hello, World!"
buffer_size = 5
expected_chunks = ["Hello", ", Wor", "ld!"]
assert buffered_read(data, buffer_size) == expected_chunks
def test_buffered_read_with_large_buffer():
data = "Hello, World!"
buffer_s... | [
{
"docstring": "Buffers the input stream data into chunks of buffer_size and yields each chunk.\n\nParameters:\ninput_stream: An input stream to buffer.\nbuffer_size: Size of each buffer chunk in bytes.\n\nYields:\nChunks of buffered data from the input stream.",
"function_declaration": "def buffer_stream(i... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import io\n\ndef buffered_stream(input_stream, buffer_size=1024):\n \"\"\"\n Read data from input_stream using a buffer.\n\n :param input_stream: An input stream to read data from.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067132",
"row_id": 67132,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135958']"
} | 0.403219 | Filter_67132 | I | [
"buffer_stream",
"buffered_read"
] | 2 | [
[
"buffered_read",
"buffer_stream"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77c4dd5cded8899e870cf0e38523f3f2a2d24071 | 9392e9ec993eca5ccadacdc572cd4213b281e863 | |||
v1.0 | instruct | Filter | Filter_67133_I | Can you provide a Python code snippet that demonstrates how to create a custom progress bar using tkinter and ttk? | import tkinter as tk
from tkinter import ttk
import time
def update_progress_bar(progress_bar, label, max_value):
"""
Updates the progress bar from 0 to max_value over the span of max_value seconds.
Args:
- progress_bar: A ttk Progressbar object.
- label: A tk.Label object to display the progr... | # Test for verifying the functionality of the progress bar implementation
# Note: GUI tests are complex and typically require a different testing approach including UI automation tools.
# Here, we demonstrate a basic test to check the function signatures and basic logic without the GUI part.
from solution import updat... | [
{
"docstring": "Updates the progress bar from 0 to max_value over the span of max_value seconds.\n\nArgs:\n- progress_bar: A ttk Progressbar object.\n- label: A tk.Label object to display the progress percentage.\n- max_value: The maximum value of the progress bar.",
"function_declaration": "def update_prog... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"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 create_progress_bar(root):\n \"\"\"\n Creates a simple progress bar in a tkinter window.\n \"\"\"\n # Create a frame for the pr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067133",
"row_id": 67133,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_135965']"
} | 0.397539 | Filter_67133 | I | [
"update_progress_bar",
"create_custom_progress_bar"
] | 2 | [
[
"create_custom_progress_bar",
"update_progress_bar"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31e6c8d9df32e22f29800a43073c38a97e7dbe7f | 1950ea3cc8c79b1aab038153714f71aa4bbfb5a8 | |||
v1.0 | instruct | Filter | Filter_67175_I | Can you provide me with a Python script that can generate a Low Poly style 3D model of a sphere? generate a obj file | from math import pi, sin, cos
def write_obj_file(vertices, faces, filename):
with open(filename, 'w') as obj_file:
for vertex in vertices:
obj_file.write(f"v {vertex[0]} {vertex[1]} {vertex[2]}\n")
for face in faces:
obj_file.write(f"f {' '.join(map(str, face))}\n")
def gen... | import os
def test_generate_low_poly_sphere():
vertices, faces = generate_low_poly_sphere(1, 2)
assert len(vertices) == 9
assert len(faces) == 8
def test_write_obj_file():
vertices = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
faces = [(1, 2, 3), (3, 2, 1)]
filename = 'test.obj'
write_obj_file(verti... | [
{
"docstring": null,
"function_declaration": "def write_obj_file(vertices, faces, filename):",
"function_name": "write_obj_file",
"parameter_list": "(vertices, faces, filename)"
},
{
"docstring": null,
"function_declaration": "def generate_low_poly_sphere(radius, subdivisions):",
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef generate_low_poly_sphere(radius=1, segments=10, rings=10):\n vertices = []\n faces = []\n \n for i in range(rings + 1):\n lat = np.pi * (i / rings ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067175",
"row_id": 67175,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136049']"
} | 0.406718 | Filter_67175 | I | [
"write_obj_file",
"generate_low_poly_sphere",
"create_low_poly_sphere_obj"
] | 3 | [
[
"create_low_poly_sphere_obj",
"generate_low_poly_sphere"
],
[
"create_low_poly_sphere_obj",
"write_obj_file"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 3f96b08b0bf6a8b9a06c1fd9b6ef1117efd6c023 | e3819c5cb2b221da0d3e964a76b5e8c82a91ff9c | |||
v1.0 | instruct | Filter | Filter_67198_I | Can you help me with a Python script to analyze the textual content of a webpage? Specifically, I want to count the frequency of each word on the webpage and display the top 10 most common words. How can I achieve this? | import requests
from collections import Counter
from bs4 import BeautifulSoup
import re
def fetch_webpage_content(url):
"""
Fetches the textual content of a webpage.
:param url: URL of the webpage to fetch content from.
:return: Text content of the webpage.
"""
response = requests.get(url)
... | from solution import fetch_webpage_content, count_word_frequency, get_top_n_common_words, analyze_webpage
from collections import Counter
# Mock responses for testing
class MockResponse:
def __init__(self, text, status_code):
self.text = text
self.status_code = status_code
def raise_for_status... | [
{
"docstring": "Fetches the textual content of a webpage.\n\n:param url: URL of the webpage to fetch content from.\n:return: Text content of the webpage.",
"function_declaration": "def fetch_webpage_content(url):",
"function_name": "fetch_webpage_content",
"parameter_list": "(url)"
},
{
"doc... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom bs4 import BeautifulSoup\nfrom collections import Counter\nimport re\n\ndef fetch_webpage_text(url):\n \"\"\"\n Fetches the textual content from the specified URL.\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067198",
"row_id": 67198,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136102']"
} | 0.728411 | Filter_67198 | I | [
"fetch_webpage_content",
"count_word_frequency",
"get_top_n_common_words",
"analyze_webpage"
] | 4 | [
[
"analyze_webpage",
"count_word_frequency"
],
[
"analyze_webpage",
"fetch_webpage_content"
],
[
"analyze_webpage",
"get_top_n_common_words"
]
] | 3 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | 2aa4bef53ae210d9887800b6e9e516b27a71a6c0 | 2926570d92fb610f9d97e0348038945755708b11 | |||
v1.0 | instruct | Filter | Filter_67200_I | Can you explain the concept of indirect recursion in programming and provide an example in Python? | def function_a(n):
if n <= 0:
return "End of recursion"
print(f"function_a called with n = {n}")
return function_b(n - 1)
def function_b(n):
if n <= 0:
return "End of recursion"
print(f"function_b called with n = {n}")
return function_a(n - 2) | from solution import function_a, function_b
def test_function_a():
assert function_a(5) == "End of recursion"
assert function_a(1) == "End of recursion"
def test_function_b():
assert function_b(4) == "End of recursion"
assert function_b(2) == "End of recursion"
def test_indirect_recursion():
# Th... | [
{
"docstring": null,
"function_declaration": "def function_a(n):",
"function_name": "function_a",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def function_b(n):",
"function_name": "function_b",
"parameter_list": "(n)"
}
] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def function_a(n):\n if n <= 0:\n return \"End of recursion\"\n print(f\"function_a called with n = {n}\")\n return function_b(n - 1)\n\ndef function_b(n):\n if n <= 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067200",
"row_id": 67200,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136110']"
} | 0.464447 | Filter_67200 | I | [
"function_a",
"function_b"
] | 2 | [
[
"function_a",
"function_b"
],
[
"function_b",
"function_a"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 23e8573ae17e767599b872a37929860bd482033a | 1902e495e91489f9395647ad5c197a77f6c7848b | |||
v1.0 | instruct | Filter | Filter_67206_I | Write a Python script that finds all prime numbers within a given range, say from 10 to 50, using a function. The script should also include a check to verify if a number is prime. | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True... | from solution import is_prime, find_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5)... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find all prime numbers in the given range [start, end].",
"function_declaration": "def find_primes_in_range(start, end):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n 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": "00067206",
"row_id": 67206,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136120']"
} | 0.690125 | Filter_67206 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9d6f82c0c15184297631b3923d56d7c76b91a8a | 0ec6275a641bff56118e8d92f1a2cc557fdb17f8 | |||
v1.0 | instruct | Filter | Filter_67208_I | How can I modify the `nslookup.py` script to handle DNS queries for both IPv4 and IPv6 addresses, and print the results separately for each address type? | import socket
def get_ipv4_addresses(domain):
"""
Returns a list of IPv4 addresses for a given domain.
"""
try:
return socket.gethostbyname_ex(domain)[2]
except socket.gaierror:
return []
def get_ipv6_addresses(domain):
"""
Returns a list of IPv6 addresses for a given domai... | import pytest
from solution import get_ipv4_addresses, get_ipv6_addresses, nslookup
def test_get_ipv4_addresses():
ipv4_addresses = get_ipv4_addresses("example.com")
assert isinstance(ipv4_addresses, list)
assert all(isinstance(addr, str) for addr in ipv4_addresses)
def test_get_ipv6_addresses():
ipv6... | [
{
"docstring": "Returns a list of IPv4 addresses for a given domain.",
"function_declaration": "def get_ipv4_addresses(domain):",
"function_name": "get_ipv4_addresses",
"parameter_list": "(domain)"
},
{
"docstring": "Returns a list of IPv6 addresses for a given domain.",
"function_declar... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\n\ndef nslookup(hostname):\n \"\"\"\n Performs a DNS lookup for the given hostname and returns both IPv4 and IPv6 addresses separately.\n \n Args:\n - hostname (st... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067208",
"row_id": 67208,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136123']"
} | 0.494001 | Filter_67208 | I | [
"get_ipv4_addresses",
"get_ipv6_addresses",
"nslookup"
] | 3 | [
[
"nslookup",
"get_ipv4_addresses"
],
[
"nslookup",
"get_ipv6_addresses"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a800b58fd631c095072eb69549a40c2cbbe8461a | f0d14dd1539c8d100aaa3ef2f337e74e76cc46ec | |||
v1.0 | instruct | Filter | Filter_67212_I | Let's write 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):
"""
Check if a string is a palindrome, ignoring spaces, punctuation, and capitalization.
"""
import re
s = re.sub(r'[^A-Za-z0-9]', '', s).lower() # Remove non-alphanumeric characters and convert to lowercase
return s == s[::-1]
def filter_palindromes(strings):
"""
... | from solution import filter_palindromes
def test_filter_palindromes():
assert filter_palindromes(["racecar", "hello", "level", "world", "madam"]) == ["racecar", "level", "madam"]
assert filter_palindromes(["abc", "def", "ghi"]) == []
assert filter_palindromes(["A man, a plan, a canal, Panama", "No lemon, n... | [
{
"docstring": "Check if a string is a palindrome, ignoring spaces, punctuation, and capitalization.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Returns a new list containing only the strings from the input l... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"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 \"\"\"\n s = ''.join([c.lower() for c in s if c.isalnum()]) # Normalize the string\n re... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067212",
"row_id": 67212,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136131']"
} | 0.751715 | Filter_67212 | I | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c471beb9f2dbe813dc72f3097d8b8acd5378c56 | 1a37be72db9de70583bd73d3f1e3c9085f1de523 | |||
v1.0 | instruct | Filter | Filter_67214_I | Hey Qwen, I need help with creating a genetic algorithm in Python. Can you guide me through the process of implementing a simple genetic algorithm to solve a basic optimization problem, like finding the maximum value of a function? | import random
def initialize_population(size, chromosome_length):
population = []
for _ in range(size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
return population
def fitness_function(chromosome):
# Convert binary chromosome to... | from solution import initialize_population, fitness_function, selection, crossover, mutate, genetic_algorithm
def test_initialize_population():
population = initialize_population(10, 6)
assert len(population) == 10
for chromosome in population:
assert len(chromosome) == 6
assert all(gene in... | [
{
"docstring": null,
"function_declaration": "def initialize_population(size, chromosome_length):",
"function_name": "initialize_population",
"parameter_list": "(size, chromosome_length)"
},
{
"docstring": null,
"function_declaration": "def fitness_function(chromosome):",
"function_n... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef fitness(individual):\n \"\"\"\n Fitness function to evaluate the individual.\n In this case, it is simply the square of the value.\n \"\"\"\n return individ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067214",
"row_id": 67214,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136135']"
} | 0.418194 | Filter_67214 | I | [
"initialize_population",
"fitness_function",
"selection",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness_function"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"selection"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | c5bc8a6d3f9a0a4ecf0b57ad6632fd53892c26b0 | 2621ab785d0e08e54f6fce943020e69a04b86ba5 | |||
v1.0 | instruct | Filter | Filter_67253_I | Can you explain how to implement a simple caching system in a Python web application using Flask? | from flask import Flask, request, jsonify
from functools import wraps
import time
app = Flask(__name__)
# Simple in-memory cache
cache = {}
def cache_response(timeout=5):
def decorator(f):
@wraps(f)
def wrapped_function(*args, **kwargs):
cache_key = request.full_path
if ca... | import pytest
from solution import app, cache
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_cache_response(client):
response = client.get('/data')
assert response.status_code == 200
first_response_data = response.get_data... | [
{
"docstring": null,
"function_declaration": "def cache_response(timeout=5):",
"function_name": "cache_response",
"parameter_list": "(timeout=5)"
},
{
"docstring": null,
"function_declaration": "def get_data():",
"function_name": "get_data",
"parameter_list": "()"
},
{
"d... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, jsonify\nfrom flask_caching import Cache\n\n# Configuration for caching\nconfig = {\n \"CACHE_TYPE\": \"SimpleCache\", # You can use different types of caches such ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067253",
"row_id": 67253,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136217']"
} | 0.468955 | Filter_67253 | I | [
"cache_response",
"get_data"
] | 2 | [
[
"get_data",
"cache_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | d132aa6af8572fdf403408993bfaddb153cdd3f8 | f3ea6b102bd21697e62f57e0dc81f30e68699e6f | |||
v1.0 | instruct | Filter | Filter_67255_I | Can you explain how to implement a simple blockchain in Python? Building a blockchain involves creating blocks and linking them together in a chain. Each block contains data, a timestamp, and a hash of the previous block. This ensures that the blockchain is secure and tamper-resistant. Can you provide a basic example o... | import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def calculate_hash(index, previous_hash, timestamp, da... | from solution import Block, calculate_hash, create_genesis_block, create_block
def test_create_genesis_block():
genesis_block = create_genesis_block()
assert genesis_block.index == 0
assert genesis_block.previous_hash == "0"
assert genesis_block.data == "Genesis Block"
assert genesis_block.hash == ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"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": "00067255",
"row_id": 67255,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136221']"
} | 0.420818 | Filter_67255 | I | [
"calculate_hash",
"create_genesis_block",
"create_block"
] | 3 | [
[
"create_block",
"calculate_hash"
],
[
"create_genesis_block",
"calculate_hash"
]
] | 2 | [] | false | [
"Block"
] | true | pytest | true | [] | true | e3b6a26e92a0e8bde5da389ff9d54367d70540ff | 3092efa1f1e12a694972222bf32103bc29c4138a | |||
v1.0 | instruct | Filter | Filter_67260_I | Write a Python program that calculates the area of a triangle using Heron's formula. The program should also include a function to check if the given sides can form a valid triangle before calculating the area. | import math
def is_valid_triangle(a, b, c):
"""
Check if the given sides a, b, and c can form a valid triangle.
"""
return a + b > c and a + c > b and b + c > a
def area_of_triangle(a, b, c):
"""
Calculate the area of a triangle using Heron's formula.
"""
if not is_valid_triangle(a, b,... | from solution import is_valid_triangle, area_of_triangle
def test_valid_triangle():
assert is_valid_triangle(3, 4, 5) == True
assert is_valid_triangle(1, 1, 1) == True
assert is_valid_triangle(5, 12, 13) == True
def test_invalid_triangle():
assert is_valid_triangle(1, 2, 3) == False
assert is_vali... | [
{
"docstring": "Check if the given sides a, b, and c can form a valid triangle.",
"function_declaration": "def is_valid_triangle(a, b, c):",
"function_name": "is_valid_triangle",
"parameter_list": "(a, b, c)"
},
{
"docstring": "Calculate the area of a triangle using Heron's formula.",
"f... | [
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_valid_triangle(a, b, c):\n \"\"\"\n Checks if a, b, and c can form a valid triangle.\n \n A set of three sides can form a triangle if and only if the sum of \... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067260",
"row_id": 67260,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136230']"
} | 0.713776 | Filter_67260 | I | [
"is_valid_triangle",
"area_of_triangle"
] | 2 | [
[
"area_of_triangle",
"is_valid_triangle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f871a57929823f1a43e9526b842f04dcfbe6227 | f94d0682556fc313379db50245f866686f4d7738 | |||
v1.0 | instruct | Filter | Filter_67269_I | Write a Python script that prints the current date and time, and then waits for a user to input a number. If the number is not within the range of 1 to 100, the program should print an error message and ask the user to input the number again. The program should continue to prompt the user until a valid number is entere... | from datetime import datetime
def get_valid_number():
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if 1 <= user_input <= 100:
return user_input
else:
print("Error: Number not in range 1 to 100. Please try ... | from solution import get_valid_number
import builtins
import pytest
def test_valid_number(monkeypatch):
inputs = iter(['50'])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
assert get_valid_number() == 50
def test_number_out_of_range(monkeypatch):
inputs = iter(['150', '50'])
monkey... | [
{
"docstring": null,
"function_declaration": "def get_valid_number():",
"function_name": "get_valid_number",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def print_current_datetime_and_get_number():",
"function_name": "print_current_datetime_and_get_number"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef get_valid_number():\n while True:\n try:\n user_input = int(input(\"Enter a number between 1 and 100: \"))\n if 1 <= user_i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067269",
"row_id": 67269,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136247']"
} | 0.483563 | Filter_67269 | I | [
"get_valid_number",
"print_current_datetime_and_get_number"
] | 2 | [
[
"print_current_datetime_and_get_number",
"get_valid_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09f5e36a96b2cb70ce57aa7dd5610d5d50446c1c | 6dbeffbb43a7b02c9eb4371c7852e84dcc665fa4 | |||
v1.0 | instruct | Filter | Filter_67306_I | How can I write a Python function that calculates the sum of all prime numbers within a given range, including the endpoints, if they are prime? | 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 sum_of_primes_in_range(start, end):
"""
Calculate the sum of all prime numbers within a given range, ... | from solution import is_prime, sum_of_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
def test_sum_of_primes_in_range():
assert sum_of... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of all prime numbers within a given range, including the endpoints.",
"function_declaration": "def sum_of_p... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\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": "00067306",
"row_id": 67306,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136324']"
} | 0.717619 | Filter_67306 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a494eff96be9a6b22ccfba35f2ddfa05a928f0d4 | 31ab9b1c65cf6ecc080d2e1c9b094039e2ed7f94 | |||
v1.0 | instruct | Filter | Filter_67327_I | Can you provide a Python script that generates a list of random numbers within a specified range and checks if any of these numbers are prime? A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. | import random
def is_prime(n):
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_random_numbers(count, start, end):
"""
Generates a list o... | from solution import is_prime, generate_random_numbers, check_for_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-10) == False
d... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generates a list of 'count' random integers between 'start' and 'end' (inclusive).",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import isqrt\n\ndef 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 ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067327",
"row_id": 67327,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136359']"
} | 0.617021 | Filter_67327 | I | [
"is_prime",
"generate_random_numbers",
"check_for_primes"
] | 3 | [
[
"check_for_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | efcdf194cf3c10f38e77f46fa3c7f3d8b2a84c3a | 3b521fd3a1f2547069be778c394d58f9958883a7 | |||
v1.0 | instruct | Filter | Filter_67339_I | Please write a Python script that reads data from a local JSON file, modifies it by adding a new entry, and then writes the updated data back to the file. The JSON file should be in the format of a list of dictionaries, where each dictionary represents an individual entry. Each entry should have the following fields: "... | import json
import os
def read_json_file(file_path):
"""
Reads data from a JSON file and returns it as a Python object.
"""
if not os.path.exists(file_path):
return []
with open(file_path, 'r') as file:
data = json.load(file)
return data
def write_json_file(file_path, data):
... | import os
import json
import pytest
from solution import read_json_file, write_json_file, add_entry_to_json
@pytest.fixture
def temp_json_file(tmpdir):
return os.path.join(tmpdir, 'test_data.json')
def test_add_entry_to_empty_json(temp_json_file):
new_entry = add_entry_to_json(temp_json_file, "John Doe", "jo... | [
{
"docstring": "Reads data from a JSON file and returns it as a Python object.",
"function_declaration": "def read_json_file(file_path):",
"function_name": "read_json_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes data to a JSON file.",
"function_declaration": "def writ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef read_json_file(file_path):\n \"\"\"\n Reads data from a JSON file and returns it as a list of dictionaries.\n \"\"\"\n with open(file_path, 'r') as file:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067339",
"row_id": 67339,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136386']"
} | 0.649533 | Filter_67339 | I | [
"read_json_file",
"write_json_file",
"add_entry_to_json"
] | 3 | [
[
"add_entry_to_json",
"read_json_file"
],
[
"add_entry_to_json",
"write_json_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 843a69da1871d7c679cd96861ac542924ebeca77 | 6ffce1dc84b8317f0e268a0388f48edc94fa7e57 | |||
v1.0 | instruct | Filter | Filter_67367_I | How can I implement a spam filter using Bayesian filtering in Python? | import re
from collections import defaultdict
import math
def preprocess(text):
text = text.lower()
text = re.sub(r'\b\d+\b', ' number ', text)
text = re.sub(r'\W+', ' ', text)
return text.split()
def train(data):
spam_words = defaultdict(int)
ham_words = defaultdict(int)
spam_count = 0
... | from solution import preprocess, train, classify
def test_preprocess():
assert preprocess("Hello, World!") == ["hello", "world"]
assert preprocess("Call 1234 to win!") == ["call", "number", "to", "win"]
def test_train():
data = [("Win a free prize now", True), ("Hello, how are you", False)]
model = tr... | [
{
"docstring": null,
"function_declaration": "def preprocess(text):",
"function_name": "preprocess",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def train(data):",
"function_name": "train",
"parameter_list": "(data)"
},
{
"docstring": null,... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import defaultdict\nimport math\n\ndef preprocess(text):\n text = text.lower()\n text = re.sub(r'\\b\\d+\\b', ' number ', text)\n text = re.sub(r'\\W+', ' ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067367",
"row_id": 67367,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136433']"
} | 0.423573 | Filter_67367 | I | [
"preprocess",
"train",
"classify"
] | 3 | [
[
"classify",
"preprocess"
],
[
"train",
"preprocess"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 23b3b847b3fc4715a6eb05b47aa65d4bf93af0d4 | fa5cfc4e25f02f7949b8ef5841303e999cc3af3c | |||
v1.0 | instruct | Filter | Filter_67370_I | Write a Python script to monitor a list of websites for availability and log the results. The script should periodically check the availability of each website and log the status (up or down) along with the timestamp. The script should be able to handle multiple websites and should be configurable via a configuration f... | import requests
import time
import configparser
from datetime import datetime
def check_website(url):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return "up"
else:
return "down"
except requests.RequestException:
return "do... | import pytest
import requests
import tempfile
import os
from datetime import datetime
from unittest.mock import patch
from solution import check_website, monitor_websites
# Mock requests.get to simulate different scenarios for website availability
@patch('requests.get')
def test_check_website_up(mock_get):
mock_ge... | [
{
"docstring": null,
"function_declaration": "def check_website(url):",
"function_name": "check_website",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def monitor_websites(config_path):",
"function_name": "monitor_websites",
"parameter_list": "(confi... | [
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 time\nimport configparser\nfrom datetime import datetime\n\ndef check_website(url):\n try:\n response = requests.get(url, timeout=5)\n if response.stat... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067370",
"row_id": 67370,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136441']"
} | 0.6043 | Filter_67370 | I | [
"check_website",
"monitor_websites"
] | 2 | [
[
"monitor_websites",
"check_website"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 8cfca18641429ab79bdd2a1ca1cdef10cdc07fb2 | 908dc5a7429817472f5fa8930e2c082970aaa802 | |||
v1.0 | instruct | Filter | Filter_67376_I | I want to create a Rock Paper Scissors game in Python. Can you provide me with a basic example of how to structure this game? | import random
def get_computer_choice():
"""
Randomly selects and returns the computer's choice from 'rock', 'paper', or 'scissors'.
"""
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def determine_winner(player, computer):
"""
Determines the winner of the game.
... | from solution import determine_winner, play_round
def test_determine_winner_tie():
assert determine_winner('rock', 'rock') == 'Tie'
assert determine_winner('paper', 'paper') == 'Tie'
assert determine_winner('scissors', 'scissors') == 'Tie'
def test_determine_winner_player_wins():
assert determine_... | [
{
"docstring": "Randomly selects and returns the computer's choice from 'rock', 'paper', or 'scissors'.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of the game.\n\nReturns:\n ... | [
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 Returns random choice for the computer: 'rock', 'paper', or 'scissors'.\n \"\"\"\n choices = [\"rock\", \"paper\", \"scissors... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067376",
"row_id": 67376,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136451']"
} | 0.358791 | Filter_67376 | I | [
"get_computer_choice",
"determine_winner",
"play_round"
] | 3 | [
[
"play_round",
"determine_winner"
],
[
"play_round",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fc042b7ac9c1b45734ea387187550a10f2366e04 | d24d37295b6a4a0dda2d0ef6cb08fb34117a06f6 | |||
v1.0 | instruct | Filter | Filter_67380_I | Can you provide a step-by-step guide on how to create a simple two-player Tic Tac Toe game in Python? | def initialize_board():
"""
Initialize the empty game board.
"""
return [[' ' for _ in range(3)] for _ in range(3)]
def print_board(board):
"""
Print the current state of the board.
"""
for row in board:
print('|'.join(row))
print('-' * 5)
def check_winner(board):
"... | from solution import initialize_board, check_winner, make_move
def test_initialize_board():
board = initialize_board()
expected_board = [[' ' for _ in range(3)] for _ in range(3)]
assert board == expected_board
def test_make_move():
board = initialize_board()
assert make_move(board, 'X', 0, 0) == ... | [
{
"docstring": "Initialize the empty game board.",
"function_declaration": "def initialize_board():",
"function_name": "initialize_board",
"parameter_list": "()"
},
{
"docstring": "Print the current state of the board.",
"function_declaration": "def print_board(board):",
"function_na... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def initialize_board():\n \"\"\"\n Initialize the empty game board.\n \"\"\"\n return [[' ' for _ in range(3)] for _ in range(3)]\n\ndef print_board(board):\n \"\"\"\n Print ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067380",
"row_id": 67380,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136460']"
} | 0.395765 | Filter_67380 | I | [
"initialize_board",
"print_board",
"check_winner",
"make_move",
"tic_tac_toe"
] | 5 | [
[
"tic_tac_toe",
"check_winner"
],
[
"tic_tac_toe",
"initialize_board"
],
[
"tic_tac_toe",
"make_move"
],
[
"tic_tac_toe",
"print_board"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 8a3c317f2a84b33aa6d3e27825332d09c5f6aa76 | 50d1d2b176d47a7729a9fd0ea3b5c58fe52f311a | |||
v1.0 | instruct | Filter | Filter_67388_I | Write a Python function that takes an integer `n` as input and returns a list of all the prime numbers less than `n`. | def is_prime(num):
"""
Helper function to determine if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
retu... | from solution import is_prime, 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(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
def test_primes_less_than(... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers less than n.",
"function_declaration": "def primes_less_than(n)... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def primes_less_than(n):\n \"\"\"\n Returns a list of all prime numbers less than n.\n \"\"\"\n if n <= 2:\n return []\n \n primes = []\n for num in range(2, n):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067388",
"row_id": 67388,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136481']"
} | 0.815227 | Filter_67388 | I | [
"is_prime",
"primes_less_than"
] | 2 | [
[
"primes_less_than",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87fd09784a15dde1f21fdd54305289070704a295 | 06fa763660fc2fec448a312a9309dc27f5f7e82d | |||
v1.0 | instruct | Filter | Filter_67408_I | Design a Python function that takes a list of integer pairs and returns a list of boolean values indicating whether each pair is an amicable pair. An amicable pair consists of two different numbers for which the sum of the proper divisors (excluding the number itself) of each is equal to the other number. | def sum_of_proper_divisors(n):
return sum(i for i in range(1, n) if n % i == 0)
def is_amicable_pair(pair):
a, b = pair
if a == b:
return False
return sum_of_proper_divisors(a) == b and sum_of_proper_divisors(b) == a
def check_amicable_pairs(pairs):
"""
Takes a list of integer pairs an... | from solution import check_amicable_pairs, is_amicable_pair, sum_of_proper_divisors
def test_sum_of_proper_divisors():
assert sum_of_proper_divisors(220) == 284
assert sum_of_proper_divisors(284) == 220
assert sum_of_proper_divisors(6) == 6 # 1 + 2 + 3 = 6
assert sum_of_proper_divisors(10) == 8 # 1 + 2... | [
{
"docstring": null,
"function_declaration": "def sum_of_proper_divisors(n):",
"function_name": "sum_of_proper_divisors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_amicable_pair(pair):",
"function_name": "is_amicable_pair",
"parameter_list": ... | [
1,
0,
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 if n < 2:\n return 0\n divisors_sum = 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n divisors_sum += i\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067408",
"row_id": 67408,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136527']"
} | 0.612975 | Filter_67408 | I | [
"sum_of_proper_divisors",
"is_amicable_pair",
"check_amicable_pairs"
] | 3 | [
[
"check_amicable_pairs",
"is_amicable_pair"
],
[
"is_amicable_pair",
"sum_of_proper_divisors"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5055f7ea5a04955d142d48985b3005b85e8d719a | 88f060f105cc00a27f68f0c4f9a3b172b373df65 | |||
v1.0 | instruct | Filter | Filter_67410_I | Can you provide a detailed explanation of how to implement a basic Shallow Neural Network using NumPy in Python? Building a neural network from scratch is a great way to understand the underlying mathematics and mechanisms. Let's break it down step by step. | import numpy as np
def sigmoid(x):
"""
Calculate sigmoid function
"""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
"""
Calculate derivative of sigmoid function
"""
return x * (1 - x)
def forward_propagation(X, weights):
"""
Perform forward propagation
"""
lay... | from solution import sigmoid, sigmoid_derivative, predict, train_neural_network
import numpy as np
def test_sigmoid():
assert np.isclose(sigmoid(0), 0.5)
assert np.isclose(sigmoid(np.log(1/3)), 0.25)
def test_sigmoid_derivative():
assert np.isclose(sigmoid_derivative(0.5), 0.25)
assert np.isclose(sigm... | [
{
"docstring": "Calculate sigmoid function",
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": "Calculate derivative of sigmoid function",
"function_declaration": "def sigmoid_derivative(x):",
"function_name": "sigmoid_de... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\nclass ShallowNeuralNetwork:\n def __init__(self, input_size, hidden_size, output_size):\n np.random.seed(1)\n self.input_size = input_size\n self.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067410",
"row_id": 67410,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136533']"
} | 0.332928 | Filter_67410 | I | [
"sigmoid",
"sigmoid_derivative",
"forward_propagation",
"back_propagation",
"train_neural_network",
"predict"
] | 6 | [
[
"back_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"predict",
"forward_propagation"
],
[
"train_neural_network",
"back_propagation"
],
[
"train_neural_network",
"forward_propagation"
]
] | 5 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | d774ea9d7bd53347100a8de332514974b333a844 | f9e180e15cb98465136db0a1fcd27153f08b305e | |||
v1.0 | instruct | Filter | Filter_67422_I | Can you provide a Python code to simulate a simple dice game where two players roll a die, and the player with the higher number wins the round? The game continues until one player reaches a score of 5 points. The program should display the result of each round and the final winner. | import random
def roll_die():
return random.randint(1, 6)
def dice_game():
player1_score = 0
player2_score = 0
round_number = 1
while player1_score < 5 and player2_score < 5:
player1_roll = roll_die()
player2_roll = roll_die()
print(f"Round {round_number}: Player 1 rolled... | from solution import roll_die, dice_game
def test_roll_die():
for _ in range(100):
roll = roll_die()
assert 1 <= roll <= 6
# Testing the dice_game function can be challenging due to its random nature,
# so we will simulate a controlled version of the game for repeatable results.
def mock_roll_die... | [
{
"docstring": null,
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def dice_game():",
"function_name": "dice_game",
"parameter_list": "()"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"\n Simulates rolling a 6-sided die.\n Returns a random integer between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_round... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067422",
"row_id": 67422,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136559']"
} | 0.489169 | Filter_67422 | I | [
"roll_die",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 821ad168aeadf83d48565edbf7a62882da388279 | 39244298416a0c2a7faa86576046009d324ac98a | |||
v1.0 | instruct | Filter | Filter_67439_I | How can I modify the given code to print the Fibonacci sequence up to the 10th term in Python? | def generate_fibonacci_sequence(n):
"""
Generates the Fibonacci sequence up to the n-th term.
"""
if n <= 0:
return []
elif n == 1:
return [0]
sequence = [0, 1]
for i in range(2, n):
next_term = sequence[-1] + sequence[-2]
sequence.append(next_term)
... | from solution import generate_fibonacci_sequence
def test_generate_fibonacci_sequence():
assert generate_fibonacci_sequence(0) == []
assert generate_fibonacci_sequence(1) == [0]
assert generate_fibonacci_sequence(2) == [0, 1]
assert generate_fibonacci_sequence(3) == [0, 1, 1]
assert generate_fibona... | [
{
"docstring": "Generates the Fibonacci sequence up to the n-th term.",
"function_declaration": "def generate_fibonacci_sequence(n):",
"function_name": "generate_fibonacci_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Prints the Fibonacci sequence up to the n-th term.",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_sequence(n_terms):\n \"\"\"\n Returns a list containing the Fibonacci sequence up to n_terms.\n \"\"\"\n if n_terms <= 0:\n return []\n elif n_terms == 1:\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00067439",
"row_id": 67439,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136596']"
} | 0.675303 | Filter_67439 | I | [
"generate_fibonacci_sequence",
"print_fibonacci_sequence"
] | 2 | [
[
"print_fibonacci_sequence",
"generate_fibonacci_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8dfdef81e2c12778630b35d4f24b36162e621d1e | ada1c6b4d2c3eed6b3d6142d21af639b4c401259 | |||
v1.0 | instruct | Filter | Filter_67454_I | How can I generate and plot the Mandelbrot set using Python and Matplotlib? | import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iter):
"""
Given a complex number `c`, this function performs the Mandelbrot iteration, returning the iteration count
at which the magnitude of the series first exceeded 2, or max_iter if the sequence did not diverge.
"""
z =... | from solution import mandelbrot, generate_mandelbrot
def test_mandelbrot():
assert mandelbrot(complex(0, 0), 100) == 100 # 0 belongs to the Mandelbrot set
assert mandelbrot(complex(1, 0), 100) < 100 # 1 does not belong to the Mandelbrot set
def test_generate_mandelbrot():
width, height = 100, 100
x... | [
{
"docstring": "Given a complex number `c`, this function performs the Mandelbrot iteration, returning the iteration count\nat which the magnitude of the series first exceeded 2, or max_iter if the sequence did not diverge.",
"function_declaration": "def mandelbrot(c, max_iter):",
"function_name": "mand... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(c, max_iter):\n \"\"\"\n Computes Mandelbrot set membership for a specific point `c` in the complex plane.\n Dete... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067454",
"row_id": 67454,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136629']"
} | 0.485593 | Filter_67454 | I | [
"mandelbrot",
"generate_mandelbrot",
"plot_mandelbrot"
] | 3 | [
[
"generate_mandelbrot",
"mandelbrot"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 453a463336b28f4866d1f9adbad33d2e47ded28c | 899de06b5999965a38d4f43590ab8122c4750276 | |||
v1.0 | instruct | Filter | Filter_67460_I | Can you explain the working of the Knuth-Morris-Pratt (KMP) algorithm and provide an example in code? | def calculate_lps(pattern):
"""
Preprocesses the pattern and returns the lps array.
Args:
pattern (str): The pattern to be searched.
Returns:
list: The lps (longest prefix suffix) array.
"""
length = 0
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if patte... | from solution import calculate_lps, kmp_search
def test_calculate_lps():
assert calculate_lps("AABAACAABAA") == [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]
assert calculate_lps("ABCDE") == [0, 0, 0, 0, 0]
assert calculate_lps("AAAA") == [0, 1, 2, 3]
assert calculate_lps("") == []
def test_kmp_search_pattern_in_... | [
{
"docstring": "Preprocesses the pattern and returns the lps array.\n\nArgs:\npattern (str): The pattern to be searched.\n\nReturns:\nlist: The lps (longest prefix suffix) array.",
"function_declaration": "def calculate_lps(pattern):",
"function_name": "calculate_lps",
"parameter_list": "(pattern)"
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_lps(pattern):\n \"\"\"\n Preprocesses the pattern and returns the lps array.\n\n Args:\n pattern (str): The pattern to be searched.\n\n Returns:\n list: The lps... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067460",
"row_id": 67460,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136639']"
} | 0.431712 | Filter_67460 | I | [
"calculate_lps",
"kmp_search"
] | 2 | [
[
"kmp_search",
"calculate_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f9624aa35a64cb8b32749eaf701b973e1fc681de | 195123533e9607559fc98325f38ae0af426bb542 | |||
v1.0 | instruct | Filter | Filter_67544_I | Write a Python program to find the prime numbers between two given numbers, `m` and `n`, inclusive. The function should return a list of these prime numbers. Additionally, include a test function to verify the correctness of your prime-finding function. | def is_prime(num):
"""
Helper function to determine if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
retu... | from solution import find_primes
def test_prime_within_range():
assert find_primes(10, 20) == [11, 13, 17, 19]
def test_prime_single_number():
assert find_primes(5, 5) == [5]
assert find_primes(4, 4) == []
def test_prime_with_no_primes():
assert find_primes(14, 16) == []
def test_prime_negative_rang... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of prime numbers between m and n, inclusive.",
"function_declaration": "def find_pri... | [
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 \"\"\" Check if a number is prime \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067544",
"row_id": 67544,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136795']"
} | 0.582067 | Filter_67544 | I | [
"is_prime",
"find_primes"
] | 2 | [
[
"find_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 88c6e3f87bce03a318d86e663eaf799741206287 | 53cb044d94e4a546a70ccdbe9c9c8dd7714d0c92 | |||
v1.0 | instruct | Filter | Filter_67585_I | Write a Python program that sorts an array of integers using the merge sort algorithm and counts the number of inversions in the process. An inversion happens when for any two indices i and j, if i < j and arr[i] > arr[j], then the pair (i, j) is an inversion. | def merge_sort_and_count(arr):
"""
Sorts the array using merge sort and counts the number of inversions.
"""
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
left, left_inversions = merge_sort_and_count(arr[:mid])
right, right_inversions = merge_sort_and_count(arr[mid:])
mer... | from solution import merge_sort_and_count
def test_no_inversions():
arr = [1, 2, 3, 4, 5]
sorted_arr, inv_count = merge_sort_and_count(arr)
assert sorted_arr == [1, 2, 3, 4, 5]
assert inv_count == 0
def test_one_inversion():
arr = [1, 3, 2, 4, 5]
sorted_arr, inv_count = merge_sort_and_count(ar... | [
{
"docstring": "Sorts the array using merge sort and counts the number of inversions.",
"function_declaration": "def merge_sort_and_count(arr):",
"function_name": "merge_sort_and_count",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array and counts th... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_and_count(arr):\n \"\"\"\n Sorts an array using the merge sort algorithm and counts the number of inversions.\n :param arr: List of integers\n :return: A tuple conta... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067585",
"row_id": 67585,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136881']"
} | 0.676276 | Filter_67585 | I | [
"merge_sort_and_count",
"merge_and_count"
] | 2 | [
[
"merge_sort_and_count",
"merge_and_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb1e968e3f3dfe55e3ce6dac717842a5b6a5f213 | c13b3dfcbf8a5e428f3d8dc568eea435b5163e7e | |||
v1.0 | instruct | Filter | Filter_67587_I | Can you provide a Python code snippet for generating a simple text-based adventure game? | def start_game():
"""
Starts the text-based adventure game.
"""
print("Welcome to the Text Adventure Game!")
print("You find yourself in a dark room with two doors: one to your left and one to your right.")
print("Which door do you choose? (left/right)")
choice1 = input("> ")
if choice... | import builtins
from unittest.mock import patch
from solution import start_game, left_room, right_room
def test_invalid_first_choice():
with patch('builtins.input', side_effect=['up']), patch('builtins.print') as mock_print:
start_game()
mock_print.assert_any_call("Invalid choice. Game over.")
de... | [
{
"docstring": "Starts the text-based adventure game.",
"function_declaration": "def start_game():",
"function_name": "start_game",
"parameter_list": "()"
},
{
"docstring": "Handles the events in the left room.",
"function_declaration": "def left_room():",
"function_name": "left_room... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def intro():\n \"\"\"\n Displays the introduction of the game and the initial choice.\n \"\"\"\n return \"You are standing in an open field west of a white house, with a boarded fr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067587",
"row_id": 67587,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136884']"
} | 0.463221 | Filter_67587 | I | [
"start_game",
"left_room",
"right_room"
] | 3 | [
[
"start_game",
"left_room"
],
[
"start_game",
"right_room"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ec02ce0a158105222d1e565d40f33e90a7342a0b | dfb0b21ea1522ca9475b18f6aaeb23865fde331f | |||
v1.0 | instruct | Filter | Filter_67607_I | Can you provide a Python code to simulate a simple dice rolling game where a player rolls two dice and wins if the sum is 7 or 11? | import random
def roll_dice():
"""
Simulates rolling two dice and returns their sum.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def is_winner(roll_sum):
"""
Determines if the result of rolling two dice is a win.
Winning occurs if the sum is 7 or ... | from solution import roll_dice, is_winner, roll_and_check_win
def test_roll_dice():
for _ in range(100):
roll_sum = roll_dice()
assert 2 <= roll_sum <= 12, "Roll sum should be between 2 and 12"
def test_is_winner():
assert is_winner(7) == True, "Sum of 7 should be a win"
assert is_winner(1... | [
{
"docstring": "Simulates rolling two dice and returns their sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Determines if the result of rolling two dice is a win.\nWinning occurs if the sum is 7 or 11.",
"functio... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Rolls two dice and returns their values as a tuple.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067607",
"row_id": 67607,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136936']"
} | 0.536491 | Filter_67607 | I | [
"roll_dice",
"is_winner",
"roll_and_check_win"
] | 3 | [
[
"roll_and_check_win",
"is_winner"
],
[
"roll_and_check_win",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1f09425a1a67b711c0ec3eda95e99ce9470391de | aac0c4eca0641f9245a9b7d88f50ef4326c726a7 | |||
v1.0 | instruct | Filter | Filter_67610_I | Can you provide a Python code example for creating a simple animation of a bouncing ball using the `matplotlib` library? | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def init():
ball.set_data([], [])
return ball,
def animate(i):
x = radius * np.cos(angles[i]) + center_x
y = radius * np.sin(angles[i]) + center_y
if y < radius:
y = radius
ball.set_data(x, y)
... | from solution import create_bouncing_ball_animation
def test_create_bouncing_ball_animation():
# This test is a bit complex because it deals with visual components and animations and there is no straightforward return value to test.
# Therefore, the test will only assert that the function can be called without... | [
{
"docstring": null,
"function_declaration": "def init():",
"function_name": "init",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def animate(i):",
"function_name": "animate",
"parameter_list": "(i)"
},
{
"docstring": null,
"function_declara... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ndef init():\n ball.set_data([], [])\n return ball,\n\ndef animate(i):\n x = radius * n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00067610",
"row_id": 67610,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136945']"
} | 0.428371 | Filter_67610 | I | [
"init",
"animate",
"create_bouncing_ball_animation"
] | 3 | [
[
"create_bouncing_ball_animation",
"animate"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | f2102fdcd7215557e786198b919fde0e23f9f7f0 | 62046de5682c3636e3321544af48974edf551eeb | |||
v1.0 | instruct | Filter | Filter_67618_I | Can you provide a Python code snippet that prints the prime numbers between 1 and 50? | 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 Fals... | from solution import is_prime, print_primes_up_to_50
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
def test_print_primes_up_to_50():
correct_primes = ... | [
{
"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": "Prints the prime numbers between 1 and 50.",
"function_declaration": "def print_primes_up_to_5... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067618",
"row_id": 67618,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_136957']"
} | 0.642878 | Filter_67618 | I | [
"is_prime",
"print_primes_up_to_50"
] | 2 | [
[
"print_primes_up_to_50",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db615f3969be7fdcb1ba78609dec6b8615b74c40 | 1691c3389863135eed9e20a016e0c70988e1ac2d | |||
v1.0 | instruct | Filter | Filter_67669_I | Write a Python script to simulate rolling a fair six-sided die repeatedly until a specific number, say 6, appears. The script should count and print the number of rolls it took to get the 6. Additionally, the script should simulate this process 100 times and calculate the average number of rolls needed to roll a 6. | import random
def roll_until_six():
"""
Rolls a fair six-sided die until a 6 appears.
Returns the number of rolls it took to get a 6.
"""
rolls = 0
while True:
rolls += 1
if random.randint(1, 6) == 6:
break
return rolls
def simulate_rolls(simulations=100):
"... | from solution import roll_until_six, simulate_rolls
def test_roll_until_six():
for _ in range(100):
rolls = roll_until_six()
assert isinstance(rolls, int)
assert rolls > 0
def test_simulate_rolls():
average_rolls = simulate_rolls(100)
assert isinstance(average_rolls, float)
ass... | [
{
"docstring": "Rolls a fair six-sided die until a 6 appears.\nReturns the number of rolls it took to get a 6.",
"function_declaration": "def roll_until_six():",
"function_name": "roll_until_six",
"parameter_list": "()"
},
{
"docstring": "Simulates rolling a fair six-sided die 100 times unti... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die_until_six():\n \"\"\"\n Rolls a fair six-sided die until a 6 appears.\n \n Returns:\n int: The number of rolls it took to get a 6.\n \"\"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067669",
"row_id": 67669,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137063']"
} | 0.605582 | Filter_67669 | I | [
"roll_until_six",
"simulate_rolls"
] | 2 | [
[
"simulate_rolls",
"roll_until_six"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5dda6f5153cc9e03c148efc75e2a8bb13d90edd9 | cce2a4df29dd9d8140b2118a9920ab5e4ff95c98 | |||
v1.0 | instruct | Filter | Filter_67672_I | How can I design a simple text-based game in Python as a learning project? | import random
def generate_random_number():
"""
Generates a random number between 1 and 100.
"""
return random.randint(1, 100)
def check_guess(random_number, guess):
"""
Checks if the guess is correct, too high, or too low.
Parameters:
random_number (int): The number to guess.
... | from solution import generate_random_number, check_guess
def test_generate_random_number():
number = generate_random_number()
assert 1 <= number <= 100
def test_check_guess_correct():
assert check_guess(50, 50) == "Correct"
def test_check_guess_too_low():
assert check_guess(50, 40) == "Too low"
def ... | [
{
"docstring": "Generates a random number between 1 and 100.",
"function_declaration": "def generate_random_number():",
"function_name": "generate_random_number",
"parameter_list": "()"
},
{
"docstring": "Checks if the guess is correct, too high, or too low.\n\nParameters:\nrandom_number (in... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Room:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.items = []\n self.connected_rooms = {}\n\n def... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00067672",
"row_id": 67672,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_137072']"
} | 0.447735 | Filter_67672 | I | [
"generate_random_number",
"check_guess",
"play_game"
] | 3 | [
[
"play_game",
"check_guess"
],
[
"play_game",
"generate_random_number"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | af2fd235b07a58d5400b6fbb158e391cf39594f5 | d557b6c222a92a976e8b48333da67ff6cd41a94a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.