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_48106_I | Write a Python program that implements the merge sort algorithm. The program should take a list of integers as input and return the sorted list. Make sure to include comments in your code to explain the key steps of the algorithm. | def merge_sort(arr):
"""
Implementation of merge sort algorithm to sort a list of integers.
"""
# Base case: if the list contains 0 or 1 elements, it is already sorted
if len(arr) <= 1:
return arr
# Recursive case: divide the list into two halves
mid = len(arr) // 2
left_half = ... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
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():
assert... | [
{
"docstring": "Implementation of merge sort algorithm to sort a list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Helper function to merge two sorted lists.",
"function_declaration": "def merge... | [
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 of integers using merge sort algorithm.\n\n Parameters:\n arr (list): A list of integers to be sorted\n\n Returns:\n list: A so... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048106",
"row_id": 48106,
"seed_ids": "['Qwen2.5-72B-Instruct_101270']"
} | 0.596902 | Filter_48106 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79912a76866d0e60e25021301fe06b03ae35a0f6 | 4565d042a3e32584a5ba10df4062f0977b36d2fd | |||
v1.0 | instruct | Filter | Filter_48108_I | I have a list of URLs and I need to extract the domain names from them. Can you provide a Python script that can do this? | from urllib.parse import urlparse
def extract_domain(url):
"""
Extracts the domain name from a given URL.
Parameters:
url (str): The URL from which to extract the domain name.
Returns:
str: The domain name extracted from the URL.
"""
parsed_url = urlparse(url)
return parse... | from solution import extract_domain, extract_domains
def test_extract_domain():
assert extract_domain("http://www.example.com") == "www.example.com"
assert extract_domain("https://example.com/path/to/page") == "example.com"
assert extract_domain("ftp://subdomain.example.com/resource") == "subdomain.example... | [
{
"docstring": "Extracts the domain name from a given URL.\n\nParameters:\nurl (str): The URL from which to extract the domain name.\n\nReturns:\nstr: The domain name extracted from the URL.",
"function_declaration": "def extract_domain(url):",
"function_name": "extract_domain",
"parameter_list": "(... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from urllib.parse import urlparse\n\ndef extract_domains(urls):\n \"\"\"\n Extracts the domain names from a list of URLs.\n \n :param urls: List of URLs\n :return: List of domai... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048108",
"row_id": 48108,
"seed_ids": "['Qwen2.5-72B-Instruct_101272']"
} | 0.684189 | Filter_48108 | I | [
"extract_domain",
"extract_domains"
] | 2 | [
[
"extract_domains",
"extract_domain"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4e27e079a176b1b35dc663dd74644a1922e8ef0f | 5e907ad32b4b839d75a645ed60a7f04ef1987616 | |||
v1.0 | instruct | Filter | Filter_48111_I | Explain how you can use an AWS Lambda function to automatically resize images uploaded to an S3 bucket, and then store the resized images in another S3 bucket. | import boto3
from PIL import Image
import io
s3_client = boto3.client('s3')
def resize_image(image_data: bytes, width: int, height: int) -> bytes:
"""
Resize the input image to the specified width and height.
Parameters:
- image_data: a byte stream of the image.
- width: the desired width of ... | import pytest
from PIL import Image
import io
from solution import resize_image
def test_resize_image():
# Create a dummy image for testing
original_image = Image.new('RGB', (800, 800), color = 'red')
original_byte_array = io.BytesIO()
original_image.save(original_byte_array, format='JPEG')
origin... | [
{
"docstring": "Resize the input image to the specified width and height.\n\nParameters:\n- image_data: a byte stream of the image.\n- width: the desired width of the resized image.\n- height: the desired height of the resized image.\n\nReturns:\n- A byte stream of the resized image.",
"function_declaration... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import boto3\nfrom PIL import Image\nimport io\n\ns3_client = boto3.client('s3')\n\ndef resize_image(image_data: bytes, width: int, height: int) -> bytes:\n \"\"\"\n Resize the input ima... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048111",
"row_id": 48111,
"seed_ids": "['Qwen2.5-72B-Instruct_101276']"
} | 0.385227 | Filter_48111 | I | [
"resize_image",
"lambda_handler"
] | 2 | [
[
"lambda_handler",
"resize_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL",
"boto3"
] | false | 41eb566046a3fc3a601a63ecbff2297166309356 | 20531ff9c9f0b0e2b63fd9bbc81f798607d3221d | |||
v1.0 | instruct | Filter | Filter_48128_I | I have a collection of images, and I need to perform a batch conversion from JPEG to PNG format. I'm using Python for this task. Could you provide me with a script that can accomplish this? | from PIL import Image
import os
def convert_jpeg_to_png(source_folder, target_folder):
"""
Converts all JPEG images in the source_folder to PNG format and saves them in the target_folder.
Args:
source_folder (str): The folder containing the source JPEG images.
target_folder (str): The ... | import os
from PIL import Image
from solution import convert_jpeg_to_png_for_tests
def setup_module(module):
os.makedirs('test_source', exist_ok=True)
os.makedirs('test_target', exist_ok=True)
# Create dummy JPEG files for testing
for i in range(3):
img = Image.new('RGB', (100, 100), color = (i... | [
{
"docstring": "Converts all JPEG images in the source_folder to PNG format and saves them in the target_folder.\n\nArgs:\n source_folder (str): The folder containing the source JPEG images.\n target_folder (str): The folder to save the converted PNG images.",
"function_declaration": "def convert_jpeg... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image\nimport os\n\ndef convert_jpeg_to_png(input_folder, output_folder):\n \"\"\"\n Converts all JPEG images in the input_folder to PNG format and saves them to the outp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048128",
"row_id": 48128,
"seed_ids": "['Qwen2.5-72B-Instruct_101300']"
} | 0.379242 | Filter_48128 | I | [
"convert_jpeg_to_png",
"convert_jpeg_to_png_for_tests"
] | 2 | [
[
"convert_jpeg_to_png_for_tests",
"convert_jpeg_to_png"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 5a380238d0081987f5734a1e55de255a5114402f | 9131a84df51013b391bb34cf2d1ce33e5445bbdf | |||
v1.0 | instruct | Filter | Filter_48130_I | Write a Python function to generate a list of prime numbers between 1 and a given number `n`, and then use this function to find the sum of all prime numbers between 1 and `n`. The function should return the sum. | def is_prime(num):
"""Checks if a number is prime."""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
retu... | from solution import prime_sum
def test_prime_sum_small_numbers():
assert prime_sum(1) == 0 # no primes less than 2
assert prime_sum(10) == 17 # primes between 1 and 10 are 2, 3, 5, 7
def test_prime_sum_medium_numbers():
assert prime_sum(20) == 77 # primes between 1 and 20 are 2, 3, 5, 7, 11, 13, 17, 1... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the sum of all prime numbers between 1 and n.",
"function_declaration": "def prime_sum(n):",
"function_name":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"Checks if a number is prime.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n r... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048130",
"row_id": 48130,
"seed_ids": "['Qwen2.5-72B-Instruct_101302']"
} | 0.682709 | Filter_48130 | I | [
"is_prime",
"prime_sum"
] | 2 | [
[
"prime_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 578650749c57bda734d8a348415b13a261903eb7 | c496d1e9e6b9bcb712b1c604f4e454244ea2e58d | |||
v1.0 | instruct | Filter | Filter_48136_I | How can I implement a real-time stock price checker in Python that updates every 5 seconds? | import requests
import time
def get_stock_price(symbol):
"""
Fetches the stock price for the given symbol from a financial API.
:param symbol: The stock symbol to check the price for.
:return: The current stock price.
"""
# Note: Replace with actual API endpoint and API key
URL = f"htt... | import time
from unittest.mock import patch, MagicMock
from solution import get_stock_price
@patch('solution.requests.get')
def test_get_stock_price(mock_get):
# Mock API response
mock_response = MagicMock()
mock_response.json.return_value = {'price': 150.0}
mock_get.return_value = mock_response
... | [
{
"docstring": "Fetches the stock price for the given symbol from a financial API.\n\n:param symbol: The stock symbol to check the price for.\n:return: The current stock price.",
"function_declaration": "def get_stock_price(symbol):",
"function_name": "get_stock_price",
"parameter_list": "(symbol)"
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport time\n\ndef get_stock_price(symbol):\n \"\"\"\n Fetches the stock price for the given symbol from a financial API.\n \n :param symbol: The stock symbol to c... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048136",
"row_id": 48136,
"seed_ids": "['Qwen2.5-72B-Instruct_101311']"
} | 0.461138 | Filter_48136 | I | [
"get_stock_price",
"real_time_stock_checker"
] | 2 | [
[
"real_time_stock_checker",
"get_stock_price"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 3e7c70045fbe343abbd766ca757b908fed79ac50 | 94614863457358e3da18a62ce3b3857ba1a8292d | |||
v1.0 | instruct | Filter | Filter_48144_I | Write a Python function to generate the first n Fibonacci numbers, and then modify the function to allow for calculating the nth Fibonacci number using memoization to optimize performance. Additionally, include a feature to calculate the sum of all the even-valued terms among the first n Fibonacci numbers. Provide a br... | def generate_fibonacci(n):
"""
Generates the first n Fibonacci numbers.
"""
if n <= 0:
return []
fib_sequence = [0] * n
fib_sequence[0] = 0
if n > 1:
fib_sequence[1] = 1
for i in range(2, n):
fib_sequence[i] = fib_sequence[i - 1] + fib_sequence[i - 2]
... | from solution import generate_fibonacci, nth_fibonacci_memo, sum_even_fibonacci
def test_generate_fibonacci():
assert generate_fibonacci(0) == []
assert generate_fibonacci(1) == [0]
assert generate_fibonacci(2) == [0, 1]
assert generate_fibonacci(5) == [0, 1, 1, 2, 3]
assert generate_fibonacci(10) ... | [
{
"docstring": "Generates the first n Fibonacci numbers.",
"function_declaration": "def generate_fibonacci(n):",
"function_name": "generate_fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Returns the nth Fibonacci number using memoization.",
"function_declaration": "def nth_fibona... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci(n):\n \"\"\"\n Generates the first n Fibonacci numbers.\n \"\"\"\n fib_sequence = []\n a, b = 0, 1\n while len(fib_sequence) < n:\n fib_sequence.append(a... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048144",
"row_id": 48144,
"seed_ids": "['Qwen2.5-72B-Instruct_101322']"
} | 0.751385 | Filter_48144 | I | [
"generate_fibonacci",
"nth_fibonacci_memo",
"sum_even_fibonacci"
] | 3 | [
[
"sum_even_fibonacci",
"generate_fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8aded1ae3d5facd132210fe1316858d83875ed41 | 7d4aa747941ff482ad6728947408d17af0e62069 | |||
v1.0 | instruct | Filter | Filter_48150_I | Create a python script that reads a CSV file containing a column of email addresses and sends a personalized email to each address using SMTP. The script should be able to handle exceptions and log any errors. The CSV file has a header row, and the column containing email addresses is named 'Email'. Use a fictional SMT... | import csv
import smtplib
import logging
from email.mime.text import MIMEText
# Setup logging
logging.basicConfig(filename='email_sender.log', level=logging.ERROR)
def send_personalized_emails(file_path, smtp_server, smtp_port, smtp_user, smtp_password):
try:
with open(file_path, newline='') as csvfile:
... | import tempfile
import os
import pytest
import smtplib
from unittest.mock import patch, MagicMock
from solution import send_personalized_emails
# Mock SMTP class to prevent actual email sending
class MockSMTP(MagicMock):
def sendmail(self, *args, **kwargs):
pass
@pytest.fixture
def csv_file():
dat... | [
{
"docstring": null,
"function_declaration": "def send_personalized_emails(file_path, smtp_server, smtp_port, smtp_user, smtp_password):",
"function_name": "send_personalized_emails",
"parameter_list": "(file_path, smtp_server, smtp_port, smtp_user, smtp_password)"
},
{
"docstring": null,
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport smtplib\nfrom email.mime.text import MIMEText\nimport logging\n\n# Setup logging\nlogging.basicConfig(filename='email_sender.log', level=logging.ERROR)\n\ndef read_emails_fr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048150",
"row_id": 48150,
"seed_ids": "['Qwen2.5-72B-Instruct_101336']"
} | 0.59868 | Filter_48150 | I | [
"send_personalized_emails",
"send_email"
] | 2 | [
[
"send_personalized_emails",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 545ca301a17f5edcf9b6373d2de481644f03be91 | 6003f041082904a1fc9fd9aefede3700c0a53337 | |||
v1.0 | instruct | Filter | Filter_48154_I | Create a Python function that generates a random integer between 1 and 100 and checks if it is a prime number. The function should return a tuple containing the generated number and a boolean indicating whether or not it is a prime number. Use the function to generate and test 10 random numbers, and print the results. | import random
def is_prime(n):
"""
Check if a number n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import is_prime, generate_and_check_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(97) == True
assert is_prime(9... | [
{
"docstring": "Check if a number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a random integer between 1 and 100 and check if it is prime.\nReturns a tuple (number, is_prime).",
"funct... | [
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 is_prime(n):\n \"\"\"\n Check if the number n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048154",
"row_id": 48154,
"seed_ids": "['Qwen2.5-72B-Instruct_101341']"
} | 0.629803 | Filter_48154 | I | [
"is_prime",
"generate_and_check_prime"
] | 2 | [
[
"generate_and_check_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 662aedbc30881bad95e18e72314cdccf745e8a6d | 737a477cbbd692e23c145dcf6fbc03cbbe1abe38 | |||
v1.0 | instruct | Filter | Filter_48166_I | Write a program in Python that reads a file, tokenizes the content into words, and counts the frequency of each word. The program should then print the top 10 most frequent words along with their counts. Assume the file contains plain text and consider words to be sequences of characters separated by spaces. Ignore cas... | from collections import Counter
import re
def read_file(filepath):
"""
Reads the content of the file specified by `filepath`.
Parameters:
- filepath: str, path to the file
Returns:
- str, content of the file
"""
with open(filepath, 'r') as file:
return file.read()
def... | import pytest
from solution import read_file, tokenize, count_word_frequencies, top_n_frequent_words
def test_tokenize():
text = "Hello, hello world! This is a test. Test."
expected_tokens = ['hello', 'hello', 'world', 'this', 'is', 'a', 'test', 'test']
assert tokenize(text) == expected_tokens
def test_co... | [
{
"docstring": "Reads the content of the file specified by `filepath`.\n\nParameters:\n- filepath: str, path to the file\n\nReturns:\n- str, content of the file",
"function_declaration": "def read_file(filepath):",
"function_name": "read_file",
"parameter_list": "(filepath)"
},
{
"docstring"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport re\n\ndef read_file(filepath):\n \"\"\"\n Reads the content of the file specified by `filepath`.\n \n Parameters:\n - filepath: str, path... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048166",
"row_id": 48166,
"seed_ids": "['Qwen2.5-72B-Instruct_101358']"
} | 0.756082 | Filter_48166 | I | [
"read_file",
"tokenize",
"count_word_frequencies",
"top_n_frequent_words"
] | 4 | [
[
"top_n_frequent_words",
"count_word_frequencies"
],
[
"top_n_frequent_words",
"read_file"
],
[
"top_n_frequent_words",
"tokenize"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e9ef2181585fa70d33a11e37b237a97dea12676c | f27d4462cf16eee2b76b9786162c1e833bc8987c | |||
v1.0 | instruct | Filter | Filter_48169_I | Create a Python function that sorts a given list of tuples based on the second element of each tuple in descending order. The function should be named `sort_by_second_desc` and it should take a list of tuples as its only argument. Additionally, write a check function named `verify_sort` that takes a list of tuples (inp... | def sort_by_second_desc(tuples_list):
"""
Sorts a given list of tuples based on the second element of each tuple in descending order.
"""
return sorted(tuples_list, key=lambda x: x[1], reverse=True)
def verify_sort(input_list, expected_list):
"""
Verifies that the sort_by_second_desc function s... | from solution import sort_by_second_desc, verify_sort
def test_sort_by_second_desc():
# Test case 1: Normal case
input_list = [(1, 3), (4, 1), (2, 2), (3, 5)]
expected_list = [(3, 5), (1, 3), (2, 2), (4, 1)]
actual_list = sort_by_second_desc(input_list)
assert actual_list == expected_list
def test... | [
{
"docstring": "Sorts a given list of tuples based on the second element of each tuple in descending order.",
"function_declaration": "def sort_by_second_desc(tuples_list):",
"function_name": "sort_by_second_desc",
"parameter_list": "(tuples_list)"
},
{
"docstring": "Verifies that the sort_b... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sort_by_second_desc(tuples_list):\n \"\"\"\n Sorts a given list of tuples based on the second element of each tuple in descending order.\n \"\"\"\n return sorted(tuples_list, k... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048169",
"row_id": 48169,
"seed_ids": "['Qwen2.5-72B-Instruct_101365']"
} | 0.728396 | Filter_48169 | I | [
"sort_by_second_desc",
"verify_sort"
] | 2 | [
[
"verify_sort",
"sort_by_second_desc"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b7a55d140ce0686c93cebadb5cad2eab69d6828b | a92db2ea49851cb7c50d19c8ef9dbd3617fb7b13 | |||
v1.0 | instruct | Filter | Filter_48174_I | I'm trying to create a simple web application using Flask that displays a form for users to input a URL. After the user submits the form, the application should check if the URL is valid and display a message indicating whether it is valid or not. Can you provide a basic code example to achieve this? | from flask import Flask, request, render_template_string
app = Flask(__name__)
def is_valid_url(url):
import re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost... | from solution import is_valid_url
def test_is_valid_url():
assert is_valid_url("http://example.com") == True
assert is_valid_url("https://example.com") == True
assert is_valid_url("ftp://example.com") == True
assert is_valid_url("http://localhost") == True
assert is_valid_url("http://123.123.123.12... | [
{
"docstring": null,
"function_declaration": "def is_valid_url(url):",
"function_name": "is_valid_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template_string\nfrom urllib.parse import urlparse\n\napp = Flask(__name__)\n\nform_html = \"\"\"\n<!DOCTYPE html>\n<html>\n<head>\n <title>URL Valida... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048174",
"row_id": 48174,
"seed_ids": "['Qwen2.5-72B-Instruct_101374']"
} | 0.543016 | Filter_48174 | I | [
"is_valid_url",
"index"
] | 2 | [
[
"index",
"is_valid_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 536fe023972df6520438a04823ff38d94e827f59 | 041420b9ca6f4ec451d717973057c8b4267c941c | |||
v1.0 | instruct | Filter | Filter_48238_I | I need to understand how to implement a basic neural network using PyTorch. Can you guide me through the process? | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Step 1: Define the Dataset
def generate_data():
# Dummy data: y = 2 * x + 1
x = torch.linspace(-10, 10, 100).view(-1, 1)
y = 2 * x + 1
return x, y
# Step 2: Define the Neural Network... | import torch
from solution import SimpleNN, run_training_pipeline
def test_generate_data():
x, y = generate_data()
assert x.shape == y.shape
assert x.shape == (100, 1)
def test_model_initialization():
model = SimpleNN()
assert isinstance(model, nn.Module)
assert hasattr(model, 'linear')
def t... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n# Define the neural network class\nclass SimpleNN(nn.Module):\n def __init__(self):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048238",
"row_id": 48238,
"seed_ids": "['Qwen2.5-72B-Instruct_101488']"
} | 0.283379 | Filter_48238 | I | [
"generate_data",
"train_model",
"run_training_pipeline"
] | 3 | [
[
"run_training_pipeline",
"generate_data"
],
[
"run_training_pipeline",
"train_model"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 407f6fedc5e9038850d5b175238abfdbb7846a9e | eef71f711f1d435a99969e8b631ee02a261e7783 | |||
v1.0 | instruct | Filter | Filter_48241_I | Write a Python function that generates a list of 10 random numbers between 1 and 100, and then find the second largest number in that list. Return the second largest number. | import random
def generate_random_numbers():
"""
Generates a list of 10 random numbers between 1 and 100.
"""
return [random.randint(1, 100) for _ in range(10)]
def find_second_largest(numbers):
"""
Returns the second largest number in a list.
"""
unique_numbers = list(set(numbers))
... | from solution import find_second_largest, generate_random_numbers, get_second_largest_random_number
def test_generate_random_numbers_length():
assert len(generate_random_numbers()) == 10
def test_generate_random_numbers_range():
numbers = generate_random_numbers()
assert all(1 <= num <= 100 for num in num... | [
{
"docstring": "Generates a list of 10 random numbers between 1 and 100.",
"function_declaration": "def generate_random_numbers():",
"function_name": "generate_random_numbers",
"parameter_list": "()"
},
{
"docstring": "Returns the second largest number in a list.",
"function_declaration"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_numbers():\n \"\"\"\n Generates a list of 10 random numbers between 1 and 100.\n \"\"\"\n return [random.randint(1, 100) for _ in range(10)]\n\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048241",
"row_id": 48241,
"seed_ids": "['Qwen2.5-72B-Instruct_101491']"
} | 0.626318 | Filter_48241 | I | [
"generate_random_numbers",
"find_second_largest",
"get_second_largest_random_number"
] | 3 | [
[
"get_second_largest_random_number",
"find_second_largest"
],
[
"get_second_largest_random_number",
"generate_random_numbers"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 60693c72f8424260a60f2c37c8385faf5e4d381e | eb655fd53ef862f32adf4c922fefcdbabd6952e4 | |||
v1.0 | instruct | Filter | Filter_48253_I | How can I create a Python script that checks if a specific website is up and running? I want the script to send an email notification if the website is down. | import smtplib
import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def check_website(url):
"""
Checks if the specified website is up and running.
"""
try:
response = requests.get(url, timeout=10)
return response.status_code == 200
exce... | import pytest
from unittest.mock import patch
from solution import check_website, send_email_notification, notify_if_website_down
@patch('requests.get')
def test_check_website_up(mock_get):
mock_get.return_value.status_code = 200
assert check_website("http://example.com") == True
@patch('requests.get')
def te... | [
{
"docstring": "Checks if the specified website is up and running.",
"function_declaration": "def check_website(url):",
"function_name": "check_website",
"parameter_list": "(url)"
},
{
"docstring": "Sends an email notification.",
"function_declaration": "def send_email_notification(to_em... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nimport requests\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef is_website_up(url):\n \"\"\"\n Checks if the website is up an... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048253",
"row_id": 48253,
"seed_ids": "['Qwen2.5-72B-Instruct_101512']"
} | 0.547182 | Filter_48253 | I | [
"check_website",
"send_email_notification",
"notify_if_website_down"
] | 3 | [
[
"notify_if_website_down",
"check_website"
],
[
"notify_if_website_down",
"send_email_notification"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 290fb12d10bebcfbfa4f92f1f56329f6e277fbca | 54d75bb05c6e181b8f7b237e61291fd313bd6888 | |||
v1.0 | instruct | Filter | Filter_48282_I | How can I implement a simple recommendation system for a movie streaming service using Python and collaborative filtering? | import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import pairwise_distances
def calculate_similarity(ratings_matrix):
"""
Calculate the cosine similarity between users.
"""
similarity_matrix = cosine_similarity(ratings_matrix)
np.fill... | import numpy as np
import pytest
from solution import calculate_similarity, predict_ratings, recommend_movies
def test_calculate_similarity():
ratings_matrix = np.array([[4, 0, 0, 5, 1, 0, 0],
[5, 5, 4, 0, 0, 0, 0],
[0, 0, 0, 2, 4, 5, 0],
... | [
{
"docstring": "Calculate the cosine similarity between users.",
"function_declaration": "def calculate_similarity(ratings_matrix):",
"function_name": "calculate_similarity",
"parameter_list": "(ratings_matrix)"
},
{
"docstring": "Predict ratings for each user.",
"function_declaration": ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndef recommend_movies(user_movie_matrix, target_user_index, num_recommendations):\n \"\"\"\n Recommends movie... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048282",
"row_id": 48282,
"seed_ids": "['Qwen2.5-72B-Instruct_101555']"
} | 0.379623 | Filter_48282 | I | [
"calculate_similarity",
"predict_ratings",
"recommend_movies"
] | 3 | [
[
"recommend_movies",
"predict_ratings"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 6ffa059227a2e61f48808aef36ced45c6cd35fdb | f960561777717a81764c235c44a9fbcfb3f8b69c | |||
v1.0 | instruct | Filter | Filter_48299_I | Write a Python script that reads a text file, counts the number of words, and outputs the 10 most common words along with their counts. Assume the text file contains a typical English text, and you should ignore case sensitivity and punctuation. | import re
from collections import Counter
def read_file(file_path):
"""
Reads the content of the file at the given file path and returns it as a string.
"""
with open(file_path, 'r') as file:
return file.read()
def count_words(text):
"""
Counts the number of words in the given text, ig... | import pytest
from solution import read_file, count_words, most_common_words, get_most_common_words
def test_read_file(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("Hello world! This is a test file.")
content = read_file(test_file)
assert content == "Hello world! This is a tes... | [
{
"docstring": "Reads the content of the file at the given file path and returns it as a string.",
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Counts the number of words in the given text, ignoring case... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import Counter\n\ndef read_and_count_words(file_path):\n \"\"\"\n Reads a text file, counts the number of words, and returns the top 10 most common words and ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048299",
"row_id": 48299,
"seed_ids": "['Qwen2.5-72B-Instruct_101584']"
} | 0.757766 | Filter_48299 | I | [
"read_file",
"count_words",
"most_common_words",
"get_most_common_words"
] | 4 | [
[
"get_most_common_words",
"count_words"
],
[
"get_most_common_words",
"most_common_words"
],
[
"get_most_common_words",
"read_file"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7b42315494a67ce66e8227bf491f51de04fc516e | 0288b5f66e5ec046c48f80d3b9eb16d8c247ef26 | |||
v1.0 | instruct | Filter | Filter_48339_I | Write a Python program that can encode a message using a simple Caesar cipher. The program should accept a string and a shift value as inputs and return the encoded message. Additionally, the program should be able to decode the message back to its original form when given the encoded message and the shift value. Ensur... | def caesar_cipher_encode(message, shift):
"""
Encodes the given message using the Caesar cipher with the specified shift.
Parameters:
- message: The input string message to encode.
- shift: The number by which to shift each letter.
Returns:
- The encoded message.
"""
encode... | from solution import caesar_cipher_encode, caesar_cipher_decode
def test_encode_lowercase():
assert caesar_cipher_encode("abc", 3) == "def"
def test_encode_uppercase():
assert caesar_cipher_encode("XYZ", 3) == "ABC"
def test_encode_with_wraparound():
assert caesar_cipher_encode("xyz", 3) == "abc"
de... | [
{
"docstring": "Encodes the given message using the Caesar cipher with the specified shift.\n\nParameters:\n- message: The input string message to encode.\n- shift: The number by which to shift each letter.\n\nReturns:\n- The encoded message.",
"function_declaration": "def caesar_cipher_encode(message, shif... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encode(message, shift):\n \"\"\"\n Encodes the message using a Caesar cipher with the given shift.\n \"\"\"\n encoded_message = []\n \n for char in message:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048339",
"row_id": 48339,
"seed_ids": "['Qwen2.5-72B-Instruct_101651']"
} | 0.675476 | Filter_48339 | I | [
"caesar_cipher_encode",
"caesar_cipher_decode"
] | 2 | [
[
"caesar_cipher_decode",
"caesar_cipher_encode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61d35de3cae5bfd651fee34554b16e64df8e5ff2 | 4a646542d87718bcc87ea73365d8e6ef89438ffb | |||
v1.0 | instruct | Filter | Filter_48353_I | I need to create a Python script that can take in a list of numbers and return the mean, median, and mode of the list. Can you provide a sample script for this? | from collections import Counter
import statistics
def calculate_mean(numbers):
"""
Returns the mean of the list of numbers.
"""
return sum(numbers) / len(numbers)
def calculate_median(numbers):
"""
Returns the median of the list of numbers.
"""
numbers_sorted = sorted(numbers)
n = ... | from solution import calculate_mean, calculate_median, calculate_mode, calculate_statistics
def test_calculate_mean():
assert calculate_mean([1, 2, 3, 4, 5]) == 3
assert calculate_mean([10, 20, 30, 40, 50]) == 30
assert abs(calculate_mean([1.5, 2.5, 3.5, 4.5, 5.5]) - 3.5) < 1e-9
def test_calculate_median(... | [
{
"docstring": "Returns the mean of the list of numbers.",
"function_declaration": "def calculate_mean(numbers):",
"function_name": "calculate_mean",
"parameter_list": "(numbers)"
},
{
"docstring": "Returns the median of the list of numbers.",
"function_declaration": "def calculate_media... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from statistics import mean, median, mode\n\ndef calculate_statistics(numbers):\n \"\"\"\n Returns the mean, median, and mode of a list of numbers.\n \n If there are multiple modes... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048353",
"row_id": 48353,
"seed_ids": "['Qwen2.5-72B-Instruct_101670']"
} | 0.751983 | Filter_48353 | I | [
"calculate_mean",
"calculate_median",
"calculate_mode",
"calculate_statistics"
] | 4 | [
[
"calculate_statistics",
"calculate_mean"
],
[
"calculate_statistics",
"calculate_median"
],
[
"calculate_statistics",
"calculate_mode"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1dcbe583bc6d6eaaa1804f4af5afd3668936c208 | 3fc03bfd0c784f9291a524ca33aa167e7c20e705 | |||
v1.0 | instruct | Filter | Filter_48359_I | Write a Python function `find_max` that takes a list of numerical values and returns the maximum value found in the list. Ensure your function can handle an empty list scenario by returning `None` in such cases. Additionally, include a simple check function `verify_find_max` that tests the `find_max` function with pred... | def find_max(numbers):
"""
Returns the maximum value from the list of numerical values.
If the list is empty, return None.
"""
if not numbers:
return None
return max(numbers)
def verify_find_max():
assert find_max([1, 2, 3, 4, 5]) == 5
assert find_max([-10, -5, -2, -1]) == -1
... | from solution import find_max
def test_find_max_with_positive_numbers():
assert find_max([1, 3, 5, 7, 9]) == 9
def test_find_max_with_negative_numbers():
assert find_max([-10, -20, -30, -5]) == -5
def test_find_max_with_single_element():
assert find_max([10]) == 10
def test_find_max_with_empty_list():
... | [
{
"docstring": "Returns the maximum value from the list of numerical values.\nIf the list is empty, return None.",
"function_declaration": "def find_max(numbers):",
"function_name": "find_max",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def verify_find... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_max(lst):\n \"\"\"\n Returns the maximum value in the list. If the list is empty, returns None.\n \"\"\"\n if not lst:\n return None\n return max(lst)\n\ndef ver... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048359",
"row_id": 48359,
"seed_ids": "['Qwen2.5-72B-Instruct_101681']"
} | 0.720362 | Filter_48359 | I | [
"find_max",
"verify_find_max"
] | 2 | [
[
"verify_find_max",
"find_max"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 24d8cfa48d12951729949096699fd37d2e279827 | bccade7c6e61659b44eca9eca54beae1c464d542 | |||
v1.0 | instruct | Filter | Filter_48367_I | How can I generate a 3D model of a house from a set of 2D images using Python? | import cv2
import numpy as np
from pathlib import Path
def load_images(image_dir):
"""
Load images from a directory.
:param image_dir: Path to the directory containing images.
:return: List of loaded images.
"""
image_paths = sorted(Path(image_dir).glob("*.jpg"))
images = [cv2.imread(s... | import os
import pytest
from solution import load_images, detect_and_match_features, create_3d_point_cloud, generate_3d_model
def test_load_images(tmp_path):
# Setup
img = np.zeros((100, 100, 3), dtype=np.uint8)
for i in range(3):
cv2.imwrite(str(tmp_path / f"test{i}.jpg"), img)
# Test
... | [
{
"docstring": "Load images from a directory.\n\n:param image_dir: Path to the directory containing images.\n:return: List of loaded images.",
"function_declaration": "def load_images(image_dir):",
"function_name": "load_images",
"parameter_list": "(image_dir)"
},
{
"docstring": "Detect and ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef generate_3d_model_from_2d_images(images):\n \"\"\"\n Generates a 3D m... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048367",
"row_id": 48367,
"seed_ids": "['Qwen2.5-72B-Instruct_101692']"
} | 0.347649 | Filter_48367 | I | [
"load_images",
"detect_and_match_features",
"create_3d_point_cloud",
"generate_3d_model"
] | 4 | [
[
"generate_3d_model",
"create_3d_point_cloud"
],
[
"generate_3d_model",
"detect_and_match_features"
],
[
"generate_3d_model",
"load_images"
]
] | 3 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 01af2cc6d3e53741135386ecf4c7312a2cb15ab6 | 7dc6b6bd6b568d75291ef0c8e61d2f303e7714e8 | |||
v1.0 | instruct | Filter | Filter_48377_I | Write a program to implement a simple Caesar cipher encryption and decryption. The program should accept a string and a shift value as input and output the encrypted and decrypted strings. The shift value should be between 1 and 25. Handle uppercase and lowercase letters appropriately, and leave non-alphabet characters... | def caesar_encrypt(text, shift):
"""
Encrypts the given text using Caesar cipher with a shift.
Parameters:
text (str): The text to be encrypted.
shift (int): The shift value.
Returns:
str: The encrypted text.
"""
encrypted_text = []
for char in text:
if cha... | from solution import caesar_encrypt, caesar_decrypt
def test_caesar_encrypt():
assert caesar_encrypt("hello", 3) == "khoor"
assert caesar_encrypt("HELLO", 3) == "KHOOR"
assert caesar_encrypt("Hello, World!", 5) == "Mjqqt, Btwqi!"
assert caesar_encrypt("abc", 27) == "bcd" # shift greater than 26
def t... | [
{
"docstring": "Encrypts the given text using Caesar cipher with a shift.\n\nParameters:\ntext (str): The text to be encrypted.\nshift (int): The shift value.\n\nReturns:\nstr: The encrypted text.",
"function_declaration": "def caesar_encrypt(text, shift):",
"function_name": "caesar_encrypt",
"param... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"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 provided shift.\n \n Parameters:\n text (str): The input string to encryp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048377",
"row_id": 48377,
"seed_ids": "['Qwen2.5-72B-Instruct_101706']"
} | 0.62445 | Filter_48377 | I | [
"caesar_encrypt",
"caesar_decrypt"
] | 2 | [
[
"caesar_decrypt",
"caesar_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8adbfc5448a717ebd199cb8721d793f270ad6c6b | 12692ef6d050cfe770babc95307a6c12e48e3148 | |||
v1.0 | instruct | Filter | Filter_48397_I | Write a Python function to simulate the rolling of two six-sided dice and calculate the sum of the two dice. The function should simulate the roll and return the sum. Additionally, create a loop to simulate 1000 rolls and count how many times each possible sum (2 through 12) occurs. Print the results in a readable form... | import random
from collections import Counter
def roll_two_dice():
"""
Simulates rolling two six-sided dice and returns the sum of the two dice.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def simulate_rolls(num_rolls):
"""
Simulates rolling two dice ... | from solution import roll_two_dice, simulate_rolls
def test_roll_two_dice_range():
for _ in range(100):
result = roll_two_dice()
assert 2 <= result <= 12
def test_simulate_rolls_output(capsys):
simulate_rolls(1000)
captured = capsys.readouterr()
output_lines = captured.out.strip().spli... | [
{
"docstring": "Simulates rolling two six-sided dice and returns the sum of the two dice.",
"function_declaration": "def roll_two_dice():",
"function_name": "roll_two_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates rolling two dice 'num_rolls' times and counts the occurrence of ea... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling two six-sided dice and returns the sum.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048397",
"row_id": 48397,
"seed_ids": "['Qwen2.5-72B-Instruct_101741']"
} | 0.664783 | Filter_48397 | I | [
"roll_two_dice",
"simulate_rolls"
] | 2 | [
[
"simulate_rolls",
"roll_two_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 131cb0e82c8fbb301cf8f5e4a2a46b49a876038a | f26953e7aad345f46047cef779a0f7ea5ea3380c | |||
v1.0 | instruct | Filter | Filter_48406_I | How can I create a Python script that automatically sends an email when a specific condition is met in a dataset? | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd
def check_condition_and_send_email(dataset, column, threshold, email_info):
"""
Checks if any value in the specified column exceeds the threshold.
If the condition is met, sends an email n... | import pandas as pd
from unittest.mock import patch
from solution import check_condition_and_send_email
@patch('solution.send_email')
def test_check_condition_and_send_email_condition_met(mock_send_email):
dataset = pd.DataFrame({'values': [10, 20, 30, 40]})
email_info = {
'sender_email': 'your_email@e... | [
{
"docstring": "Checks if any value in the specified column exceeds the threshold.\nIf the condition is met, sends an email notification.\n\nParameters:\n- dataset: pd.DataFrame\n- column: str\n- threshold: float\n- email_info: dict with keys 'sender_email', 'receiver_email', 'smtp_server', 'smtp_port', 'login'... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef send_email(subject, body, to_email, from_email, from_password, smtp_server, smtp_por... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048406",
"row_id": 48406,
"seed_ids": "['Qwen2.5-72B-Instruct_101754']"
} | 0.470779 | Filter_48406 | I | [
"check_condition_and_send_email",
"send_email"
] | 2 | [
[
"check_condition_and_send_email",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 6d0d0f270533baf0a3b799fa2f5197f0361e48ee | 5cb9b80a8964642b693ae110feb3ec877d55cd00 | |||
v1.0 | instruct | Filter | Filter_48411_I | How can I create a Python program to generate random math problems for kids, including addition, subtraction, multiplication, and division, with a user-friendly interface? | import random
def generate_addition_problem():
a = random.randint(0, 10)
b = random.randint(0, 10)
return f"What is {a} + {b}?", a + b
def generate_subtraction_problem():
a = random.randint(0, 10)
b = random.randint(0, a) # ensures non-negative result
return f"What is {a} - {b}?", a - b
def ... | from solution import generate_addition_problem, generate_subtraction_problem, generate_multiplication_problem, generate_division_problem
def test_generate_addition_problem():
problem, answer = generate_addition_problem()
parts = problem.split()
assert parts[0] == "What", "Invalid problem generated"
ass... | [
{
"docstring": null,
"function_declaration": "def generate_addition_problem():",
"function_name": "generate_addition_problem",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_subtraction_problem():",
"function_name": "generate_subtraction_problem"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_addition_problem():\n a = random.randint(0, 10)\n b = random.randint(0, 10)\n return f\"What is {a} + {b}?\", a + b\n\ndef generate_subtraction_problem()... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048411",
"row_id": 48411,
"seed_ids": "['Qwen2.5-72B-Instruct_101762']"
} | 0.510946 | Filter_48411 | I | [
"generate_addition_problem",
"generate_subtraction_problem",
"generate_multiplication_problem",
"generate_division_problem",
"generate_random_math_problem",
"user_friendly_interface"
] | 6 | [
[
"generate_random_math_problem",
"generate_addition_problem"
],
[
"generate_random_math_problem",
"generate_division_problem"
],
[
"generate_random_math_problem",
"generate_multiplication_problem"
],
[
"generate_random_math_problem",
"generate_subtraction_problem"
],
... | 5 | [] | false | [] | false | pytest | true | [] | true | 05c5b16ef107726c22d5d43431bf5ff8a2144d08 | 0c59a63213d91057f869bdfaca56c7c5d685df50 | |||
v1.0 | instruct | Filter | Filter_48455_I | Write a program that can convert temperatures from Celsius to Fahrenheit and vice versa. The program should prompt the user to choose the conversion direction and then input the temperature value. After the conversion, the program should display the result. Make sure to include error handling for invalid input. | def celsius_to_fahrenheit(celsius):
"""
Converts Celsius to Fahrenheit.
"""
return celsius * 9/5 + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Converts Fahrenheit to Celsius.
"""
return (fahrenheit - 32) * 5/9
def convert_temperature(direction, temperature):
"""
Converts temp... | from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, convert_temperature
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenheit(-40) == -40
def test_fahrenheit_to_celsius():
assert fahrenheit_to_celsiu... | [
{
"docstring": "Converts Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Converts Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Converts Celsius to Fahrenheit.\n \"\"\"\n return (celsius * 9/5) + 32\n\ndef fahrenheit_to_celsius(fahrenheit):\n \"\"\"\n Con... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048455",
"row_id": 48455,
"seed_ids": "['Qwen2.5-72B-Instruct_101839']"
} | 0.437756 | Filter_48455 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"convert_temperature"
] | 3 | [
[
"convert_temperature",
"celsius_to_fahrenheit"
],
[
"convert_temperature",
"fahrenheit_to_celsius"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b9b62d8fbe9d155e10e0f275079425e63d38602e | 488ee27f4b230a923d473f2febeaf707505d1db1 | |||
v1.0 | instruct | Filter | Filter_48460_I | How can I create a Python script that can find and print all the prime numbers between 1 and 1000? | def is_prime(n):
"""
Check if a number is prime.
:param n: Integer to check for primality
:return: Boolean, True if n 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 = 5
while (i... | from solution import is_prime, find_primes_between_1_and_1000
def test_is_prime():
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
def test_fin... | [
{
"docstring": "Check if a number is prime.\n\n:param n: Integer to check for primality\n:return: Boolean, True if n is prime, False otherwise",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find and return a list of all p... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_primes_up_to_1000():\n \"\"\"\n Returns a list of all prime numbers between 1 and 1000.\n \"\"\"\n def is_prime(n):\n if n <= 1:\n return False\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048460",
"row_id": 48460,
"seed_ids": "['Qwen2.5-72B-Instruct_101850']"
} | 0.625295 | Filter_48460 | I | [
"is_prime",
"find_primes_between_1_and_1000",
"print_primes_between_1_and_1000"
] | 3 | [
[
"find_primes_between_1_and_1000",
"is_prime"
],
[
"print_primes_between_1_and_1000",
"find_primes_between_1_and_1000"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3350e3f9ec259bcd4f3c4570e9b44983d79555f3 | 45bae1e9da8210c4521c0a658f373c42887b70df | |||
v1.0 | instruct | Filter | Filter_48462_I | I need to write a Python function that can read a CSV file and then clean the data. The CSV file has a column with text data that needs to be processed. The specific task is to remove any HTML tags that might be present in the text of each row in this column. How can I achieve this using Python? | import csv
import re
def clean_html_tags(text):
"""
Removes HTML tags from a given text.
"""
clean = re.compile('<.*?>')
return re.sub(clean, '', text)
def clean_csv_html(input_csv, output_csv, text_column):
"""
Reads a CSV file, cleans HTML tags from the specified text column,
and wri... | import tempfile
import os
import csv
from solution import clean_html_tags, clean_csv_html
def write_temp_csv(content):
fd, path = tempfile.mkstemp(suffix=".csv", text=True)
with os.fdopen(fd, 'w', newline='', encoding='utf-8') as tmp:
writer = csv.writer(tmp)
for row in content:
wri... | [
{
"docstring": "Removes HTML tags from a given text.",
"function_declaration": "def clean_html_tags(text):",
"function_name": "clean_html_tags",
"parameter_list": "(text)"
},
{
"docstring": "Reads a CSV file, cleans HTML tags from the specified text column,\nand writes the cleaned data to a ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nimport pandas as pd\n\ndef remove_html_tags(text):\n \"\"\"\n Remove html tags from a string\n \"\"\"\n clean = re.compile('<.*?>')\n return re.sub(clean, '', text)\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048462",
"row_id": 48462,
"seed_ids": "['Qwen2.5-72B-Instruct_101852']"
} | 0.624586 | Filter_48462 | I | [
"clean_html_tags",
"clean_csv_html"
] | 2 | [
[
"clean_csv_html",
"clean_html_tags"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d548d28a1a13a9db5b5647dbeb497e025f765a15 | 9151e8f0c658c9e2714464875668a38d88cb7d34 | |||
v1.0 | instruct | Filter | Filter_48476_I | Write a python function to generate a random number between 1 and 100, and then check if the number is a prime number. The function should return the number and a boolean indicating whether it is prime. | import random
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
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
re... | from solution import is_prime, generate_and_check_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(12) == False
assert is_prime(1) == False
assert is_prime(... | [
{
"docstring": "Check if a number is prime.\n\nArgs:\n- n (int): The number to check.\n\nReturns:\n- bool: True if the number is prime, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a random num... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_number_and_check_prime():\n \"\"\"\n Generates a random number between 1 and 100, and checks if it is a prime number.\n \n Returns:\n tuple:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048476",
"row_id": 48476,
"seed_ids": "['Qwen2.5-72B-Instruct_101874']"
} | 0.689796 | Filter_48476 | I | [
"is_prime",
"generate_and_check_prime"
] | 2 | [
[
"generate_and_check_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f5d2a37ee089faa66e4079955aec9f147b9fd9f | 27392a238f88831da1ba84b3e9bdd9b898563b43 | |||
v1.0 | instruct | Filter | Filter_48477_I | How can I design a basic chatbot using Python and Flask for a customer service application? | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return "Welcome to the Customer Service Chatbot!"
@app.route('/chatbot', methods=['POST'])
def chatbot():
user_input = request.json.get('message')
if not user_input:
return jsonify({'respo... | import pytest
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_home(client):
"""Test the home route"""
rv = client.get('/')
assert rv.status_code == 200
assert b"Welcome to the Customer Service Chatbot!" in rv.data
def test_cha... | [
{
"docstring": null,
"function_declaration": "def home():",
"function_name": "home",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def chatbot():",
"function_name": "chatbot",
"parameter_list": "()"
},
{
"docstring": "Generate a simple response b... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\ndef get_response(user_input):\n \"\"\"\n Returns a response based on the user_input.\n \"\"\"\n user_input = u... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048477",
"row_id": 48477,
"seed_ids": "['Qwen2.5-72B-Instruct_101875']"
} | 0.384467 | Filter_48477 | I | [
"home",
"chatbot",
"generate_response"
] | 3 | [
[
"chatbot",
"generate_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 586dc7a4d721f5adee2b47dcd9347d6dd7168062 | e68d05bfaed9c00337b32b15d71165b20eb61ac5 | |||
v1.0 | instruct | Filter | Filter_48515_I | Write a Python function that takes a list of integers as input and returns a new list with each element decremented by 10. Ensure your code is self-contained and imports all necessary packages. The function should be named `decrement_list` and include a docstring explaining its purpose. Additionally, provide a check fu... | def decrement_list(input_list):
"""
Takes a list of integers and returns a new list with each element decremented by 10.
Parameters:
input_list (list of int): The list of integers to be decremented.
Returns:
list of int: A new list with each integer decremented by 10.
"""
retur... | from solution import decrement_list, verify_results
def test_decrement_list_example_1():
assert decrement_list([10, 20, 30]) == [0, 10, 20]
def test_decrement_list_example_2():
assert decrement_list([15, -5, 0]) == [5, -15, -10]
def test_decrement_list_example_3():
assert decrement_list([]) == []
def te... | [
{
"docstring": "Takes a list of integers and returns a new list with each element decremented by 10.\n\nParameters:\ninput_list (list of int): The list of integers to be decremented.\n\nReturns:\nlist of int: A new list with each integer decremented by 10.",
"function_declaration": "def decrement_list(input... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def decrement_list(lst):\n \"\"\"\n Takes a list of integers and returns a new list with each element decremented by 10.\n \n Parameters:\n lst (list of int): The list of intege... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048515",
"row_id": 48515,
"seed_ids": "['Qwen2.5-72B-Instruct_101943']"
} | 0.578206 | Filter_48515 | I | [
"decrement_list",
"verify_results"
] | 2 | [
[
"verify_results",
"decrement_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7909eab5e76f4862060c7b2f61560c8e2892c090 | c5c59a923a1f1d307df504429cae4d358e395b58 | |||
v1.0 | instruct | Filter | Filter_48517_I | Create a Python program that converts temperatures from Celsius to Fahrenheit and vice versa. The user should be able to choose which conversion they want to perform, and the program should validate the user's input to ensure it is a valid temperature and conversion type. If the input is invalid, the program should pro... | def celsius_to_fahrenheit(celsius):
"""
Convert Celsius to Fahrenheit.
"""
return celsius * 9/5 + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Convert Fahrenheit to Celsius.
"""
return (fahrenheit - 32) * 5/9
def convert_temperature(conversion_type, value):
"""
Perform the con... | from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, convert_temperature
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenheit(-40) == -40
def test_fahrenheit_to_celsius():
assert fahrenheit_to_celsiu... | [
{
"docstring": "Convert Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Convert Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius(f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Converts Celsius to Fahrenheit\n \"\"\"\n return (celsius * 9/5) + 32\n\ndef fahrenheit_to_celsius(fahrenheit):\n \"\"\"\n Conv... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048517",
"row_id": 48517,
"seed_ids": "['Qwen2.5-72B-Instruct_101946']"
} | 0.421044 | Filter_48517 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"convert_temperature"
] | 3 | [
[
"convert_temperature",
"celsius_to_fahrenheit"
],
[
"convert_temperature",
"fahrenheit_to_celsius"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 094c2295225bf80271bd9efbce3720d9c7f5e248 | d6ba986cf2f521dc9ebb33de62bbab471576896f | |||
v1.0 | instruct | Filter | Filter_48525_I | I am trying to create a Python script that can download files from a list of URLs and save them to a specific directory on my local machine. Can you provide a basic script that can handle this task? It would be great if the script could also check if the download was successful and log any errors. | import os
import requests
def download_file(url, dest_folder):
"""
Downloads a file from a given URL and saves it to the specified folder.
Args:
url (str): The URL of the file to download.
dest_folder (str): The directory where the file will be saved.
Returns:
bool: True if the do... | from solution import download_file, download_files
import os
def test_download_file_success(monkeypatch):
class MockResponse:
def __init__(self, content=b"test content", status_code=200):
self.content = content
self.status_code = status_code
def raise_for_status... | [
{
"docstring": "Downloads a file from a given URL and saves it to the specified folder.\n\nArgs:\nurl (str): The URL of the file to download.\ndest_folder (str): The directory where the file will be saved.\n\nReturns:\nbool: True if the download was successful, False otherwise.",
"function_declaration": "de... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\n\ndef download_file(url, dest_folder):\n \"\"\"\n Downloads a file from a given URL and saves it to the specified folder.\n \n Args:\n url (str): The... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048525",
"row_id": 48525,
"seed_ids": "['Qwen2.5-72B-Instruct_101962']"
} | 0.611549 | Filter_48525 | I | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 26b1000b0b5931673773125573f4f10a3c3a2efc | f17289adc90913f210bb8e012be014bac020b4dd | |||
v1.0 | instruct | Filter | Filter_48534_I | Create a Python function to calculate the sum of all prime numbers in a given list of integers. If the list does not contain any prime numbers, the function should return 0. For instance, if the input list is [2, 3, 4, 5, 6], the function should return 10, as 2, 3, and 5 are prime numbers, and their sum is 10. | 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 sum_of_primes(numbers):
"""
Returns the sum of all prime numbers in a given list of integers.
"""
return sum(num for num in numbers if is_prim... | from solution import sum_of_primes
def test_sum_of_primes_all_primes():
assert sum_of_primes([2, 3, 5, 7]) == 17
def test_sum_of_primes_mixed():
assert sum_of_primes([2, 3, 4, 5, 6]) == 10
def test_sum_of_primes_no_primes():
assert sum_of_primes([4, 6, 8, 10]) == 0
def test_sum_of_primes_empty_list():
... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers in a given list of integers.",
"function_declaration": "def sum_of_primes(numbers):",
"function_name": "sum_of... | [
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 n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048534",
"row_id": 48534,
"seed_ids": "['Qwen2.5-72B-Instruct_101973']"
} | 0.676462 | Filter_48534 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 83597a0e3796d94bc71112d6c45701ced72fdf1e | 7790e33ad340ef88acff1a84324d787554f91d87 | |||
v1.0 | instruct | Filter | Filter_48545_I | Can you help me with a coding challenge? I need to write a Python program that reads a text file, counts the frequency of each word, and then sorts the words by their frequency in descending order. Finally, I want to print the top 10 most frequent words along with their counts. Can you guide me through this? | from collections import Counter
def read_file(file_path):
"""
Reads the file and returns its content as a string.
"""
with open(file_path, 'r') as file:
return file.read()
def count_word_frequency(text):
"""
Counts the frequency of each word in the given text.
"""
words = text.... | import pytest
from collections import Counter
from solution import count_word_frequency, read_file, get_top_n_words, process_text_file
def test_count_word_frequency():
text = "test word word frequency word count test"
expected_output = Counter({"word": 3, "test": 2, "frequency": 1, "count": 1})
assert coun... | [
{
"docstring": "Reads the file and returns its content as a string.",
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Counts the frequency of each word in the given text.",
"function_declaration": "def ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_word_frequency(file_path):\n \"\"\"\n Reads a text file, counts the frequency of each word,\n and returns a list of tuples with the 10 most frequent words and their counts.\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048545",
"row_id": 48545,
"seed_ids": "['Qwen2.5-72B-Instruct_101986']"
} | 0.731345 | Filter_48545 | I | [
"read_file",
"count_word_frequency",
"get_top_n_words",
"process_text_file"
] | 4 | [
[
"process_text_file",
"count_word_frequency"
],
[
"process_text_file",
"get_top_n_words"
],
[
"process_text_file",
"read_file"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4df430907fcee8b946ee9ea2898d08d1ff28777e | 794170d4bd991744d0c5f625f7c91e3a41c75890 | |||
v1.0 | instruct | Filter | Filter_48557_I | I need help with a coding challenge. I have to create a function in Python that generates the first 10 numbers of the Fibonacci sequence, but I want to do it in a way that each number is computed using a generator, so I can iterate through the sequence without storing all the numbers in memory. Can you show me how to d... | def fibonacci_generator():
"""
Generator function that yields the Fibonacci sequence.
"""
a, b = 0, 1
for _ in range(10):
yield a
a, b = b, a + b
def get_first_10_fibonacci_numbers():
"""
Returns the first 10 numbers of the Fibonacci sequence using the generator.
"""
... | from solution import fibonacci_generator, get_first_10_fibonacci_numbers
def test_fibonacci_generator():
fib_generator = fibonacci_generator()
assert next(fib_generator) == 0
assert next(fib_generator) == 1
assert next(fib_generator) == 1
assert next(fib_generator) == 2
assert next(fib_generato... | [
{
"docstring": "Generator function that yields the Fibonacci sequence.",
"function_declaration": "def fibonacci_generator():",
"function_name": "fibonacci_generator",
"parameter_list": "()"
},
{
"docstring": "Returns the first 10 numbers of the Fibonacci sequence using the generator.",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_generator():\n \"\"\"\n Generator function that yields numbers in the Fibonacci sequence.\n \"\"\"\n a, b = 0, 1\n yield a\n yield b\n while True:\n a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048557",
"row_id": 48557,
"seed_ids": "['Qwen2.5-72B-Instruct_102005']"
} | 0.663794 | Filter_48557 | I | [
"fibonacci_generator",
"get_first_10_fibonacci_numbers"
] | 2 | [
[
"get_first_10_fibonacci_numbers",
"fibonacci_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e01d60ab7d7092e86007f8b12804fb0d81c61728 | 8140739fd0b8f3a9032802824f4d8d57d1ac610e | |||
v1.0 | instruct | Filter | Filter_48561_I | Create a Python function that simulates the rolling of a 6-sided die, where the probability of each side landing face up can be customized. The function should also be able to simulate rolling the die multiple times and return the results as a list of outcomes. | import random
def weighted_roll(weights):
"""
Simulates rolling a 6-sided die with custom probabilities for each side.
Args:
weights (list of float): List of 6 probabilities for each side (1 to 6).
Returns:
int: The result of the die roll (1 to 6).
"""
if len(weights) != 6:
... | from solution import weighted_roll, roll_die_multiple_times
def test_weighted_roll_basic_functionality():
weights = [1/6] * 6 # Fair die
for i in range(100):
result = weighted_roll(weights)
assert 1 <= result <= 6, f"Result out of bounds: {result}"
def test_weighted_roll_invalid_weights():
... | [
{
"docstring": "Simulates rolling a 6-sided die with custom probabilities for each side.\n\nArgs:\nweights (list of float): List of 6 probabilities for each side (1 to 6).\n\nReturns:\nint: The result of the die roll (1 to 6).",
"function_declaration": "def weighted_roll(weights):",
"function_name": "we... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef weighted_die_roll(weights, rolls=1):\n \"\"\"\n Simulates rolling a 6-sided die with customized probabilities.\n \n Args:\n weights (list): A list of 6 elem... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048561",
"row_id": 48561,
"seed_ids": "['Qwen2.5-72B-Instruct_102010']"
} | 0.608181 | Filter_48561 | I | [
"weighted_roll",
"roll_die_multiple_times"
] | 2 | [
[
"roll_die_multiple_times",
"weighted_roll"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b607acc754335151800964f79eefb9d9ba41fd26 | 292ecd5630955759274288e8402c9fedca971a71 | |||
v1.0 | instruct | Filter | Filter_48580_I | Create a Python script that converts a given temperature from Celsius to Fahrenheit and vice versa. The script should take user input for the temperature and the conversion type (C to F or F to C), and then output the converted temperature. Ensure the script handles invalid inputs gracefully. | def celsius_to_fahrenheit(celsius):
"""
Converts Celsius to Fahrenheit.
"""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Converts Fahrenheit to Celsius.
"""
return (fahrenheit - 32) * 5/9
def convert_temperature(value, conversion_type):
"""
Converts th... | def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenheit(-40) == -40
def test_fahrenheit_to_celsius():
assert fahrenheit_to_celsius(32) == 0
assert fahrenheit_to_celsius(212) == 100
assert fahrenheit_to_celsius... | [
{
"docstring": "Converts Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Converts Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Converts Celsius to Fahrenheit.\n \"\"\"\n return (celsius * 9/5) + 32\n\ndef fahrenheit_to_celsius(fahrenheit):\n \"\"\"\n Con... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048580",
"row_id": 48580,
"seed_ids": "['Qwen2.5-72B-Instruct_102034']"
} | 0.401796 | Filter_48580 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"convert_temperature"
] | 3 | [
[
"convert_temperature",
"celsius_to_fahrenheit"
],
[
"convert_temperature",
"fahrenheit_to_celsius"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 1545d3cc1b232215dc6159ed29d134e2acf78a48 | cb776e7f50deeff6d80f050563456d0afa71dfc0 | |||
v1.0 | instruct | Filter | Filter_48616_I | I need to create a Python script that can parse a text file and extract all email addresses and phone numbers from it. How can I do this? | import re
def extract_emails_and_phones(text):
"""
Extracts all email addresses and phone numbers from the input text.
Parameters:
text (str): The input text from which to extract emails and phone numbers.
Returns:
tuple: A tuple of two lists - (emails, phone_numbers)
"""
email_patter... | from solution import extract_emails_and_phones, extract_from_file
def test_extract_emails_and_phones():
text = """Contact us at support@example.com or sales@example.com.
You can also reach us at (123) 456-7890 or 987-654-3210."""
emails, phone_numbers = extract_emails_and_phones(text)
... | [
{
"docstring": "Extracts all email addresses and phone numbers from the input text.\n\nParameters:\ntext (str): The input text from which to extract emails and phone numbers.\n\nReturns:\ntuple: A tuple of two lists - (emails, phone_numbers)",
"function_declaration": "def extract_emails_and_phones(text):",
... | [
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 extract_emails_and_phones(text):\n \"\"\"\n Extracts email addresses and phone numbers from a given text.\n \n Parameters:\n text (str): A string containing the... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048616",
"row_id": 48616,
"seed_ids": "['Qwen2.5-72B-Instruct_102089']"
} | 0.555062 | Filter_48616 | I | [
"extract_emails_and_phones",
"extract_from_file"
] | 2 | [
[
"extract_from_file",
"extract_emails_and_phones"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f53b9b9f3c9187eac2d9abcab2f480292e4bdc1 | 69fd17c69991953fa0f66aa9dee3a4c291165044 | |||
v1.0 | instruct | Filter | Filter_48633_I | How can I implement a function in Python to convert a given string to a Caesar cipher, and then decrypt it back to the original string? Can you also explain the Caesar cipher briefly? | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the given text using the Caesar cipher algorithm.
:param text: The input string to be encrypted.
:param shift: The number of positions to shift each character.
:return: The encrypted string.
"""
encrypted_text = []
for char in text:
... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("HELLO", 3) == "KHOOR"
assert caesar_cipher_encrypt("hello", 3) == "khoor"
assert caesar_cipher_encrypt("HELLO WORLD!", 1) == "IFMMP XPSME!"
assert caesar_cipher_encrypt("abc... | [
{
"docstring": "Encrypts the given text using the Caesar cipher algorithm.\n\n:param text: The input string to be encrypted.\n:param shift: The number of positions to shift each character.\n:return: The encrypted string.",
"function_declaration": "def caesar_cipher_encrypt(text, shift):",
"function_name... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encrypt(text, shift):\n \"\"\"\n Encrypts a given text using Caesar cipher with the specified shift.\n \"\"\"\n encrypted_text = []\n for char in text:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048633",
"row_id": 48633,
"seed_ids": "['Qwen2.5-72B-Instruct_102113']"
} | 0.615343 | Filter_48633 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 144852ee600185db9c2b6155d9b3bc9b97d37e40 | e5084b13c51dac43398cfd8626195419ef6679cd | |||
v1.0 | instruct | Filter | Filter_48651_I | How can I train a basic neural network using PyTorch for a simple regression problem? | import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# Define the simple neural network
class SimpleNN(nn.Module):
def __init__(self, input_dim, output_dim):
super(SimpleNN, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
... | import torch
from solution import SimpleNN, train_model
def test_model_output_shape():
model, X_train, y_train = train_model()
assert X_train.shape == model(X_train).shape, "The shape of model output should match the shape of input X"
def test_linear_relationship():
model, X_train, y_train = train_model()... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Define a simple neural network\nclass SimpleNN(nn.Module):\n def __init__(self, input_dim, hidden_dim, output_dim):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048651",
"row_id": 48651,
"seed_ids": "['Qwen2.5-72B-Instruct_102143']"
} | 0.43147 | Filter_48651 | I | [
"generate_synthetic_data",
"train_model"
] | 2 | [
[
"train_model",
"generate_synthetic_data"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"numpy",
"torch"
] | false | 4d50f278fcef47bb41d5156ebefcbebf46af7437 | 4eaba3335b93702b0b7edd970045579cbcfc872d | |||
v1.0 | instruct | Filter | Filter_48652_I | I want to create a Python function that generates a random number and checks if it is a prime number. If the number is not prime, the function should keep generating new numbers until a prime number is found. Can you help me write this function? | import random
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
... | from solution import is_prime, generate_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(20) == False
assert is_prime(23) == True
assert is_prime(1) == False
assert is_prime(0) == Fal... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a random prime number.",
"function_declaration": "def generate_prime():",
"function_name": "generate_prime",
... | [
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 is_prime(n):\n \"\"\"\n Check if n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048652",
"row_id": 48652,
"seed_ids": "['Qwen2.5-72B-Instruct_102145']"
} | 0.648453 | Filter_48652 | I | [
"is_prime",
"generate_prime"
] | 2 | [
[
"generate_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6860da6ee85acfeac1b331fa199980f2fd2a6c96 | c8126e4cc6ac0889fb3a2863a146a82adec15917 | |||
v1.0 | instruct | Filter | Filter_48664_I | Write a Python program that calculates the product of the lengths of two strings provided by the user, and then determines if the product is a prime number. The program should output the product and whether or not it is a prime number. | def is_prime(n):
"""
Returns True if the given number n is prime, otherwise False.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
p = 3
while p * p <= n:
if n % p == 0:
return False
p += 2
return True... | from solution import is_prime, product_of_lengths_and_prime_check
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(1) == False
assert is_prime(0) == False
def test... | [
{
"docstring": "Returns True if the given number n is prime, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the product of the lengths of str1 and str2 and a boolean indicating if the product is p... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if the given number n is prime, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048664",
"row_id": 48664,
"seed_ids": "['Qwen2.5-72B-Instruct_102162']"
} | 0.777467 | Filter_48664 | I | [
"is_prime",
"product_of_lengths_and_prime_check"
] | 2 | [
[
"product_of_lengths_and_prime_check",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 605f6193125cd620f0f0f1b9f3629fd744b05c40 | 70601874508d00e923aa9aefefa88b82d450800a | |||
v1.0 | instruct | Filter | Filter_48668_I | I'm working on a project that involves generating a large amount of text data for training a machine learning model. I'm using Python for this task. Could you provide me with a script that can generate a specified number of random sentences, each with a random number of words ranging from a minimum to a maximum number ... | import random
import string
def generate_random_sentence(min_words=5, max_words=15):
"""
Generates a random sentence with a random number of words ranging from min_words to max_words.
"""
words = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog",
"and", "the", "dish", "ran",... | from solution import generate_random_sentence, generate_random_sentences
def test_generate_random_sentence():
sentence = generate_random_sentence(5, 15)
words = sentence.strip('.').split()
assert len(words) >= 5
assert len(words) <= 15
assert sentence[0].isupper()
assert sentence[-1] == '.'
de... | [
{
"docstring": "Generates a random sentence with a random number of words ranging from min_words to max_words.",
"function_declaration": "def generate_random_sentence(min_words=5, max_words=15):",
"function_name": "generate_random_sentence",
"parameter_list": "(min_words=5, max_words=15)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_random_word():\n \"\"\"\n Generates a random word.\n \"\"\"\n length = random.randint(3, 10)\n return ''.join(random.choice(string.a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048668",
"row_id": 48668,
"seed_ids": "['Qwen2.5-72B-Instruct_102175']"
} | 0.657885 | Filter_48668 | I | [
"generate_random_sentence",
"generate_random_sentences"
] | 2 | [
[
"generate_random_sentences",
"generate_random_sentence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f140f29bdba503378b259d61d9922012453e83a9 | 82017019978600206867e7b949a06271d91b146a | |||
v1.0 | instruct | Filter | Filter_48675_I | How can I create a simple chatbot using Python and Flask to respond to basic greetings? | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json.get('message', '').strip().lower()
response_message = get_response(user_message)
return jsonify({'response': response_message})
def get_response(message):
if m... | import pytest
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_greeting_hello(client):
response = client.post('/chat', json={'message': 'hello'})
json_data = response.get_json()
assert json_data['response'] == 'Hello! How can I help... | [
{
"docstring": null,
"function_declaration": "def chat():",
"function_name": "chat",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_response(message):",
"function_name": "get_response",
"parameter_list": "(message)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\ndef get_response(message_text):\n \"\"\"\n Returns a response based on the input message text.\n \"\"\"\n mess... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048675",
"row_id": 48675,
"seed_ids": "['Qwen2.5-72B-Instruct_102186']"
} | 0.42109 | Filter_48675 | I | [
"chat",
"get_response"
] | 2 | [
[
"chat",
"get_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | d70d526c2b059958c20d2732b9159481aa53eae1 | 0168ef26086543a1fce86d53cf70aea71cbef95c | |||
v1.0 | instruct | Filter | Filter_48678_I | I need to design a Python function that takes a string and an integer as inputs. The function should encode the string by shifting each letter by the integer value, wrapping around the alphabet if necessary. For example, shifting "a" by 1 results in "b", and shifting "z" by 1 results in "a". The function should handle ... | def shift_char(c, shift):
"""
Shifts a single character by the specified amount, wrapping around the alphabet.
"""
if 'a' <= c <= 'z':
return chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
elif 'A' <= c <= 'Z':
return chr((ord(c) - ord('A') + shift) % 26 + ord('A'))
else:
... | from solution import encode_string
def test_encode_string_all_lowercase():
assert encode_string("abc", 1) == "bcd"
assert encode_string("xyz", 3) == "abc"
def test_encode_string_all_uppercase():
assert encode_string("ABC", 2) == "CDE"
assert encode_string("XYZ", 5) == "CDE"
def test_encode_string_mix... | [
{
"docstring": "Shifts a single character by the specified amount, wrapping around the alphabet.",
"function_declaration": "def shift_char(c, shift):",
"function_name": "shift_char",
"parameter_list": "(c, shift)"
},
{
"docstring": "Encodes the given string by shifting each letter by the spe... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher(s, shift):\n \"\"\"\n Encodes the input string by shifting its letters by the specified integer value.\n Handles both uppercase and lowercase letters, leaving non-al... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048678",
"row_id": 48678,
"seed_ids": "['Qwen2.5-72B-Instruct_102191']"
} | 0.713645 | Filter_48678 | I | [
"shift_char",
"encode_string"
] | 2 | [
[
"encode_string",
"shift_char"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8af1b590f913d8671b2e0e54bd0b25aa47c8919d | b4eefded741ad676ff400d0d7309bd41c3107333 | |||
v1.0 | instruct | Filter | Filter_48683_I | How can I create a simple chatbot using Python and Flask that can answer basic questions about the weather? | from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
# Example to handle basic weather query
def get_weather(description):
api_key = 'YOUR_API_KEY'
base_url = 'http://api.openweathermap.org/data/2.5/weather?'
city_name = 'London' # A fixed city for simplicity
complete_url =... | import pytest
from flask import Flask
from solution import app as flask_app
@pytest.fixture
def client():
with flask_app.test_client() as client:
with flask_app.app_context():
yield client
def test_weather_query(client, monkeypatch):
class MockResponse:
@staticmethod
def js... | [
{
"docstring": null,
"function_declaration": "def get_weather(description):",
"function_name": "get_weather",
"parameter_list": "(description)"
},
{
"docstring": null,
"function_declaration": "def chatbot():",
"function_name": "chatbot",
"parameter_list": "()"
}
] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n# Dummy data for weather responses\nweather_data = {\n \"new york\": \"The weather in New York is sunny with a high of ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048683",
"row_id": 48683,
"seed_ids": "['Qwen2.5-72B-Instruct_102196']"
} | 0.417768 | Filter_48683 | I | [
"get_weather",
"chatbot"
] | 2 | [
[
"chatbot",
"get_weather"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"requests"
] | false | 503f1a9f7225d4eee5847915156ae10cb7b01dfe | b093c8312e6f701c2abaef1daed9e71de2c18a92 | |||
v1.0 | instruct | Filter | Filter_48684_I | How can I create a Python script that automatically sends an email when a specific condition is met, such as a file size exceeding a certain limit? | import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, login, password):
"""
Send an email with the specified subject and body to the specified email address.
"""
msg = MIME... | import pytest
import os
from unittest.mock import patch, MagicMock
from solution import check_file_size_and_send_email
def test_check_file_size_and_send_email_exceeds_limit(tmp_path):
# Create a temporary file
file_path = tmp_path / "testfile.txt"
file_path.write_text("A" * 100) # 100 bytes
email_det... | [
{
"docstring": "Send an email with the specified subject and body to the specified email address.",
"function_declaration": "def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, login, password):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, fro... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport os\n\ndef send_email(receiver_email, subject, body, smtp_server, smtp_port, sender_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048684",
"row_id": 48684,
"seed_ids": "['Qwen2.5-72B-Instruct_102197']"
} | 0.47851 | Filter_48684 | I | [
"send_email",
"check_file_size_and_send_email"
] | 2 | [
[
"check_file_size_and_send_email",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7094ebd7b5bfa22c4c2e0053968791b7f5731640 | 2da2d890f6e6e9ed369747d8b384a1a6e162d84c | |||
v1.0 | instruct | Filter | Filter_48701_I | I have a Python program that simulates a simple dice game. The game is played between two players who each roll a six-sided die. The player with the highest roll wins the round. If both players roll the same number, it's a tie. I want to enhance this program by adding a feature that tracks the number of wins, losses, a... | import random
def roll_die():
"""
Simulates rolling a six-sided die.
Returns a random integer between 1 and 6 inclusive.
"""
return random.randint(1, 6)
def play_round():
"""
Simulates a single round of the dice game.
Returns the outcome as a string: 'win', 'loss', or 'tie'.
"""
... | from solution import roll_die, play_round, play_game
def test_roll_die():
roll = roll_die()
assert 1 <= roll <= 6
def test_play_round():
outcomes = {'win', 'loss', 'tie'}
roll_outcome = play_round()
assert roll_outcome in outcomes
def test_play_game_counts():
rounds = 1000
results = play_... | [
{
"docstring": "Simulates rolling a six-sided die.\nReturns a random integer between 1 and 6 inclusive.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a single round of the dice game.\nReturns the outcome as a str... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass DiceGame:\n def __init__(self):\n self.player1_wins = 0\n self.player2_wins = 0\n self.ties = 0\n\n def roll_dice(self):\n return rando... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048701",
"row_id": 48701,
"seed_ids": "['Qwen2.5-72B-Instruct_102222']"
} | 0.498541 | Filter_48701 | I | [
"roll_die",
"play_round",
"play_game"
] | 3 | [
[
"play_game",
"play_round"
],
[
"play_round",
"roll_die"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0a27b5d2b864b1a61dcc06a0c3cbbf31843abe97 | 5bc471aea6a1b8f3368e6713869baed8b5a48f10 | |||
v1.0 | instruct | Filter | Filter_48703_I | I'm working on a project where I need to simulate the behavior of a simple mechanical system using Python. Specifically, I need to model a harmonic oscillator, which is a common example of a system governed by a second-order differential equation. However, I'm not very familiar with how to solve such equations numerica... | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def harmonic_oscillator(y, t, k, m):
"""
Defines the differential equations for the harmonic oscillator.
Arguments:
y : list - a tuple containing the position and velocity [y0, y1]
t : float - time
k : fl... | from solution import solve_harmonic_oscillator
import numpy as np
def test_solve_harmonic_oscillator():
k = 1.0
m = 1.0
initial_position = 1.0
initial_velocity = 0.0
t = np.linspace(0, 10, 1000)
solution = solve_harmonic_oscillator(initial_position, initial_velocity, k, m, t)
position ... | [
{
"docstring": "Defines the differential equations for the harmonic oscillator.\n\nArguments:\ny : list - a tuple containing the position and velocity [y0, y1]\nt : float - time\nk : float - spring constant\nm : float - mass\n\nReturns:\ndydt : list - derivatives of y",
"function_declaration": "def harmonic... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\n\ndef harmonic_oscillator(y, t, k, m):\n \"\"\"\n Defines the differential equations for the harm... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048703",
"row_id": 48703,
"seed_ids": "['Qwen2.5-72B-Instruct_102224']"
} | 0.316066 | Filter_48703 | I | [
"harmonic_oscillator",
"solve_harmonic_oscillator",
"plot_oscillator"
] | 3 | [
[
"solve_harmonic_oscillator",
"harmonic_oscillator"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 05e6f0d61d04037b7e2ac29f59c52d918f5df6b4 | a979df231b6100d058b80217b4bbb8a5466ea81d | |||
v1.0 | instruct | Filter | Filter_48717_I | I want to write a program that generates a random number and checks if it's a prime number. How can I do this in Python? | import random
def is_prime(n):
"""
Checks if the given number n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return F... | from solution import is_prime, generate_random_number, check_random_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(11) == True
... | [
{
"docstring": "Checks if the given number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generates a random number between 1 and 100.",
"function_declaration": "def generate_random_number():",
... | [
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 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\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048717",
"row_id": 48717,
"seed_ids": "['Qwen2.5-72B-Instruct_102246']"
} | 0.623104 | Filter_48717 | I | [
"is_prime",
"generate_random_number",
"check_random_prime"
] | 3 | [
[
"check_random_prime",
"generate_random_number"
],
[
"check_random_prime",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f94d31c59b8996b7d1399537caa2db30eab02db1 | 25cd343650a919538b90b673163ee06d3d8a1b46 | |||
v1.0 | instruct | Filter | Filter_48726_I | Write a Python script that automates the process of checking the status of a website and sends an email notification if the website is down. The script should use the requests library to check the website and the smtplib library to send the email. Assume you have the necessary permissions and credentials to send emails... | import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def check_website_status(url):
try:
response = requests.get(url)
if response.status_code == 200:
return 'Website is up'
else:
return 'Website is down'
... | import requests
import smtplib
from solution import check_website_status, send_email_notification, automate_website_check_and_notify
def test_check_website_status_up(monkeypatch):
class MockResponse:
status_code = 200
def __init__(self, *args, **kwargs):
pass
def mock_get(*arg... | [
{
"docstring": null,
"function_declaration": "def check_website_status(url):",
"function_name": "check_website_status",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def send_email_notification(subject, message, from_email, to_email, smtp_server, smtp_port, s... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport smtplib\nfrom email.message import EmailMessage\n\ndef check_website_status(url):\n \"\"\"\n Checks the status of the given website.\n \n Args:\n url (st... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048726",
"row_id": 48726,
"seed_ids": "['Qwen2.5-72B-Instruct_102260']"
} | 0.525003 | Filter_48726 | I | [
"check_website_status",
"send_email_notification",
"automate_website_check_and_notify"
] | 3 | [
[
"automate_website_check_and_notify",
"check_website_status"
],
[
"automate_website_check_and_notify",
"send_email_notification"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 47ac6ac7692782f109e471fcbec2c6b28abc8872 | fb0add96e71b57b7de040e072dcff83d145194c5 | |||
v1.0 | instruct | Filter | Filter_48733_I | I need to create a Python program that simulates a simple dice game. The game should involve two players, and each player rolls a six-sided die. The player with the higher number wins the round. If both players roll the same number, it's a tie. The game should run for a specified number of rounds, and at the end, the p... | import random
def roll_dice():
return random.randint(1, 6)
def play_round():
player1_roll = roll_dice()
player2_roll = roll_dice()
if player1_roll > player2_roll:
return 1 # Player 1 wins
elif player2_roll > player1_roll:
return 2 # Player 2 wins
else:
return 0 ... | import pytest
from unittest.mock import patch
from solution import roll_dice, play_round, play_game
def test_roll_dice():
with patch('solution.random.randint', return_value=3):
assert roll_dice() == 3
def test_play_round_player1_wins():
with patch('solution.roll_dice', side_effect=[5, 3]): # Mock rol... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def play_round():",
"function_name": "play_round",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulate rolling a six-sided die.\n Returns a random integer between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_rou... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048733",
"row_id": 48733,
"seed_ids": "['Qwen2.5-72B-Instruct_102271']"
} | 0.495321 | Filter_48733 | I | [
"roll_dice",
"play_round",
"play_game"
] | 3 | [
[
"play_game",
"play_round"
],
[
"play_round",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b04303d0c73874e1724aa4498aa74fd3e4111d5c | bf8b21a909e718daf9da636546490135d27aa43a | |||
v1.0 | instruct | Filter | Filter_48742_I | Write a Python program to find the number of prime numbers between two given numbers. The program should take two integers as input and output the count of prime numbers between them, inclusive. Ensure your code is well-documented and efficient for larger inputs. | def is_prime(n):
"""
Check if a number n is a prime number.
:param n: Integer to be checked.
:return: True if n 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 = 5
while i * i <= n:
... | from solution import count_primes_between
def test_no_primes_in_range():
assert count_primes_between(14, 16) == 0
def test_some_primes_in_range():
assert count_primes_between(10, 20) == 4
def test_range_with_only_primes():
assert count_primes_between(2, 7) == 4
def test_single_number_is_prime():
ass... | [
{
"docstring": "Check if a number n is a prime number.\n:param n: Integer to be checked.\n:return: True if n is prime, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Count the number of prime numbers betw... | [
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 :param n: Integer to be checked.\n :return: True if prime, False otherwise.\n \"\"\"\n if n <= 1:\n return Fa... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048742",
"row_id": 48742,
"seed_ids": "['Qwen2.5-72B-Instruct_102280']"
} | 0.662881 | Filter_48742 | I | [
"is_prime",
"count_primes_between"
] | 2 | [
[
"count_primes_between",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aafed03de04018adcabd320fe00d4bb3cb76f816 | b4c2a7fbbe7a7059f2a03ca7b25c94657b3befe6 | |||
v1.0 | instruct | Filter | Filter_48750_I | How can I write a Python program to calculate the sum of the first 100 prime numbers? | def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += ... | from solution import is_prime, sum_of_first_100_primes
# Tests for 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(29) == True
assert is_prime(30) == False
assert is_prime(1) == False
... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the sum of the first 100 prime numbers.",
"function_declaration": "def sum_of_first_100_primes():",
"function... | [
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 n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048750",
"row_id": 48750,
"seed_ids": "['Qwen2.5-72B-Instruct_102300']"
} | 0.617281 | Filter_48750 | I | [
"is_prime",
"sum_of_first_100_primes"
] | 2 | [
[
"sum_of_first_100_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b09241aaf69df4bd1f3a59730ca508b25fcc715 | 43f78363cfc4378dfdcd667ccf23dbcabf9afc21 | |||
v1.0 | instruct | Filter | Filter_48758_I | How can I create a custom function in Python that modifies a string by adding a prefix and suffix to it, and then apply this function to a column in a pandas DataFrame? | import pandas as pd
def modify_string(s, prefix, suffix):
"""
Modifies the string s by adding a prefix and suffix to it.
"""
return f"{prefix}{s}{suffix}"
def apply_custom_function(df, column_name, prefix, suffix):
"""
Applies the modify_string function to a specified column in the DataFrame.
... | from solution import modify_string, apply_custom_function
import pandas as pd
def test_modify_string():
assert modify_string("text", "pre-", "-suf") == "pre-text-suf"
assert modify_string("data", "A-", "-Z") == "A-data-Z"
assert modify_string("", "start-", "-end") == "start--end"
def test_apply_custom_fun... | [
{
"docstring": "Modifies the string s by adding a prefix and suffix to it.",
"function_declaration": "def modify_string(s, prefix, suffix):",
"function_name": "modify_string",
"parameter_list": "(s, prefix, suffix)"
},
{
"docstring": "Applies the modify_string function to a specified column ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef modify_string(s, prefix, suffix):\n \"\"\"\n Modifies the input string by adding a prefix and a suffix.\n \"\"\"\n return f\"{prefix}{s}{suffix}\"\n\ndef... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048758",
"row_id": 48758,
"seed_ids": "['Qwen2.5-72B-Instruct_102314']"
} | 0.581747 | Filter_48758 | I | [
"modify_string",
"apply_custom_function"
] | 2 | [
[
"apply_custom_function",
"modify_string"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 4c22b6e4104b426ba27611a9d0e373ff2d4f9821 | da5a9c09ebc281035ec59bec5fd763741c7324b3 | |||
v1.0 | instruct | Filter | Filter_48765_I | How can I create a basic chatbot using Python and Flask that responds to specific keywords with predefined answers? | from flask import Flask, request, jsonify
app = Flask(__name__)
# Predefined responses based on keywords
responses = {
"hello": "Hi there!",
"how are you": "I'm good, thank you! How can I assist you today?",
"bye": "Goodbye! Have a great day!",
"default": "I'm sorry, I don't understand that. Could you... | import pytest
from flask import Flask, jsonify, request
from solution import app, get_response
def test_get_response():
assert get_response("hello") == "Hi there!"
assert get_response("how are you") == "I'm good, thank you! How can I assist you today?"
assert get_response("bye") == "Goodbye! Have a great d... | [
{
"docstring": "This function checks if user_input contains any of the predefined keywords\nand returns the corresponding response.",
"function_declaration": "def get_response(user_input):",
"function_name": "get_response",
"parameter_list": "(user_input)"
},
{
"docstring": "This endpoint ac... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\nresponses = {\n \"hello\": \"Hi there! How can I help you?\",\n \"bye\": \"Goodbye! Have a great day!\",\n \"than... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048765",
"row_id": 48765,
"seed_ids": "['Qwen2.5-72B-Instruct_102324']"
} | 0.391045 | Filter_48765 | I | [
"get_response",
"chat"
] | 2 | [
[
"chat",
"get_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 4a13d68a85b31e0df585258276409465aa927f32 | 47033a7591f3b3f3c321aff755a9d718982cae2a | |||
v1.0 | instruct | Filter | Filter_48773_I | Create a Python program to simulate the rolling of two six-sided dice. The program should roll the dice 100 times, calculate the sum of the two dice for each roll, and print out the frequency of each possible sum (2 through 12). | import random
from collections import Counter
def roll_dice():
return random.randint(1, 6), random.randint(1, 6)
def roll_dice_100_times():
sum_frequencies = Counter()
for _ in range(100):
dice1, dice2 = roll_dice()
dice_sum = dice1 + dice2
sum_frequencies[dice_sum] += 1
return... | from solution import roll_dice, roll_dice_100_times
def test_roll_dice():
dice1, dice2 = roll_dice()
assert 1 <= dice1 <= 6
assert 1 <= dice2 <= 6
def test_roll_dice_100_times_length():
result = roll_dice_100_times()
assert len(result) == 11 # Sums range from 2 to 12, so there should be 11 possib... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def roll_dice_100_times():",
"function_name": "roll_dice_100_times",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom collections import defaultdict\n\ndef roll_dice_simulation(num_rolls=100):\n \"\"\"\n Simulates rolling two six-sided dice a specified number of times.\n Returns t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048773",
"row_id": 48773,
"seed_ids": "['Qwen2.5-72B-Instruct_102336']"
} | 0.647245 | Filter_48773 | I | [
"roll_dice",
"roll_dice_100_times"
] | 2 | [
[
"roll_dice_100_times",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 176af3528faca230746f22a56ddf9b2619bf65d6 | 804b6e93c5cd19f5bcb7c91dafd1f7a7a9b93cc1 | |||
v1.0 | instruct | Filter | Filter_48807_I | Write a Python function to compute the Fibonacci sequence up to a given number n, and return the sequence as a list. Additionally, create a second function to find the sum of even-valued terms in the generated Fibonacci sequence. Ensure that the code is optimized for performance. | def fibonacci_sequence(n):
"""
Returns the Fibonacci sequence up to a given number n as a list.
"""
fib_seq = [0, 1]
while True:
next_value = fib_seq[-1] + fib_seq[-2]
if next_value > n:
break
fib_seq.append(next_value)
return fib_seq
def sum_of_even_fibonacc... | from solution import fibonacci_sequence, sum_of_even_fibonacci
def test_fibonacci_sequence():
assert fibonacci_sequence(10) == [0, 1, 1, 2, 3, 5, 8]
assert fibonacci_sequence(1) == [0, 1, 1]
assert fibonacci_sequence(0) == [0, 1]
assert fibonacci_sequence(100) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 8... | [
{
"docstring": "Returns the Fibonacci sequence up to a given number n as a list.",
"function_declaration": "def fibonacci_sequence(n):",
"function_name": "fibonacci_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of even-valued terms in the Fibonacci sequence up to a gi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci(n):\n \"\"\"\n Returns the Fibonacci sequence up to the given number n.\n \"\"\"\n if n <= 0:\n return []\n \n sequence = [0, 1]\n while sequence[-1] ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048807",
"row_id": 48807,
"seed_ids": "['Qwen2.5-72B-Instruct_102388']"
} | 0.720049 | Filter_48807 | I | [
"fibonacci_sequence",
"sum_of_even_fibonacci"
] | 2 | [
[
"sum_of_even_fibonacci",
"fibonacci_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b40a6986b8e0827247a47a038a8326d51f7b9a83 | 689ea249b1203f4b0f1993dc5fd3186195a21180 | |||
v1.0 | instruct | Filter | Filter_48817_I | I need to write a Python script that reads a file containing a list of IP addresses, one per line, and checks if each IP address is valid. A valid IP address consists of four decimal numbers separated by dots, where each number is between 0 and 255. How can I accomplish this? | import re
def is_valid_ip(ip):
"""
Checks if the given IP address is valid.
"""
pattern = re.compile(r'^(\d{1,3}\.){3}\d{1,3}$')
if not pattern.match(ip):
return False
parts = ip.split('.')
for part in parts:
if not 0 <= int(part) <= 255:
return False
return ... | import tempfile
from solution import is_valid_ip, read_and_validate_ips
def test_is_valid_ip():
assert is_valid_ip("192.168.0.1") == True
assert is_valid_ip("255.255.255.255") == True
assert is_valid_ip("0.0.0.0") == True
assert is_valid_ip("256.256.256.256") == False
assert is_valid_ip("192.168.0... | [
{
"docstring": "Checks if the given IP address is valid.",
"function_declaration": "def is_valid_ip(ip):",
"function_name": "is_valid_ip",
"parameter_list": "(ip)"
},
{
"docstring": "Reads a file containing a list of IP addresses, one per line,\nand checks if each IP address is valid.\n\nRet... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_ip(ip):\n \"\"\"\n Returns True if the IP address is valid, otherwise False.\n \"\"\"\n pattern = re.compile(r'^(\\d{1,3}\\.){3}\\d{1,3}$')\n if patter... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048817",
"row_id": 48817,
"seed_ids": "['Qwen2.5-72B-Instruct_102409']"
} | 0.567103 | Filter_48817 | I | [
"is_valid_ip",
"read_and_validate_ips"
] | 2 | [
[
"read_and_validate_ips",
"is_valid_ip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b5a83088feb9be60ee9f4e2635fca14a683d93f | 9f12aaea67dde837afd3f32f910482c9d3741e3f | |||
v1.0 | instruct | Filter | Filter_48848_I | Can you help me write a Python program to find the largest palindrome made from the product of two 3-digit numbers? | def is_palindrome(n):
"""
Checks if the number n is a palindrome.
"""
return str(n) == str(n)[::-1]
def largest_palindrome_product():
"""
Returns the largest palindrome made from the product of two 3-digit numbers.
"""
max_palindrome = 0
for i in range(100, 1000):
for j in r... | from solution import is_palindrome, largest_palindrome_product
def test_is_palindrome():
assert is_palindrome(121) is True
assert is_palindrome(123) is False
assert is_palindrome(12321) is True
assert is_palindrome(12345) is False
def test_largest_palindrome_product():
assert largest_palindrome_pr... | [
{
"docstring": "Checks if the number n is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Returns the largest palindrome made from the product of two 3-digit numbers.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(n):\n \"\"\"\n Checks if a given number n is a palindrome.\n \"\"\"\n return str(n) == str(n)[::-1]\n\ndef largest_palindrome_product():\n \"\"\"\n Finds th... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048848",
"row_id": 48848,
"seed_ids": "['Qwen2.5-72B-Instruct_102458']"
} | 0.676575 | Filter_48848 | I | [
"is_palindrome",
"largest_palindrome_product"
] | 2 | [
[
"largest_palindrome_product",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3bb3feff6e4a134df4bec2c0bc6f5ef4ba672e71 | 14b47413b712496b3bb04e905ae9341acc5235f3 | |||
v1.0 | instruct | Filter | Filter_48880_I | Create a Python program that takes a list of integers as input and returns a new list containing only the prime numbers from the original list. Ensure your program is efficient and well-documented. | def is_prime(n):
"""
Checks if a number is prime.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i i... | from solution import filter_primes
def test_filter_primes_all_prime():
assert filter_primes([2, 3, 5, 7, 11]) == [2, 3, 5, 7, 11]
def test_filter_primes_none_prime():
assert filter_primes([4, 6, 8, 9, 10]) == []
def test_filter_primes_mixed():
assert filter_primes([2, 4, 6, 7, 11, 15, 19]) == [2, 7, 11, ... | [
{
"docstring": "Checks if a number is prime.\nArgs:\nn (int): The number to check for primality.\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": "Filters the ... | [
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 given number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048880",
"row_id": 48880,
"seed_ids": "['Qwen2.5-72B-Instruct_102511']"
} | 0.622386 | Filter_48880 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a633bbc13e910d8f1fa60f62e2119d2e231d135a | 8ba19e288a5e6439db72d1170896edab96ff3a21 | |||
v1.0 | instruct | Filter | Filter_48885_I | Create a Python program that simulates a simple digital clock, which displays the current time and updates every second. The program should also include a feature to set a specific alarm time, and when the current time matches the alarm time, it should print a message indicating the alarm has gone off. The alarm messag... | import time
from datetime import datetime
def digital_clock():
"""
Simulates a simple digital clock, updating the time every second.
"""
while True:
current_time = datetime.now().strftime("%H:%M:%S")
print(f"\r{current_time}", end="")
time.sleep(1)
def check_alarm(alarm_time, a... | from datetime import datetime, timedelta
from solution import set_alarm
def test_set_alarm_same_time():
future_time = (datetime.now() + timedelta(seconds=2)).strftime("%H:%M:%S")
set_alarm(future_time, "Test Alarm!")
def test_set_alarm_with_custom_message():
future_time = (datetime.now() + timedelta(secon... | [
{
"docstring": "Simulates a simple digital clock, updating the time every second.",
"function_declaration": "def digital_clock():",
"function_name": "digital_clock",
"parameter_list": "()"
},
{
"docstring": "Checks if the current time matches the alarm time and prints the alarm message if tr... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom datetime import datetime\n\ndef run_clock(alarm_time=None, alarm_message=\"Alarm!\"):\n \"\"\"\n Runs a digital clock that displays the current time and updates every s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048885",
"row_id": 48885,
"seed_ids": "['Qwen2.5-72B-Instruct_102522']"
} | 0.481235 | Filter_48885 | I | [
"digital_clock",
"check_alarm",
"set_alarm"
] | 3 | [
[
"set_alarm",
"check_alarm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9151fd7562674154391eb73a2cd5c3205fb3cc88 | d7c0a9051fee95437657bb166c9b65897814a10d | |||
v1.0 | instruct | Filter | Filter_48891_I | Write a Python function to find the kth smallest element in a given unsorted list. The function should have a time complexity better than O(n log n), where n is the number of elements in the list. The function should also handle duplicate elements properly, ensuring that the kth smallest element is returned, not just t... | import random
def partition(arr, left, right, pivot_index):
pivot_value = arr[pivot_index]
arr[pivot_index], arr[right] = arr[right], arr[pivot_index]
store_index = left
for i in range(left, right):
if arr[i] < pivot_value:
arr[store_index], arr[i] = arr[i], arr[store_index]
... | from solution import kth_smallest
def test_kth_smallest_single_element():
assert kth_smallest([5], 1) == 5
def test_kth_smallest_multiple_elements():
assert kth_smallest([7, 10, 4, 3, 20, 15], 3) == 7
def test_kth_smallest_with_duplicates():
assert kth_smallest([7, 10, 4, 4, 3, 20, 15], 3) == 4
def test... | [
{
"docstring": null,
"function_declaration": "def partition(arr, left, right, pivot_index):",
"function_name": "partition",
"parameter_list": "(arr, left, right, pivot_index)"
},
{
"docstring": null,
"function_declaration": "def quickselect(arr, left, right, k_smallest):",
"function_... | [
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 quick_select(arr, k):\n \"\"\"\n Returns the kth smallest element in the given unsorted list `arr`.\n \"\"\"\n if arr is None or k < 0 or k >= len(arr):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048891",
"row_id": 48891,
"seed_ids": "['Qwen2.5-72B-Instruct_102535']"
} | 0.705919 | Filter_48891 | I | [
"partition",
"quickselect",
"kth_smallest"
] | 3 | [
[
"kth_smallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2f0337c38a31c3d3474e8201c266c5ff1ed7cb08 | c93e1f86345faeb738b53b8f7935fcd37b303fb2 | |||
v1.0 | instruct | Filter | Filter_48906_I | Write a Python script that reads a list of numbers from a text file, calculates the average of these numbers, and writes the result to another text file. Ensure the script handles file opening, reading, and writing properly, and closes all files after operations. The script should also handle potential exceptions such ... | def read_numbers_from_file(file_path):
"""
Reads a list of numbers from a file and returns them as a list of floats.
"""
try:
with open(file_path, 'r') as file:
numbers = file.readlines()
# Convert numbers to float and strip any newline characters
return [float(num.st... | import os
import pytest
# Assume the function names are correct as per the above imports
def test_read_numbers_from_file(tmp_path):
file = tmp_path / "numbers.txt"
file.write_text("1\n2\n3\n4\n5\n")
numbers = read_numbers_from_file(file)
assert numbers == [1, 2, 3, 4, 5]
def test_read_numbers_fr... | [
{
"docstring": "Reads a list of numbers from a file and returns them as a list of floats.",
"function_declaration": "def read_numbers_from_file(file_path):",
"function_name": "read_numbers_from_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes the average of a list of numbers ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_average(input_file, output_file):\n \"\"\"\n This function reads a list of numbers from a text file, calculates the average of these numbers,\n and writes the result to ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048906",
"row_id": 48906,
"seed_ids": "['Qwen2.5-72B-Instruct_102558']"
} | 0.689466 | Filter_48906 | I | [
"read_numbers_from_file",
"write_average_to_file",
"calculate_average_from_file"
] | 3 | [
[
"calculate_average_from_file",
"read_numbers_from_file"
],
[
"calculate_average_from_file",
"write_average_to_file"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | cf1db29d9e41352d50416c20ee3564ec20036630 | 09d095a491757829915023e2f8de5e209d56e7eb | |||
v1.0 | instruct | Filter | Filter_48918_I | Create a Python program to check if a given number is a palindrome. The program should also be able to handle multiple numbers provided in a list and return a dictionary with the numbers as keys and a boolean value indicating if they are palindromes or not as the values. Additionally, ensure the program can handle nega... | def is_palindrome(number):
"""
Checks if the given number is a palindrome.
"""
# Negative numbers are not palindromes
if number < 0:
return False
# Convert number to string and check if it is equal to its reverse
num_str = str(number)
return num_str == num_str[::-1]
def check_pa... | from solution import is_palindrome, check_palindromes
def test_is_palindrome_single_digit():
assert is_palindrome(5) is True
def test_is_palindrome_positive_palindrome():
assert is_palindrome(121) is True
def test_is_palindrome_positive_non_palindrome():
assert is_palindrome(123) is False
def test_is_pa... | [
{
"docstring": "Checks if the given number is a palindrome.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Checks if each number in the provided list is a palindrome.\n\nArgs:\n numbers (list): List... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(num):\n \"\"\"\n Check if the given number is a palindrome.\n \n A palindrome reads the same backward as forward.\n \n Args:\n num (int): The number to c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048918",
"row_id": 48918,
"seed_ids": "['Qwen2.5-72B-Instruct_102578']"
} | 0.750335 | Filter_48918 | I | [
"is_palindrome",
"check_palindromes"
] | 2 | [
[
"check_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc164a2187e6346bbfbcdbe7e539d9e391fce0b8 | c72e30a86f626f32c6395961f134d03bad70e6be | |||
v1.0 | instruct | Filter | Filter_48930_I | I need to create a Python script that can monitor the disk usage of a system and send an alert when the disk usage exceeds 80%. How can I achieve this? | import shutil
import smtplib
from email.mime.text import MIMEText
def check_disk_usage(disk, threshold=80):
"""
Check the disk usage and return True if it's above the threshold.
Args:
disk (str): The disk to check, e.g., '/'.
threshold (int): The percentage threshold to trigger an alert.
"""
... | from unittest import mock
from solution import check_disk_usage, send_alert, monitor_disk_usage
@mock.patch('shutil.disk_usage')
def test_check_disk_usage(mock_disk_usage):
# Mock the return value of shutil.disk_usage
mock_disk_usage.return_value = mock.Mock(total=100, free=15, used=85)
# Test when di... | [
{
"docstring": "Check the disk usage and return True if it's above the threshold.\nArgs:\ndisk (str): The disk to check, e.g., '/'.\nthreshold (int): The percentage threshold to trigger an alert.",
"function_declaration": "def check_disk_usage(disk, threshold=80):",
"function_name": "check_disk_usage",
... | [
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\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_disk_usage(threshold=80):\n \"\"\"\n Checks the disk usag... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048930",
"row_id": 48930,
"seed_ids": "['Qwen2.5-72B-Instruct_102595']"
} | 0.518238 | Filter_48930 | I | [
"check_disk_usage",
"send_alert",
"monitor_disk_usage"
] | 3 | [
[
"monitor_disk_usage",
"check_disk_usage"
],
[
"monitor_disk_usage",
"send_alert"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9ab79148fa3a7ae3d3f339f2e4634f42e4da89ce | c03d3487e7dc34499d89be1c772eaed3b1e8c7db | |||
v1.0 | instruct | Filter | Filter_48942_I | How can I create a Python function that checks if a given year is a leap year, and then use this function to determine the number of leap years between two given years (inclusive)? | def is_leap_year(year):
"""
Checks if a given year is a leap year.
A year is a leap year if it is evenly divisible by 4,
except for end-of-century years, which must be divisible by 400.
"""
if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):
return True
return False
def co... | from solution import is_leap_year, count_leap_years
def test_is_leap_year():
assert is_leap_year(2000) == True
assert is_leap_year(1900) == False
assert is_leap_year(2004) == True
assert is_leap_year(2001) == False
def test_count_leap_years():
assert count_leap_years(2000, 2020) == 6
assert co... | [
{
"docstring": "Checks if a given year is a leap year.\nA year is a leap year if it is evenly divisible by 4, \nexcept for end-of-century years, which must be divisible by 400.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_leap_year(year):\n \"\"\"\n Determine whether a given year is a leap year.\n \"\"\"\n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048942",
"row_id": 48942,
"seed_ids": "['Qwen2.5-72B-Instruct_102619']"
} | 0.688296 | Filter_48942 | I | [
"is_leap_year",
"count_leap_years"
] | 2 | [
[
"count_leap_years",
"is_leap_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a341151f0694b5faa9ee728160bcce6cf7b6885 | 54498bdea1e2790965f25fdaf6fede485c689801 | |||
v1.0 | instruct | Filter | Filter_48949_I | How can I write a function in Python that converts a string to its corresponding ASCII values and then back to the original string? I would like the function to return both the ASCII values and the original string. Can you provide a code example? | def string_to_ascii(s):
"""
Converts a string to its corresponding ASCII values.
Returns a list of ASCII values.
"""
return [ord(char) for char in s]
def ascii_to_string(ascii_list):
"""
Converts a list of ASCII values to the original string.
Returns the original string.
"""
ret... | from solution import string_conversion, string_to_ascii, ascii_to_string
def test_string_to_ascii():
assert string_to_ascii("test") == [116, 101, 115, 116]
assert string_to_ascii("123") == [49, 50, 51]
assert string_to_ascii("!@#") == [33, 64, 35]
assert string_to_ascii("") == []
def test_ascii_to_str... | [
{
"docstring": "Converts a string to its corresponding ASCII values.\nReturns a list of ASCII values.",
"function_declaration": "def string_to_ascii(s):",
"function_name": "string_to_ascii",
"parameter_list": "(s)"
},
{
"docstring": "Converts a list of ASCII values to the original string.\nR... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def str_to_ascii_and_back(input_str):\n \"\"\"\n Converts a string to its corresponding ASCII values and then back to the original string.\n Returns both the ASCII values and the orig... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048949",
"row_id": 48949,
"seed_ids": "['Qwen2.5-72B-Instruct_102633']"
} | 0.620443 | Filter_48949 | I | [
"string_to_ascii",
"ascii_to_string",
"string_conversion"
] | 3 | [
[
"string_conversion",
"ascii_to_string"
],
[
"string_conversion",
"string_to_ascii"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 29e9ac81280e06a60f06f20c5f03191935838613 | f8b83808012cde08d1eff322d086a8920ea38e78 | |||
v1.0 | instruct | Filter | Filter_48983_I | Write a Python program that prompts the user to enter a string and then checks if the string is a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forward, such as "madam" or "racecar". The program should ignore spaces, punctuation, and capitalization when determining if the strin... | import re
def is_palindrome(s):
"""
Checks if a given string s is a palindrome, ignoring spaces,
punctuation, and capitalization.
"""
# Remove non-alphanumeric characters and convert to lowercase
cleaned_s = re.sub(r'[^A-Za-z0-9]', '', s).lower()
# Check if the cleaned string is the sa... | from solution import is_palindrome, check_palindrome
def test_is_palindrome_with_palindrome():
assert is_palindrome("A man, a plan, a canal, Panama") == True
def test_is_palindrome_with_non_palindrome():
assert is_palindrome("This is not a palindrome") == False
def test_is_palindrome_with_mixed_case():
a... | [
{
"docstring": "Checks if a given string s is a palindrome, ignoring spaces,\npunctuation, and capitalization.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the given string `s` is a palindrome and pr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_palindrome(s):\n \"\"\"\n Checks if a given string s is a palindrome, ignoring spaces,\n punctuation, and capitalization.\n \"\"\"\n # Remove non-alphanumeri... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048983",
"row_id": 48983,
"seed_ids": "['Qwen2.5-72B-Instruct_102684']"
} | 0.749356 | Filter_48983 | I | [
"is_palindrome",
"check_palindrome"
] | 2 | [
[
"check_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f04c1ce5a80250d526ebad18aa595d262a44a1c4 | a5ca503f1f3bb22a1331969bd6872807a318ca1e | |||
v1.0 | instruct | Filter | Filter_48984_I | I need to create a Python script that monitors the size of a specific directory and sends an email alert if the size exceeds a certain threshold. Can you provide a basic example of how to achieve this? | import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def get_directory_size(directory):
"""
Returns the size of the directory in bytes.
"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(directory):
for file in filenames:
... | import pytest
from solution import get_directory_size, send_email_alert, monitor_directory
import tempfile
import os
def test_get_directory_size():
with tempfile.TemporaryDirectory() as tempdir:
file1 = os.path.join(tempdir, "file1.txt")
file2 = os.path.join(tempdir, "file2.txt")
with open(... | [
{
"docstring": "Returns the size of the directory in bytes.",
"function_declaration": "def get_directory_size(directory):",
"function_name": "get_directory_size",
"parameter_list": "(directory)"
},
{
"docstring": "Sends an email alert with the given subject and message.",
"function_decla... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef get_directory_size(directory):\n \"\"\"\n Returns the size of the d... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048984",
"row_id": 48984,
"seed_ids": "['Qwen2.5-72B-Instruct_102686']"
} | 0.55764 | Filter_48984 | I | [
"get_directory_size",
"send_email_alert",
"monitor_directory"
] | 3 | [
[
"monitor_directory",
"get_directory_size"
],
[
"monitor_directory",
"send_email_alert"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 45507436be467c1e7e114571f055db6fcc79a195 | bbd8c20541ad324f03c05da16f4a8a9ea215b988 | |||
v1.0 | instruct | Filter | Filter_48989_I | Can you help me create a simple to-do list application in Python that allows users to add, remove, and mark tasks as completed? I want to use a text file to store the tasks so they persist between sessions. It should also have a simple command-line interface. | import os
TASKS_FILE = 'tasks.txt'
def load_tasks():
"""Load tasks from the tasks file."""
if not os.path.exists(TASKS_FILE):
return []
with open(TASKS_FILE, 'r') as file:
tasks = [line.strip().split(',') for line in file.readlines()]
tasks = [{'task': t[0], 'completed': t[1] == ... | import os
import pytest
from solution import add_task, remove_task, mark_task_completed, get_tasks
TASKS_FILE = 'tasks.txt'
# Setup and Teardown
def setup_module(module):
""" setup any state specific to the execution of the given module."""
if os.path.exists(TASKS_FILE):
os.remove(TASKS_FILE)
def tea... | [
{
"docstring": "Load tasks from the tasks file.",
"function_declaration": "def load_tasks():",
"function_name": "load_tasks",
"parameter_list": "()"
},
{
"docstring": "Save tasks to the tasks file.",
"function_declaration": "def save_tasks(tasks):",
"function_name": "save_tasks",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\nTODO_FILE = 'todo_list.txt'\n\ndef read_tasks():\n if not os.path.exists(TODO_FILE):\n return []\n \n with open(TODO_FILE, 'r') as file:\n tasks = [line.str... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00048989",
"row_id": 48989,
"seed_ids": "['Qwen2.5-72B-Instruct_102696']"
} | 0.43256 | Filter_48989 | I | [
"load_tasks",
"save_tasks",
"add_task",
"remove_task",
"mark_task_completed",
"get_tasks"
] | 6 | [
[
"add_task",
"load_tasks"
],
[
"add_task",
"save_tasks"
],
[
"get_tasks",
"load_tasks"
],
[
"mark_task_completed",
"load_tasks"
],
[
"mark_task_completed",
"save_tasks"
],
[
"remove_task",
"load_tasks"
],
[
"remove_task",
"save_tasks"
... | 7 | [] | false | [] | false | pytest | true | [] | true | fdc413265a2df70fc184002fa0c7a5519e154e44 | d77b9316bcda5475cb32986ac2916599d4144bfc | |||
v1.0 | instruct | Filter | Filter_48996_I | Given the task to implement a neural network for text classification using PyTorch, how would you structure the code to ensure it is modular, efficient, and easy to understand for someone new to the field? Please include key components like the data loading, model definition, training loop, and evaluation. | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np
# Define a custom Dataset for text data
class TextDataset(Dataset):
def __init__(self, t... | from solution import TextDataset, TextClassificationModel, train_model, evaluate_model
import torch
def test_text_dataset():
texts = ["this is a positive example", "this is a negative example"]
labels = [1, 0]
vocab = {'<PAD>': 0, '<UNK>': 1, 'this': 2, 'is': 3, 'a': 4, 'positive': 5, 'example': 6, 'negati... | [] | [
0,
0,
1
] | 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\nfrom torch.utils.data import DataLoader, Dataset\nfrom sklearn.model_selection import train_test_split\n\n# Define the Dataset... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00048996",
"row_id": 48996,
"seed_ids": "['Qwen2.5-72B-Instruct_102707']"
} | 0.361413 | Filter_48996 | I | [
"train_model",
"evaluate_model",
"example_usage"
] | 3 | [
[
"example_usage",
"evaluate_model"
],
[
"example_usage",
"train_model"
]
] | 2 | [] | false | [
"TextDataset",
"TextClassificationModel"
] | true | pytest | true | [
"numpy",
"sklearn",
"torch"
] | false | 69e7f3f5eeb3f7177ccfdab9cae92153aaf5175c | 34ac61eb7d2c7eb5722e615d3a81d219290bf739 | |||
v1.0 | instruct | Filter | Filter_48997_I | Write a Python program that simulates the rolling of two six-sided dice. The program should roll the dice 100 times, calculate the sum of the two dice for each roll, and then print out the frequency of each possible sum (2 through 12) in a tabular format. Additionally, the program should calculate and print the average... | import random
from collections import defaultdict
def roll_dice():
"""
Roll two six-sided dice.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1, die2
def simulate_dice_rolls(num_rolls=100):
"""
Simulate rolling two six-sided dice `num_rolls` times.
Calculate... | from solution import roll_dice, simulate_dice_rolls
def test_roll_dice():
die1, die2 = roll_dice()
assert 1 <= die1 <= 6
assert 1 <= die2 <= 6
def test_simulate_dice_rolls_format():
result = simulate_dice_rolls(num_rolls=10)
lines = result.strip().split('\n')
# Check header
assert lin... | [
{
"docstring": "Roll two six-sided dice.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulate rolling two six-sided dice `num_rolls` times.\nCalculate the frequency of each possible sum and the average sum of all rolls... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom collections import defaultdict\n\ndef roll_dice():\n \"\"\"\n Roll two six-sided dice.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00048997",
"row_id": 48997,
"seed_ids": "['Qwen2.5-72B-Instruct_102708']"
} | 0.675515 | Filter_48997 | I | [
"roll_dice",
"simulate_dice_rolls"
] | 2 | [
[
"simulate_dice_rolls",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a5ba69230569996f4a4d00cfe75f7f187216c9b0 | 32106ddcd734594a0087fd0ec3e5569b426b4831 | |||
v1.0 | instruct | Filter | Filter_49079_I | How can I design a simple machine learning model to predict stock prices using Python? I want to use historical stock price data for training. Can you provide a basic example? | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
def create_dataset(data, window_size):
X, y = [], []
for i in range(len(data) - window_size):
X.append(data[i:(i +... | from solution import create_dataset, train_model, predict_next_day
import numpy as np
def test_create_dataset():
data = [1, 2, 3, 4, 5, 6, 7, 8]
X, y = create_dataset(data, window_size=3)
assert (X == np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]])).all()
assert (y == np.array([4, 5, ... | [
{
"docstring": null,
"function_declaration": "def create_dataset(data, window_size):",
"function_name": "create_dataset",
"parameter_list": "(data, window_size)"
},
{
"docstring": "Create a simple linear regression model to predict stock prices using historical prices.\n\nParameters:\nhistor... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049079",
"row_id": 49079,
"seed_ids": "['Qwen2.5-72B-Instruct_102836']"
} | 0.531475 | Filter_49079 | I | [
"create_dataset",
"train_model",
"predict_next_day"
] | 3 | [
[
"train_model",
"create_dataset"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 40ebe62f8d3f91bc76c867cec0f74ffff388743d | b6555d98bc726ff26b8b759c3431647297a49bc1 | |||
v1.0 | instruct | Filter | Filter_49080_I | I want to create a Python script to monitor the temperature of a Raspberry Pi and log it to a file. How can I do this? | import time
import os
def get_temperature():
"""
Fetches the temperature of the Raspberry Pi.
Returns the temperature in Celsius as a float.
"""
temp_str = os.popen('vcgencmd measure_temp').readline()
temp_celsius = float(temp_str.replace("temp=", "").replace("'C\n", ""))
return temp_celsiu... | import os
import pytest
from unittest.mock import patch
from solution import get_temperature, log_temperature, monitor_temperature
# Test get_temperature
def test_get_temperature():
with patch('os.popen') as mock_popen:
mock_popen.return_value.readline.return_value = 'temp=55.0\'C\n'
assert get_te... | [
{
"docstring": "Fetches the temperature of the Raspberry Pi.\nReturns the temperature in Celsius as a float.",
"function_declaration": "def get_temperature():",
"function_name": "get_temperature",
"parameter_list": "()"
},
{
"docstring": "Logs the current temperature of the Raspberry Pi to t... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport os\n\ndef read_temperature():\n \"\"\"\n Reads the temperature of the Raspberry Pi.\n \"\"\"\n # Use the appropriate command to read the temperature hardware\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049080",
"row_id": 49080,
"seed_ids": "['Qwen2.5-72B-Instruct_102837']"
} | 0.452793 | Filter_49080 | I | [
"get_temperature",
"log_temperature",
"monitor_temperature"
] | 3 | [
[
"log_temperature",
"get_temperature"
],
[
"monitor_temperature",
"log_temperature"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | baf1d91db5818c3d18d0bf13ac8fb4574f7ba2eb | f3588aee1cac771e18fc63d92d13b34f1ea4bf7e | |||
v1.0 | instruct | Filter | Filter_49083_I | Can you provide an example of a simple chatbot that can be created using Python and the Flask framework? It would be great if you could include the necessary code and a brief explanation of how it works. | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/chatbot', methods=['POST'])
def chatbot():
user_message = request.json.get('message')
response = get_response(user_message)
return jsonify({'response': response})
def get_response(message):
"""
Generate a simple response... | import pytest
from flask import json
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_hello_response(client):
response = client.post('/chatbot', json={'message': 'hello'})
json_data = response.get_json()
assert response.status_code ... | [
{
"docstring": null,
"function_declaration": "def chatbot():",
"function_name": "chatbot",
"parameter_list": "()"
},
{
"docstring": "Generate a simple response based on user message.",
"function_declaration": "def get_response(message):",
"function_name": "get_response",
"paramet... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n@app.route('/chatbot', methods=['POST'])\ndef chatbot():\n user_message = request.json.get('message')\n response = g... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049083",
"row_id": 49083,
"seed_ids": "['Qwen2.5-72B-Instruct_102841']"
} | 0.386758 | Filter_49083 | I | [
"chatbot",
"get_response"
] | 2 | [
[
"chatbot",
"get_response"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | faa56e3077b6a696bb2a4b184f349168aa6d44eb | 9072d7ad4a3e74407ab7aba3a45553acf7573c8e | |||
v1.0 | instruct | Filter | Filter_49087_I | I need to create a Python script that checks a list of domain names to see if they are valid and if they are currently active (i.e., they can be resolved to an IP address). Can you help me with that? | import re
import socket
def is_valid_domain(domain):
"""
Check if the given domain name is valid.
"""
regex = re.compile(
r'^(?:[a-zA-Z0-9]' # First character of the domain
r'(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)' # Sub domain + hostname
r'+[a-zA-Z]{2,6}\.?$' # First level TLD
... | from solution import is_valid_domain, is_domain_active, check_domains
def test_is_valid_domain():
assert is_valid_domain('example.com') == True
assert is_valid_domain('sub.example.com') == True
assert is_valid_domain('example') == False
assert is_valid_domain('!invalid.domain') == False
assert is_v... | [
{
"docstring": "Check if the given domain name is valid.",
"function_declaration": "def is_valid_domain(domain):",
"function_name": "is_valid_domain",
"parameter_list": "(domain)"
},
{
"docstring": "Check if the given domain name is currently active.",
"function_declaration": "def is_dom... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nimport socket\n\ndef is_valid_domain(domain):\n \"\"\"\n Check if the given domain name is valid.\n \"\"\"\n regex = re.compile(\n r'^(?:[a-zA-Z0-9]' # First char... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049087",
"row_id": 49087,
"seed_ids": "['Qwen2.5-72B-Instruct_102848']"
} | 0.65146 | Filter_49087 | I | [
"is_valid_domain",
"is_domain_active",
"check_domains"
] | 3 | [
[
"check_domains",
"is_domain_active"
],
[
"check_domains",
"is_valid_domain"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 595793580e9446103583ca68b522e02c180d08af | 8bb0a3ba886b940d6187122a7d41c1309afcc594 | |||
v1.0 | instruct | Filter | Filter_49097_I | Given a sequence of numbers, how can I efficiently find the longest increasing subsequence in Python? Please provide a code snippet. | def longest_increasing_subsequence(nums):
"""
Returns the length of the longest increasing subsequence in a list of numbers.
"""
if not nums:
return 0
# This list will store the smallest end element of an increasing subsequence
# of each possible length.
sub = []
for nu... | from solution import longest_increasing_subsequence
def test_longest_increasing_subsequence():
assert longest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) == 6
assert longest_increasing_subsequence([3, 10, 2, 1, 20]) == 3
assert longest_increasing_subsequence([3, 2]) == 1
assert longest_... | [
{
"docstring": "Returns the length of the longest increasing subsequence in a list of numbers.",
"function_declaration": "def longest_increasing_subsequence(nums):",
"function_name": "longest_increasing_subsequence",
"parameter_list": "(nums)"
},
{
"docstring": "A helper function to perform ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_increasing_subsequence(arr):\n \"\"\"\n Function to find the longest increasing subsequence in a sequence of numbers.\n \n Parameters:\n arr (list of int): A list of... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049097",
"row_id": 49097,
"seed_ids": "['Qwen2.5-72B-Instruct_102865']"
} | 0.597504 | Filter_49097 | I | [
"longest_increasing_subsequence",
"binary_search"
] | 2 | [
[
"longest_increasing_subsequence",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87b05f1db6e266b3722403589d6c45c0e57d9fd5 | 94e397fd36720222b01f8fe563764f498fa733a8 | |||
v1.0 | instruct | Filter | Filter_49102_I | How can I design a Python function that generates a random number between 1 and 100 and checks if this number is a prime number? If it's a prime, the function should return the number and a message "is a prime number"; if not, it should return the number and the message "is not a prime number". Additionally, implement ... | import random
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... | from solution import is_prime, generate_and_check_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(97) == True
assert is_prime(1... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a random number and check if it is a prime number.",
"function_declaration": "def generate_and_check_prime():",
"... | [
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 is_prime(n):\n \"\"\"\n Returns True if the number is prime, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049102",
"row_id": 49102,
"seed_ids": "['Qwen2.5-72B-Instruct_102870']"
} | 0.643755 | Filter_49102 | I | [
"is_prime",
"generate_and_check_prime",
"main"
] | 3 | [
[
"generate_and_check_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad3d9e2c03dc851192ba9bbb8cad17b0bf998b96 | 4f90959437df4482bb5306072e1e37940072f4e9 | |||
v1.0 | instruct | Filter | Filter_49111_I | I am trying to create a Python program that can encrypt and decrypt a message using the Caesar cipher. I want to create a function that takes a message and a key (number of positions to shift each letter) and returns the encrypted message. Additionally, I want to create a function that can decrypt the message given the... | def encrypt_caesar_cipher(message, key):
"""
Encrypts the message using Caesar Cipher with the given key.
Args:
message (str): The message to be encrypted.
key (int): The number of positions to shift each letter.
Returns:
str: The encrypted message.
"""
encrypted_message = ... | def test_encrypt_caesar_cipher():
assert encrypt_caesar_cipher("HELLO", 3) == "KHOOR"
assert encrypt_caesar_cipher("hello", 3) == "khoor"
assert encrypt_caesar_cipher("Hello, World!", 3) == "Khoor, Zruog!"
assert encrypt_caesar_cipher("xyz", 3) == "abc"
assert encrypt_caesar_cipher("", 3) == ""
def... | [
{
"docstring": "Encrypts the message using Caesar Cipher with the given key.\n\nArgs:\nmessage (str): The message to be encrypted.\nkey (int): The number of positions to shift each letter.\n\nReturns:\nstr: The encrypted message.",
"function_declaration": "def encrypt_caesar_cipher(message, key):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def encrypt_caesar_cipher(message, key):\n \"\"\"\n Encrypts a message using the Caesar cipher with the given key.\n\n Parameters:\n message (str): The message to encrypt.\n key... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049111",
"row_id": 49111,
"seed_ids": "['Qwen2.5-72B-Instruct_102880']"
} | 0.6634 | Filter_49111 | I | [
"encrypt_caesar_cipher",
"decrypt_caesar_cipher"
] | 2 | [
[
"decrypt_caesar_cipher",
"encrypt_caesar_cipher"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5203d10dbf49bf5201f229f6722fce2dd9d0f748 | cbc1097f383adb01f569ba47fd0c69d85586ce50 | |||
v1.0 | instruct | Filter | Filter_49114_I | How can I design a Python function that can encrypt a string using the Caesar cipher, and also decrypt it back to the original string? Please include a detailed example. | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the given text using the Caesar cipher technique.
Parameters:
text (str): the string to be encrypted
shift (int): the number of positions to shift each character
Returns:
str: the encrypted string
"""
result = ""
... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("Hello, World!", 3) == "Khoor, Zruog!"
assert caesar_cipher_encrypt("abc", 1) == "bcd"
assert caesar_cipher_encrypt("xyz", 3) == "abc"
assert caesar_cipher_encrypt("ABC", 3) ... | [
{
"docstring": "Encrypts the given text using the Caesar cipher technique.\n\nParameters:\ntext (str): the string to be encrypted\nshift (int): the number of positions to shift each character\n\nReturns:\nstr: the encrypted string",
"function_declaration": "def caesar_cipher_encrypt(text, shift):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encrypt(text, shift):\n \"\"\"\n Encrypts the input text using Caesar cipher with the given shift.\n \n Parameters:\n text (str): The input string to be encryp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049114",
"row_id": 49114,
"seed_ids": "['Qwen2.5-72B-Instruct_102887']"
} | 0.659181 | Filter_49114 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4bd397f1f0cf75c60b60f34de5dd9995da63d493 | 742ac6e3a32e95b000965c22e8230438ce34ff72 | |||
v1.0 | instruct | Filter | Filter_49136_I | How can I create a Python function that generates a random integer between 1 and 100, and how can I use it in a program to simulate a simple dice game where the player wins if the number is even? | import random
def generate_random_integer():
"""
Generates and returns a random integer between 1 and 100.
"""
return random.randint(1, 100)
def dice_game():
"""
Simulates a dice game where the player wins if the generated number is even. Returns a
tuple (number, result) where number is t... | from solution import generate_random_integer, dice_game
def test_generate_random_integer():
random_numbers = [generate_random_integer() for _ in range(100)]
for number in random_numbers:
assert 1 <= number <= 100
def test_dice_game_win():
for _ in range(100):
number, result = dice_game()
... | [
{
"docstring": "Generates and returns a random integer between 1 and 100.",
"function_declaration": "def generate_random_integer():",
"function_name": "generate_random_integer",
"parameter_list": "()"
},
{
"docstring": "Simulates a dice game where the player wins if the generated number is e... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_number():\n \"\"\"\n Generates and returns a random integer between 1 and 100.\n \"\"\"\n return random.randint(1, 100)\n\ndef simulate_dice_ga... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049136",
"row_id": 49136,
"seed_ids": "['Qwen2.5-72B-Instruct_102924']"
} | 0.581185 | Filter_49136 | I | [
"generate_random_integer",
"dice_game"
] | 2 | [
[
"dice_game",
"generate_random_integer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 940e935b17b8ab41ec080a3e63aa5f0d0cada6d5 | 9ff9b4b87833714a4f6ccc193948194023393f31 | |||
v1.0 | instruct | Filter | Filter_49167_I | How can I create a simple Python program that generates random numbers and checks if they are prime? | import random
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
... | import pytest
from solution import is_prime, generate_random_number, generate_and_check_prime
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... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a random number between start and end (inclusive).",
"function_declaration": "def generate_random_number(start=1, end... | [
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_random_number(start=1, end=100):\n \"\"\"\n Generates a random number between start and end (inclusive).\n \"\"\"\n return random.randint(start, end)\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049167",
"row_id": 49167,
"seed_ids": "['Qwen2.5-72B-Instruct_102982']"
} | 0.593638 | Filter_49167 | I | [
"is_prime",
"generate_random_number",
"generate_and_check_prime"
] | 3 | [
[
"generate_and_check_prime",
"generate_random_number"
],
[
"generate_and_check_prime",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8e2c98d5843bb3926aa3bb4d79ef7b9dccb3c071 | 399b9b147483d83806e2319b0f5858876d588f43 | |||
v1.0 | instruct | Filter | Filter_49180_I | How can I use a generator to create a sequence of prime numbers in Python? | def is_prime(number):
"""
Helper function to determine if a number is prime.
"""
if number <= 1:
return False
if number == 2:
return True
if number % 2 == 0:
return False
for i in range(3, int(number ** 0.5) + 1, 2):
if number % i == 0:
return Fals... | from solution import prime_generator, is_prime
def test_is_prime_function():
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
def test_prime_generator():
gen = prime_gen... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(number):",
"function_name": "is_prime",
"parameter_list": "(number)"
},
{
"docstring": "Generator to create an infinite sequence of prime numbers.",
"function_declaration": "def pri... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number 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 =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049180",
"row_id": 49180,
"seed_ids": "['Qwen2.5-72B-Instruct_102999']"
} | 0.566468 | Filter_49180 | I | [
"is_prime",
"prime_generator"
] | 2 | [
[
"prime_generator",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dcab2688182ff279b201d6252b3b11abc2f7be0d | 070541133d4fb45a9511c607ac371948e7e4d3b0 | |||
v1.0 | instruct | Filter | Filter_49195_I | How can I create a Python script to download images from a list of URLs and save them to a specific directory, ensuring that the script can handle errors gracefully and retry failed downloads a specified number of times? | import os
import requests
from time import sleep
def download_image(url, save_directory, retries=3):
"""
Downloads an image from a URL and saves it to the specified directory.
Args:
url: The URL of the image to download.
save_directory: The directory to save the downloaded image.
retries: ... | import pytest
from unittest.mock import patch, Mock
import os
import shutil
from solution import download_image, download_images
# Test function for download_image
@patch('solution.requests.get')
def test_download_image_success(mock_get):
mock_response = Mock()
mock_response.status_code = 200
mock_respons... | [
{
"docstring": "Downloads an image from a URL and saves it to the specified directory.\n\nArgs:\nurl: The URL of the image to download.\nsave_directory: The directory to save the downloaded image.\nretries: The number of times to retry downloading in case of failure.",
"function_declaration": "def download_... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\nfrom time import sleep\n\ndef download_image(url, save_directory, retries=3):\n \"\"\"\n Downloads an image from a URL and saves it to the specified directory... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049195",
"row_id": 49195,
"seed_ids": "['Qwen2.5-72B-Instruct_103023']"
} | 0.569797 | Filter_49195 | I | [
"download_image",
"download_images"
] | 2 | [
[
"download_images",
"download_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | e39461ed2088de5fc8e0426049525da445596477 | b5fa0db6fc508b021f6cd34f8edbf4142e525477 | |||
v1.0 | instruct | Filter | Filter_49201_I | Write a Python program to simulate a simple game of rock-paper-scissors. The game should be played against the computer, and the user should be able to choose between rock, paper, and scissors. The program should determine the winner based on the classic rules: rock beats scissors, scissors beats paper, and paper beats... | import random
def get_computer_choice():
"""
Returns the computer's choice of rock, paper, or scissors.
"""
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of the rock-paper-scissors game.
Parameters:
... | from solution import determine_winner
def test_determine_winner_tie():
assert determine_winner('rock', 'rock') == 'tie'
assert determine_winner('paper', 'paper') == 'tie'
assert determine_winner('scissors', 'scissors') == 'tie'
def test_determine_winner_player_win():
assert determine_winner('rock', 's... | [
{
"docstring": "Returns the computer's choice of rock, paper, or scissors.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of the rock-paper-scissors game.\n\nParameters:\nplayer_c... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly returns 'rock', 'paper', or 'scissors'.\n \"\"\"\n return random.choice(['rock', 'paper', 'scissors'])\n\ndef determ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049201",
"row_id": 49201,
"seed_ids": "['Qwen2.5-72B-Instruct_103038']"
} | 0.514956 | Filter_49201 | I | [
"get_computer_choice",
"determine_winner",
"play_game"
] | 3 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1b5057469124f6dfd813eaaff3dad15ccf7fc836 | a90cbcb06f5b239d1037eb5ef5848d60d6e89574 | |||
v1.0 | instruct | Filter | Filter_49208_I | Can you help me with a simple Python script to convert temperatures from Celsius to Fahrenheit and vice versa? I would like to be able to input a temperature and specify the conversion direction (Celsius to Fahrenheit or Fahrenheit to Celsius). | def celsius_to_fahrenheit(celsius):
"""
Convert Celsius to Fahrenheit.
"""
return (celsius * 9 / 5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Convert Fahrenheit to Celsius.
"""
return (fahrenheit - 32) * 5 / 9
def convert_temperature(value, to_scale):
"""
Convert temperat... | from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, convert_temperature
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenheit(-40) == -40
def test_fahrenheit_to_celsius():
assert fahrenheit_to_celsiu... | [
{
"docstring": "Convert Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Convert Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius(f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Converts Celsius to Fahrenheit.\n Formula: (celsius * 9/5) + 32\n \"\"\"\n return (celsius * 9/5) + 32\n\ndef fahrenheit_to_celsiu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049208",
"row_id": 49208,
"seed_ids": "['Qwen2.5-72B-Instruct_103050']"
} | 0.408351 | Filter_49208 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"convert_temperature"
] | 3 | [
[
"convert_temperature",
"celsius_to_fahrenheit"
],
[
"convert_temperature",
"fahrenheit_to_celsius"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ea33226e767d67b466ef2736f8acb91e6344787a | 9e4cd351732ba7751ff52240b9e2f1eef67ee439 | |||
v1.0 | instruct | Filter | Filter_49219_I | Create a Python script that takes an input of a string and checks if the string is a palindrome. If the string is a palindrome, the script should print "The string is a palindrome"; otherwise, it should print "The string is not a palindrome". | def is_palindrome(s):
"""
Checks if the input string s is a palindrome.
"""
s = s.replace(" ", "").lower() # Remove spaces and convert to lower case
return s == s[::-1]
def check_palindrome(s):
if is_palindrome(s):
return "The string is a palindrome"
else:
return "The strin... | from solution import is_palindrome, check_palindrome
def test_is_palindrome():
assert is_palindrome("radar") == True
assert is_palindrome("hello") == False
assert is_palindrome("A man a plan a canal Panama") == True
assert is_palindrome("No lemon no melon") == True
assert is_palindrome("12321") == ... | [
{
"docstring": "Checks if the input string s is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def check_palindrome(s):",
"function_name": "check_palindrome",
... | [
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(s):\n \"\"\"\n Checks if the input string is a palindrome.\n\n :param s: Input string to be checked\n :return: A message indicating whether the string is a palind... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049219",
"row_id": 49219,
"seed_ids": "['Qwen2.5-72B-Instruct_103069']"
} | 0.848556 | Filter_49219 | I | [
"is_palindrome",
"check_palindrome"
] | 2 | [
[
"check_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 092502a069f6ef3352cac668529e9d7778da8719 | 1d69709e2c9ccb3cffc56dfdd4d745789c45a63b | |||
v1.0 | instruct | Filter | Filter_49268_I | Write a function in Python to simulate the rolling of two six-sided dice. The function should return the sum of the two dice. Also, simulate 1000 rolls and calculate the average result. Print the average at the end. | import random
def roll_dice():
"""
Simulates the rolling of two six-sided dice and returns the sum.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def simulate_rolls(num_rolls):
"""
Simulates num_rolls of two six-sided dice and calculates the average sum... | def test_roll_dice():
results = [roll_dice() for _ in range(1000)]
assert all(result >= 2 and result <= 12 for result in results)
def test_roll_dice_distribution():
results = [roll_dice() for _ in range(10000)]
assert 2 in results
assert 12 in results
def test_simulate_rolls_average():
average... | [
{
"docstring": "Simulates the rolling of two six-sided dice and returns the sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates num_rolls of two six-sided dice and calculates the average sum.",
"function_dec... | [
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_two_dice():\n \"\"\"\n Simulates the rolling of two six-sided dice and returns their sum.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randin... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049268",
"row_id": 49268,
"seed_ids": "['Qwen2.5-72B-Instruct_103149']"
} | 0.629882 | Filter_49268 | I | [
"roll_dice",
"simulate_rolls"
] | 2 | [
[
"simulate_rolls",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 424094aa70eb1ce4f09a478fac42e54fd7ff0384 | e2d190085d676f6aadf983cfa721502fbc7fc3b0 | |||
v1.0 | instruct | Filter | Filter_49284_I | Create a Python script that takes a list of strings and returns a new list containing only the strings that are palindromes. Ensure your script is well-commented and follows best practices for readability and efficiency. | def is_palindrome(s):
"""
Returns True if the string s is a palindrome, otherwise returns False.
"""
return s == s[::-1]
def filter_palindromes(strings):
"""
Takes a list of strings and returns a new list containing only the palindromes.
"""
return [s for s in strings if is_palindrome(s... | from solution import is_palindrome, filter_palindromes
def test_is_palindrome():
assert is_palindrome("madonna") == False
assert is_palindrome("madam") == True
assert is_palindrome("") == True
assert is_palindrome("a") == True
assert is_palindrome("racecar") == True
assert is_palindrome("apple"... | [
{
"docstring": "Returns True if the string s is a palindrome, otherwise returns False.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Takes a list of strings and returns a new list containing only the palindrome... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Check if a given string is a palindrome.\n \n Parameters:\n s (str): The string to be checked.\n \n Returns:\n bool: True if the string... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049284",
"row_id": 49284,
"seed_ids": "['Qwen2.5-72B-Instruct_103168']"
} | 0.717204 | Filter_49284 | I | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4339f6b9fb12d6e8ce3af21659c8c90d90c69465 | 972a24396358682edd90a3da29914ce3015aff6e | |||
v1.0 | instruct | Filter | Filter_49300_I | Write a Python program that will read a text file, count the frequency of each word, and then print the words along with their frequencies in descending order. The program should also ignore common English stop words (e.g., "the", "is", "at", "which"). Provide the code and a brief explanation of how it works. | from collections import Counter
import re
def read_file(file_path):
"""
Reads the content of the file specified by file_path.
"""
with open(file_path, 'r') as file:
return file.read()
def count_word_frequencies(text):
"""
Counts the frequency of each word in the given text, ignoring co... | from solution import count_word_frequencies, read_file
import pytest
# Mock text for testing
mock_text = """
This is a sample text. This text is for testing. This sample should cover basic cases.
"""
def test_count_word_frequencies():
expected_result = {
'sample': 2,
'text': 2,
'testing': ... | [
{
"docstring": "Reads the content of the file specified by file_path.",
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Counts the frequency of each word in the given text, ignoring common stop words.\nRetu... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import Counter\n\n# Define a list of common English stop words\nSTOP_WORDS = set([\n \"the\", \"is\", \"at\", \"which\", \"on\", \"and\", \"a\", \"an\", \"in\", ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049300",
"row_id": 49300,
"seed_ids": "['Qwen2.5-72B-Instruct_103191']"
} | 0.745077 | Filter_49300 | I | [
"read_file",
"count_word_frequencies",
"word_frequencies_from_file"
] | 3 | [
[
"word_frequencies_from_file",
"count_word_frequencies"
],
[
"word_frequencies_from_file",
"read_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 136b9cd721d3a7180bdca90f92b4f06176ea13d7 | 0fb1ca667b7f7b17dd3cd9c458338431f7d62ff0 | |||
v1.0 | instruct | Filter | Filter_49304_I | How can I create a Python function that checks if a given number is a prime number and also determines if the number is a palindrome? The function should return a tuple containing two boolean values: the first indicating if the number is prime, and the second indicating if the number is a palindrome. | def is_prime(num):
"""
Returns True if num is a prime number, otherwise False.
"""
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:
... | from solution import is_prime, is_palindrome, check_prime_and_palindrome
def test_is_prime_with_prime_numbers():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(17) == True
assert is_prime(19) == True
assert is_prime(23) == True
def test_is_prime_with_non_prime_numbers():
... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns True if num is a palindrome, otherwise False.",
"function_declaration": "def is_palind... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049304",
"row_id": 49304,
"seed_ids": "['Qwen2.5-72B-Instruct_103196']"
} | 0.666127 | Filter_49304 | I | [
"is_prime",
"is_palindrome",
"check_prime_and_palindrome"
] | 3 | [
[
"check_prime_and_palindrome",
"is_palindrome"
],
[
"check_prime_and_palindrome",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e1508f75f68b18137944c4fec6aa67375d94e469 | e92e5f2f3094abee9fb251a4f2a56c71f068f608 | |||
v1.0 | instruct | Filter | Filter_49310_I | Is there a way to find the closest point in a given set of points to a specific point in Python? I have a list of points and I want to find out which one is nearest to a target point. Could you provide a Python code snippet to accomplish this using the Euclidean distance? Assume the points are in a 2D space and represe... | def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in 2D space.
"""
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
def closest_point(points, target):
"""
Given a list of points, find the point that is closest to the targe... | from solution import closest_point
def test_single_point():
assert closest_point([(1, 2)], (3, 4)) == (1, 2)
def test_multiple_points():
points = [(1, 2), (3, 4), (6, 8)]
assert closest_point(points, (2, 3)) == (1, 2)
def test_exact_target_in_points():
points = [(1, 2), (5, 6), (3, 3)]
assert clo... | [
{
"docstring": "Calculate the Euclidean distance between two points in 2D space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Given a list of points, find the point that is ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two 2D points.\n \"\"\"\n return math.sqrt((point1[0] - point2[0]) ** 2 ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049310",
"row_id": 49310,
"seed_ids": "['Qwen2.5-72B-Instruct_103207']"
} | 0.64495 | Filter_49310 | I | [
"euclidean_distance",
"closest_point"
] | 2 | [
[
"closest_point",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2701b00960dde40b6c475cd192d4544c041f584 | 4f0f37bce4c1cb972e4ad6f532715a6e72420a9a | |||
v1.0 | instruct | Filter | Filter_49371_I | Write a Python program to solve the 0-1 knapsack problem using dynamic programming. The program should take as input the maximum weight the knapsack can carry, a list of item weights, and a list of item values. It should return the maximum value that can be carried in the knapsack. Also, include a function to print the... | def knapsack(max_weight, weights, values):
"""
Returns the maximum value that can be carried in the knapsack and the items contributing to this value.
:param max_weight: Maximum weight the knapsack can carry
:param weights: List of item weights
:param values: List of item values
:return: (m... | from solution import knapsack
def test_knapsack_basic():
max_weight = 50
weights = [10, 20, 30]
values = [60, 100, 120]
max_value, items = knapsack(max_weight, weights, values)
assert max_value == 220
assert items == [1, 2]
def test_knapsack_single_item():
max_weight = 10
weights = [10... | [
{
"docstring": "Returns the maximum value that can be carried in the knapsack and the items contributing to this value.\n\n:param max_weight: Maximum weight the knapsack can carry\n:param weights: List of item weights\n:param values: List of item values\n:return: (max_value, items) where max_value is max value ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def knapsack(max_weight, weights, values):\n \"\"\"\n Solves the 0-1 Knapsack problem using dynamic programming.\n Returns the maximum value that can be carried in the knapsack.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049371",
"row_id": 49371,
"seed_ids": "['Qwen2.5-72B-Instruct_103303']"
} | 0.508624 | Filter_49371 | I | [
"knapsack",
"print_knapsack_items"
] | 2 | [
[
"print_knapsack_items",
"knapsack"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fe5987317e79a27f12637ee8186f45961e0b26db | 0fd82e15591238c52f0ef27011c3c6bac778e33e | |||
v1.0 | instruct | Filter | Filter_49377_I | Create a Python script to rename files in a directory based on a user-defined pattern. The script should prompt the user for the directory path, the current file name pattern, and the new file name pattern. For example, if the current pattern is "img_####.jpg" and the new pattern is "image_####.jpg", the script should ... | import os
import re
def rename_files(directory, current_pattern, new_pattern):
"""
Rename files in a directory based on the given patterns.
Parameters:
- directory (str): The path to the directory containing the files.
- current_pattern (str): The current file name pattern, e.g., "img_####.jpg... | import os
import pytest
from solution import rename_files
def test_rename_files(tmpdir):
# Create a temporary directory with some test files
test_dir = tmpdir.mkdir("test_files")
file1 = test_dir.join("img_0001.jpg")
file2 = test_dir.join("img_0002.jpg")
file3 = test_dir.join("img_0003.jpg")
fi... | [
{
"docstring": "Rename files in a directory based on the given patterns.\n\nParameters:\n- directory (str): The path to the directory containing the files.\n- current_pattern (str): The current file name pattern, e.g., \"img_####.jpg\".\n- new_pattern (str): The new file name pattern, e.g., \"image_####.jpg\"."... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport re\n\ndef rename_files(directory, current_pattern, new_pattern):\n \"\"\"\n Rename files in a directory based on the given patterns.\n \n Parameters:\n - direc... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00049377",
"row_id": 49377,
"seed_ids": "['Qwen2.5-72B-Instruct_103314']"
} | 0.656902 | Filter_49377 | I | [
"rename_files",
"prompt_user_and_run"
] | 2 | [
[
"prompt_user_and_run",
"rename_files"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 069f31bce0c2223ae1d11e95905da67065067b6e | e7c4e5b8314802ba071ca2d35014b48a3fc0f031 | |||
v1.0 | instruct | Filter | Filter_49379_I | Given a list of words, write a function in Python that checks if a given word is a palindrome. Then, use this function to filter a list of words to return only the palindromes. For example, given the list `['radar', 'apple', 'level', 'world']`, the function should return `['radar', 'level']`. | def is_palindrome(word):
"""
Checks if the given word is a palindrome.
"""
return word == word[::-1]
def filter_palindromes(word_list):
"""
Filters a list of words and returns a list of palindromes.
"""
return [word for word in word_list if is_palindrome(word)] | from solution import is_palindrome, filter_palindromes
def test_is_palindrome_with_palindromes():
assert is_palindrome('radar')
assert is_palindrome('level')
def test_is_palindrome_with_non_palindromes():
assert not is_palindrome('apple')
assert not is_palindrome('world')
def test_is_palindrome_with_... | [
{
"docstring": "Checks if the given word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Filters a list of words and returns a list of palindromes.",
"function_declaration": "def filter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(word):\n \"\"\"\n Checks if a given word is a palindrome.\n \"\"\"\n return word == word[::-1]\n\ndef filter_palindromes(words):\n \"\"\"\n Filters the list... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049379",
"row_id": 49379,
"seed_ids": "['Qwen2.5-72B-Instruct_103319']"
} | 0.717859 | Filter_49379 | I | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1e2410fb0a8fff597e20b854c546d8d4520e2874 | eb178dba74a3d5ae3e48e3cb5f7929cc49798301 | |||
v1.0 | instruct | Filter | Filter_49380_I | I'm trying to understand how to implement a basic machine learning model using PyTorch. Can you guide me through the process of creating a simple linear regression model? I'm familiar with the basics of Python and machine learning concepts but new to PyTorch. | import torch
import torch.nn as nn
import torch.optim as optim
class LinearRegressionModel(nn.Module):
def __init__(self):
super(LinearRegressionModel, self).__init__()
self.linear = nn.Linear(1, 1) # input and output are both 1-dimensional
def forward(self, x):
return self.linear(x)
... | import torch
from solution import LinearRegressionModel, train_model, create_and_train_model
def test_linear_regression_initialization():
model = LinearRegressionModel()
assert isinstance(model.linear, nn.Linear)
assert model.linear.in_features == 1
assert model.linear.out_features == 1
def test_forwa... | [] | [
0,
0,
1
] | 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\nfrom torch.utils.data import DataLoader, TensorDataset\n\n# Step 1: Create a dataset\n# For simplicity, we will create a synth... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00049380",
"row_id": 49380,
"seed_ids": "['Qwen2.5-72B-Instruct_103321']"
} | 0.440971 | Filter_49380 | I | [
"train_model",
"create_and_train_model"
] | 2 | [
[
"create_and_train_model",
"train_model"
]
] | 1 | [] | false | [
"LinearRegressionModel"
] | true | pytest | true | [
"torch"
] | false | ecc5556729ad4cd40eca4d1629204e1234ba07df | 2ca78a4e13e2c775eaae7055513fcd78d2f9a230 | |||
v1.0 | instruct | Filter | Filter_49385_I | I need to create a Python script that reads a CSV file containing user information, including names, email addresses, and phone numbers. The script should then send a personalized email to each user with a unique link. The link should be generated dynamically and include a unique identifier for each user, such as a UUI... | import csv
import smtplib
import uuid
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def generate_unique_link(user_id):
"""
Generate a unique link for the user. The link includes a UUID.
"""
unique_id = uuid.uuid4()
return f'https://example.com/welcome?user_id={... | import pytest
import uuid
from solution import generate_unique_link, send_email
def test_generate_unique_link():
user_id = "12345"
unique_link = generate_unique_link(user_id)
assert unique_link.startswith(f'https://example.com/welcome?user_id={user_id}&unique_id=')
assert len(unique_link) > len(f'http... | [
{
"docstring": "Generate a unique link for the user. The link includes a UUID.",
"function_declaration": "def generate_unique_link(user_id):",
"function_name": "generate_unique_link",
"parameter_list": "(user_id)"
},
{
"docstring": "Send an email to the specified recipient.",
"function_d... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport uuid\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef read_user_data(csv_filename):\n \"\"\"\n Reads user data from the specified CSV file.\n \n Args... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049385",
"row_id": 49385,
"seed_ids": "['Qwen2.5-72B-Instruct_103328']"
} | 0.521308 | Filter_49385 | I | [
"generate_unique_link",
"send_email",
"read_csv_and_send_emails"
] | 3 | [
[
"read_csv_and_send_emails",
"generate_unique_link"
],
[
"read_csv_and_send_emails",
"send_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f9d48e1c939cb30469a0a21b4a27c0880871c69f | ec77325bd2c824737cb076f81ae75d7f913cb3ed | |||
v1.0 | instruct | Filter | Filter_49479_I | Create a Python program that reads a CSV file containing a list of names and their corresponding email addresses, and sends a personalized greeting email to each person using a SMTP server. The CSV file has two columns: "Name" and "Email". Use the `smtplib` and `email` libraries in Python to accomplish this task. Assum... | import csv
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def send_email(recipient_name, recipient_email):
"""
Sends a pe... | from solution import send_email, read_csv_and_send_emails
import os
def test_send_email(monkeypatch):
monkeypatch.setenv('EMAIL_USER', 'test_sender@example.com')
monkeypatch.setenv('EMAIL_PASS', 'password')
# Mocking smtplib.SMTP for test purposes
class MockSMTP:
def __init__(self, smtp_se... | [
{
"docstring": "Sends a personalized greeting email to the specified recipient.",
"function_declaration": "def send_email(recipient_name, recipient_email):",
"function_name": "send_email",
"parameter_list": "(recipient_name, recipient_email)"
},
{
"docstring": "Reads a CSV file and sends per... | [
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 os\nimport smtplib\nimport logging\nfrom email.mime.text import MIMEText\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO)\n\ndef send_email(to_email, to_name,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00049479",
"row_id": 49479,
"seed_ids": "['Qwen2.5-72B-Instruct_103474']"
} | 0.553285 | Filter_49479 | I | [
"send_email",
"read_csv_and_send_emails"
] | 2 | [
[
"read_csv_and_send_emails",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 340aba8de376877cf449175415a965d0a1a5677a | c52c53efac7a29ec2c96bd79dcd1e3e058f549d8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.