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_59114_I | Create a Python function that calculates the median of a given list of numbers without sorting the entire list. Use the Quickselect algorithm to find the median efficiently. Make sure your function handles different scenarios: odd/even number of elements, and also repeated elements. Include a check function with provid... | def quickselect(arr, k):
"""
Helper function that implements the quickselect algorithm to find
the k-th smallest element in the unsorted list `arr`.
"""
if len(arr) == 1:
return arr[0]
pivot = arr[len(arr) // 2]
lows = [el for el in arr if el < pivot]
highs = [el for el in arr i... | def test_quickselect_odd_length():
assert quickselect([1, 3, 4, 2, 5], 2) == 3
def test_quickselect_even_length():
assert quickselect([1, 3, 4, 2], 2) == 3
def test_median_odd_length():
assert median([1, 3, 4, 2, 5]) == 3
def test_median_even_length():
assert median([1, 3, 2, 4]) == 2.5
def test_med... | [
{
"docstring": "Helper function that implements the quickselect algorithm to find\nthe k-th smallest element in the unsorted list `arr`.",
"function_declaration": "def quickselect(arr, k):",
"function_name": "quickselect",
"parameter_list": "(arr, k)"
},
{
"docstring": "Calculate the median ... | [
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 quickselect(arr, k):\n if len(arr) == 1:\n return arr[0]\n\n pivot = random.choice(arr)\n lows = [el for el in arr if el < pivot]\n highs = [el for el i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059114",
"row_id": 59114,
"seed_ids": "['Qwen2.5-72B-Instruct_119563']"
} | 0.770723 | Filter_59114 | I | [
"quickselect",
"median",
"check"
] | 3 | [
[
"check",
"median"
],
[
"median",
"quickselect"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 7b5c2f044e2534f340bc07dc182c20a7339cd32d | c07b1e7ed261c00e121ff03c3d23111ff18c881d | |||
v1.0 | instruct | Filter | Filter_59134_I | Design a Python function that dynamically adjusts the learning rate of a PyTorch optimizer based on the change in loss between epochs. If the loss increases, the function should decrease the learning rate by a factor of 10. If the loss decreases, the learning rate remains unchanged. The function should be designed to s... | import torch
import torch.optim as optim
def adjust_learning_rate(optimizer, current_loss, previous_loss):
"""
Adjusts the learning rate of the optimizer based on the change in loss between epochs.
Parameters:
- optimizer (torch.optim.Optimizer): The optimizer whose learning rate needs to be adjus... | import torch
import torch.nn as nn
import torch.optim as optim
from solution import adjust_learning_rate
def test_adjust_learning_rate_decrease():
model = nn.Linear(2, 1)
optimizer = optim.SGD(model.parameters(), lr=0.1)
previous_loss = 0.5
current_loss = 0.6 # Current loss increased
adjust... | [
{
"docstring": "Adjusts the learning rate of the optimizer based on the change in loss between epochs.\n\nParameters:\n- optimizer (torch.optim.Optimizer): The optimizer whose learning rate needs to be adjusted.\n- current_loss (float): The loss value of the current epoch.\n- previous_loss (float): The loss val... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.optim as optim\nimport torch.nn as nn\n\ndef adjust_learning_rate(optimizer, current_loss, previous_loss, factor=10.0):\n \"\"\"\n Adjusts the learning rate of... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059134",
"row_id": 59134,
"seed_ids": "['Qwen2.5-72B-Instruct_119596']"
} | 0.446151 | Filter_59134 | I | [
"adjust_learning_rate",
"train"
] | 2 | [
[
"train",
"adjust_learning_rate"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | ea5b950105ad9d0ebc7f48a3495183dc1ac81d42 | 32ffb1d6035e00c5969233374ca615598d7f6789 | |||
v1.0 | instruct | Filter | Filter_59148_I | What are the steps to create a `reduce` function in Python that multiplies all elements in a list? | def multiply(x, y):
"""
Returns the product of x and y.
"""
return x * y
def reduce(function, iterable, initializer=None):
"""
Reduce function that applies the binary function 'function' cumulatively to the items of 'iterable',
from left to right, so as to reduce the iterable to a single va... | from solution import multiply, reduce, multiply_elements_in_list
def test_multiply():
assert multiply(2, 3) == 6
assert multiply(-1, 5) == -5
assert multiply(0, 4) == 0
def test_reduce_with_initializer():
assert reduce(multiply, [1, 2, 3, 4], 10) == 240
def test_reduce_without_initializer():
asse... | [
{
"docstring": "Returns the product of x and y.",
"function_declaration": "def multiply(x, y):",
"function_name": "multiply",
"parameter_list": "(x, y)"
},
{
"docstring": "Reduce function that applies the binary function 'function' cumulatively to the items of 'iterable',\nfrom left to right... | [
0,
0,
1
] | 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_all_elements(lst):\n \"\"\"\n Multiplies all elements in the given list.\n \n :param lst: List of numbers\n :return: The product of ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059148",
"row_id": 59148,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119625']"
} | 0.573638 | Filter_59148 | I | [
"multiply",
"reduce",
"multiply_elements_in_list"
] | 3 | [
[
"multiply_elements_in_list",
"multiply"
],
[
"multiply_elements_in_list",
"reduce"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3c16a337e95b5bb7c4d8591bf54809aa5c64470e | 41a8fed64eb508ed5bd7976a898a93d3260a191c | |||
v1.0 | instruct | Filter | Filter_59150_I | Write a Python program that simulates a simple calculator. The program should display a simple text-based menu where the user can choose between addition, subtraction, multiplication, division, and exit. The user should be prompted to enter two numbers and then perform the selected operation. The program should handle ... | 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 "Cannot divide by zero"
return a / b
def calculator():
while True:
print("Simple Calculator")
print("1. Addition")
print("2. Subtr... | from solution import add, subtract, multiply, divide
def test_add():
assert add(3, 2) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(3, 2) == 1
assert subtract(-1, 1) == -2
assert subtract(0, 0) == 0
def test_multiply():
assert multiply(3, 2) == 6
... | [
{
"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,
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 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_1 | {
"original_instruction": "",
"prompt_id": "00059150",
"row_id": 59150,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119632']"
} | 0.546211 | Filter_59150 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 76d9c5b4aaeb012c208cc6fe831ab28ed0615007 | 87cd828ed8c2071ae71631d0dac2b233ae573a7d | |||
v1.0 | instruct | Filter | Filter_59153_I | How can I create an HTTP server in Python 3 that supports asynchronous operations using the `aiohttp` library? How can I test it using cURL commands? | import aiohttp
import aiohttp.web
async def handle(request):
name = request.rel_url.query.get('name', 'World')
text = f"Hello, {name}!"
return aiohttp.web.Response(text=text)
async def init_app():
app = aiohttp.web.Application()
app.router.add_get('/', handle)
return app
def main():
app =... | import asyncio
from aiohttp import web
import pytest
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from solution import init_app
class TestMyApp(AioHTTPTestCase):
async def get_application(self):
return await init_app()
@unittest_run_loop
async def test_handle_default(self):
... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from aiohttp import web\n\nasync def handle(request):\n name = request.match_info.get('name', \"Anonymous\")\n text = f\"Hello, {name}\"\n return web.Response(text=text)\n\nasync def ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059153",
"row_id": 59153,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119638']"
} | 0.563849 | Filter_59153 | I | [
"handle",
"init_app",
"main"
] | 3 | [
[
"init_app",
"handle"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 7472b589661039cab71a214333a35881a7216972 | 9f14e10586b7a5f680510af322b4cbf163bea27e | |||
v1.0 | instruct | Filter | Filter_59190_I | Write a Python function that calculates the similarity between two strings using the Levenshtein distance algorithm. The function should return a value between 0 and 1, where 0 indicates no similarity and 1 indicates identical strings. | def levenshtein_distance(s1, s2):
"""
Calculate the Levenshtein distance between two strings.
"""
if len(s1) < len(s2):
return levenshtein_distance(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i... | from solution import string_similarity
def test_similarity_identical_strings():
assert string_similarity("hello", "hello") == 1.0
def test_similarity_completely_different_strings():
assert string_similarity("abc", "xyz") == 0.0
def test_similarity_partial_match():
assert string_similarity("kitten", "sitt... | [
{
"docstring": "Calculate the Levenshtein distance between two strings.",
"function_declaration": "def levenshtein_distance(s1, s2):",
"function_name": "levenshtein_distance",
"parameter_list": "(s1, s2)"
},
{
"docstring": "Calculate the similarity between two strings using the Levenshtein d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def levenshtein_similarity(s1, s2):\n \"\"\"\n Calculate the Levenshtein similarity between two strings and return a value between 0 and 1.\n 0 indicates no similarity and 1 indicates... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059190",
"row_id": 59190,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119704']"
} | 0.780819 | Filter_59190 | I | [
"levenshtein_distance",
"string_similarity"
] | 2 | [
[
"string_similarity",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7da4fd2b7160bb9134de493404e381d85ac66049 | bb14ca3696b69aae990c8ca79d1f0e8d15905f94 | |||
v1.0 | instruct | Filter | Filter_59192_I | Can you explain how to generate a simple De Bruijn sequence for a binary alphabet using Python? | def de_bruijn(k, n):
"""
Generate a De Bruijn sequence for alphabet k and length n.
:param k: int, size of the alphabet (binary for 2 so k=2)
:param n: int, length of combinations
:return: str, de Bruijn sequence
"""
a = [0] * k * n
sequence = []
def db(t, p):
if t > n:... | from solution import generate_binary_de_bruijn
def test_generate_binary_de_bruijn_length_1():
assert generate_binary_de_bruijn(1) == "01"
def test_generate_binary_de_bruijn_length_2():
assert generate_binary_de_bruijn(2) == "0011"
def test_generate_binary_de_bruijn_length_3():
assert generate_binary_de_b... | [
{
"docstring": "Generate a De Bruijn sequence for alphabet k and length n.\n\n:param k: int, size of the alphabet (binary for 2 so k=2)\n:param n: int, length of combinations\n:return: str, de Bruijn sequence",
"function_declaration": "def de_bruijn(k, n):",
"function_name": "de_bruijn",
"parameter_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def de_bruijn(k, n):\n \"\"\"\n Generates a De Bruijn sequence for an alphabet of size k and order n.\n For a binary alphabet (0, 1), k should be 2.\n \"\"\"\n a = [0] * k * n\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059192",
"row_id": 59192,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119707']"
} | 0.514847 | Filter_59192 | I | [
"de_bruijn",
"generate_binary_de_bruijn"
] | 2 | [
[
"generate_binary_de_bruijn",
"de_bruijn"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 92d4040f9130863fb568ec2a1abc289bcb351517 | 07d8cb4f19c5ff16524543c508e25734f3850f9e | |||
v1.0 | instruct | Filter | Filter_59249_I | How can we design a high-quality Python question that incorporates the given text and involves creating a program to generate a report based on the average systolic blood pressure? | def calculate_average_systolic_pressure(readings):
"""
Calculates the average systolic blood pressure from a list of readings.
readings: A list of integers representing systolic blood pressure readings.
Returns the average systolic blood pressure if readings is not empty,
otherwise retur... | from solution import calculate_average_systolic_pressure, generate_pressure_report
def test_calculate_average_systolic_pressure():
assert calculate_average_systolic_pressure([110, 120, 130]) == 120
assert calculate_average_systolic_pressure([]) == None
assert calculate_average_systolic_pressure([90, 90, 90... | [
{
"docstring": "Calculates the average systolic blood pressure from a list of readings.\n\nreadings: A list of integers representing systolic blood pressure readings.\n\nReturns the average systolic blood pressure if readings is not empty, \notherwise returns None.",
"function_declaration": "def calculate_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_bp_report(records):\n if not records:\n return \"Average BP: N/A\\nMax BP: N/A\\nMin BP: N/A\"\n\n total_bp = 0\n max_bp_record = min_bp_record = records[0]\n\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059249",
"row_id": 59249,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119803']"
} | 0.471763 | Filter_59249 | I | [
"calculate_average_systolic_pressure",
"generate_pressure_report"
] | 2 | [
[
"generate_pressure_report",
"calculate_average_systolic_pressure"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1e07ba7ce60e4c90fddacde627db927317a6cd8c | 5544557b4d6e6ebf252df0300280c131a4c5ea13 | |||
v1.0 | instruct | Filter | Filter_59252_I | How can I create a custom URL shortener service using Python and Flask? | from flask import Flask, request, redirect, jsonify
import string
import random
app = Flask(__name__)
# In-memory storage for URLs
url_mapping = {}
# Base URL for the shortener service
BASE_URL = "http://localhost:5000/"
def generate_short_code(length=6):
"""Generate a random short code for the URL."""
retu... | from solution import app, generate_short_code
import pytest
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_generate_short_code_length():
code = generate_short_code()
assert len(code) == 6
def test_generate_short_code_unique():
code1 = generate_short_code... | [
{
"docstring": "Generate a random short code for the URL.",
"function_declaration": "def generate_short_code(length=6):",
"function_name": "generate_short_code",
"parameter_list": "(length=6)"
},
{
"docstring": "Endpoint to create a shortened URL.",
"function_declaration": "def shorten_u... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, jsonify\nimport string\nimport random\n\napp = Flask(__name__)\n\n# In-memory storage for URLs\nurl_mapping = {}\n\n# Base URL for the shortener ser... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00059252",
"row_id": 59252,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119811']"
} | 0.546627 | Filter_59252 | I | [
"generate_short_code",
"shorten_url",
"redirect_to_url"
] | 3 | [
[
"shorten_url",
"generate_short_code"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 2801e3445f5ec694586f89d60aa1f7012551d814 | 9d64a2aea73e9213d8902cf5c8885b9e2e819525 | |||
v1.0 | instruct | Filter | Filter_59282_I | Write a Python function that empirically fits a given dataset to a sigmoid function using curve fitting techniques. The function should take in a dataset of x and y values, and return the parameters of the sigmoid function (amplitude, center, and slope) that best fit the data. | import numpy as np
from scipy.optimize import curve_fit
def sigmoid(x, A, C, K):
"""
Sigmoid function: f(x) = A / (1 + exp(-K*(x-C)))
"""
return A / (1 + np.exp(-K * (x - C)))
def fit_sigmoid(x_data, y_data):
"""
Fits the input x and y data to a sigmoid function and returns the
parameters... | import numpy as np
from solution import fit_sigmoid, sigmoid
def test_fit_sigmoid_simple_data():
x_data = np.linspace(-10, 10, 50)
y_data = sigmoid(x_data, A=1, C=0, K=1)
A, C, K = fit_sigmoid(x_data, y_data)
assert np.isclose(A, 1, atol=0.1)
assert np.isclose(C, 0, atol=0.1)
assert np.isclose(... | [
{
"docstring": "Sigmoid function: f(x) = A / (1 + exp(-K*(x-C)))",
"function_declaration": "def sigmoid(x, A, C, K):",
"function_name": "sigmoid",
"parameter_list": "(x, A, C, K)"
},
{
"docstring": "Fits the input x and y data to a sigmoid function and returns the \nparameters A (amplitude),... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.optimize import curve_fit\n\ndef sigmoid(x, amplitude, center, slope):\n \"\"\"\n Sigmoid function.\n \"\"\"\n return amplitude / (1 + np.exp(-slope ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059282",
"row_id": 59282,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119864']"
} | 0.621309 | Filter_59282 | I | [
"sigmoid",
"fit_sigmoid"
] | 2 | [
[
"fit_sigmoid",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | ee45c02ac7e0dc69480034c40fd86e44437b5b8b | 88d5af738cc3f7178e8ec14d42c17a0eb00320d1 | |||
v1.0 | instruct | Filter | Filter_59313_I | How can I modify the given code to create a personalized greeting message for each participant in a conference by reading the names and email addresses from a CSV file and sending these greetings by email? | import csv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(to_email, subject, message_body):
"""
Sends an email with the given subject and message body to the specified email address.
"""
from_email = 'your_email@example.com'
from_pa... | import pytest
from unittest.mock import patch, Mock
from solution import send_email, generate_greetings
@patch('smtplib.SMTP')
def test_send_email(mock_smtp):
mock_server = Mock()
mock_smtp.return_value = mock_server
send_email('test@example.com', 'Test Subject', 'Test Message')
mock_server.starttls.... | [
{
"docstring": "Sends an email with the given subject and message body to the specified email address.",
"function_declaration": "def send_email(to_email, subject, message_body):",
"function_name": "send_email",
"parameter_list": "(to_email, subject, message_body)"
},
{
"docstring": "Reads a... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef send_greeting_email(name, email, sender_email, sender_password, smtp_ser... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059313",
"row_id": 59313,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119947']"
} | 0.412912 | Filter_59313 | I | [
"send_email",
"generate_greetings"
] | 2 | [
[
"generate_greetings",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d0876bee2d0bc008508f4ed479a31ebedbcc2be | 6b603799b5269e7eccc978f09063b519499eff4e | |||
v1.0 | instruct | Filter | Filter_59320_I | Can you provide a Python code to emulate a simple neural network using NumPy for a given XOR problem? | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def train_xor_nn(X, y, learning_rate=1.0, epochs=10000):
np.random.seed(1)
input_layer_neurons = X.shape[1]
hidden_layer_neurons = 2
output_neurons = 1
hidden_weights = np.random.... | import numpy as np
from solution import train_xor_nn, predict_xor_nn
def test_xor_nn():
# XOR inputs and outputs
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# Train the neural network
hidden_weights, hidden_bias, output_weights, output_bias = train_xor_nn(... | [
{
"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\nclass SimpleNeuralNetwork:\n def __init__(self):\n # Initialize weights randomly with mean 0\n self.weights_input_hidden = 2 * np.random.random((2, 2)) -... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059320",
"row_id": 59320,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119959']"
} | 0.46268 | Filter_59320 | I | [
"sigmoid",
"sigmoid_derivative",
"train_xor_nn",
"predict_xor_nn"
] | 4 | [
[
"predict_xor_nn",
"sigmoid"
],
[
"train_xor_nn",
"sigmoid"
],
[
"train_xor_nn",
"sigmoid_derivative"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 582ebdc31162fdd8280e1b6e991cb92017585abc | 33146807ec9035f0c422875cd9931346d185fb19 | |||
v1.0 | instruct | Filter | Filter_59331_I | Write a Python function to find the next prime number after a given number. The function should take an integer as input and return the next prime number greater than the given number. If the input number is less than 2, the function should return 2 as the first prime number. | def is_prime(n):
"""
Returns True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import next_prime
def test_next_prime_after_0():
assert next_prime(0) == 2
def test_next_prime_after_1():
assert next_prime(1) == 2
def test_next_prime_after_2():
assert next_prime(2) == 3
def test_next_prime_after_3():
assert next_prime(3) == 5
def test_next_prime_after_7():
asse... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the next prime number greater than n. If n is less than 2, returns 2.",
"function_declaratio... | [
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, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00059331",
"row_id": 59331,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_119980']"
} | 0.641357 | Filter_59331 | I | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cefa00212684a70ffcdf1878e1e12122224bd15f | 039e4d1f2d508ad68a4b9ac42181aaaa0e3e938a | |||
v1.0 | instruct | Filter | Filter_59359_I | Could you provide a Python script that validates email addresses from a CSV file? The script should check if the email addresses are syntactically correct and flag invalid ones. The CSV file has a header and the column containing email addresses is named "email". The script should output a new CSV file with two columns... | import csv
import re
def validate_email(email):
"""Checks if an email address is syntactically correct."""
email_regex = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
return bool(email_regex.match(email))
def validate_emails_in_csv(input_file, output_file):
"""Reads an input CSV file... | import os
import csv
from solution import validate_email, validate_emails_in_csv
def test_validate_email():
assert validate_email("test@example.com") == True
assert validate_email("user.name+tag+sorting@example.com") == True
assert validate_email("invalidemail.com") == False
assert validate_email("inva... | [
{
"docstring": "Checks if an email address is syntactically correct.",
"function_declaration": "def validate_email(email):",
"function_name": "validate_email",
"parameter_list": "(email)"
},
{
"docstring": "Reads an input CSV file with email addresses, validates them, and writes the result t... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"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 given email address using regular expression.\n \"\"\"\n regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059359",
"row_id": 59359,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120033']"
} | 0.631304 | Filter_59359 | I | [
"validate_email",
"validate_emails_in_csv"
] | 2 | [
[
"validate_emails_in_csv",
"validate_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 362f0ac1324de4ea39da5abbe14fc71b1d206a0d | c82b6bdee951a587cc707358c2aa59f9c1da0595 | |||
v1.0 | instruct | Filter | Filter_59372_I | Can you provide a Python code to create a simple animation using the turtle graphics module? | import turtle
def draw_square(t, size):
"""
Draw a square with the given turtle `t` and side length `size`.
"""
for _ in range(4):
t.forward(size)
t.right(90)
def animate_square():
"""
Create a simple animation of a rotating square using the turtle graphics module.
"""
... | import turtle
from solution import draw_square
def test_draw_square(monkeypatch):
"""
Test the draw_square function by counting the number of turtle commands executed.
"""
commands = []
class MockTurtle:
def forward(self, distance):
commands.append(f"forward {distance}")
... | [
{
"docstring": "Draw a square with the given turtle `t` and side length `size`.",
"function_declaration": "def draw_square(t, size):",
"function_name": "draw_square",
"parameter_list": "(t, size)"
},
{
"docstring": "Create a simple animation of a rotating square using the turtle graphics mod... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef draw_square(t, size):\n \"\"\"\n Draws a square using the turtle t of side length size.\n \"\"\"\n for _ in range(4):\n t.forward(size)\n t.right... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059372",
"row_id": 59372,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120052']"
} | 0.595337 | Filter_59372 | I | [
"draw_square",
"animate_square"
] | 2 | [
[
"animate_square",
"draw_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 140620f088cd21389ead3bb95227816378d0fb8f | d7612eaf2512ecf61ba354a3d5ced630c0db077d | |||
v1.0 | instruct | Filter | Filter_59395_I | Can you help me write a Python program to simulate a simple dice game where each player rolls a dice and the player with the higher number wins? If it's a tie, the players roll the dice again until there's a winner? | import random
def roll_dice():
"""
Simulates rolling a six-sided die.
Returns an integer between 1 and 6 (inclusive).
"""
return random.randint(1, 6)
def dice_game():
"""
Simulates a simple dice game where two players roll a dice.
The player with the higher number wins.
If it's a t... | from solution import roll_dice, dice_game
def test_roll_dice():
for _ in range(100): # Testing multiple times for randomness
roll = roll_dice()
assert 1 <= roll <= 6
def test_dice_game():
for _ in range(100): # Testing multiple games
player1_roll, player2_roll = dice_game()
a... | [
{
"docstring": "Simulates rolling a six-sided die.\nReturns an integer between 1 and 6 (inclusive).",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a simple dice game where two players roll a dice.\nThe player wi... | [
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 a dice by generating a random number between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_dice_game():\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059395",
"row_id": 59395,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120106']"
} | 0.475147 | Filter_59395 | I | [
"roll_dice",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5fbe3db1c191dcdad31663b4af30c661877249f6 | d4ba7e08e034d09f8dfd9f281024a5628c033612 | |||
v1.0 | instruct | Filter | Filter_59406_I | Write a Python program to simulate the classic game of Rock-Paper-Scissors. The program should allow the user to play against the computer, and the computer's choice should be random. The game should continue until the user decides to quit by entering a specific keyword. The program should also keep track of the score ... | import random
def get_computer_choice():
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(player_choice, computer_choice):
if player_choice == computer_choice:
return 'tie'
elif (player_choice == 'rock' and computer_choice == 'scissors') or \
(player_choice == 'pap... | import pytest
from solution import get_computer_choice, determine_winner, validate_choice
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
assert get_computer_choice() in choices
def test_determine_winner():
assert determine_winner('rock', 'scissors') == 'player'
assert determin... | [
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def determine_winner(player_choice, computer_choice):",
"function_name": "determine_winner",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly selects and returns the computer's choice for Rock-Paper-Scissors.\n \"\"\"\n return random.choice(['rock', 'paper',... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059406",
"row_id": 59406,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120124']"
} | 0.47876 | Filter_59406 | I | [
"get_computer_choice",
"determine_winner",
"validate_choice",
"play_game"
] | 4 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"get_computer_choice"
],
[
"play_game",
"validate_choice"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e0a4c3ed2ad576ecb8d8946d7198e3456c94ae71 | ba67a253f0a19b97ffc48b399f2f0d99dd0f3fb8 | |||
v1.0 | instruct | Filter | Filter_59533_I | Can you help me with a Python code to find the nth prime number? Sure, I need to find the 10,001st prime number specifically. | def is_prime(n):
"""
Determines 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... | from solution import is_prime, find_nth_prime
def test_is_prime():
# Test small prime numbers
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(7) == True
# Test small non-prime numbers
assert is_prime(0) == False
assert is_prime(1) == Fal... | [
{
"docstring": "Determines if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the nth prime number.",
"function_declaration": "def find_nth_prime(n):",
"function_name": "find_nth_prime",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Determines if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00059533",
"row_id": 59533,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120372']"
} | 0.640592 | Filter_59533 | I | [
"is_prime",
"find_nth_prime"
] | 2 | [
[
"find_nth_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb1dc3f18b7605ecab808421aad34efe6db4b42e | a145d55f5efb85c95dc0125d3e82aabd9cdc11bb | |||
v1.0 | instruct | Filter | Filter_59539_I | How can we use Python code to simulate the behavior of a simple pendulum in a physics experiment? | import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
def simple_pendulum(t, y, L, g):
"""
Defines the differential equations for a simple pendulum.
Arguments:
t : float
Time variable
y : list of floats
[theta, omega] where theta is the angular di... | import numpy as np
from solution import simple_pendulum, simulate_pendulum
def test_simple_pendulum():
L = 1.0
g = 9.81
t = 0
y = [np.pi / 4, 0.0] # 45 degrees initial angle, no initial angular velocity
dydt = simple_pendulum(t, y, L, g)
assert isinstance(dydt, list)
assert len(dydt) == 2
... | [
{
"docstring": "Defines the differential equations for a simple pendulum.\n\nArguments:\nt : float\n Time variable\ny : list of floats\n [theta, omega] where theta is the angular displacement and omega is the angular velocity\nL : float\n Length of the pendulum\ng : float\n Acceleration due to gravi... | [
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 simple_pendulum(theta0, L, g=9.81, dt=0.01, T=10):\n \"\"\"\n Simulates the motion of a simple pendulum using the Runge-Kutta m... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059539",
"row_id": 59539,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120391']"
} | 0.361419 | Filter_59539 | I | [
"simple_pendulum",
"simulate_pendulum"
] | 2 | [
[
"simulate_pendulum",
"simple_pendulum"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | c45541bd8f1b659885315c5d35badb5a1584065f | e2fa0064d1e6d7da92a58002fb2a91654ee57757 | |||
v1.0 | instruct | Filter | Filter_59657_I | Can you provide a Python code snippet that encapsulates the logic for handling new orders in an e-commerce platform? This snippet should include checks for stock availability, order processing, and order confirmation. | class Product:
def __init__(self, product_id, name, stock):
self.product_id = product_id
self.name = name
self.stock = stock
class Order:
def __init__(self, order_id, product, quantity):
self.order_id = order_id
self.product = product
self.quantity = quantity
... | from solution import Product, Order, check_stock, process_order, handle_new_order
def test_check_stock():
product = Product(1, 'Laptop', 10)
assert check_stock(product, 5) == True
assert check_stock(product, 10) == True
assert check_stock(product, 15) == False
def test_process_order():
product = P... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class OutOfStockException(Exception):\n pass\n\nclass InsufficientStockException(Exception):\n pass\n\nclass ECommercePlatform:\n def __init__(self):\n self.inventory = {}\n\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059657",
"row_id": 59657,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120634']"
} | 0.356642 | Filter_59657 | I | [
"check_stock",
"process_order",
"handle_new_order"
] | 3 | [
[
"handle_new_order",
"process_order"
],
[
"process_order",
"check_stock"
]
] | 2 | [] | false | [
"Product",
"Order"
] | true | pytest | true | [] | true | 089b6d9ac0827d889ca96082358df58dc857ea43 | f60b30458598f1b97e49e555c0ef31e614cecc32 | |||
v1.0 | instruct | Filter | Filter_59662_I | Can you assist with creating a Python program that identifies and counts the number of prime numbers within a given range? | 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, count_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5) == False
def test_count_prime... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Counts the number of prime numbers within a given range [start, end].",
"function_declaration": "def count_primes_in_range(sta... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059662",
"row_id": 59662,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120641']"
} | 0.828118 | Filter_59662 | I | [
"is_prime",
"count_primes_in_range"
] | 2 | [
[
"count_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09ce2d7d88f244ba702e2223c9ab6ebe4eed2ae7 | a4dfefedfbedd0b6c97c63f1b65d293b49b63507 | |||
v1.0 | instruct | Filter | Filter_59672_I | Write a Python program that reads a newline-separated list of words from a file and checks each word to see if it is a palindrome. The program should output the words that are palindromes along with the line number where they appear. | def is_palindrome(word):
"""
Check if a word is a palindrome.
A palindrome reads the same forwards and backwards.
"""
return word == word[::-1]
def find_palindromes_in_file(file_path):
"""
Reads words from a file and finds palindromes along with their line numbers.
:param file_path: Pa... | import tempfile
import os
from solution import find_palindromes_in_file, is_palindrome
def test_is_palindrome():
assert is_palindrome("madam") == True
assert is_palindrome("racecar") == True
assert is_palindrome("hello") == False
assert is_palindrome("level") == True
assert is_palindrome("") == Tru... | [
{
"docstring": "Check if a word is a palindrome.\nA palindrome reads the same forwards and backwards.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Reads words from a file and finds palindromes along with... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(word):\n \"\"\"\n Returns True if the word is a palindrome, otherwise False.\n \"\"\"\n return word == word[::-1]\n\ndef find_palindromes_in_file(file_path):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059672",
"row_id": 59672,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120657']"
} | 0.704183 | Filter_59672 | I | [
"is_palindrome",
"find_palindromes_in_file"
] | 2 | [
[
"find_palindromes_in_file",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ca58c66a99f58c0432c4acb4ed78e3ec5e1d894 | 7fb09e90a378fa1d3851711f14c114eef97a5ca9 | |||
v1.0 | instruct | Filter | Filter_59699_I | How can I create a Python function that generates a random quote and share it on Twitter? | import tweepy
import random
def get_random_quote():
"""
Returns a random quote from a predefined list.
"""
quotes = [
"The only limit to our realization of tomorrow is our doubts of today. - Franklin D. Roosevelt",
"Do not watch the clock. Do what it does. Keep going. - Sam Levenson",
... | import pytest
from unittest.mock import patch
from solution import get_random_quote, post_to_twitter
def test_get_random_quote():
quotes = [
"The only limit to our realization of tomorrow is our doubts of today. - Franklin D. Roosevelt",
"Do not watch the clock. Do what it does. Keep going. - Sam L... | [
{
"docstring": "Returns a random quote from a predefined list.",
"function_declaration": "def get_random_quote():",
"function_name": "get_random_quote",
"parameter_list": "()"
},
{
"docstring": "Posts a random quote to Twitter using the provided API keys and tokens.",
"function_declarati... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport tweepy\n\ndef get_api():\n \"\"\"\n Initializes and returns the Twitter API client.\n \"\"\"\n # These should be stored safely (e.g., using environment variab... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059699",
"row_id": 59699,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120713']"
} | 0.504173 | Filter_59699 | I | [
"get_random_quote",
"post_to_twitter"
] | 2 | [
[
"post_to_twitter",
"get_random_quote"
]
] | 1 | [] | false | [] | false | pytest | true | [
"tweepy"
] | false | 651a719789d0cc36cded3608bdf07fdcbba6b547 | 55331f93ab73e376d0aa5a657d055fe71ac689cc | |||
v1.0 | instruct | Filter | Filter_59731_I | Can you demonstrate how to create a Python function that utilizes the `multiprocessing` module to parallelize the execution of tasks using a pool? | import multiprocessing
def square_number(n):
"""
Returns the square of a given number.
"""
return n * n
def parallel_square(numbers):
"""
Applies `square_number` function to a list of numbers in parallel.
Parameters:
numbers (list): list of numbers to square
Returns:
... | from solution import square_number, parallel_square
def test_square_number():
assert square_number(2) == 4
assert square_number(-2) == 4
assert square_number(0) == 0
def test_parallel_square():
numbers = [1, 2, 3, 4, 5]
squared_numbers = parallel_square(numbers)
assert squared_numbers == [1, 4... | [
{
"docstring": "Returns the square of a given number.",
"function_declaration": "def square_number(n):",
"function_name": "square_number",
"parameter_list": "(n)"
},
{
"docstring": "Applies `square_number` function to a list of numbers in parallel.\n\nParameters:\nnumbers (list): list of num... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\n\ndef square(n):\n \"\"\"\n Returns the square of a given number n.\n \"\"\"\n return n * n\n\ndef parallel_square(numbers, pool_size):\n \"\"\"\n Use... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059731",
"row_id": 59731,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120787']"
} | 0.631997 | Filter_59731 | I | [
"square_number",
"parallel_square"
] | 2 | [
[
"parallel_square",
"square_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec8b34c534a336e3ff0a485100de2e2d4b797d06 | 1150c2ec3ed2ccc284cd19b1a4d403a42ca0f3e7 | |||
v1.0 | instruct | Filter | Filter_59738_I | Can you show me how to implement a simple game of rock-paper-scissors in Python? | import random
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of a rock-paper-scissors game.
Args:
player_choice (str): The choice of the player ('rock', 'paper', or 'scissors').
computer_choice (str): The choice of the computer ('rock', 'paper', or 'scissors').... | from solution import determine_winner, rock_paper_scissors
def test_determine_winner():
assert determine_winner('rock', 'scissors') == 'player'
assert determine_winner('rock', 'paper') == 'computer'
assert determine_winner('rock', 'rock') == 'tie'
assert determine_winner('paper', 'rock') == 'player'
... | [
{
"docstring": "Determines the winner of a rock-paper-scissors game.\n\nArgs:\nplayer_choice (str): The choice of the player ('rock', 'paper', or 'scissors').\ncomputer_choice (str): The choice of the computer ('rock', 'paper', or 'scissors').\n\nReturns:\nstr: 'player' if the player wins, 'computer' if the com... | [
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 a random choice between 'rock', 'paper', and 'scissors' for the computer.\n \"\"\"\n choices = ['rock', 'paper', 'sci... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059738",
"row_id": 59738,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120797']"
} | 0.426585 | Filter_59738 | I | [
"determine_winner",
"rock_paper_scissors"
] | 2 | [
[
"rock_paper_scissors",
"determine_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9e50b5b53198aac5913260c803ee90a5cd167457 | 05d4c96ccfba85874e608714771af9d83d985823 | |||
v1.0 | instruct | Filter | Filter_59741_I | Create a Python script that utilizes the datetime module to get the current date and time, and then converts this datetime object into a string in the format "YYYY-MM-DD HH:MM:SS". Additionally, the script should write this formatted date and time string to a file named "datetime.txt". | import datetime
def get_current_datetime():
"""
Returns the current date and time as a string in the format "YYYY-MM-DD HH:MM:SS".
"""
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
def write_datetime_to_file():
"""
Writes the current date and time to a file named '... | import os
from solution import get_current_datetime, write_datetime_to_file
def test_get_current_datetime_format():
datetime_str = get_current_datetime()
assert len(datetime_str) == 19
assert datetime_str[4] == '-'
assert datetime_str[7] == '-'
assert datetime_str[10] == ' '
assert datetime_str... | [
{
"docstring": "Returns the current date and time as a string in the format \"YYYY-MM-DD HH:MM:SS\".",
"function_declaration": "def get_current_datetime():",
"function_name": "get_current_datetime",
"parameter_list": "()"
},
{
"docstring": "Writes the current date and time to a file named 'd... | [
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_current_datetime_string():\n \"\"\"\n Returns the current date and time as a string in the format \"YYYY-MM-DD HH:MM:SS\".\n \"\"\"\n now =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059741",
"row_id": 59741,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120800']"
} | 0.743032 | Filter_59741 | I | [
"get_current_datetime",
"write_datetime_to_file"
] | 2 | [
[
"write_datetime_to_file",
"get_current_datetime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed6db81fde738dd267ad98e91f128323c22f1865 | edea42b12ad1f763d16e2cfe68ed6eacbfa71ef4 | |||
v1.0 | instruct | Filter | Filter_59750_I | In a consignment store, there are three categories of items: electronics, books, and clothing. The storekeeper receives a shipment consisting of 100 unique items from each category. Each item in the shipment is uniquely identified by its category and a six-digit number. The storekeeper must ensure that 20% of the items... | import random
def generate_labels(category, count):
"""
Generate unique labels for items in a category.
"""
return [f"{category}{str(i).zfill(6)}" for i in range(1, count+1)]
def allocate_to_sales_floor(categories, total_items, sales_percentage):
"""
Allocate a percentage of items from each ca... | from solution import generate_labels, allocate_to_sales_floor
def test_generate_labels():
labels = generate_labels('E', 3)
assert labels == ['E000001', 'E000002', 'E000003']
def test_allocate_to_sales_floor_sales_percentage():
categories = ['E', 'B', 'C']
total_items = 100
sales_percentage = 0.20
... | [
{
"docstring": "Generate unique labels for items in a category.",
"function_declaration": "def generate_labels(category, count):",
"function_name": "generate_labels",
"parameter_list": "(category, count)"
},
{
"docstring": "Allocate a percentage of items from each category to the sales floor... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_items(category, count=100):\n return [f\"{category}-{str(i).zfill(6)}\" for i in range(count)]\n\ndef select_items_for_sales_floor(items, percentage=0.2):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059750",
"row_id": 59750,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120821']"
} | 0.551447 | Filter_59750 | I | [
"generate_labels",
"allocate_to_sales_floor",
"simulate_store_management"
] | 3 | [
[
"allocate_to_sales_floor",
"generate_labels"
],
[
"simulate_store_management",
"allocate_to_sales_floor"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ece5dba1b24c2eff385919d15105bfefb3f8de72 | 18a5b378a8c8095013c4e019056c3414374fddb9 | |||
v1.0 | instruct | Filter | Filter_59752_I | Can you provide a Python code to simulate the lazy caterer's sequence and visualize it using matplotlib? | import matplotlib.pyplot as plt
def lazy_caterer_sequence(n):
"""
Returns the first n terms of the Lazy Caterer's Sequence.
"""
return [(i * (i + 1)) // 2 + 1 for i in range(n)]
def visualize_lazy_caterer_sequence(n):
"""
Visualizes the Lazy Caterer's Sequence up to the nth term using matplotl... | from solution import lazy_caterer_sequence
def test_lazy_caterer_sequence_base_cases():
assert lazy_caterer_sequence(0) == []
assert lazy_caterer_sequence(1) == [1]
assert lazy_caterer_sequence(2) == [1, 2]
def test_lazy_caterer_sequence_general_case():
assert lazy_caterer_sequence(5) == [1, 2, 4, 7, ... | [
{
"docstring": "Returns the first n terms of the Lazy Caterer's Sequence.",
"function_declaration": "def lazy_caterer_sequence(n):",
"function_name": "lazy_caterer_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Visualizes the Lazy Caterer's Sequence up to the nth term using matplotlib... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\n\ndef lazy_caterer(n):\n \"\"\"\n Returns the maximum number of pieces a circle can be divided into\n with n straight cuts.\n \"\"\"\n return (n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059752",
"row_id": 59752,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120826']"
} | 0.526991 | Filter_59752 | I | [
"lazy_caterer_sequence",
"visualize_lazy_caterer_sequence"
] | 2 | [
[
"visualize_lazy_caterer_sequence",
"lazy_caterer_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | b0d1681ce498442d2649b2738f05515c6021dcd8 | 09a21d82a56650e9209ac81c057e99d22497dbb4 | |||
v1.0 | instruct | Filter | Filter_59761_I | How can I create a simple embarrassingly parallel map-reduce code to sum a large list of numbers using Python's `concurrent.futures` module? | from concurrent.futures import ProcessPoolExecutor, as_completed
def chunkify(lst, n):
"""
Divide a list into n chunks
"""
return [lst[i::n] for i in range(n)]
def partial_sum(numbers):
"""
Calculate the sum of a list of numbers
"""
return sum(numbers)
def parallel_sum(numbers, num_wo... | from solution import parallel_sum
def test_parallel_sum_small_list():
numbers = [1, 2, 3, 4, 5]
assert parallel_sum(numbers) == 15
def test_parallel_sum_large_list():
numbers = list(range(1, 10001)) # Sum should be 50005000 for 1 to 10000
assert parallel_sum(numbers) == 50005000
def test_parallel_su... | [
{
"docstring": "Divide a list into n chunks",
"function_declaration": "def chunkify(lst, n):",
"function_name": "chunkify",
"parameter_list": "(lst, n)"
},
{
"docstring": "Calculate the sum of a list of numbers",
"function_declaration": "def partial_sum(numbers):",
"function_name": "... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\n\ndef map_function(numbers):\n \"\"\"\n This function will act as the map function, summing a chunk of numbers.\n \"\"\"\n return sum(numbers)\n\ndef red... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059761",
"row_id": 59761,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120846']"
} | 0.447619 | Filter_59761 | I | [
"chunkify",
"partial_sum",
"parallel_sum"
] | 3 | [
[
"parallel_sum",
"chunkify"
],
[
"parallel_sum",
"partial_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b2b11cc741e5db44a66feed32ce138842f7581b3 | b2b0d39c70e3bf27b0a60603d1c3f251cf697c48 | |||
v1.0 | instruct | Filter | Filter_59768_I | Write a Python code that prints all prime numbers between 2 and 100. | def is_prime(num):
"""
Returns True if num is a prime number, else returns False.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def primes_between(start, end):
"""
Returns a list of all prime nu... | from solution import is_prime, primes_between
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(11) == True
assert is_prime(25) == False
assert is_prime(97) == True
assert is_prime(1) == False
assert is_prime(0) == Fal... | [
{
"docstring": "Returns True if num is a prime number, else returns False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers between 'start' and 'end' inclusive.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def print_primes():\n \"\"\"\n Prints all prime numbers between 2 and 100.\n \"\"\"\n primes = []\n for num in range(2, 101):\n is_prime = True\n for i in range(2,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059768",
"row_id": 59768,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120857']"
} | 0.667053 | Filter_59768 | I | [
"is_prime",
"primes_between"
] | 2 | [
[
"primes_between",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f94a4e37a8eda6b89dc7456f09c58d2cb4347493 | 10fd9e69eb5875f19d7bf4b1d34083e68248a4c7 | |||
v1.0 | instruct | Filter | Filter_59792_I | I need to create a Python function to calculate the total area covered by a set of rectangles. Each rectangle is defined by its bottom-left corner `(x1, y1)` and top-right corner `(x2, y2)`. How can I implement this in Python? | def rectangle_area(x1, y1, x2, y2):
"""
Calculates the area of a single rectangle given its bottom-left (x1, y1)
and top-right (x2, y2) corners.
"""
return (x2 - x1) * (y2 - y1)
def total_area(rectangles):
"""
Computes the total area covered by a list of rectangles.
Each rectangle is de... | from solution import rectangle_area, total_area
def test_rectangle_area():
assert rectangle_area(0, 0, 2, 2) == 4
assert rectangle_area(1, 1, 4, 5) == 12
assert rectangle_area(-1, -1, 1, 1) == 4
assert rectangle_area(0, 0, 0, 0) == 0
def test_total_area_empty():
assert total_area([]) == 0
def tes... | [
{
"docstring": "Calculates the area of a single rectangle given its bottom-left (x1, y1)\nand top-right (x2, y2) corners.",
"function_declaration": "def rectangle_area(x1, y1, x2, y2):",
"function_name": "rectangle_area",
"parameter_list": "(x1, y1, x2, y2)"
},
{
"docstring": "Computes the t... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_total_area(rectangles):\n \"\"\"\n Calculates the total area covered by a set of rectangles.\n \n Each rectangle is defined by its bottom-left corner (x1, y1) and\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059792",
"row_id": 59792,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120906']"
} | 0.64942 | Filter_59792 | I | [
"rectangle_area",
"total_area"
] | 2 | [
[
"total_area",
"rectangle_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cadd08a0e30b2d7d05df6a28f8f7a63acd05db7f | db03dcc4864759a64476a678ff45d23162ed601e | |||
v1.0 | instruct | Filter | Filter_59800_I | Can you suggest a programming problem that involves creating a simple recommendation system for books using collaborative filtering? | import numpy as np
from scipy.stats import pearsonr
def pearson_correlation(user1_ratings, user2_ratings):
common_books = set(user1_ratings.keys()).intersection(set(user2_ratings.keys()))
if len(common_books) == 0:
return 0 # No common books, no similarity
user1 = np.array([user1_ratings[book... | import pytest
from solution import recommend_books
def test_recommend_books_basic():
ratings = {
'user1': {'book1': 4, 'book2': 5, 'book3': 3},
'user2': {'book1': 5, 'book3': 4, 'book4': 2},
'user3': {'book1': 3, 'book2': 4, 'book4': 5},
}
result = recommend_books('user1', ratings, ... | [
{
"docstring": null,
"function_declaration": "def pearson_correlation(user1_ratings, user2_ratings):",
"function_name": "pearson_correlation",
"parameter_list": "(user1_ratings, user2_ratings)"
},
{
"docstring": null,
"function_declaration": "def recommend_books(user_id, ratings, k):",
... | [
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\nfrom scipy.stats import pearsonr\n\ndef pearson_correlation(user1_ratings, user2_ratings):\n common_books = set(user1_ratings.keys()).intersection(set(user2_ratings.keys... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00059800",
"row_id": 59800,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_120921']"
} | 0.391843 | Filter_59800 | I | [
"pearson_correlation",
"recommend_books"
] | 2 | [
[
"recommend_books",
"pearson_correlation"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 3c862e611a32c76115e1bcb05c7e72adda0223f9 | 9f691f976dd6441d4f61e46630acf8b231545c05 | |||
v1.0 | instruct | Filter | Filter_59882_I | Write a Python function that simulates a simple dice game. The game involves rolling a six-sided die and keeping track of the score. The player wins if their score reaches or exceeds 20. The die rolls are simulated using the `random` module, and the game continues until the player wins or chooses to stop. | import random
def roll_dice():
"""
Simulate rolling a six-sided die.
"""
return random.randint(1, 6)
def dice_game(keep_playing):
"""
Simulate a simple dice game. Roll a six-sided die and keep track of the score.
The player wins if their score reaches or exceeds 20.
:param keep_pl... | from solution import roll_dice, dice_game
def test_roll_dice():
roll = roll_dice()
assert 1 <= roll <= 6
def test_dice_game_win():
def always_play(score):
return True
score, won = dice_game(always_play)
assert won is True
assert score >= 20
def test_dice_game_stop_early():
de... | [
{
"docstring": "Simulate rolling a six-sided die.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulate a simple dice game. Roll a six-sided die and keep track of the score.\nThe player wins if their score reaches or ex... | [
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 six-sided die.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_dice_game():\n \"\"\"\n Simulates a dice gam... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059882",
"row_id": 59882,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121075']"
} | 0.557698 | Filter_59882 | I | [
"roll_dice",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 75cd743fb2e23f27df189a3b0f5fb1538c084cbb | b1d41c2387111e021461b22e916f280d30a156a5 | |||
v1.0 | instruct | Filter | Filter_59889_I | Sure, I'm curious about the basics of how to create a blockchain in Python. Could you guide me through a simple implementation? | import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def calculate_hash(index, previous_hash, timestamp, da... | from solution import Block, calculate_hash, create_genesis_block, create_new_block
def test_block_creation():
data = "some data"
previous_hash = "0"
timestamp = int(time.time())
hash_value = calculate_hash(1, previous_hash, timestamp, data)
block = Block(1, previous_hash, timestamp, data, hash_valu... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport time\n\nclass Block:\n def __init__(self, index, previous_hash, timestamp, data, hash):\n self.index = index\n self.previous_hash = previous_hash\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059889",
"row_id": 59889,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121095']"
} | 0.388202 | Filter_59889 | I | [
"calculate_hash",
"create_genesis_block",
"create_new_block"
] | 3 | [
[
"create_genesis_block",
"calculate_hash"
],
[
"create_new_block",
"calculate_hash"
]
] | 2 | [] | false | [
"Block"
] | true | pytest | true | [] | true | c76ada4e74a72aec9e4b30827a33ae4b8de2dfb1 | 5f0fc8c42946c111537ec366345e1adafc4c3bda | |||
v1.0 | instruct | Filter | Filter_59901_I | Can you help me generate a Python script to simulate a simple game of dice where two players roll two dice each and the player with the higher total wins? If the totals are equal, it results in a tie. How can I implement this? | import random
def roll_dice():
"""
Simulates rolling two six-sided dice and returns their total.
"""
return random.randint(1, 6) + random.randint(1, 6)
def play_game():
"""
Simulates a simple dice game between two players.
- Player 1 and Player 2 each roll two dice.
- The player with t... | from solution import play_game, roll_dice
def test_roll_dice():
for _ in range(100):
roll = roll_dice()
assert 2 <= roll <= 12 # Since the minimum is 2 (1+1) and maximum is 12 (6+6)
def test_play_game():
outcomes = {"Player 1 wins": 0, "Player 2 wins": 0, "Tie": 0}
for _ in range(1000):
... | [
{
"docstring": "Simulates rolling two six-sided dice and returns their total.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a simple dice game between two players.\n- Player 1 and Player 2 each roll two dice.\n... | [
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 Simulates rolling two six-sided dice and returns their total.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059901",
"row_id": 59901,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121117']"
} | 0.491808 | Filter_59901 | I | [
"roll_dice",
"play_game"
] | 2 | [
[
"play_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 37faf6409d36a152f126dcbd0433a5a173ff7b47 | d969793baa21ffb3314ef8b0c5faf6940ceea640 | |||
v1.0 | instruct | Filter | Filter_59940_I | Can you provide a Python function to solve the 8-puzzle problem using the A* algorithm with the Manhattan distance heuristic? | import heapq
def manhattan_distance(state, goal):
"""
Calculate the Manhattan distance of a puzzle state from the goal state.
"""
distance = 0
for i in range(1, 9):
ix, iy = divmod(state.index(i), 3)
gx, gy = divmod(goal.index(i), 3)
distance += abs(ix - gx) + abs(iy - gy)
... | from solution import a_star
def test_a_star_easy():
start = (1, 2, 3, 4, 5, 6, 0, 7, 8)
goal = (1, 2, 3, 4, 5, 6, 7, 8, 0)
result = a_star(start, goal)
assert result[-1] == goal, f"Failed: {result}"
def test_a_star_medium():
start = (1, 2, 3, 4, 0, 6, 7, 5, 8)
goal = (1, 2, 3, 4, 5, 6, 7, 8, 0... | [
{
"docstring": "Calculate the Manhattan distance of a puzzle state from the goal state.",
"function_declaration": "def manhattan_distance(state, goal):",
"function_name": "manhattan_distance",
"parameter_list": "(state, goal)"
},
{
"docstring": "Returns a list of neighbors of a puzzle state.... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\nclass Node:\n def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):\n self.state = state\n self.parent = parent\n self.action = acti... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00059940",
"row_id": 59940,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121184']"
} | 0.454076 | Filter_59940 | I | [
"manhattan_distance",
"get_neighbors",
"a_star"
] | 3 | [
[
"a_star",
"get_neighbors"
],
[
"a_star",
"manhattan_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9530d860addb70947855995d0703f1c5a5b9abf5 | 7d05e5a0bf9d5cf7e06080f44d57d1f0e95d0b8e | |||
v1.0 | instruct | Filter | Filter_59990_I | How does the given Python code simulate a stack and its operations using functions? The code includes functions for initializing a stack, pushing elements, popping elements, and checking if the stack is empty. | def initialize_stack():
"""
Initializes and returns an empty stack.
"""
return []
def push(stack, element):
"""
Pushes an element onto the stack.
"""
stack.append(element)
def pop(stack):
"""
Pops and returns the top element from the stack. Returns None if the stack is empty.
... | from solution import initialize_stack, push, pop, is_empty
def test_initialize_stack():
stack = initialize_stack()
assert stack == []
def test_push():
stack = initialize_stack()
push(stack, 1)
assert stack == [1]
push(stack, 2)
assert stack == [1, 2]
def test_pop():
stack = initialize... | [
{
"docstring": "Initializes and returns an empty stack.",
"function_declaration": "def initialize_stack():",
"function_name": "initialize_stack",
"parameter_list": "()"
},
{
"docstring": "Pushes an element onto the stack.",
"function_declaration": "def push(stack, element):",
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Stack:\n def __init__(self):\n \"\"\"\n Initializes an empty stack.\n \"\"\"\n self.stack = []\n\n def push(self, item):\n \"\"\"\n Pushes... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00059990",
"row_id": 59990,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121297']"
} | 0.451319 | Filter_59990 | I | [
"initialize_stack",
"push",
"pop",
"is_empty"
] | 4 | [
[
"pop",
"is_empty"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9b9ac94696a6bce4ec859ff06f8f982742bcd09d | cd15bbc0a139a412dee180c2ed46975a2afafcc2 | |||
v1.0 | instruct | Filter | Filter_60000_I | Can you provide a simple example of how to simulate a blockchain network using Python? Simulating a blockchain can help understand how blocks are chained together and how transactions are verified and added to the chain. | import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def calculate_hash(index, previous_hash, timestamp, da... | from solution import Block, calculate_hash, create_genesis_block, create_new_block
def test_calculate_hash():
assert calculate_hash(0, "0", 123456, "Genesis Block") == hashlib.sha256("00123456Genesis Block".encode('utf-8')).hexdigest()
def test_create_genesis_block():
genesis_block = create_genesis_block()
... | [] | [
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": "00060000",
"row_id": 60000,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121321']"
} | 0.410721 | Filter_60000 | I | [
"calculate_hash",
"create_genesis_block",
"create_new_block"
] | 3 | [
[
"create_genesis_block",
"calculate_hash"
],
[
"create_new_block",
"calculate_hash"
]
] | 2 | [] | false | [
"Block"
] | true | pytest | true | [] | true | 2f7c865926a0401b5dfbd057f7bff0e530303df6 | 75dce588c4a75fb628542c686f382dba4a0cd93e | |||
v1.0 | instruct | Filter | Filter_60002_I | You are tasked with creating a Python script that reads from a file, parses the data to find all occurrences of a specific pattern (e.g., email addresses), and then writes the results to another file. Your script should be able to handle exceptions gracefully, such as file not found errors or read/write errors. Additio... | import re
def read_file(file_path):
"""
Reads the content of a file.
"""
try:
with open(file_path, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"File not found: {file_path}")
return None
except IOError as e:
print(f"Error reading ... | from solution import read_file, write_file, find_emails, validate_email, process_files
def test_read_file():
assert read_file("non_existent_file.txt") is None
def test_write_file():
test_data = "Test write data"
output_path = "test_output.txt"
write_file(output_path, test_data)
assert read_file(ou... | [
{
"docstring": "Reads the content of a file.",
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes data to a file.",
"function_declaration": "def write_file(file_path, data):",
"function_name": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef read_file(file_path):\n \"\"\"\n Reads content from the specified file path.\n Returns the content of the file as a string.\n \"\"\"\n try:\n with open(f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060002",
"row_id": 60002,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121323']"
} | 0.547416 | Filter_60002 | I | [
"read_file",
"write_file",
"find_emails",
"validate_email",
"process_files"
] | 5 | [
[
"process_files",
"find_emails"
],
[
"process_files",
"read_file"
],
[
"process_files",
"validate_email"
],
[
"process_files",
"write_file"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | e93c1b78cebf503ed25c1550f3ca059302227775 | 034e1f91a96dcd2894ba69be5035624c3c9ef24c | |||
v1.0 | instruct | Filter | Filter_60016_I | Can you provide a Python implementation of the Merge Sort algorithm? | def merge_sort(arr):
"""
Sorts an array in ascending order using the merge sort algorithm.
:param arr: List of elements to be sorted
:return: Sorted list
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[m... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element_list():
assert merge_sort([1]) == [1]
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():
a... | [
{
"docstring": "Sorts an array in ascending order using the merge sort algorithm.\n\n:param arr: List of elements to be sorted\n:return: Sorted list",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array in ascending order using the Merge Sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n\n def merge(left, right):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060016",
"row_id": 60016,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121348']"
} | 0.550876 | Filter_60016 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0e3d299d7fcc6e6f85800921612196a1493d344 | a087e24deb1e6b5a6f7a07caed58614e1ea126fe | |||
v1.0 | instruct | Filter | Filter_60048_I | Write a Python code to implement a simple Caesar Cipher for both encryption and decryption. The Caesar Cipher shifts each letter in the plaintext by a fixed number of places down the alphabet. For example, with a shift of 3, 'A' becomes 'D', 'B' becomes 'E', and so on. The cipher should maintain the case of the letters... | def caesar_cipher_encrypt(text, shift):
"""
Encrypts a given text using Caesar Cipher with the given shift.
"""
result = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
ascii_offset = 65 if char.isupper() else 97
encrypted_char = chr... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt_simple():
assert caesar_cipher_encrypt('abc', 3) == 'def'
assert caesar_cipher_encrypt('ABC', 3) == 'DEF'
def test_caesar_cipher_encrypt_with_wrap():
assert caesar_cipher_encrypt('xyz', 3) == 'abc'
assert ... | [
{
"docstring": "Encrypts a given text using Caesar Cipher with the given shift.",
"function_declaration": "def caesar_cipher_encrypt(text, shift):",
"function_name": "caesar_cipher_encrypt",
"parameter_list": "(text, shift)"
},
{
"docstring": "Decrypts a given text that was encrypted using C... | [
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(plaintext, shift):\n \"\"\"\n Encrypts plaintext using Caesar Cipher with given shift.\n \"\"\"\n encrypted_text = ''\n \n for char in plaintext:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060048",
"row_id": 60048,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121398']"
} | 0.680795 | Filter_60048 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1aa8efdb35ed2aa6cc722bb0a127ba487276a792 | 631f15dd284abf721c476516aa0fc0faae8ab6b8 | |||
v1.0 | instruct | Filter | Filter_60070_I | Can you explain how functions with `*args` and `**kwargs` work in Python? | def example_function(*args, **kwargs):
"""
Demonstrates the use of *args and **kwargs in a Python function.
*args allows a function to accept any number of positional arguments.
**kwargs allows a function to accept any number of keyword arguments.
Args:
*args: Variable length tuple of ... | from solution import demo_func
def test_no_args_kwargs():
assert demo_func() == ((), {})
def test_only_positional_args():
assert demo_func(1, 2, 3) == ((1, 2, 3), {})
def test_only_keyword_args():
assert demo_func(a=1, b=2, c=3) == ((), {'a': 1, 'b': 2, 'c': 3})
def test_both_args_kwargs():
assert d... | [
{
"docstring": "Demonstrates the use of *args and **kwargs in a Python function.\n\n*args allows a function to accept any number of positional arguments.\n**kwargs allows a function to accept any number of keyword arguments.\n\nArgs:\n*args: Variable length tuple of non-keyword arguments.\n**kwargs: Variable le... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_args_kwargs(*args, **kwargs):\n \"\"\"\n Example function that processes positional and keyword arguments.\n \"\"\"\n results = {\n 'args': [arg for arg in args]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060070",
"row_id": 60070,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121435']"
} | 0.492356 | Filter_60070 | I | [
"example_function",
"demo_func"
] | 2 | [
[
"demo_func",
"example_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c3fcb060a3019090e06aeab9b2aa1f6e16ab26c | 562e41436f66f0333659822aefe7edfc3ad5a98e | |||
v1.0 | instruct | Filter | Filter_60091_I | I want to create a Python code to simulate a simple text-based game where the user has to guess the word. The game should have a list of possible words, and the user gets a certain number of attempts to guess the word. If the user guesses the word correctly, they win; otherwise, they lose after exhausting all their att... | import random
def choose_word(word_list):
"""
Chooses a random word from the provided word list.
"""
return random.choice(word_list)
def guess_word_game(word_list, attempts):
"""
Simulates the word guessing game where the user has to guess the word.
Parameters:
- word_list: List o... | from solution import choose_word, guess_word_game
def test_choose_word():
word_list = ["apple", "banana", "cherry"]
word = choose_word(word_list)
assert word in word_list
def test_guess_word_game_win(monkeypatch):
word_list = ["apple"]
attempts = 3
inputs = iter(["apple"])
monkeypatch.seta... | [
{
"docstring": "Chooses a random word from the provided word list.",
"function_declaration": "def choose_word(word_list):",
"function_name": "choose_word",
"parameter_list": "(word_list)"
},
{
"docstring": "Simulates the word guessing game where the user has to guess the word.\n\nParameters:... | [
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 choose_word(words):\n \"\"\"\n Randomly choose a word from the list of words.\n \"\"\"\n return random.choice(words)\n\ndef display_progress(word, guesses):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060091",
"row_id": 60091,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121484']"
} | 0.560528 | Filter_60091 | I | [
"choose_word",
"guess_word_game"
] | 2 | [
[
"guess_word_game",
"choose_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 135cfa583cbde4f32e496986157737e6682e5efb | 104210917e1c2d6a21a054168a8a594b106c75aa | |||
v1.0 | instruct | Filter | Filter_60105_I | Hello Qwen, could you provide an example of how I might structure a Python function to take advantage of parallel processing using the multiprocessing library? | import multiprocessing
def square_number(n):
"""
Function to square a number.
"""
return n * n
def parallel_square(numbers):
"""
Function to calculate squares of numbers in parallel.
"""
with multiprocessing.Pool() as pool:
results = pool.map(square_number, numbers)
return ... | from solution import square_number, parallel_square
def test_square_number():
assert square_number(2) == 4
assert square_number(-3) == 9
assert square_number(0) == 0
def test_parallel_square():
numbers = [1, 2, 3, 4, 5]
expected = [1, 4, 9, 16, 25]
assert parallel_square(numbers) == expected | [
{
"docstring": "Function to square a number.",
"function_declaration": "def square_number(n):",
"function_name": "square_number",
"parameter_list": "(n)"
},
{
"docstring": "Function to calculate squares of numbers in parallel.",
"function_declaration": "def parallel_square(numbers):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\n\ndef square(x):\n \"\"\"\n Function that returns the square of a number.\n \"\"\"\n return x * x\n\ndef parallel_process(items, func, num_processes=None):\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060105",
"row_id": 60105,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121521']"
} | 0.611517 | Filter_60105 | I | [
"square_number",
"parallel_square"
] | 2 | [
[
"parallel_square",
"square_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50329ce2371d81eaed6c98663076ac7c69ec0e3e | 4a6ab2e95cbf68d956c63f74469a4c5c10f924bc | |||
v1.0 | instruct | Filter | Filter_60168_I | Can you create a program in Python that takes a list of integers and returns the prime numbers in the list? | def is_prime(n):
"""
Helper function to determine 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 get_prime_numbers(lst):
"""
Returns a list of prime numbers from the input list... | from solution import get_prime_numbers
def test_get_prime_numbers_all_primes():
assert get_prime_numbers([2, 3, 5, 7, 11, 13]) == [2, 3, 5, 7, 11, 13]
def test_get_prime_numbers_no_primes():
assert get_prime_numbers([4, 6, 8, 10, 12]) == []
def test_get_prime_numbers_mixed():
assert get_prime_numbers([2,... | [
{
"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 a list of prime numbers from the input list.",
"function_declaration": "def get_prime_numbers(l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060168",
"row_id": 60168,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121649']"
} | 0.650681 | Filter_60168 | I | [
"is_prime",
"get_prime_numbers"
] | 2 | [
[
"get_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4eb7c30ba72a910c7582a2dc7742204a5f92ebce | 02c453b6ab138478cf49cd32886d488515b9e19d | |||
v1.0 | instruct | Filter | Filter_60195_I | Can you provide a Python code snippet that displays the first 10 prime numbers? | def is_prime(n):
"""
Checks if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return... | from solution import is_prime, first_n_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(11) == True
def test_first_n_primes():
assert first_n_primes(1) == [2... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of the first n prime numbers.",
"function_declaration": "def first_n_primes(n):",
"function_name": "firs... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060195",
"row_id": 60195,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121692']"
} | 0.60587 | Filter_60195 | I | [
"is_prime",
"first_n_primes"
] | 2 | [
[
"first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05ddb40301420e8b6bb11966458ab1a89f9c7581 | 3530dbb8967bbfbfed9260bc6781ff928bf2abb3 | |||
v1.0 | instruct | Filter | Filter_60199_I | Can you provide a Python code for sorting a list of numbers using the merge sort algorithm? | def merge_sort(arr):
"""
Sorts an array of numbers in ascending order using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, r... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5,... | [
{
"docstring": "Sorts an array of numbers in ascending order using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array.",
"function_declarati... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(lst):\n \"\"\"\n Sorts a list of numbers using the merge sort algorithm.\n \"\"\"\n if len(lst) <= 1:\n return lst\n \n mid = len(lst) // 2\n lef... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060199",
"row_id": 60199,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121698']"
} | 0.636747 | Filter_60199 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 834eeee9bf95f78af9ca91e74f14986096bd9a02 | 8bd7c6c73e514676058084287206a2e014909e0c | |||
v1.0 | instruct | Filter | Filter_60210_I | In Python, how can I ensure that a function runs only after another function has completed its execution? | def first_function():
"""
Sample first function
"""
print("First function is running.")
def second_function():
"""
Sample second function that should run only after first_function
"""
print("Second function is running.")
def execute_functions_sequentially():
"""
Execute fir... | from solution import execute_functions_sequentially, first_function, second_function
def test_execute_functions_sequentially(capsys):
execute_functions_sequentially()
captured = capsys.readouterr()
assert "First function is running." in captured.out
assert "Second function is running." in captured.out
... | [
{
"docstring": "Sample first function",
"function_declaration": "def first_function():",
"function_name": "first_function",
"parameter_list": "()"
},
{
"docstring": "Sample second function that should run only after first_function",
"function_declaration": "def second_function():",
"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def first_function():\n \"\"\"\n Sample first function\n \"\"\"\n print(\"First function is running.\")\n\ndef second_function():\n \"\"\"\n Sample second function that shoul... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00060210",
"row_id": 60210,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121721']"
} | 0.512533 | Filter_60210 | I | [
"first_function",
"second_function",
"execute_functions_sequentially"
] | 3 | [
[
"execute_functions_sequentially",
"first_function"
],
[
"execute_functions_sequentially",
"second_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d5b96af0e0ca67f61e9d3e052a225ec94ec0fd20 | ae92f1560ba4afb79712359af2a90882589b8c8f | |||
v1.0 | instruct | Filter | Filter_60248_I | Create a comprehensive guide on how to create a chatbot using Python and Flask for a small business. For a small business, the goal should be to use the chatbot to assist customers with basic inquiries, such as contact information, business hours, and product details. Here’s a step-by-step guide on how to build a simpl... | # Solution: Guide to create a chatbot using Python and Flask for Small Business
# Step 1: Setting Up the Environment
# First, ensure you have Python installed on your system.
# Install Flask using pip if you haven't already:
# pip install Flask
# Step 2: Create a Flask Application
from flask import Flask, request, js... | import pytest
from solution import app, get_response
# Test Chatbot Logic Function
def test_get_response_contact():
assert get_response("What is your contact information?") == "For inquiries, please call (123) 456-7890 or email us at info@business.com."
def test_get_response_hours():
assert get_response("What... | [
{
"docstring": null,
"function_declaration": "def get_response(message):",
"function_name": "get_response",
"parameter_list": "(message)"
},
{
"docstring": null,
"function_declaration": "def chatbot():",
"function_name": "chatbot",
"parameter_list": "()"
}
] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Solution: Guide to create a chatbot using Python and Flask for Small Business\n\n# Step 1: Setting Up the Environment\n# First, ensure you have Python installed on your system.\n# Install Fl... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00060248",
"row_id": 60248,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121805']"
} | 0.450093 | Filter_60248 | I | [
"get_response",
"chatbot"
] | 2 | [
[
"chatbot",
"get_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 502dc7d078a46272e865d122949dcafb6d14582e | bb7f78ac68a79120a458ada08171716b16608714 | |||
v1.0 | instruct | Filter | Filter_60275_I | Hello, Qwen! How can I create a Python function that prints the name of a given object? If the object is a string, it should just print the object; if the object is a list, it should print the name of the list variable; if the object is a integer or float, it should print something like "Number: {value}"; and if the ob... | import inspect
def get_variable_name(var, locals_dict):
"""
Helper function to get the name of the variable.
"""
for name, value in locals_dict.items():
if value is var:
return name
return None
def print_object_name(obj):
"""
Prints the name of the given object.
"""... | import pytest
from solution import print_object_name
def test_print_object_name_string(capfd):
print_object_name("Hello")
out, err = capfd.readouterr()
assert out.strip() == "Hello"
def test_print_object_name_list(capfd):
test_list = [1, 2, 3]
print_object_name(test_list)
out, err = capfd.rea... | [
{
"docstring": "Helper function to get the name of the variable.",
"function_declaration": "def get_variable_name(var, locals_dict):",
"function_name": "get_variable_name",
"parameter_list": "(var, locals_dict)"
},
{
"docstring": "Prints the name of the given object.",
"function_declarat... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import inspect\n\ndef print_object_name(obj, var_name):\n \"\"\"\n Prints the name of a given object based on its type.\n \n :param obj: The object whose name will be printed.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060275",
"row_id": 60275,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121862']"
} | 0.420552 | Filter_60275 | I | [
"get_variable_name",
"print_object_name"
] | 2 | [
[
"print_object_name",
"get_variable_name"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04e4ec77074a56a825061cd15c2acf2561b1f51f | 115de89956c0fc10241d2849ea049dfb0335c6ec | |||
v1.0 | instruct | Filter | Filter_60298_I | Write a Python function that takes a list of strings as input and returns a new list containing only the strings that are palindromes. A palindrome is a string that reads the same forward and backward. Consider both uppercase and lowercase letters as equal for the purpose of checking palindromes. | def is_palindrome(s):
"""
Helper function to determine if a given string is a palindrome.
"""
s = s.lower()
return s == s[::-1]
def filter_palindromes(strings):
"""
Returns a list containing only the palindrome strings from the input list.
"""
return [s for s in strings if is_palind... | from solution import is_palindrome, filter_palindromes
def test_is_palindrome():
assert is_palindrome("racecar")
assert is_palindrome("RaceCar")
assert not is_palindrome("hello")
assert is_palindrome("Aba")
assert not is_palindrome("Python")
assert is_palindrome("Anna")
def test_filter_palindr... | [
{
"docstring": "Helper function to determine if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Returns a list containing only the palindrome strings from the input list.",
"fu... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Checks if a given string is a palindrome.\n \"\"\"\n s = s.lower()\n return s == s[::-1]\n\ndef filter_palindromes(strings):\n \"\"\"\n Fi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060298",
"row_id": 60298,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121903']"
} | 0.788768 | Filter_60298 | I | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8c9433139484c947ec39643be8274b614d57f22 | 5b0584bd41f578f233471d7b83a5b95418f6280b | |||
v1.0 | instruct | Filter | Filter_60307_I | Write a Python script to automate the process of displaying terminal information such as hostname, IP address, and MAC address. The script should be cross-platform, compatible with both Unix-based systems (like Linux and macOS) and Windows. | import socket
import platform
import uuid
import os
def get_hostname():
"""
Returns the hostname of the machine.
"""
return socket.gethostname()
def get_ip_address():
"""
Returns the IP address of the machine.
"""
hostname = get_hostname()
return socket.gethostbyname(hostname)
def... | from solution import get_hostname, get_ip_address, get_mac_address, get_system_info
def test_get_hostname():
hostname = get_hostname()
assert isinstance(hostname, str)
assert len(hostname) > 0
def test_get_ip_address():
ip_address = get_ip_address()
assert isinstance(ip_address, str)
assert le... | [
{
"docstring": "Returns the hostname of the machine.",
"function_declaration": "def get_hostname():",
"function_name": "get_hostname",
"parameter_list": "()"
},
{
"docstring": "Returns the IP address of the machine.",
"function_declaration": "def get_ip_address():",
"function_name": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport uuid\nimport platform\n\ndef get_terminal_info():\n # Get the hostname\n hostname = socket.gethostname()\n \n # Get the IP address\n ip_address = socket.ge... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060307",
"row_id": 60307,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121925']"
} | 0.37542 | Filter_60307 | I | [
"get_hostname",
"get_ip_address",
"get_mac_address",
"get_system_info"
] | 4 | [
[
"get_ip_address",
"get_hostname"
],
[
"get_system_info",
"get_hostname"
],
[
"get_system_info",
"get_ip_address"
],
[
"get_system_info",
"get_mac_address"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | cfe6bf709e0019629c1e3bbfa4478c006a53024f | 44274c32e807d19e3392cbf5c2591ac3d0841ed6 | |||
v1.0 | instruct | Filter | Filter_60309_I | Can you provide a simple Python script that checks for prime numbers within a given range and prints them? | def is_prime(n):
"""
Determines if n is a prime number.
:param n: Integer to check for primality.
:return: 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
... | 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(13) == True
assert is_prime(20) == False
def test_primes_in_range():
assert primes_in_range(10, 2... | [
{
"docstring": "Determines if n is a prime number.\n\n:param n: Integer to check for primality.\n:return: True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds all prime number... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if the number n is prime, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060309",
"row_id": 60309,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121931']"
} | 0.707268 | Filter_60309 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c230583b63a52460848685817d325dd6a2375595 | ae48e098fff49775f26dba33754745b1eaf2cf8d | |||
v1.0 | instruct | Filter | Filter_60327_I | Can you provide a Python code snippet that demonstrates the use of logical operators (`and`, `or`, `not`) in a practical scenario? | def is_user_authenticated(username, password, database):
"""
Checks if the provided username and password match the records in the database.
Parameters:
username (str): The username provided by the user.
password (str): The password provided by the user.
database (dict): A dictionary where ... | from solution import is_user_authenticated, can_access_resource
def test_is_user_authenticated():
database = {"user1": "pass1", "user2": "pass2"}
assert is_user_authenticated("user1", "pass1", database) == True
assert is_user_authenticated("user1", "wrongpass", database) == False
assert is_user_au... | [
{
"docstring": "Checks if the provided username and password match the records in the database.\n\nParameters:\nusername (str): The username provided by the user.\npassword (str): The password provided by the user.\ndatabase (dict): A dictionary where keys are usernames and values are passwords.\n\nReturns:\nbo... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_access_content(age, has_permission):\n \"\"\"\n Determine if a user can access content based on their age and permission.\n \n Args:\n age (int): The age of the user.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060327",
"row_id": 60327,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121967']"
} | 0.542088 | Filter_60327 | I | [
"is_user_authenticated",
"can_access_resource"
] | 2 | [
[
"can_access_resource",
"is_user_authenticated"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9be319d7fadd03d09fe2e1a024dd894995ff959c | 91257b47590ed947a63719cea07fd08c1f32b552 | |||
v1.0 | instruct | Filter | Filter_60340_I | How can I find the root directory of a Python project when running a script within it? | import os
def find_project_root(starting_path=__file__):
"""
Finds the root directory of a Python project.
Assumes the root directory is the one containing a certain marker file (e.g., '.git' directory).
"""
current_path = os.path.abspath(starting_path)
while True:
if is_project_ro... | import os
import tempfile
import pytest
from solution import find_project_root
@pytest.fixture
def setup_test_directory_structure():
with tempfile.TemporaryDirectory() as tmpdir:
# Simulate a typical project structure
project_root = os.path.join(tmpdir, "project")
os.makedirs(project_root)
... | [
{
"docstring": "Finds the root directory of a Python project.\nAssumes the root directory is the one containing a certain marker file (e.g., '.git' directory).",
"function_declaration": "def find_project_root(starting_path=__file__):",
"function_name": "find_project_root",
"parameter_list": "(starti... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef find_project_root(start_dir=None, marker_files=None):\n \"\"\"\n Finds the root directory of a Python project by looking for project-defining files.\n \n Args:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060340",
"row_id": 60340,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_121993']"
} | 0.453165 | Filter_60340 | I | [
"find_project_root",
"is_project_root"
] | 2 | [
[
"find_project_root",
"is_project_root"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87960aac3be99220f81f1d9e30c24a05373bacdb | 8bc7349a6fcc95e0ea74a9d21aacce5164b2a8ea | |||
v1.0 | instruct | Filter | Filter_60371_I | Write a Python function `prime_fibonacci` that returns the nth prime number found in the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. For this task, the sequence starts with 1 and 1. The function should be effici... | 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 prime_fibonacci(n):
"""
Returns the nth prime number found in the Fibonacci seque... | from solution import prime_fibonacci
def test_prime_fibonacci_first():
assert prime_fibonacci(1) == 2
def test_prime_fibonacci_second():
assert prime_fibonacci(2) == 3
def test_prime_fibonacci_third():
assert prime_fibonacci(3) == 5
def test_prime_fibonacci_fourth():
assert prime_fibonacci(4) == 13
... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the nth prime number found in the Fibonacci sequence.",
"function_declaration": "def prime_fibona... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 o... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060371",
"row_id": 60371,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122059']"
} | 0.855526 | Filter_60371 | I | [
"is_prime",
"prime_fibonacci"
] | 2 | [
[
"prime_fibonacci",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97bced579c7b22faaba7955361be74d3264e49f4 | c48141cd762fcc03a431c79a42052520bdb55760 | |||
v1.0 | instruct | Filter | Filter_60440_I | Can you set a custom reminder for a specific date in a Python application? How can this be done? | import sched
import time
from datetime import datetime
def set_reminder(reminder_time, message):
"""
Sets a reminder for the specified date and time.
Args:
reminder_time (datetime): The date and time when the reminder should trigger.
message (str): The reminder message.
"""
scheduler = sch... | from datetime import datetime, timedelta
import threading
from solution import set_reminder
def test_set_reminder():
reminder_time = datetime.now() + timedelta(seconds=5)
message = "This is your reminder!"
def run_test():
set_reminder(reminder_time, message)
# Run the reminder in a separa... | [
{
"docstring": "Sets a reminder for the specified date and time.\n\nArgs:\nreminder_time (datetime): The date and time when the reminder should trigger.\nmessage (str): The reminder message.",
"function_declaration": "def set_reminder(reminder_time, message):",
"function_name": "set_reminder",
"para... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime, timedelta\nimport threading\n\ndef set_reminder(reminder_time, message):\n \"\"\"\n Sets a reminder for the specified date and time with the given message.... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060440",
"row_id": 60440,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122199']"
} | 0.438372 | Filter_60440 | I | [
"set_reminder",
"print_reminder"
] | 2 | [
[
"set_reminder",
"print_reminder"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d1a2d38ab43c095b7fc0784aa9156ce26a73e7b | 8a0a6bd93d7b20d8024095a7f4e21d62a362d84f | |||
v1.0 | instruct | Filter | Filter_60469_I | Generate a Python script that can analyze a directory of text files and output the frequency of each word across all files. The script should ignore common stop words like "the", "and", "is", etc. It should also handle case insensitivity and punctuation. You can assume the directory path is passed as a command line arg... | import os
import sys
from collections import Counter
import string
# List of common stop words to ignore
STOP_WORDS = set([
"the", "and", "is", "in", "it", "you", "that", "he", "was", "for",
"on", "are", "with", "as", "I", "his", "they", "be", "at", "one",
"have", "this", "from", "or", "had", "by", "not"... | import os
import tempfile
from solution import count_words_in_directory
def create_temp_file(directory, filename, content):
file_path = os.path.join(directory, filename)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
return file_path
def test_count_words_in_directory():
... | [
{
"docstring": "Clean a word by removing punctuation and converting it to lower case.",
"function_declaration": "def clean_word(word):",
"function_name": "clean_word",
"parameter_list": "(word)"
},
{
"docstring": "Analyze a directory of text files and output the frequency of each word across... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport sys\nimport string\nfrom collections import defaultdict, Counter\n\ndef clean_word(word):\n \"\"\"\n Cleans punctuation from the word and converts it to lower case.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060469",
"row_id": 60469,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122251']"
} | 0.729653 | Filter_60469 | I | [
"clean_word",
"count_words_in_directory"
] | 2 | [
[
"count_words_in_directory",
"clean_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e7feeaa0291a83309062d8245f5a213e2d0eebda | 1f33561b562e7f0ea0b4791106a2e7def8d8d353 | |||
v1.0 | instruct | Filter | Filter_60493_I | I need help to understand how to implement the k-means clustering algorithm from scratch in Python. Can you provide a detailed guide with code? | import numpy as np
def initialize_centroids(X, k):
"""
Randomly initialize k centroids from the dataset X.
"""
indices = np.random.choice(X.shape[0], k, replace=False)
return X[indices]
def compute_distances(X, centroids):
"""
Compute the distance between each point in the dataset X and ea... | from solution import initialize_centroids, compute_distances, assign_clusters, update_centroids, kmeans
import numpy as np
def test_initialize_centroids():
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
centroids = initialize_centroids(X, 2)
assert centroids.shape == (2, 2)
def test_compute_distances():
... | [
{
"docstring": "Randomly initialize k centroids from the dataset X.",
"function_declaration": "def initialize_centroids(X, k):",
"function_name": "initialize_centroids",
"parameter_list": "(X, k)"
},
{
"docstring": "Compute the distance between each point in the dataset X and each centroid."... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_centroids(X, k):\n \"\"\"\n Randomly initialize the centroids by selecting k unique points from the dataset X.\n \"\"\"\n indices = np.random.c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060493",
"row_id": 60493,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122288']"
} | 0.594228 | Filter_60493 | I | [
"initialize_centroids",
"compute_distances",
"assign_clusters",
"update_centroids",
"kmeans"
] | 5 | [
[
"kmeans",
"assign_clusters"
],
[
"kmeans",
"compute_distances"
],
[
"kmeans",
"initialize_centroids"
],
[
"kmeans",
"update_centroids"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | d50c3b0a000b099ce4efdd503f03ee44f843bcd9 | 15ac493a14fbe69342ae90afe0efcb7984709840 | |||
v1.0 | instruct | Filter | Filter_60499_I | I need help creating a Python script that generates a list of prime numbers within a given range. Can you provide a sample script? | def is_prime(number):
"""
Checks if a number is prime.
"""
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
i = 5
while (i * i) <= number:
if number % i == 0 or number % (i + 2) == 0:
... | from solution import is_prime, generate_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(0) == Fa... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(number):",
"function_name": "is_prime",
"parameter_list": "(number)"
},
{
"docstring": "Generates a list of prime numbers in the given range [start, end).",
"function_declaration": "def generate_primes(s... | [
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, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n elif n <= 3:\n return True\n elif n % 2... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060499",
"row_id": 60499,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122305']"
} | 0.613111 | Filter_60499 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4b06dbd8c2f68fe3126af7dffef03460608200e4 | d97f4a724c5ec2fde5109450b5890ff09ea9b34b | |||
v1.0 | instruct | Filter | Filter_60516_I | If I have a function `foo` that takes inputs `a`, `b`, and `c` and returns their sum, and another function `bar` that takes one input `x` and returns the result of `foo` with `x`, `x+1`, and `x+2`, how can I implement these functions in Python? | def foo(a, b, c):
"""
Returns the sum of a, b, and c.
"""
return a + b + c
def bar(x):
"""
Returns the result of foo(x, x+1, x+2).
"""
return foo(x, x + 1, x + 2) | from solution import foo, bar
def test_foo_all_positive():
assert foo(1, 2, 3) == 6
def test_foo_mixed_numbers():
assert foo(-1, 0, 1) == 0
def test_foo_all_negative():
assert foo(-1, -2, -3) == -6
def test_foo_with_zero():
assert foo(0, 0, 0) == 0
def test_bar_positive_input():
assert bar(1) =... | [
{
"docstring": "Returns the sum of a, b, and c.",
"function_declaration": "def foo(a, b, c):",
"function_name": "foo",
"parameter_list": "(a, b, c)"
},
{
"docstring": "Returns the result of foo(x, x+1, x+2).",
"function_declaration": "def bar(x):",
"function_name": "bar",
"parame... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def foo(a, b, c):\n \"\"\"\n Returns the sum of a, b, and c.\n \"\"\"\n return a + b + c\n\ndef bar(x):\n \"\"\"\n Calls the foo function with x, x+1, and x+2.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060516",
"row_id": 60516,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122340']"
} | 0.564304 | Filter_60516 | I | [
"foo",
"bar"
] | 2 | [
[
"bar",
"foo"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 062c77f77b35598865ad552dd378ce89adfbf5ee | 3475bdcfd7a8567dd5e5ec9a7b031af1e841681c | |||
v1.0 | instruct | Filter | Filter_60622_I | How can I write a Python script to check if an FTP server is up and running using the `ftplib` library? How can I modify this script to log the status of each check to a file with timestamps? | import ftplib
import logging
from datetime import datetime
def check_ftp_server(host, port=21, timeout=5):
"""
Checks if the FTP server is up and running.
Parameters:
- host: The FTP server hostname or IP address.
- port: The port number to connect to the FTP server (default: 21).
- timeou... | import pytest
from solution import check_ftp_server, log_ftp_check_status
import os
def test_check_ftp_server_up(monkeypatch):
class MockFTP:
def connect(self, host, port, timeout):
pass
def login(self):
pass
def __enter__(self):
return self
def _... | [
{
"docstring": "Checks if the FTP server is up and running.\n\nParameters:\n- host: The FTP server hostname or IP address.\n- port: The port number to connect to the FTP server (default: 21).\n- timeout: The timeout duration for the connection attempt (default: 5 seconds).\n\nReturns:\n- True if the connection ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from ftplib import FTP\nimport logging\nfrom datetime import datetime\n\ndef check_ftp_server(host):\n \"\"\"\n Checks if the FTP server is up and running by trying to connect and login.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060622",
"row_id": 60622,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122572']"
} | 0.626103 | Filter_60622 | I | [
"check_ftp_server",
"log_ftp_check_status"
] | 2 | [
[
"log_ftp_check_status",
"check_ftp_server"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad49cb88a4c2b036e85a45bca02dbfe9e5863e9d | 1d6a61232d5ec83bfc7b2f99b7b4887749c0d131 | |||
v1.0 | instruct | Filter | Filter_60671_I | How can I create a Python script that can identify the sentiment of user reviews on a product website using a machine learning model? | import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.pipeline import make_pipeline
from skl... | import pytest
from solution import preprocess_reviews, train_sentiment_model, predict_sentiment
def test_preprocess_reviews():
reviews = pd.Series(["This is GREAT!!!", "Awful product..."])
cleaned_reviews = preprocess_reviews(reviews)
assert cleaned_reviews[0] == "this is great"
assert cleaned_reviews[... | [
{
"docstring": null,
"function_declaration": "def preprocess_reviews(reviews):",
"function_name": "preprocess_reviews",
"parameter_list": "(reviews)"
},
{
"docstring": null,
"function_declaration": "def train_sentiment_model(reviews, labels):",
"function_name": "train_sentiment_model... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfro... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00060671",
"row_id": 60671,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122671']"
} | 0.516035 | Filter_60671 | I | [
"preprocess_reviews",
"train_sentiment_model",
"predict_sentiment"
] | 3 | [
[
"predict_sentiment",
"preprocess_reviews"
],
[
"train_sentiment_model",
"preprocess_reviews"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 05512c2f824d29ebaf234bca4483c783192c55de | 935e529e1b42b7513b0f3faef8752bfdd65469b0 | |||
v1.0 | instruct | Filter | Filter_60758_I | How can I create a web application using Flask that allows users to upload images and apply image filters to them using OpenCV? | from flask import Flask, request, render_template, redirect, url_for
import cv2
import numpy as np
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif... | def test_allowed_file():
assert allowed_file('test.jpg') == True
assert allowed_file('test.jpeg') == True
assert allowed_file('test.png') == True
assert allowed_file('test.gif') == True
assert allowed_file('test.txt') == False
def test_apply_filter():
dummy_image = np.zeros((100, 100, 3), dtype... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def apply_filter(image_path, filter_type):",
"function_name": "apply_filter",
"parameter_li... | [
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, render_template, request, send_file\nimport cv2\nimport numpy as np\nimport os\nfrom PIL import Image\n\napp = Flask(__name__)\n\nUPLOAD_FOLDER = 'uploads'\nos.makedir... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060758",
"row_id": 60758,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122835']"
} | 0.424226 | Filter_60758 | I | [
"allowed_file",
"apply_filter",
"upload_file",
"display_image"
] | 4 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"apply_filter"
]
] | 2 | [] | false | [] | false | pytest | false | [
"cv2",
"flask",
"numpy"
] | false | 8b59959c72d9d7b323f9b5a04f23012c6ae4830e | 37403ca31c347aec4804527c51b6d96949731402 | |||
v1.0 | instruct | Filter | Filter_60761_I | Can you provide a Python function that implements the K-Nearest Neighbors (KNN) algorithm from scratch using numpy? | import numpy as np
from collections import Counter
def euclidean_distance(point1, point2):
"""
Computes the Euclidean distance between two points.
"""
return np.sqrt(np.sum((np.array(point1) - np.array(point2)) ** 2))
def knn_predict(X_train, y_train, X_test, k=3):
"""
Predict the class labels... | import numpy as np
from solution import euclidean_distance, knn_predict
def test_euclidean_distance():
assert euclidean_distance([0, 0], [3, 4]) == 5.0
assert euclidean_distance([1, 2], [4, 6]) == 5.0
assert euclidean_distance([1, 1], [1, 1]) == 0.0
def test_knn_predict():
X_train = np.array([[1, 2], ... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n return np.sqrt(np.sum((point1 - point2)**2))\n\ndef knn_predict(X_train, y_train, X_test, k)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060761",
"row_id": 60761,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122845']"
} | 0.551431 | Filter_60761 | I | [
"euclidean_distance",
"knn_predict"
] | 2 | [
[
"knn_predict",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 87d1044d2c55f7284593250729c11ba658579949 | 2ff461da6802bd685a58498e783207ce517c8405 | |||
v1.0 | instruct | Filter | Filter_60771_I | Write a Python script that uses the function `f(x, y) = x + y` and applies it to a list of tuples. Each tuple contains two numbers. The script should use the `map` function to apply this function to every pair of numbers in the list of tuples. | def add(x, y):
"""
Returns the sum of x and y.
"""
return x + y
def apply_add_function_to_list_of_tuples(pairs):
"""
Takes a list of tuples (pairs) and applies the add function using map.
Args:
pairs (list of tuple): A list where each element is a tuple containing two numbers.
... | from solution import add, apply_add_function_to_list_of_tuples
def test_add():
assert add(2, 3) == 5
assert add(0, 5) == 5
assert add(-1, -1) == -2
assert add(-1, 3) == 2
def test_apply_add_function_to_list_of_tuples():
assert apply_add_function_to_list_of_tuples([(1, 2), (3, 4), (0, 5)]) == [3, 7... | [
{
"docstring": "Returns the sum of x and y.",
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": "Takes a list of tuples (pairs) and applies the add function using map.\n\nArgs:\npairs (list of tuple): A list where each element is a... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_tuples(tuples_list):\n \"\"\"\n Applies the function f(x, y) = x + y to a list of tuples using map.\n Each tuple contains two numbers.\n \n Args:\n tuples_list (list)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060771",
"row_id": 60771,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122865']"
} | 0.710757 | Filter_60771 | I | [
"add",
"apply_add_function_to_list_of_tuples"
] | 2 | [
[
"apply_add_function_to_list_of_tuples",
"add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1aa5428cbab4d813886e1728cbea429deca460b3 | 63d1aa5ffd637d450e19f76f60d4fc2b7235a602 | |||
v1.0 | instruct | Filter | Filter_60800_I | Generate a Python program that reads data from a CSV file, processes it, and writes the processed data to a new CSV file. The program should handle potential errors such as missing files or invalid data types during reading and writing. Error messages should be user-friendly and informative. | import csv
def read_csv(input_file):
"""
Reads data from a CSV file and returns it as a list of dictionaries.
"""
data = []
try:
with open(input_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
data.append(row)
except FileNotFo... | from solution import read_csv, process_data, write_csv, process_csv
import os
def test_read_csv(tmp_path):
infile = tmp_path / "test_input.csv"
with open(infile, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows([{"... | [
{
"docstring": "Reads data from a CSV file and returns it as a list of dictionaries.",
"function_declaration": "def read_csv(input_file):",
"function_name": "read_csv",
"parameter_list": "(input_file)"
},
{
"docstring": "Processes the data. For demonstration purposes, let's just capitalize a... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef process_csv(input_file, output_file):\n \"\"\"\n Reads data from the input CSV file, processes it, and writes the processed data to the output CSV file.\n \n Para... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060800",
"row_id": 60800,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122911']"
} | 0.657027 | Filter_60800 | I | [
"read_csv",
"process_data",
"write_csv",
"process_csv"
] | 4 | [
[
"process_csv",
"process_data"
],
[
"process_csv",
"read_csv"
],
[
"process_csv",
"write_csv"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 2eec6db10ae3cf47938de22895a4ecc85a48fe2e | e88a9b20edaad8531caafbec15ac7ba0667e4398 | |||
v1.0 | instruct | Filter | Filter_60818_I | How can I write a Python program to monitor network traffic and analyze bandwidth usage using basic libraries? | import time
import psutil
def bytes_to_readable_format(bytes_val):
"""
Converts bytes to a more readable format (KB, MB, GB).
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_val < 1024:
return f"{bytes_val:.2f} {unit}"
bytes_val /= 1024
def monitor_network_traffic(d... | import time
import psutil
from solution import monitor_network_traffic, bytes_to_readable_format
def test_bytes_to_readable_format():
assert bytes_to_readable_format(1023) == "1023.00 B"
assert bytes_to_readable_format(1024) == "1.00 KB"
assert bytes_to_readable_format(1048576) == "1.00 MB"
assert byte... | [
{
"docstring": "Converts bytes to a more readable format (KB, MB, GB).",
"function_declaration": "def bytes_to_readable_format(bytes_val):",
"function_name": "bytes_to_readable_format",
"parameter_list": "(bytes_val)"
},
{
"docstring": "Monitors network traffic and analyzes bandwidth usage.\... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport time\n\ndef get_network_stats():\n \"\"\"\n Returns network I/O statistics.\n \"\"\"\n io_counters = psutil.net_io_counters()\n return io_counters.bytes_se... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060818",
"row_id": 60818,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_122952']"
} | 0.410556 | Filter_60818 | I | [
"bytes_to_readable_format",
"monitor_network_traffic"
] | 2 | [
[
"monitor_network_traffic",
"bytes_to_readable_format"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | a7cad0db2f720772c8dc5399a5f848af6e277430 | a907401766424d8684dd5e8969d578cc3227336e | |||
v1.0 | instruct | Filter | Filter_60853_I | Write a Python code to display the first 10 Fibonacci numbers using recursion. | def fibonacci(n):
"""
Returns the nth Fibonacci number using recursion.
"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def first_10_fibonacci():
"""
Returns the first 10 Fibonacci numbers.
"""
return [fibona... | from solution import fibonacci, first_10_fibonacci
def test_fibonacci_base_cases():
assert fibonacci(0) == 0
assert fibonacci(1) == 1
def test_fibonacci_recursive_cases():
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
def test_first_10_fib... | [
{
"docstring": "Returns the nth Fibonacci number using recursion.",
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Returns the first 10 Fibonacci numbers.",
"function_declaration": "def first_10_fibonacci():",
"fu... | [
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 <= 1:\n return n\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\ndef first_10_fi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060853",
"row_id": 60853,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123020']"
} | 0.720366 | Filter_60853 | I | [
"fibonacci",
"first_10_fibonacci"
] | 2 | [
[
"first_10_fibonacci",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84e94d32a51243c42853c7cd92c0f677401beb6e | 7959e2c88369429f8da437f61057fd9f3a9346f9 | |||
v1.0 | instruct | Filter | Filter_60893_I | Write a Python program to calculate the Mandelbrot set using multiprocessing. The program should utilize the `multiprocessing` library to distribute the computation across multiple processes. The output should be a colormap of the Mandelbrot set. | import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
def mandelbrot(c, max_iter):
"""
Determines the number of iterations for which the point `c` remains within the Mandelbrot set.
"""
z = 0
for n in range(max_iter):
if abs(z) > 2:
return n
... | import numpy as np
from solution import mandelbrot, mandelbrot_set, display_mandelbrot
def test_mandelbrot():
assert mandelbrot(complex(0, 0), 1000) == 1000
assert mandelbrot(complex(1, 1), 1000) < 1000
def test_mandelbrot_set_dimensions():
xmin, xmax, ymin, ymax, width, height, max_iter = -2.0, 2.0, ... | [
{
"docstring": "Determines the number of iterations for which the point `c` remains within the Mandelbrot set.",
"function_declaration": "def mandelbrot(c, max_iter):",
"function_name": "mandelbrot",
"parameter_list": "(c, max_iter)"
},
{
"docstring": "Computes the Mandelbrot set for the giv... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(c, max_iter):\n z = c\n for n in range(max_iter):\n if abs(z) > 2:\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060893",
"row_id": 60893,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123106']"
} | 0.431829 | Filter_60893 | I | [
"mandelbrot",
"mandelbrot_set",
"display_mandelbrot"
] | 3 | [
[
"display_mandelbrot",
"mandelbrot_set"
],
[
"mandelbrot_set",
"mandelbrot"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 5e5d229ef9ac096101f38afea07dec28db2e302f | 6b647ef8c8b2d3c11a6e590260585bdc87d6b1b4 | |||
v1.0 | instruct | Filter | Filter_60905_I | Can you explain the concept of early stopping in training neural networks and provide an example of how to implement it using PyTorch? | import torch
import torch.nn as nn
import torch.optim as optim
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(10, 50)
self.fc2 = nn.Linear(50, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
... | import pytest
import torch
from solution import SimpleNN, train_model
def test_early_stopping():
model = SimpleNN()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# Creating simple dummy data loaders
train_loader = [(torch.randn(64, 10), torch.randn(64,... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef train_model(model, train_loader, criterion, optimizer, num_epochs, patience):\n \"\"\"\n Train the model with earl... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060905",
"row_id": 60905,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123131']"
} | 0.396851 | Filter_60905 | I | [
"train_model",
"example_model_training"
] | 2 | [
[
"example_model_training",
"train_model"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 420c38a567877650046894141da5cf97b2f98b32 | 36d8616df1fd8f40a11dc0e6ddc616e31b901830 | |||
v1.0 | instruct | Filter | Filter_60914_I | Create a Python function that calculates the sum of all prime numbers within a given range using the Sieve of Eratosthenes algorithm. The function should accept two parameters, `start` and `end`, representing the range within which to find and sum the prime numbers. | def sieve_of_eratosthenes(n):
"""Generate a list of primes up to n (inclusive) using the Sieve of Eratosthenes algorithm."""
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False # 0 and 1 are not primes
for start in range(2, int(n**0.5) + 1):
if sieve[start]:
for i in range(start * ... | from solution import sum_of_primes_in_range
def test_primes_in_full_range():
assert sum_of_primes_in_range(1, 10) == 17 # primes are 2, 3, 5, 7
def test_no_primes_in_range():
assert sum_of_primes_in_range(14, 16) == 0 # no primes in this range
def test_one_prime_in_range():
assert sum_of_primes_in_rang... | [
{
"docstring": "Generate a list of primes up to n (inclusive) using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sum_primes_in_range(start, end):\n \"\"\"\n Calculate the sum of all prime numbers within a given range using the Sieve of Eratosthenes algorithm.\n \n Parameters:\n start (... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060914",
"row_id": 60914,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123143']"
} | 0.657164 | Filter_60914 | I | [
"sieve_of_eratosthenes",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a6f6459ed96d9e6c713967462137461d905df9b1 | 0598c83743b3b622b009bbdc03d2b3adc808ea10 | |||
v1.0 | instruct | Filter | Filter_60920_I | Can you provide a Python code to solve a Sudoku puzzle using a backtracking algorithm? | def is_valid(board, row, col, num):
"""
Check if 'num' can be placed at board[row][col] without violating Sudoku rules.
"""
for i in range(9):
# Check the row
if board[row][i] == num:
return False
# Check the column
if board[i][col] == num:
return ... | import pytest
from solution import is_valid, sudoku_solver, print_board
def test_is_valid():
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, ... | [
{
"docstring": "Check if 'num' can be placed at board[row][col] without violating Sudoku rules.",
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": "Solve the Sudoku puzzle using backtracki... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if it's valid to place the number 'num' at the position (row, col) on the board.\n \"\"\"\n for i in range(9):\n if boar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060920",
"row_id": 60920,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123154']"
} | 0.458971 | Filter_60920 | I | [
"is_valid",
"sudoku_solver",
"print_board"
] | 3 | [
[
"sudoku_solver",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84053ee56ddeab600ab1c739578ad0ec4e0f9da4 | 66f54be3f577ac4830743b386faeab499307b83f | |||
v1.0 | instruct | Filter | Filter_60939_I | How can I write a Python code to find the sum of all prime numbers within a given range? | def is_prime(n):
"""
Checks if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def sum_of_primes_in_range(start,... | 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(19) == True
assert is_prime(-1) == False
assert is_prime(0) == False
assert is_prime(1... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within the given range [start, end].",
"function_declaration": "def sum_of_primes_in_ran... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number n is prime.\n \"\"\"\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060939",
"row_id": 60939,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123184']"
} | 0.699478 | Filter_60939 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1faf06add082dd39d1d1499fc1bbd66617c65170 | ca26b565fa38ae4568863f98721f60e45e6c69de | |||
v1.0 | instruct | Filter | Filter_60956_I | How can I create a Python script to monitor the CPU usage of a server and send an alert if it exceeds a certain threshold? | import psutil
import smtplib
from email.mime.text import MIMEText
def send_alert(to_email, subject, message):
"""
Sends an email alert to the specified email address.
"""
from_email = "your_email@example.com"
from_password = "your_email_password"
msg = MIMEText(message)
msg['Subject'] = su... | import pytest
from unittest.mock import patch, call
from solution import send_alert, monitor_cpu_usage
@patch('smtplib.SMTP_SSL')
def test_send_alert(mock_smtp):
to_email = "test_email@example.com"
subject = "Test Subject"
message = "This is a test message"
send_alert(to_email, subject, message)
... | [
{
"docstring": "Sends an email alert to the specified email address.",
"function_declaration": "def send_alert(to_email, subject, message):",
"function_name": "send_alert",
"parameter_list": "(to_email, subject, message)"
},
{
"docstring": "Monitors CPU usage and sends an alert if it exceeds... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef check_cpu_usage(threshold):\n \"\"\"\n Checks the current CPU usage percentage.\n \"\"\"\n return psutil.... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060956",
"row_id": 60956,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123219']"
} | 0.626734 | Filter_60956 | I | [
"send_alert",
"monitor_cpu_usage"
] | 2 | [
[
"monitor_cpu_usage",
"send_alert"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | e7e2f5e7a817ed2d340f8ef96d2735d7f2807895 | d5f1f617581b02f514ef0b4ea9bc886052936f29 | |||
v1.0 | instruct | Filter | Filter_60979_I | Generate a Python script that prompts the user for a number between 1 and 100, checks if the number is a palindrome and whether it is a prime number. A number is a palindrome if it reads the same backward as forward, and a number is prime if it has no divisors other than 1 and itself. | def is_palindrome(n):
"""
Check if a number is a palindrome.
"""
str_n = str(n)
return str_n == str_n[::-1]
def is_prime(n):
"""
Check if a number is a prime number.
"""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
retu... | from solution import is_palindrome, is_prime, check_number_properties
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(11) == True
assert is_palindrome(44) == True
assert is_palindrome(1) == True
def test_is_prime():
assert is_... | [
{
"docstring": "Check if a number is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_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_palindrome(n):\n \"\"\"\n Check if a number is a palindrome.\n \"\"\"\n str_n = str(n)\n return str_n == str_n[::-1]\n\ndef is_prime(n):\n \"\"\"\n Check if a numbe... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00060979",
"row_id": 60979,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123270']"
} | 0.617596 | Filter_60979 | I | [
"is_palindrome",
"is_prime",
"check_number_properties"
] | 3 | [
[
"check_number_properties",
"is_palindrome"
],
[
"check_number_properties",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 08e5d684aae064833d86793776e56079c739631f | 2feb83bc120124b6117bf1d7a9bea2f1cfd37c3c | |||
v1.0 | instruct | Filter | Filter_60980_I | Create a Python script that prints out all the prime numbers between 1 and 100. | def is_prime(n):
"""
Checks if a number n is a prime number.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def primes_between_1_and_100():
"""
Returns a list of all prime numbers between 1 and 100.
... | from solution import is_prime, primes_between_1_and_100
def test_is_prime():
assert not is_prime(1) # 1 is not a prime number
assert is_prime(2) # 2 is a prime number
assert is_prime(3) # 3 is a prime number
assert not is_prime(4) # 4 is not a prime number
assert is_prime(5) # 5 is a prime num... | [
{
"docstring": "Checks if a number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers between 1 and 100.",
"function_declaration": "def primes_between_1_and_100():"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_primes_up_to_100():\n \"\"\"\n Returns a list of all prime numbers between 1 and 100.\n \"\"\"\n primes = []\n for num in range(2, 101):\n is_prime = True\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00060980",
"row_id": 60980,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123271']"
} | 0.618934 | Filter_60980 | I | [
"is_prime",
"primes_between_1_and_100"
] | 2 | [
[
"primes_between_1_and_100",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5fe24038d7d1453ff030777da016d86b4c56406c | 618d8384b2041c8af7d90ddf99be6c153846ac16 | |||
v1.0 | instruct | Filter | Filter_60982_I | How can I write a Python script that finds all the prime numbers within a given range and returns them as a list? | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def find_primes_i... | from solution import find_primes_in_range, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(0) == False
assert is_prime(1) == False
assert is_prime(-7) == False
def test_find_primes_in... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers within the given range [start, end).",
"function_declaration": "def fin... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060982",
"row_id": 60982,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123274']"
} | 0.675225 | Filter_60982 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97aaf376e50716c117a85b1d0ae30f2cbae1d055 | 909093be4779489bb1cbb59484cdb014564d3d7d | |||
v1.0 | instruct | Filter | Filter_60984_I | Can you provide a Python code snippet that generates a list of prime numbers up to a given number `n`? | def is_prime(num):
"""
Checks if a number is a prime number.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def generate_primes(n):
"""
Generates a list of prime numbers up to the given number n (... | from solution import is_prime, generate_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_generate_primes_emp... | [
{
"docstring": "Checks if a number is a prime number.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generates a list of prime numbers up to the given number n (inclusive).",
"function_declaration": "def generate_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_primes(n):\n \"\"\"\n Generates a list of prime numbers up to and including n.\n \"\"\"\n if n < 2:\n return []\n \n primes = []\n is_prime = [True] * ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060984",
"row_id": 60984,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123276']"
} | 0.68115 | Filter_60984 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed883d0a166511d0e809a464888865da759e1d7d | b5a09018ef9e536d176be9fad14aec2cef8b2dd3 | |||
v1.0 | instruct | Filter | Filter_60990_I | How can I create a template for a new blog post in a Python program? How can I dynamically generate blog post titles and content based on user input or predefined patterns? | import datetime
def get_current_date():
"""
Returns the current date in YYYY-MM-DD format.
"""
return datetime.datetime.now().strftime("%Y-%m-%d")
def create_blog_post(title, content):
"""
Returns a formatted blog post with the given title and content.
"""
date = get_current_date()
... | from solution import create_blog_post, generate_title, get_current_date
def test_get_current_date():
import datetime
assert get_current_date() == datetime.datetime.now().strftime("%Y-%m-%d")
def test_generate_title():
title = generate_title("My Blog", "Introduction")
assert title.startswith("My Blog -... | [
{
"docstring": "Returns the current date in YYYY-MM-DD format.",
"function_declaration": "def get_current_date():",
"function_name": "get_current_date",
"parameter_list": "()"
},
{
"docstring": "Returns a formatted blog post with the given title and content.",
"function_declaration": "de... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_blog_post(template, title, author, content):\n \"\"\"\n Create a blog post based on the template, title, author, and content.\n \"\"\"\n return template.format(title=tit... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00060990",
"row_id": 60990,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123286']"
} | 0.410568 | Filter_60990 | I | [
"get_current_date",
"create_blog_post",
"generate_title"
] | 3 | [
[
"create_blog_post",
"get_current_date"
],
[
"generate_title",
"get_current_date"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8704d3b6314d0106f3619dbc2e759830915e323b | 6f1ba171b90c27a134c51b513d08a7ade3f79f17 | |||
v1.0 | instruct | Filter | Filter_61006_I | Can you help me with a Python function to generate a list of prime numbers within a given range? | def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_primes(start, end):
"""
Returns a list of prime numbers between the given start and end values (inclusive).
"""
primes = []
for n... | from solution import generate_primes, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(11) == True
assert is_prime(1) == False
assert is_prime(-7) == False
def test_generate_primes_sma... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers between the given start and end values (inclusive).",
"function_declaration": "def generate_primes(start, end):",
"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_primes(start, end):\n \"\"\"\n Returns a list of prime numbers within the given range [start, end].\n\n Args:\n start (int): The starting bound of the range.\n end ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061006",
"row_id": 61006,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123327']"
} | 0.696396 | Filter_61006 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 936110022373132f00ed1813011d433f1bfccaa0 | 14832b22b2e2dc872d9903f65e0af21cefb612ae | |||
v1.0 | instruct | Filter | Filter_61028_I | Could you provide a Python script that logs the time of day when a user logs in and logs out? This script should prompt the user for their username and then log their login and logout times to a file. The script should handle multiple user sessions and record each session accurately. | import datetime
def log_event(username, event):
"""
Logs login or logout event with timestamp for the given username.
"""
with open('user_log.txt', 'a') as file:
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(f'{username} {event} at {timestamp}\n')
def log... | import datetime
from solution import log_event, login, logout
def test_log_event():
username = 'test_user'
event = 'test_event'
log_event(username, event)
with open('user_log.txt', 'r') as file:
lines = file.readlines()
last_log = lines[-1]
assert f'{username} {event} at ' in ... | [
{
"docstring": "Logs login or logout event with timestamp for the given username.",
"function_declaration": "def log_event(username, event):",
"function_name": "log_event",
"parameter_list": "(username, event)"
},
{
"docstring": null,
"function_declaration": "def login(username):",
"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import datetime\n\ndef log_event(username, event):\n \"\"\"\n Logs the time of the event (login/logout) for the given username to a file.\n \"\"\"\n with open(\"user_logs.txt\", \"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061028",
"row_id": 61028,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123381']"
} | 0.447032 | Filter_61028 | I | [
"log_event",
"login",
"logout"
] | 3 | [
[
"login",
"log_event"
],
[
"logout",
"log_event"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 66e8223eefeb80586ea8c773415eac3e4d3b95dc | bc9c78ad62451e58fedf1c84c2bdfecaff0a3597 | |||
v1.0 | instruct | Filter | Filter_61080_I | Create a simple Python script to generate a list of prime numbers within a given range. The script should take two arguments: the start and end of the range. It should use a function to check if a number is prime and another function to generate the list of primes. Make sure to add comments to explain the code. | def is_prime(n):
"""
Check if a number is prime.
Args:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i =... | from solution import is_prime, generate_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(13) == True
def test_generate_primes():
assert generate_primes(1, 10... | [
{
"docstring": "Check if a number is prime.\n\nArgs:\nn (int): The number to check.\n\nReturns:\nbool: True if the number is prime, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of prime ... | [
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 Parameters:\n n (int): The number to check.\n \n Returns:\n bool: True if the number is prime, otherwise Fa... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061080",
"row_id": 61080,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123499']"
} | 0.617829 | Filter_61080 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f86d7ce8a1806f4e09da5ec55d20fdd6883d860 | 381ca618dfef48187a18d70e88d23a736bc149c4 | |||
v1.0 | instruct | Filter | Filter_61082_I | Write a Python script that checks the status of a local Apache web server and restarts it if it's not running. This script should be designed to run on a Linux system. | import subprocess
def check_apache_status():
"""
Checks the status of the Apache server.
Returns True if the server is running, False otherwise.
"""
try:
result = subprocess.run(['systemctl', 'is-active', 'apache2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.stdo... | from unittest.mock import patch, MagicMock
from solution import check_apache_status, restart_apache, ensure_apache_is_running
def test_check_apache_status_running():
with patch('subprocess.run') as mocked_run:
mocked_run.return_value.stdout = b'active\n'
assert check_apache_status() == True
def te... | [
{
"docstring": "Checks the status of the Apache server.\nReturns True if the server is running, False otherwise.",
"function_declaration": "def check_apache_status():",
"function_name": "check_apache_status",
"parameter_list": "()"
},
{
"docstring": "Restarts the Apache server.\nReturns True... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import subprocess\n\ndef check_apache_status():\n \"\"\"\n Checks the status of the Apache web server.\n Returns 'running' if the Apache server is running, 'not running' otherwise.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061082",
"row_id": 61082,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123502']"
} | 0.532007 | Filter_61082 | I | [
"check_apache_status",
"restart_apache",
"ensure_apache_is_running"
] | 3 | [
[
"ensure_apache_is_running",
"check_apache_status"
],
[
"ensure_apache_is_running",
"restart_apache"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1a5ee4b03f286bd293c18b7eb7b939acb7a2f315 | 45d03561594837b1849bb83c02f833cffc5cab60 | |||
v1.0 | instruct | Filter | Filter_61103_I | How can I create a Python script to simulate and visualize a simple harmonic oscillator using the `scipy` and `matplotlib` libraries? | import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
def harmonic_oscillator(t, y):
"""
Defines the differential equations for the harmonic oscillator.
Arguments:
t : float
Current time point.
y : array
Current values of the state... | import numpy as np
from solution import harmonic_oscillator, simulate_oscillator, plot_oscillator
def test_harmonic_oscillator():
t = 0
y = [1.0, 0]
dydt = harmonic_oscillator(t, y)
assert np.isclose(dydt[0], 0.0)
assert np.isclose(dydt[1], -1.0)
def test_simulate_oscillator():
y0 = [1.0, 0.0]... | [
{
"docstring": "Defines the differential equations for the harmonic oscillator.\n\nArguments:\n t : float\n Current time point.\n y : array\n Current values of the state variables [position, velocity].\n\nReturns:\n dydt : array\n Derivatives [d(position)/dt, d(velocity)/dt].",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\n\ndef simple_harmonic_oscillator(y, t, omega):\n \"\"\"\n Differential equation for a simple harm... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061103",
"row_id": 61103,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123541']"
} | 0.547421 | Filter_61103 | I | [
"harmonic_oscillator",
"simulate_oscillator",
"plot_oscillator"
] | 3 | [
[
"simulate_oscillator",
"harmonic_oscillator"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | ed30090cf52a3587ff5d9fa26f689ff7b4b2c8cc | dbd57510d60558d8178e7d5cec3bf4a38e0f3df0 | |||
v1.0 | instruct | Filter | Filter_61140_I | Can you provide a detailed Python code example for a simple blackjack game? This should include setting up the deck, shuffling, dealing cards, and basic game logic for a single-player game against the dealer? | import random
def create_deck():
"""Initialize a standard deck of 52 cards."""
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = [{'rank': rank, 'suit': suit} for suit in suits for rank in ranks]
return de... | from solution import create_deck, shuffle_deck, deal_card, calculate_hand_value
def test_create_deck():
deck = create_deck()
assert len(deck) == 52
assert {'rank': 'Ace', 'suit': 'Spades'} in deck
assert {'rank': '2', 'suit': 'Hearts'} in deck
def test_shuffle_deck():
deck = create_deck()
shuf... | [
{
"docstring": "Initialize a standard deck of 52 cards.",
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": "Shuffle the deck of cards.",
"function_declaration": "def shuffle_deck(deck):",
"function_name": "shuffle_... | [
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_deck():\n suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']\n deck... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061140",
"row_id": 61140,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123604']"
} | 0.374083 | Filter_61140 | I | [
"create_deck",
"shuffle_deck",
"deal_card",
"calculate_hand_value",
"play_blackjack"
] | 5 | [
[
"play_blackjack",
"calculate_hand_value"
],
[
"play_blackjack",
"create_deck"
],
[
"play_blackjack",
"deal_card"
],
[
"play_blackjack",
"shuffle_deck"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 6ccc4647ee828e54d5d17cd20a49e48ea68b498d | 035cfbfc9834a6ebaebc83d3a23cc1e8fd2eb847 | |||
v1.0 | instruct | Filter | Filter_61149_I | Hello Qwen, I'm working on my programming project and I need some help. I'm implementing a feature where I need to find the maximum number in an array using a recursive function. Can you guide me on how to do this? | def find_max(arr, n):
"""
Recursively find the maximum number in the array `arr` of length `n`.
"""
if n == 1:
return arr[0]
else:
return max(arr[n-1], find_max(arr, n-1))
# Convenience function to easily call find_max
def find_max_in_array(arr):
if not arr:
raise Value... | from solution import find_max_in_array
def test_find_max_in_array_single_element():
assert find_max_in_array([10]) == 10
def test_find_max_in_array_all_positive():
assert find_max_in_array([1, 2, 3, 4, 5]) == 5
def test_find_max_in_array_mixed_signs():
assert find_max_in_array([1, -2, 3, -4, 5]) == 5
de... | [
{
"docstring": "Recursively find the maximum number in the array `arr` of length `n`.",
"function_declaration": "def find_max(arr, n):",
"function_name": "find_max",
"parameter_list": "(arr, n)"
},
{
"docstring": null,
"function_declaration": "def find_max_in_array(arr):",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_max_recursive(arr, n=None):\n \"\"\"\n Returns the maximum number in the array using recursion.\n \"\"\"\n if n is None:\n n = len(arr)\n \n # Base case: when... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061149",
"row_id": 61149,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123619']"
} | 0.637358 | Filter_61149 | I | [
"find_max",
"find_max_in_array"
] | 2 | [
[
"find_max_in_array",
"find_max"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c4196fd4bd700355c25f960aa603063e1f2226c | eb633803e39ced6b0c8d2558901d1a8c16114246 | |||
v1.0 | instruct | Filter | Filter_61214_I | Can you provide a Python code snippet to demonstrate the Caesar cipher encryption and decryption? | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the given text using Caesar cipher with the given shift.
Parameters:
text (str): The input string to encrypt.
shift (int): The number of positions to shift each character.
Returns:
str: The encrypted text.
"""
encrypted_t... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("abc", 1) == "bcd"
assert caesar_cipher_encrypt("xyz", 2) == "zab"
assert caesar_cipher_encrypt("Hello, World!", 3) == "Khoor, Zruog!"
assert caesar_cipher_encrypt("Python3.8... | [
{
"docstring": "Encrypts the given text using Caesar cipher with the given shift.\n\nParameters:\ntext (str): The input string to encrypt.\nshift (int): The number of positions to shift each character.\n\nReturns:\nstr: The encrypted text.",
"function_declaration": "def caesar_cipher_encrypt(text, shift):",... | [
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 given text using Caesar cipher with the specified shift.\n \"\"\"\n encrypted_text = []\n\n for char in text:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061214",
"row_id": 61214,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123740']"
} | 0.598619 | Filter_61214 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f94c94e571e5e9c7255528b4b6ab002c8944ffee | f070409ab34eb6299bed8d9542ef0eaca441e6da | |||
v1.0 | instruct | Filter | Filter_61232_I | Write a Python code to find the largest palindrome number less than a given number N. | def is_palindrome(n):
"""
Returns True if n is a palindrome, False otherwise.
"""
s = str(n)
return s == s[::-1]
def largest_palindrome_less_than(N):
"""
Returns the largest palindrome number less than N.
"""
for i in range(N-1, 0, -1):
if is_palindrome(i):
retur... | from solution import is_palindrome, largest_palindrome_less_than
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(12321) == True
assert is_palindrome(123) == False
assert is_palindrome(1221) == True
assert is_palindrome(10) == False
def test_largest_palindrome_less_... | [
{
"docstring": "Returns True if n is a palindrome, False otherwise.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Returns the largest palindrome number less than N.",
"function_declaration": "def largest_pa... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def largest_palindrome_less_than(N):\n \"\"\"\n This function returns the largest palindrome number that is less than N.\n \"\"\"\n def is_palindrome(num):\n return str(num)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061232",
"row_id": 61232,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123782']"
} | 0.784488 | Filter_61232 | I | [
"is_palindrome",
"largest_palindrome_less_than"
] | 2 | [
[
"largest_palindrome_less_than",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26e09f3a91ae78398313e772ca9080154bb82958 | de2c7a907d24e7762f4160326fdd432079213a7b | |||
v1.0 | instruct | Filter | Filter_61264_I | Write a Python function named `find_fibonacci_prime` that takes an integer `n` as input and returns the nth Fibonacci number that is also prime. The function should be efficient and use a helper function to check for primality. | def is_prime(num):
"""Check if a number is a prime number."""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
... | from solution import is_prime, find_fibonacci_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(13) == True
assert is_prime(15) == False
def test_find_fibonacci_prime():
assert find_fibona... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generate an infinite sequence of Fibonacci numbers.",
"function_declaration": "def generate_fibonacci_sequence():... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if num is a prime number.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061264",
"row_id": 61264,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123851']"
} | 0.843809 | Filter_61264 | I | [
"is_prime",
"generate_fibonacci_sequence",
"find_fibonacci_prime"
] | 3 | [
[
"find_fibonacci_prime",
"generate_fibonacci_sequence"
],
[
"find_fibonacci_prime",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d82dac862bee508677602ed2429c2baa1e5db11b | a3322dff6eb3d3ca7cdaf6b663ffbfdecb00cc91 | |||
v1.0 | instruct | Filter | Filter_61301_I | I'm trying to train a custom language model using Hugging Face's Transformers library. I have a dataset ready, and I want to fine-tune a pre-trained model. Can you guide me through the process? | # Step 1: Install the Transformers library
# This can be done via pip if not already installed:
# pip install transformers datasets
import pandas as pd
from datasets import Dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
def load_dataset(data_path):
"... | from solution import load_dataset, prepare_dataset, tokenize_data, fine_tune_model
import pandas as pd
import os
def test_load_dataset():
data = {'text': ["Hello world", "Goodbye world"], 'label': [0, 1]}
df = pd.DataFrame(data)
df.to_csv("test_dataset.csv", index=False)
loaded_df = load_dataset("test... | [
{
"docstring": "Load dataset from a given path.\nAssuming the dataset is a CSV file for simplicity.",
"function_declaration": "def load_dataset(data_path):",
"function_name": "load_dataset",
"parameter_list": "(data_path)"
},
{
"docstring": "Load and prepare dataset for training.",
"func... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments\nfrom datasets import load_dataset\n\ndef prepare_data(dataset_path):\n \"\"\"\n Load and tokenize dat... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061301",
"row_id": 61301,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123928']"
} | 0.251938 | Filter_61301 | I | [
"load_dataset",
"prepare_dataset",
"tokenize_data",
"fine_tune_model"
] | 4 | [
[
"fine_tune_model",
"tokenize_data"
],
[
"prepare_dataset",
"load_dataset"
]
] | 2 | [] | false | [] | false | pytest | true | [
"datasets",
"pandas",
"transformers"
] | false | 4deab7c4b6ec7cded643b9efaeb9753fd6e0ae9e | fb6443e0e70e91626df2c0542594dcab40b72551 | |||
v1.0 | instruct | Filter | Filter_61302_I | Write a Python function to find the maximum area of a rectangle formed by binary submatrices with all 1s in a given binary matrix. The function should take a 2D list `matrix` as input and return an integer representing the maximum area of such a rectangle. | def maximalRectangle(matrix):
"""
Finds the maximum area of a rectangle formed by binary submatrices with all 1s in the given binary matrix.
:param matrix: A 2D list representing the binary matrix
:return: The maximum area of rectangle formed by 1s
"""
if not matrix:
return 0
r... | from solution import maximalRectangle
def test_maximal_rectangle_empty_matrix():
assert maximalRectangle([]) == 0
def test_maximal_rectangle_all_zeros():
matrix = [
['0', '0', '0'],
['0', '0', '0'],
['0', '0', '0']
]
assert maximalRectangle(matrix) == 0
def test_maximal_rectan... | [
{
"docstring": "Finds the maximum area of a rectangle formed by binary submatrices with all 1s in the given binary matrix.\n\n:param matrix: A 2D list representing the binary matrix\n:return: The maximum area of rectangle formed by 1s",
"function_declaration": "def maximalRectangle(matrix):",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximalRectangle(matrix):\n \"\"\"\n Given a 2D binary matrix filled with 0s and 1s, return the area of the largest rectangle containing only 1s.\n \"\"\"\n if not matrix or no... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061302",
"row_id": 61302,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123929']"
} | 0.683966 | Filter_61302 | I | [
"maximalRectangle",
"largest_rectangle_area"
] | 2 | [
[
"maximalRectangle",
"largest_rectangle_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 70851c0a0729d31d40b88d8223c0a204ae8b598d | e0eeee13dda42929d84c366bbf0a1e6cf9a433df | |||
v1.0 | instruct | Filter | Filter_61319_I | Could you provide a detailed explanation of how to implement a Generative Adversarial Network (GAN) using PyTorch? Building a GAN from scratch can be quite complex, and a step-by-step guide would be very helpful. | import torch
import torch.nn as nn
import torch.optim as optim
# Generator Network
class Generator(nn.Module):
def __init__(self, input_size, output_size):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.Linear(input_size, 128),
nn.ReLU(True),
nn.... | from solution import Generator, Discriminator
import torch
def test_generator_output_shape():
gen = Generator(100, 784)
noise = torch.randn(1, 100)
fake_data = gen(noise)
assert fake_data.shape == torch.Size([1, 784])
def test_discriminator_output_shape():
disc = Discriminator(784)
fake_data =... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Hyperparameters\nlatent_size = 64... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061319",
"row_id": 61319,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_123956']"
} | 0.20282 | Filter_61319 | I | [
"train_discriminator",
"train_generator",
"train_gan"
] | 3 | [
[
"train_gan",
"train_discriminator"
],
[
"train_gan",
"train_generator"
]
] | 2 | [] | false | [
"Generator",
"Discriminator"
] | true | pytest | true | [
"torch"
] | false | 9c24fabc93513ae87e20de65d6915cb65997f1d3 | 78be14bd0bb5a12e3ef32863e315dbb7047ff762 | |||
v1.0 | instruct | Filter | Filter_61363_I | Can you help me with a Python code to simulate a simple dice game where two players take turns rolling a six-sided die? The game continues until one of the players reaches a score of 20 or more, and the player with the higher score at that point wins. If the scores are tied, it's a draw. How can I implement this? | import random
def roll_dice():
return random.randint(1, 6)
def simple_dice_game():
player1_score = 0
player2_score = 0
turn = 1 # 1 for player 1's turn, 2 for player 2's turn
while player1_score < 20 and player2_score < 20:
if turn == 1:
player1_score += roll_dice()
... | from solution import roll_dice, simple_dice_game
def test_roll_dice():
for _ in range(100):
roll = roll_dice()
assert 1 <= roll <= 6
def test_simple_dice_game():
# Due to the randomness in the dice roll, we will run multiple simulations and check that
# the result is always one of the expe... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def simple_dice_game():",
"function_name": "simple_dice_game",
"parameter_list": "()"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided die.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_dice_game():\n \"\"\"\n Simulates a dice ga... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061363",
"row_id": 61363,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124053']"
} | 0.473885 | Filter_61363 | I | [
"roll_dice",
"simple_dice_game"
] | 2 | [
[
"simple_dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 750c69b6bc2d78dc44439e2b3300f23f7b1b3a9b | e7a586fe5b594f3e7d306dec275418d7f4cd0696 | |||
v1.0 | instruct | Filter | Filter_61380_I | Can you provide a code snippet that demonstrates how to create a simple text adventure game in Python? | class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.exits = {}
def set_exit(self, direction, room):
self.exits[direction] = room
def get_room_in_direction(self, direction):
return self.exits.get(dir... | def test_room_creation():
room = Room("Test Room", "This is a test room.")
assert room.name == "Test Room"
assert room.description == "This is a test room."
assert room.exits == {}
def test_setting_exits():
room1 = Room("Room 1", "You are in room 1.")
room2 = Room("Room 2", "You are in room 2."... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_adventure():\n print(\"Welcome to the Adventure Game!\")\n print(\"You find yourself in a dark forest.\")\n choice = input(\"Do you want to go left or right? [left/right]: \... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061380",
"row_id": 61380,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124092']"
} | 0.446813 | Filter_61380 | I | [
"create_game",
"play_game"
] | 2 | [
[
"play_game",
"create_game"
]
] | 1 | [] | false | [
"Room"
] | true | pytest | false | [] | true | 5a4e84d580c8ea8795adba3db241457f8654fe46 | 890c18bd03baf5414f7272dc225beac525a23241 | |||
v1.0 | instruct | Filter | Filter_61388_I | Can you help me with the code to simulate a simple game where two players take turns to roll a six-sided die and try to reach a target score? The player who reaches the target score or exceeds it first wins the game. How can I implement this in Python? | import random
def roll_die():
"""
Simulates rolling a six-sided die.
Returns a random integer between 1 and 6.
"""
return random.randint(1, 6)
def play_game(target_score):
"""
Simulates a game where two players take turns to roll a die.
The first player to reach or exceed the target sc... | from solution import roll_die, play_game
def test_roll_die():
for _ in range(100):
roll = roll_die()
assert 1 <= roll <= 6
def test_play_game():
random.seed(0) # Setting seed for reproducibility
winner, score = play_game(20)
assert winner in ["Player 1", "Player 2"]
assert score >... | [
{
"docstring": "Simulates rolling a six-sided die.\nReturns a random integer between 1 and 6.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a game where two players take turns to roll a die.\nThe first player to ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"\n Simulates rolling a six-sided die.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_turn(player_score):\n \"\"\"\n Simulates a p... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00061388",
"row_id": 61388,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124111']"
} | 0.477969 | Filter_61388 | I | [
"roll_die",
"play_game"
] | 2 | [
[
"play_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7bfea93aca61df9b6269089de5d7a5cf4036423b | 965aa36c0ef9fe5b3fe295bc4a29848ae7590593 | |||
v1.0 | instruct | Filter | Filter_61392_I | Can you provide a Python script that can identify and count the number of palindromes in a given text file? A palindrome is a word that reads the same backward as forward, ignoring punctuation and case sensitivity. | import re
def is_palindrome(word):
"""
Checks if a word is a palindrome.
"""
word = re.sub(r'[^a-zA-Z0-9]', '', word).lower()
return word == word[::-1]
def count_palindromes_in_file(file_path):
"""
Returns the number of palindromes in a given text file.
"""
with open(file_path, 'r'... | import os
import tempfile
from solution import is_palindrome, count_palindromes_in_file
def test_is_palindrome():
assert is_palindrome("racecar") == True
assert is_palindrome("A man, a plan, a canal, Panama") == True
assert is_palindrome("hello") == False
assert is_palindrome("Madam") == True
asser... | [
{
"docstring": "Checks if a word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Returns the number of palindromes in a given text file.",
"function_declaration": "def count_palindromes... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef count_palindromes(filename):\n \"\"\"\n Counts the number of palindromes in the given text file.\n \n Parameters:\n filename (str): The name of the file to be r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061392",
"row_id": 61392,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124118']"
} | 0.680968 | Filter_61392 | I | [
"is_palindrome",
"count_palindromes_in_file"
] | 2 | [
[
"count_palindromes_in_file",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dbbe83a8f8ccad3d3c47636924b98cfa051c43f5 | a8ca7f638ef64f5d579dd112a7b71bd466920cce | |||
v1.0 | instruct | Filter | Filter_61395_I | Write a Python code to simulate a simple game of Rock-Paper-Scissors using loops and conditionals. The game should allow a user to play the game with the computer, and the game runs until the user decides to quit. The computer's choice should be random. The user's score and the computer's score should be tracked and di... | import random
def get_computer_choice():
return random.choice(["rock", "paper", "scissors"])
def determine_winner(user_choice, computer_choice):
winning_combinations = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
if user_choice == computer_choice:
return... | from solution import get_computer_choice, determine_winner
def test_get_computer_choice():
choices = ["rock", "paper", "scissors"]
for _ in range(100):
assert get_computer_choice() in choices
def test_determine_winner():
assert determine_winner("rock", "scissors") == "user"
assert determine_wi... | [
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def determine_winner(user_choice, computer_choice):",
"function_name": "determine_winner",
"p... | [
1,
1,
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 return random.choice([\"rock\", \"paper\", \"scissors\"])\n\ndef determine_winner(user_choice, computer_choice):\n winning_combinations = {\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00061395",
"row_id": 61395,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124122']"
} | 0.474874 | Filter_61395 | I | [
"get_computer_choice",
"determine_winner",
"play_game"
] | 3 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 16cf427ecde83b3a8bfdc4e1e73522a59866fbe6 | e43e3b8ad29af3b3142aae6f96676cf6170c874f | |||
v1.0 | instruct | Filter | Filter_61433_I | Write a Python script to simulate a simple dice game where two players roll a six-sided die. The player with the higher roll wins the round. If both players roll the same number, it's a tie. The game continues for a specified number of rounds. The script should output the winner of each round and the final score of the... | import random
def roll_die():
return random.randint(1, 6)
def play_round():
player1_roll = roll_die()
player2_roll = roll_die()
if player1_roll > player2_roll:
return 1, 0
elif player2_roll > player1_roll:
return 0, 1
else:
return 0, 0
def play_game(rounds):
score_... | import pytest
from solution import roll_die, play_round, play_game
def test_roll_die():
for _ in range(100):
roll = roll_die()
assert 1 <= roll <= 6
def test_play_round():
for _ in range(100):
result = play_round()
assert result in [(1, 0), (0, 1), (0, 0)]
def test_play_game()... | [
{
"docstring": null,
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def play_round():",
"function_name": "play_round",
"parameter_list": "()"
},
{
"docstring": null,
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"\n Simulates rolling a six-sided die.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_round():\n \"\"\"\n Simulates a single round... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061433",
"row_id": 61433,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124200']"
} | 0.485964 | Filter_61433 | I | [
"roll_die",
"play_round",
"play_game"
] | 3 | [
[
"play_game",
"play_round"
],
[
"play_round",
"roll_die"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6d6539adb7e60fc300446e855f2bc146b3c24af5 | b77d2448722d78485fdf028ce3aafeb77e383c03 | |||
v1.0 | instruct | Filter | Filter_61461_I | I would like to create a simple calculator program in Python. Can you provide a basic example? | def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def subtract(a, b):
"""
Returns the difference of a and b.
"""
return a - b
def multiply(a, b):
"""
Returns the product of a and b.
"""
return a * b
def divide(a, b):
"""
Returns the quotient of a ... | import pytest
from solution import add, subtract, multiply, divide, calculator
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(3, 2) == 1
assert subtract(2, 3) == -1
assert subtract(0, 0) == 0
def test_multiply():
ass... | [
{
"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 of a and b.",
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"paramete... | [
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 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 raise ValueError(\"Cannot divid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00061461",
"row_id": 61461,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_124257']"
} | 0.514689 | Filter_61461 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c8b349448a75bb4cd3ffa284cb1c47d4ecdd6864 | 98214d3b3f67780c9447fa9ca379e51047bafda8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.