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_36407_I
Create an implementation of the merge sort algorithm in Python. Your implementation should have a time complexity of O(n log n) and should be able to handle large input sizes of up to 10^7 elements efficiently. Additionally, optimize the algorithm to use a space complexity of O(log n) by avoiding unnecessary memory all...
def merge_sort(arr): """ Perform merge sort on the given array with time complexity O(n log n) and space complexity O(log n). Args: arr (list): The list to be sorted. Returns: list: The sorted list. """ if len(arr) <= 1: return arr mid = len(arr) // 2 left = me...
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_unsorted_list(): assert merge...
[ { "docstring": "Perform merge sort on the given array with time complexity O(n log n) and space complexity O(log n).\n\nArgs:\narr (list): The list to be sorted.\n\nReturns:\nlist: The sorted list.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(a...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(array):\n \"\"\"\n An implementation of merge sort that sorts an array of integers in\n ascending order.\n \"\"\"\n if len(array) <= 1:\n return array\n\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036407", "row_id": 36407, "seed_ids": "['Qwen2-72B-Instruct_81328']" }
0.524738
Filter_36407
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed764170fa2544456880c5c0923b2e9919f09086
6d6115b58ad6f66cdcfa67a610228cc9070e9b10
v1.0
instruct
Filter
Filter_36467_I
Enhance the given code by making it capable of processing and evaluating more complex strings with multiple operations and numbers. Your function should not just evaluate basic expression strings, but handle multiple mathematical operations simultaneously, considering the correct order of operations, and support both p...
def evaluate_expression(expression): """ Evaluates a mathematical expression string and returns the result. Supports +, -, *, /, and parentheses for operation order. Accounts for divide by zero errors. """ try: result = eval(expression) if isinstance(result, (int, float)): ...
from solution import process_expression def test_simple_addition(): assert process_expression("2 + 3") == 5 def test_multiplication_and_addition(): assert process_expression("2 + 3 * 4") == 14 def test_parentheses(): assert process_expression("(2 + 3) * 4") == 20 def test_division(): assert process_...
[ { "docstring": "Evaluates a mathematical expression string and returns the result.\nSupports +, -, *, /, and parentheses for operation order.\nAccounts for divide by zero errors.", "function_declaration": "def evaluate_expression(expression):", "function_name": "evaluate_expression", "parameter_list...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef evaluate_expression(expression):\n \"\"\"\n Evaluates a mathematical expression string while handling\n multiple operations and numbers, considering the correct\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036467", "row_id": 36467, "seed_ids": "['Qwen2-72B-Instruct_81416']" }
0.569476
Filter_36467
I
[ "evaluate_expression", "is_valid_expression", "process_expression" ]
3
[ [ "process_expression", "evaluate_expression" ], [ "process_expression", "is_valid_expression" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c571ae4ecaea0fb62293f5805e2240b8afc2852a
3d1b392d87e96f733647ad205c203ad265cfcf7c
v1.0
instruct
Filter
Filter_36491_I
Write a python code example that demonstrates how to centre aligned and vertically "centre align" text in a console terminal output application, suitable for a fixed console window size. Also include a method to measure the text size without printing it to the console. Relevant considerations are Windows and Unix termi...
import os import shutil def get_terminal_size(): """ Get the size of the terminal window. """ size = shutil.get_terminal_size((80, 20)) # Default to (80, 20) if size cannot be determined return size.columns, size.lines def measure_text(text): """ Measure the width and height of the textua...
from solution import measure_text, print_centered import os import sys def test_measure_text_single_line(): assert measure_text("Hello, World!") == (13, 1) def test_measure_text_multi_line(): assert measure_text("Hello\nWorld!") == (6, 2) def test_measure_empty_text(): assert measure_text("") == (0, ...
[ { "docstring": "Get the size of the terminal window.", "function_declaration": "def get_terminal_size():", "function_name": "get_terminal_size", "parameter_list": "()" }, { "docstring": "Measure the width and height of the textual content.", "function_declaration": "def measure_text(text...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport shutil\n\ndef center_align_text(text, width=None):\n \"\"\"\n Centers the text horizontally in a terminal of given width.\n \"\"\"\n if width is None:\n wi...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00036491", "row_id": 36491, "seed_ids": "['Qwen2-72B-Instruct_81455']" }
0.417603
Filter_36491
I
[ "get_terminal_size", "measure_text", "print_centered" ]
3
[ [ "print_centered", "get_terminal_size" ], [ "print_centered", "measure_text" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a12e01fce229f1454801e640283d13c2154e7221
8ee4cef39752d5737a840572bf8e79014dd00232
v1.0
instruct
Filter
Filter_36503_I
Implement KMP (Knuth Morris Pratt) algorithm for string pattern-matching, handling space complexity constraints, from scratch without using built-in functions extensive for string manipulation.
def compute_lps(pattern): """ Computes the Longest Prefix which is also Suffix (LPS) array. """ lps = [0] * len(pattern) length = 0 i = 1 while i < len(pattern): if pattern[i] == pattern[length]: length += 1 lps[i] = length i += 1 else: ...
from solution import kmp_search def test_kmp_search_found(): assert kmp_search("ababcabcabababd", "ababd") == [10] assert kmp_search("abcabcabcabc", "abc") == [0, 3, 6, 9] def test_kmp_search_not_found(): assert kmp_search("abcde", "f") == [] assert kmp_search("aaaaaa", "b") == [] def test_kmp_search...
[ { "docstring": "Computes the Longest Prefix which is also Suffix (LPS) array.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "KMP algorithm for pattern matching.", "function_declaration": "def kmp_sea...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def kmp_search(text, pattern):\n \"\"\"\n KMP algorithm for string matching.\n \n :param text: The text in which to search for the pattern\n :param pattern: The pattern to searc...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036503", "row_id": 36503, "seed_ids": "['Qwen2-72B-Instruct_81479']" }
0.532074
Filter_36503
I
[ "compute_lps", "kmp_search" ]
2
[ [ "kmp_search", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9720180602be76d6c16003d1555e93ff41915625
001a48343b407fe5836dc785524d9ddf22955dd6
v1.0
instruct
Filter
Filter_36565_I
Write a python dataset loader that returns mixed batches of data between two datasets, while ensuring equal representation of both datasets in each batch. The dataset consists of tuples (x,y) where x is the data and y is the label. Specifically, the x data for the first dataset are strings representing molecular graphs...
import pickle import os import random import itertools import numpy as np from PIL import Image def encode_smiles(smiles): # This is a placeholder for the actual SMILES encoder function. # Replace this with your actual SMILES encoder implementation. return smiles def imread(filepath): # This is a plac...
import pytest from solution import load_balanced_batches, encode_smiles, imread import pickle import numpy as np from PIL import Image import os # Fixture to create temporary data @pytest.fixture(scope='module') def create_temp_data(tmpdir_factory): # Creating temporary SMILES data smiles_data = ['CCO', 'CNC',...
[ { "docstring": null, "function_declaration": "def encode_smiles(smiles):", "function_name": "encode_smiles", "parameter_list": "(smiles)" }, { "docstring": null, "function_declaration": "def imread(filepath):", "function_name": "imread", "parameter_list": "(filepath)" }, { ...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pickle\nimport os\nimport numpy as np\nfrom itertools import cycle\nfrom random import shuffle\nfrom skimage.io import imread\n\ndef encode_smiles(smiles):\n \"\"\"\n Encodes a SM...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00036565", "row_id": 36565, "seed_ids": "['Qwen2-72B-Instruct_81589']" }
0.408917
Filter_36565
I
[ "encode_smiles", "imread", "load_data", "load_image_paths", "load_balanced_batches" ]
5
[ [ "load_balanced_batches", "encode_smiles" ], [ "load_balanced_batches", "imread" ], [ "load_balanced_batches", "load_data" ], [ "load_balanced_batches", "load_image_paths" ] ]
4
[]
false
[]
false
pytest
true
[ "PIL", "numpy" ]
false
445ea87b5ccc3985cdf22ec11209bd6f65deb889
2f20a373dc43889eb3891324fb5adcb6e5f82112
v1.0
instruct
Filter
Filter_36652_I
Develop a piece of code that not only generates an array comprising of prime numbers within the range of 1 to 50 but also calculates and prints the average of these prime numbers. Additionally, the code should be efficient enough to handle computations for larger ranges without compromising on performance. The expected...
import numpy as np 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 ...
import numpy as np from solution import is_prime, get_prime_statistics def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(1) == False assert is_prime(0) == False def test_get_prime_statistics(): ...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generates an array of prime numbers between start and end (inclusive),\nand calculates statistics including mean, standard deviati...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef generate_primes(start, end):\n \"\"\"\n Generates an array of prime numbers between 'start' and 'end' (inclusive).\n \"\"\"\n primes = []\n for num in ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036652", "row_id": 36652, "seed_ids": "['Qwen2-72B-Instruct_81759']" }
0.496654
Filter_36652
I
[ "is_prime", "get_prime_statistics" ]
2
[ [ "get_prime_statistics", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
b21e2b619ceffca51ca52d5eeaf0939389abe698
66f2f7b0dd3e0a48ecab6de29f5d3173a48776c3
v1.0
instruct
Filter
Filter_36783_I
I need help creating an encryption algorithm in Python. However, I would like it to be a bit challenging and different from simple examples found online. Can you provide me with some code that implements a Polybius Square cipher with a twist? The cipher should have the ability to add a rotational shift to the square to...
def create_polybius_square(): """ Creates the Polybius square with a default configuration. """ alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # 'J' is omitted to fit in a 5x5 grid matrix = [list(alphabet[i:i+5]) for i in range(0, len(alphabet), 5)] return matrix def rotate_square(square, shift): ...
from solution import polybius_encrypt, polybius_decrypt def test_default_encryption_decryption(): plaintext = "HELLO" ciphertext = polybius_encrypt(plaintext) decryptedtext = polybius_decrypt(ciphertext) assert decryptedtext == plaintext def test_shift_encryption_decryption(): plaintext = "WO...
[ { "docstring": "Creates the Polybius square with a default configuration.", "function_declaration": "def create_polybius_square():", "function_name": "create_polybius_square", "parameter_list": "()" }, { "docstring": "Rotates the Polybius square by a given amount to the right.", "functio...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_polybius_square(shift):\n alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'\n shifted_alphabet = alphabet[shift:] + alphabet[:shift]\n square = {}\n for i in range(5):\n f...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00036783", "row_id": 36783, "seed_ids": "['Qwen2-72B-Instruct_81990']" }
0.673419
Filter_36783
I
[ "create_polybius_square", "rotate_square", "find_position", "polybius_encrypt", "polybius_decrypt" ]
5
[ [ "polybius_decrypt", "create_polybius_square" ], [ "polybius_decrypt", "rotate_square" ], [ "polybius_encrypt", "create_polybius_square" ], [ "polybius_encrypt", "find_position" ], [ "polybius_encrypt", "rotate_square" ] ]
5
[]
false
[]
false
pytest
true
[]
true
840231459e46d702239c1b429c482eaf42c22284
2f7453ff2ce1a11b914cc8239bd4af264129e21d
v1.0
instruct
Filter
Filter_36849_I
Create a virtual classroom with Python and Flask. The virtual classroom should have features including user registration, login, video conferencing, chat, and file sharing.
from flask import Flask, request, jsonify, session from werkzeug.security import generate_password_hash, check_password_hash import sqlite3 app = Flask(__name__) app.secret_key = 'supersecretkey' DATABASE = 'virtual_classroom.db' def get_db(): conn = sqlite3.connect(DATABASE) return conn @app.route('/regist...
import pytest from solution import app, get_db @pytest.fixture def client(): app.config['TESTING'] = True app.config['DATABASE'] = 'test_virtual_classroom.db' with app.test_client() as client: with app.app_context(): conn = get_db() cursor = conn.cursor() cu...
[ { "docstring": null, "function_declaration": "def get_db():", "function_name": "get_db", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def register():", "function_name": "register", "parameter_list": "()" }, { "docstring": null, "function_dec...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from flask import Flask, request, jsonify, session\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate impor...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00036849", "row_id": 36849, "seed_ids": "['Qwen2-72B-Instruct_82106']" }
0.454184
Filter_36849
I
[ "get_db", "register", "login" ]
3
[ [ "login", "get_db" ], [ "register", "get_db" ] ]
2
[]
false
[]
false
pytest
true
[ "flask", "werkzeug" ]
false
ff983e28fb36982c357a7868d2a3b55a384fe43b
6b15af1d842d52b3876162dfb44d47df33f567e6
v1.0
instruct
Filter
Filter_36919_I
Rewrite the source code given below to fix the error and modify it to accept input for 'n' from the user, where 'n' is a positive integer. Your program should also validate the input to ensure that it is a prime number and not greater than 100. If the input is not valid, display an error message and prompt the user for...
def is_prime(num): """ Check if the given number is a prime number. """ if num <= 1: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True def get_prime_input(): """ Prompts the user for input and validates that the inpu...
from solution import is_prime, get_prime_input def test_is_prime(): assert not is_prime(0) assert not is_prime(1) assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert is_prime(97) assert not is_prime(100) def test_get_prime_input(monkeypatch): inpu...
[ { "docstring": "Check if the given number is a prime number.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Prompts the user for input and validates that the input is a prime number not greater than 100.", "functi...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036919", "row_id": 36919, "seed_ids": "['Qwen2-72B-Instruct_82229']" }
0.541433
Filter_36919
I
[ "is_prime", "get_prime_input" ]
2
[ [ "get_prime_input", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5fac288c1020fd72fda0a079dfc7b385f0c68bd0
2a0dc7c28e417f21f7ea7ded1512efba828443ee
v1.0
instruct
Filter
Filter_36944_I
Given an input file that contains GEDI (Global Ecosystem Dynamics Investigation Lidar) data, build a program in Python to process the data and download corresponding tiles from Landsat 8 and Sentinel 2 archives. The program must also check and ensure the downloaded tiles are in cloudless state and have less than 10% at...
import random def process_gedi_data(file_path): """ Process GEDI data and download corresponding cloudless Landsat 8 and Sentinel 2 tiles. Args: - file_path (str): Path to the input GEDI data file. Returns: - list: List of downloaded tile paths. """ # Step 1: Read GEDI data coo...
from solution import process_gedi_data, read_gedi_file, query_and_download_tile, is_cloudless, store_downloaded_tiles def test_process_gedi_data(): tiles = process_gedi_data("mock_gedi_data.txt") assert isinstance(tiles, list) assert all(isinstance(tile, str) for tile in tiles) def test_read_gedi_file(): ...
[ { "docstring": "Process GEDI data and download corresponding cloudless Landsat 8 and Sentinel 2 tiles.\nArgs:\n- file_path (str): Path to the input GEDI data file.\n\nReturns:\n- list: List of downloaded tile paths.", "function_declaration": "def process_gedi_data(file_path):", "function_name": "process...
[ 0, 0, 0, 0, 1, 1, 1, 0, 0 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nimport os\n\ndef get_landsat8_tile(gedi_data):\n \"\"\"\n This function takes GEDI data and returns the URL of the corresponding Landsat 8 tile.\n \"\"\"\n # Place...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036944", "row_id": 36944, "seed_ids": "['Qwen2-72B-Instruct_82270']" }
0.33073
Filter_36944
I
[ "process_gedi_data", "read_gedi_file", "query_and_download_tile", "is_cloudless", "store_downloaded_tiles" ]
5
[ [ "process_gedi_data", "is_cloudless" ], [ "process_gedi_data", "query_and_download_tile" ], [ "process_gedi_data", "read_gedi_file" ], [ "process_gedi_data", "store_downloaded_tiles" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ba0ce19c87e6482e7df6cdcb0d8139a2fc10e48d
2cf9592950644b6e1082913f85019004a50f4af2
v1.0
instruct
Filter
Filter_36992_I
Given a set of numbers, write a program in Python to find the largest twin prime pair from the given set. A twin prime pair is a pair of prime numbers that are two units apart (e.g., [3, 5], [5, 7], [11, 13], etc).
def is_prime(n): """ Check if a number is prime. """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def find_largest_twin_prime_pair(numbers): """ Find the largest twin prime pair from the given set of numb...
from solution import is_prime, find_largest_twin_prime_pair 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 def test_find_largest_twin_prime_pair(): as...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Find the largest twin prime pair from the given set of numbers.", "function_declaration": "def find_largest_twin_prime_pair(nu...
[ 0, 0, 0, 1, 1, 0, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00036992", "row_id": 36992, "seed_ids": "['Qwen2-72B-Instruct_82354']" }
0.646005
Filter_36992
I
[ "is_prime", "find_largest_twin_prime_pair" ]
2
[ [ "find_largest_twin_prime_pair", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a6a26889bdd13b4575c515c480de869d8f24b5aa
2ef3592f9930499bf09c327b1fe0fc3946897d6c
v1.0
instruct
Filter
Filter_37023_I
Create a piece of code that involves implementing a machine learning model using PyTorch for a classification task on the CIFAR-10 dataset. Demonstrate the use of advanced techniques such as data augmentation, regularization, and transfer learning. Additionally, implement a custom loss function and evaluation metrics t...
import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torchvision.models import resnet18 from torch.utils.data import DataLoader import matplotlib.pyplot as plt class CustomLoss(nn.Module): def __init__(self): super(CustomLoss, se...
def test_transform_train(): import torchvision.transforms as transforms transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "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 torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nfrom torchvision.models impo...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00037023", "row_id": 37023, "seed_ids": "['Qwen2-72B-Instruct_82400']" }
0.380604
Filter_37023
I
[ "compute_metrics", "train_model", "validate_model", "main" ]
4
[ [ "train_model", "compute_metrics" ], [ "validate_model", "compute_metrics" ] ]
2
[]
false
[ "CustomLoss" ]
true
pytest
false
[ "matplotlib", "torch", "torchvision" ]
false
dc4c8e5b52f25c23422d86ad75f389343fc8a4c7
cd595ca0c52fdb6153724232b67f593ee7a84128
v1.0
instruct
Filter
Filter_37035_I
Develop a Python function that fabricates a sequence of strings. This sequence ought to commence with the input string, with each ensuing string in the sequence symbolizing the prior string's ASCII representation. Each integer in this ASCII representation should be isolated by "-" and the entire sequence should culmina...
import base64 from sympy import isprime def string_to_ascii(s): return '-'.join(str(ord(c)) for c in s) def ascii_to_string(ascii_str): return ''.join(chr(int(i)) for i in ascii_str.split('-')) def string_to_base64(s): return base64.b64encode(s.encode()).decode() def base64_to_string(b64_str): retur...
from solution import create_sequence, string_to_ascii, ascii_to_string, string_to_base64, base64_to_string def test_string_to_ascii(): assert string_to_ascii("abc") == "97-98-99" def test_ascii_to_string(): assert ascii_to_string("97-98-99") == "abc" def test_string_to_base64(): assert string_to_base64("...
[ { "docstring": null, "function_declaration": "def string_to_ascii(s):", "function_name": "string_to_ascii", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def ascii_to_string(ascii_str):", "function_name": "ascii_to_string", "parameter_list": "(ascii_str...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import base64\nimport math\n\ndef generate_ascii_representation(text):\n return \"-\".join(str(ord(char)) for char in text)\n\ndef prime_check(num):\n if num < 2:\n return False\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00037035", "row_id": 37035, "seed_ids": "['Qwen2-72B-Instruct_82421']" }
0.613353
Filter_37035
I
[ "string_to_ascii", "ascii_to_string", "string_to_base64", "base64_to_string", "create_sequence" ]
5
[ [ "create_sequence", "ascii_to_string" ], [ "create_sequence", "string_to_ascii" ], [ "create_sequence", "string_to_base64" ] ]
3
[]
false
[]
false
pytest
true
[ "sympy" ]
false
34ca43b917fc0d93f244ea624fcbbf11005e67ba
31cf10993147992cd8276270e97331614828c861
v1.0
instruct
Filter
Filter_37039_I
Modify this Python script to enhance its output so that it can solve the following problem: Given an input list of integers, this function should return two lists. The first list should contain all the prime numbers from the given list, while the second should contain the cubic root of all non-prime numbers, each round...
import math import time def is_prime(n): """ Check whether a number is a prime or not. """ 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: retu...
from solution import process_numbers def test_process_numbers_with_mixed_list(): primes, non_primes, time_elapsed = process_numbers([2, 8, 17, 27, 4]) assert primes == [2, 17] assert non_primes == [2.0, 3.0, 1.59] assert time_elapsed > 0 def test_process_numbers_with_all_primes(): primes, non_prim...
[ { "docstring": "Check whether a number is a prime or not.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns two lists:\n1. List of prime numbers from the input list.\n2. Cubic root of all non-prime numbers rounded to...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport math\n\ndef is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n i...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00037039", "row_id": 37039, "seed_ids": "['Qwen2-72B-Instruct_82426']" }
0.627003
Filter_37039
I
[ "is_prime", "process_numbers" ]
2
[ [ "process_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff079d88e7beaae4aea423a1b66683229a488ebc
e1cb47cd84969f0f5c67c1e1417de3b6d80a0f24
v1.0
instruct
Filter
Filter_37166_I
Write a loop in Python to print the first 100 prime numbers that are also palindrome numbers and have a digit sum greater than 10. Additionally, each number must be divisible by a prime number greater than itself.
def is_prime(n): """ Returns whether 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 i +=...
from solution import is_prime, is_palindrome, digit_sum, generate_prime_palindrome_sum def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(11) == True def test_is_palindrome(): assert is_palindrome(121) == True assert is_palind...
[ { "docstring": "Returns whether a number n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns whether a number n is a palindrome.", "function_declaration": "def is_palindrome(n):", "function...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00037166", "row_id": 37166, "seed_ids": "['Qwen2-72B-Instruct_82643']" }
0.583479
Filter_37166
I
[ "is_prime", "is_palindrome", "digit_sum", "generate_prime_palindrome_sum" ]
4
[ [ "generate_prime_palindrome_sum", "digit_sum" ], [ "generate_prime_palindrome_sum", "is_palindrome" ], [ "generate_prime_palindrome_sum", "is_prime" ] ]
3
[]
false
[]
false
pytest
true
[]
true
555e632c4af4c2ae466c27ee11bb7ee7270f92d1
e9debeb9be24d2a8402fa1c8e498406273265e73
v1.0
instruct
Filter
Filter_37191_I
Develop a command-line interface (CLI) tool using Python's Click library to manage system services on a Unix-like operating system. The tool should be able to start, stop, restart, and check the status of a given service. Additionally, provide a piece of erroneous code and explain why it's incorrect, then fix it.
import click import os def service_action(action, service): if action not in ['start', 'stop', 'restart', 'status']: raise ValueError("Invalid action. Use one of 'start', 'stop', 'restart', or 'status'.") if os.system(f'systemctl {action} {service}') != 0: raise SystemError(f'Failed to {ac...
from unittest.mock import patch import pytest # Import error handling fix code and manage_service function for testing. from solution import service_action def test_service_action_invalid_action(): with pytest.raises(ValueError): service_action('invalid_action', 'test_service') @patch('os.system') def te...
[ { "docstring": null, "function_declaration": "def service_action(action, service):", "function_name": "service_action", "parameter_list": "(action, service)" }, { "docstring": "A CLI tool to manage system services.\n\nACTION: start, stop, restart, status\nSERVICE: The name of the service to ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import click\nimport subprocess\n\n@click.group()\ndef cli():\n \"\"\"\n A simple CLI tool to manage system services on a Unix-like operating system.\n \"\"\"\n pass\n\n@cli.comman...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037191", "row_id": 37191, "seed_ids": "['Qwen2-72B-Instruct_82686']" }
0.402085
Filter_37191
I
[ "service_action", "manage_service" ]
2
[ [ "manage_service", "service_action" ] ]
1
[]
false
[]
false
pytest
true
[ "click" ]
false
ec6f02d483bd340d9310d212acf7702ad78d439e
5190f0b7ee2d3b319f3f115561a281b860831af8
v1.0
instruct
Filter
Filter_37304_I
How can I create a basic animation of a bouncing ball using Python's Matplotlib library? Please provide me with a JSON data format for the ball's position and velocity, as well as the code to animate the ball using Matplotlib. The animation should update every 50 milliseconds and display the ball's position in the cons...
import matplotlib.pyplot as plt import matplotlib.animation as animation # JSON data format for the ball's position and velocity ball_data = { "position": [5, 5], "velocity": [2, 3] } def update_ball_position(data, bounds): """ Update the ball's position and velocity, including bounces off the walls. ...
from solution import update_ball_position def test_ball_initial_position(): data = {"position": [5, 5], "velocity": [2, 3]} bounds = (0, 10, 0, 10) expected_position = [7, 8] update_ball_position(data, bounds) assert data["position"] == expected_position def test_ball_bounce_x_axis(): data = {...
[ { "docstring": "Update the ball's position and velocity, including bounces off the walls.\n\ndata: dict, Contains the ball's position and velocity.\nbounds: tuple, Contains the x-axis and y-axis limits (min_x, max_x, min_y, max_y).", "function_declaration": "def update_ball_position(data, bounds):", "fu...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport json\n\n# Define initial ball properties\nball_data = {\n \"x\": 0.5,\n \"y\": 0.5,\n \"vx\": 0.02,\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037304", "row_id": 37304, "seed_ids": "['Qwen2-72B-Instruct_82867']" }
0.394017
Filter_37304
I
[ "update_ball_position", "init", "animate" ]
3
[ [ "animate", "update_ball_position" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
1c80a35f732a732ebb33e3988a507c7e6f6951be
35a7e98d85bad5ee0ab80079b0cbc99f5cb52f35
v1.0
instruct
Filter
Filter_37408_I
Develop a Python-based program that utilizes the OpenCV library to help users identify and modify barber-shop type poster images. The program should enable non-technical users, like communication professionals, to quickly incorporate simple adjustments, expand colors, and optimize images specifically for a communicatio...
import cv2 import numpy as np def read_image(image_path): """ Reads an image from the specified file and returns it. """ image = cv2.imread(image_path) if image is None: raise FileNotFoundError(f"No image found at {image_path}") return image def save_image(image, output_path): """ ...
import pytest from solution import read_image, save_image, adjust_brightness_contrast, expand_colors, optimize_for_communication import os def create_test_image(): # Create a simple image for testing image = np.zeros((100, 100, 3), dtype=np.uint8) image[:] = (100, 150, 200) return image def test_read_...
[ { "docstring": "Reads an image from the specified file and returns it.", "function_declaration": "def read_image(image_path):", "function_name": "read_image", "parameter_list": "(image_path)" }, { "docstring": "Saves an image to the specified file.", "function_declaration": "def save_ima...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\nimport numpy as np\n\ndef load_image(path):\n \"\"\"\n Loads an image from the specified file path.\n \"\"\"\n return cv2.imread(path)\n\ndef save_image(image, path):\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00037408", "row_id": 37408, "seed_ids": "['Qwen2-72B-Instruct_83043']" }
0.308496
Filter_37408
I
[ "read_image", "save_image", "adjust_brightness_contrast", "expand_colors", "optimize_for_communication" ]
5
[ [ "optimize_for_communication", "adjust_brightness_contrast" ] ]
1
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
fe0a93c1318697c38714381f62be0cd9b049192e
d178e0dc092d4c5b62df4c6e608c456910ec0a63
v1.0
instruct
Filter
Filter_37431_I
Write a Python program to check if a given number is an 'almost prime' number. An 'almost prime' number is a number that has exactly two prime factors (counted with multiplicity). Also, create a function to identify the prime factors. The number will be as large as 10^12.
def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def prime_factors(n): factors = [] i =...
from solution import is_almost_prime, prime_factors, is_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 def test_prime_factors(): assert prime_factors(18) == [2, 3, 3] asse...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": null,...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n i...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00037431", "row_id": 37431, "seed_ids": "['Qwen2-72B-Instruct_83085']" }
0.643289
Filter_37431
I
[ "is_prime", "prime_factors", "is_almost_prime" ]
3
[ [ "is_almost_prime", "is_prime" ], [ "is_almost_prime", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5777f3cb46572389311551a7e82aab4fe6aefc92
5db5f7060a612df1d71edcf85f3c2f5148b32921
v1.0
instruct
Filter
Filter_37552_I
Implement the Heapsort algorithm using the following list of numbers as input: [24, 34, 5, 15, 30, 7, 8, 32]. Also, modify your implementation to make it a Min Heap and a Max Heap. Be sure to include functions to heapify your input array.
def heapify(arr, n, i, is_min_heap=True): """ Heapify function to maintain the heap property. """ largest_or_smallest = i # Initialize largest (for max heap) or smallest (for min heap) as root left = 2 * i + 1 # left child index right = 2 * i + 2 # right child index if is_min_heap: ...
from solution import heap_sort def test_heap_sort_min_heap(): data = [24, 34, 5, 15, 30, 7, 8, 32] heap_sort(data, True) assert data == [5, 7, 8, 15, 24, 30, 32, 34] def test_heap_sort_max_heap(): data = [24, 34, 5, 15, 30, 7, 8, 32] heap_sort(data, False) assert data == [5, 7, 8, 15, 24, 30, ...
[ { "docstring": "Heapify function to maintain the heap property.", "function_declaration": "def heapify(arr, n, i, is_min_heap=True):", "function_name": "heapify", "parameter_list": "(arr, n, i, is_min_heap=True)" }, { "docstring": "Function to build a heap from a list of numbers.", "func...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def heapify(arr, n, i, min_heap=True):\n \"\"\"\n To heapify subtree rooted at index i. \n n is size of heap. \n min_heap is a boolean indicator for min heap or max heap.\n \"\"...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00037552", "row_id": 37552, "seed_ids": "['Qwen2-72B-Instruct_83284']" }
0.61238
Filter_37552
I
[ "heapify", "build_heap", "heap_sort" ]
3
[ [ "build_heap", "heapify" ], [ "heap_sort", "build_heap" ], [ "heap_sort", "heapify" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5ac47e593737b07b76b58b246b78e9476223b536
205fe071376a5f462ba58e9b8772893fdae90430
v1.0
instruct
Filter
Filter_37560_I
Illustrate and explain the difference between auto-population of personal data and explicit input of personal data during the registration process for new users in a log file using Python code. Write a Python code that auto-populates personal data such as username, email, and password for new users registering on a web...
import random import datetime # Pre-existing data sets for auto-population usernames = ["user1", "user2", "user3"] emails = ["user1@example.com", "user2@example.com", "user3@example.com"] passwords = ["pass1", "pass2", "pass3"] def log_action(action, data, explicit=True): timestamp = datetime.datetime.now().strft...
import shutil import os from unittest.mock import patch from solution import register_user, log_action, auto_populate_data, explicit_input_data def test_auto_populate_data(): username, email, password = auto_populate_data() assert username in ["user1", "user2", "user3"] assert email in ["user1@example.com"...
[ { "docstring": null, "function_declaration": "def log_action(action, data, explicit=True):", "function_name": "log_action", "parameter_list": "(action, data, explicit=True)" }, { "docstring": null, "function_declaration": "def auto_populate_data():", "function_name": "auto_populate_d...
[ 0, 0, 0, 0, 1, 1, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport logging\nfrom datetime import datetime\n\n# Configure logging\nlogging.basicConfig(filename='user_registration.log', level=logging.INFO, format='%(asctime)s - %(message)s...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00037560", "row_id": 37560, "seed_ids": "['Qwen2-72B-Instruct_83293']" }
0.40583
Filter_37560
I
[ "log_action", "auto_populate_data", "explicit_input_data", "register_user" ]
4
[ [ "register_user", "auto_populate_data" ], [ "register_user", "explicit_input_data" ], [ "register_user", "log_action" ] ]
3
[]
false
[]
false
pytest
true
[]
true
da67f8b5610b6909bf448870530995b64dab3df6
2780d1c21424c2a90f1f9a7a13f52a93a2e4668f
v1.0
instruct
Filter
Filter_37635_I
Build a cinemagraph from a video with changing color using Python and codes that modify saturation and contrast of the moving objects while keeping the background static, with user-friendly GUI for parameter tuning.
import cv2 import numpy as np from tkinter import Tk, Scale, HORIZONTAL, Button def adjust_saturation_contrast(frame, saturation_scale, contrast_scale): """ Adjusts the saturation and contrast of the input frame. :param frame: Input video frame (numpy array). :param saturation_scale: Saturation ad...
from solution import adjust_saturation_contrast import numpy as np def test_adjust_saturation_contrast(): frame = np.ones((100, 100, 3), dtype=np.uint8) * 128 # Mid-gray # Test no change adjusted_frame = adjust_saturation_contrast(frame, 100, 100) assert np.array_equal(adjusted_frame, frame), "Frame ...
[ { "docstring": "Adjusts the saturation and contrast of the input frame.\n\n:param frame: Input video frame (numpy array).\n:param saturation_scale: Saturation adjustment value.\n:param contrast_scale: Contrast adjustment value.\n:return: Adjusted frame.", "function_declaration": "def adjust_saturation_contr...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\nimport numpy as np\nfrom moviepy.editor import VideoFileClip\n\ndef alter_saturation_contrast(frame, saturation=1.0, contrast=1.0):\n \"\"\"\n Alter the saturation and contra...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00037635", "row_id": 37635, "seed_ids": "['Qwen2-72B-Instruct_83421']" }
0.347831
Filter_37635
I
[ "adjust_saturation_contrast", "process_video", "start_processing", "create_gui" ]
4
[ [ "process_video", "adjust_saturation_contrast" ], [ "start_processing", "process_video" ] ]
2
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
6b835ff432d2a7fd52ccfed6f47c9555685c18ab
8ba8f1b8996fc654e89e4b842d11b0fb4aa1d2cb
v1.0
instruct
Filter
Filter_37649_I
How can I utilize the given XML data to implement a multi-step Python function that not only identifies the missing letter in a sequence of letters, but also calculates the frequency of each letter in the sequence? Please provide a code that can handle various types of sequences with the help of the provided XML format...
import xml.etree.ElementTree as ET from collections import Counter def parse_xml(xml_data): """ Parses the XML data and extracts the sequence of letters. Args: xml_data (str): A string containing XML data. Returns: str: The extracted sequence of letters. """ root = ET.fromstri...
import pytest from solution import parse_xml, find_missing_letter, calculate_frequency, process_xml_data def test_parse_xml(): xml_data = "<root><sequence>abcfg</sequence></root>" assert parse_xml(xml_data) == "abcfg" def test_find_missing_letter(): assert find_missing_letter("abcg") == "d" assert fin...
[ { "docstring": "Parses the XML data and extracts the sequence of letters.\n\nArgs:\nxml_data (str): A string containing XML data.\n\nReturns:\nstr: The extracted sequence of letters.", "function_declaration": "def parse_xml(xml_data):", "function_name": "parse_xml", "parameter_list": "(xml_data)" ...
[ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import xml.etree.ElementTree as ET\nfrom collections import Counter\n\ndef parse_xml(xml_data):\n root = ET.fromstring(xml_data)\n return root.text.strip()\n\ndef find_missing_letter(seq...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00037649", "row_id": 37649, "seed_ids": "['Qwen2-72B-Instruct_83445']" }
0.546327
Filter_37649
I
[ "parse_xml", "find_missing_letter", "calculate_frequency", "process_xml_data" ]
4
[ [ "process_xml_data", "calculate_frequency" ], [ "process_xml_data", "find_missing_letter" ], [ "process_xml_data", "parse_xml" ] ]
3
[]
false
[]
false
pytest
true
[]
true
956d578181bd15081b0cc9ead47bd2ae4fdabb3d
be977c27c147afe71789876e76a447d112a046da
v1.0
instruct
Filter
Filter_37866_I
Write a Python code to print out all the Thursdays between two provided dates. Additionally, if it's a holiday in the US (consider New Year's Day, Memorial Day, Independence Day, Labor Day, Thanksgiving Day, and Christmas Day), indicate it next to the date.
from datetime import datetime, timedelta US_HOLIDAYS = { "New Year's Day": (1, 1), "Independence Day": (7, 4), "Christmas Day": (12, 25) } def get_holidays(year): """ Generate the list of holidays for a given year. """ holidays = { datetime(year, month, day): name for name,...
from solution import get_thursdays_between def test_thursdays_in_january(): expected = [ "2023-01-05", "2023-01-12", "2023-01-19", "2023-01-26" ] assert get_thursdays_between("2023-01-01", "2023-01-31") == expected def test_thursdays_with_holiday(): expected = [ ...
[ { "docstring": "Generate the list of holidays for a given year.", "function_declaration": "def get_holidays(year):", "function_name": "get_holidays", "parameter_list": "(year)" }, { "docstring": "Get all Thursdays between start_date and end_date and indicate if they are US holidays.", "f...
[ 0, 0, 0, 0, 1, 1, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import date, timedelta\n\nUS_HOLIDAYS_2023 = {\n \"2023-01-01\": \"New Year's Day\",\n \"2023-05-29\": \"Memorial Day\",\n \"2023-07-04\": \"Independence Day\",\n \"2...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00037866", "row_id": 37866, "seed_ids": "['Qwen2-72B-Instruct_83820']" }
0.584009
Filter_37866
I
[ "get_holidays", "get_thursdays_between" ]
2
[ [ "get_thursdays_between", "get_holidays" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0a0bedd3af69966173704117434a00a9dfb81864
0b528b89c150fa599f30b33c22b29050a2c4022e
v1.0
instruct
Filter
Filter_37908_I
Write a Python program to identify and count all the elements in a given list that are unique and occur at prime index positions.
def is_prime(n): """ Returns True if n is a prime number, else False. """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def count_unique_elements_prime_indices(lst): """ Identifies and counts all the uniqu...
from solution import is_prime, count_unique_elements_prime_indices # Testing the is_prime function def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(11) == True assert is_prime(1) == False assert is_prime(0) == False asser...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Identifies and counts all the unique elements in the given list that are at prime index positions.", "fun...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n re...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00037908", "row_id": 37908, "seed_ids": "['Qwen2-72B-Instruct_83898']" }
0.643719
Filter_37908
I
[ "is_prime", "count_unique_elements_prime_indices" ]
2
[ [ "count_unique_elements_prime_indices", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a16598600bb626238a70afce752a5afe381dee9d
49397898e47a214799b4437e8463696222dc0def
v1.0
instruct
Filter
Filter_37937_I
Create a Python program that sorts an array of integers using the insertion sort algorithm. However, the program should also keep track of the number of comparisons and swaps made during the sorting process and print them out at the end. Moreover, the program should implement a custom comparator function that sorts the...
def insertion_sort_desc(arr): """ Sorts the array using insertion sort algorithm in descending order and counts the number of comparisons and swaps made. """ comparisons = 0 swaps = 0 # The comparator function for descending order def comparator(x, y): return x > y for ...
from solution import insertion_sort_desc, get_sorted_array def test_insertion_sort_desc_empty(): assert insertion_sort_desc([]) == [] def test_insertion_sort_desc_single_element(): assert insertion_sort_desc([1]) == [1] def test_insertion_sort_desc_sorted_order(): assert insertion_sort_desc([5, 4, 3, 2, ...
[ { "docstring": "Sorts the array using insertion sort algorithm in descending order\nand counts the number of comparisons and swaps made.", "function_declaration": "def insertion_sort_desc(arr):", "function_name": "insertion_sort_desc", "parameter_list": "(arr)" }, { "docstring": "Parses user...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def insertion_sort_desc(arr):\n \"\"\"\n Sorts an array of integers in descending order using insertion sort algorithm.\n Keeps track of the number of comparisons and swaps made durin...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00037937", "row_id": 37937, "seed_ids": "['Qwen2-72B-Instruct_83939']" }
0.665895
Filter_37937
I
[ "insertion_sort_desc", "get_sorted_array" ]
2
[ [ "get_sorted_array", "insertion_sort_desc" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f3476a17233ef1e773a5d3ad90bab1e91f6b03ef
dfc7ede4b41d6eb55023a6586edc32790b86eb63
v1.0
instruct
Filter
Filter_37946_I
Define a function in Python which takes a list as input and returns the sum of the elements in the list. The list can contain positive and negative integers, and it can be empty. The function should also handle lists that contain floating-point numbers. The function should only consider elements that are divisible by 3...
def digit_sum(n): """ Returns the sum of digits of the number n. """ return sum(int(d) for d in str(abs(int(n)))) def sum_divisible_by_3_elements(numbers): """ Returns the sum of the elements in the list that are divisible by 3 and have a digit sum divisible by 3. """ return sum(x ...
from solution import sum_divisible_by_3_elements def test_empty_list(): assert sum_divisible_by_3_elements([]) == 0 def test_no_elements_divisible_by_3(): assert sum_divisible_by_3_elements([1, 2, 4, 5]) == 0 def test_elements_divisible_by_3_with_digit_sum_divisible_by_3(): assert sum_divisible_by_3_elem...
[ { "docstring": "Returns the sum of digits of the number n.", "function_declaration": "def digit_sum(n):", "function_name": "digit_sum", "parameter_list": "(n)" }, { "docstring": "Returns the sum of the elements in the list that are divisible by 3 and \nhave a digit sum divisible by 3.", ...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def digit_sum(n):\n \"\"\"\n Returns the sum of the digits of n.\n \"\"\"\n return sum(int(digit) for digit in str(abs(n)))\n\ndef is_special_number(n):\n \"\"\"\n Checks if ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00037946", "row_id": 37946, "seed_ids": "['Qwen2-72B-Instruct_83955']" }
0.694062
Filter_37946
I
[ "digit_sum", "sum_divisible_by_3_elements" ]
2
[ [ "sum_divisible_by_3_elements", "digit_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4fd497360545af2732000d08ad0234d3524cc61d
e162427537197b52c718387ed6d47f12416e443c
v1.0
instruct
Filter
Filter_37966_I
You are a researcher working on finding the shortest path through a maze. Your task is to develop an algorithm to find the shortest path from the start point to the end point. The maze is represented by a 2D grid of size N x N, where some cells may be blocked, and you can only move horizontally or vertically. Each pat...
from collections import deque def shortest_path_in_maze(grid, start, end): """ Finds the shortest path in a maze from start to end and returns the length of the path. :param grid: List of List, the maze grid where 0 is a free path and 1 is a blocked cell :param start: Tuple, the starting point coo...
from solution import shortest_path_in_maze, display_maze_with_path, find_shortest_path def test_shortest_path_simple(): grid = [ [0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0] ] start = (0, 0) end = (4, 4) assert shortest_...
[ { "docstring": "Finds the shortest path in a maze from start to end and returns the length of the path.\n\n:param grid: List of List, the maze grid where 0 is a free path and 1 is a blocked cell\n:param start: Tuple, the starting point coordinates (row, col)\n:param end: Tuple, the ending point coordinates (row...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef shortest_path_maze(maze, start, end):\n \"\"\"\n Returns the shortest path in a maze from start to end.\n \n Parameters:\n maze (list[list[i...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00037966", "row_id": 37966, "seed_ids": "['Qwen2-72B-Instruct_83988']" }
0.645049
Filter_37966
I
[ "shortest_path_in_maze", "display_maze_with_path", "find_shortest_path" ]
3
[ [ "find_shortest_path", "display_maze_with_path" ], [ "find_shortest_path", "shortest_path_in_maze" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c45737d95bac2df7445b2d90028c7851f0acff3c
f2ceda1dae7882cb8cb8b7e31cf0440ee76b698b
v1.0
instruct
Filter
Filter_38001_I
Write a function to measure the similarity between two strings, using the Jaro-Winkler distance algorithm instead of the more commonly used Levenshtein distance. Your function should be adaptable to varying weights for transpositions and substitutions.
def jaro_winkler_distance(s1, s2, p=0.1, weight_for_transpositions=0.5): """ Calculate the Jaro-Winkler distance between two strings. Params: - s1 (str): First string - s2 (str): Second string - p (float): Scaling factor for the Winkler adjustment, must be between 0 and 0.25 - weight_fo...
from solution import jaro_winkler_distance def test_exact_match(): assert jaro_winkler_distance("test", "test") == 1.0 def test_no_similarity(): assert jaro_winkler_distance("abc", "xyz") == 0.0 def test_some_similarity(): assert jaro_winkler_distance("dwayne", "duane") > 0.5 assert jaro_winkler_dist...
[ { "docstring": "Calculate the Jaro-Winkler distance between two strings.\n\nParams:\n- s1 (str): First string\n- s2 (str): Second string\n- p (float): Scaling factor for the Winkler adjustment, must be between 0 and 0.25\n- weight_for_transpositions (float): Weight for the transpositions in the Jaro distance, m...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def jaro_winkler_similarity(s1, s2, weight_transpositions=1.0, weight_substitutions=1.0, p=0.1):\n \"\"\"\n Compute the Jaro-Winkler similarity between two strings s1 and s2.\n The we...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00038001", "row_id": 38001, "seed_ids": "['Qwen2-72B-Instruct_84054']" }
0.723739
Filter_38001
I
[ "jaro_winkler_distance", "jaro_distance_calculator" ]
2
[ [ "jaro_winkler_distance", "jaro_distance_calculator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0ee29d5961166fc163d0ffff49705fd37f0106d3
451be2c0e7bdc61623d69b6ca023837da27b5ae4
v1.0
instruct
Filter
Filter_38006_I
Please help design an emulation of the Game of Life (Conway's) using Python geared towards a grid of 20x20 dimension, incorporating a graphic display to visualize the cell evolution.
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def initialize_grid(size=20): """ Initialize a grid with random live(1) and dead(0) cells. """ return np.random.choice([0, 1], size*size, p=[0.8, 0.2]).reshape(size, size) def update_grid(grid): """ App...
from solution import initialize_grid, update_grid import numpy as np def test_initialize_grid(): grid = initialize_grid(size=20) assert grid.shape == (20, 20) assert set(np.unique(grid)) <= {0, 1} def test_update_grid_all_dead(): grid = np.zeros((20, 20)) new_grid = update_grid(grid) assert np...
[ { "docstring": "Initialize a grid with random live(1) and dead(0) cells.", "function_declaration": "def initialize_grid(size=20):", "function_name": "initialize_grid", "parameter_list": "(size=20)" }, { "docstring": "Apply the rules of Conway's Game of Life to update the grid.", "functio...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ndef initialize_grid(size=20):\n \"\"\"\n Initializes a grid of given size with random 0s ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00038006", "row_id": 38006, "seed_ids": "['Qwen2-72B-Instruct_84063']" }
0.381526
Filter_38006
I
[ "initialize_grid", "update_grid", "plot_game_of_life" ]
3
[ [ "plot_game_of_life", "update_grid" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
e0a6ff9965ca8add5f36cb14cbcfb13ac0c442a8
e0ab88333129de3319a9ebb05c43bc7c56f2b049
v1.0
instruct
Filter
Filter_38113_I
Please write a Python script that can convert multiple CSV files in a folder into parquet format using Pandas. The script should handle large datasets and offer optimization options for performance such as using multiple cores and optimizing memory usage. Also, the script should allow for filtering, cleaning, and trans...
import os import pandas as pd import glob from multiprocessing import Pool, cpu_count import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def process_csv_file(file_path, output_dir, clean_func=None): try: # Read CSV file logging.info(f'Reading...
import os import pandas as pd import pytest from solution import convert_csv_to_parquet, process_csv_file, sample_cleaning_function def test_process_csv_file(tmpdir): # Create a sample CSV file csv_file = tmpdir.join("test.csv") csv_file.write("A,B,value\n1,2,3\n4,5,6\n1,2,3\n") output_dir = tmpdir.mk...
[ { "docstring": null, "function_declaration": "def process_csv_file(file_path, output_dir, clean_func=None):", "function_name": "process_csv_file", "parameter_list": "(file_path, output_dir, clean_func=None)" }, { "docstring": null, "function_declaration": "def convert_csv_to_parquet(inpu...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport os\nfrom multiprocessing import Pool, cpu_count\nimport logging\n\ndef setup_logger():\n logger = logging.getLogger('CSVtoParquetLogger')\n logger.setLevel(lo...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00038113", "row_id": 38113, "seed_ids": "['Qwen2-72B-Instruct_84250']" }
0.457989
Filter_38113
I
[ "process_csv_file", "convert_csv_to_parquet", "sample_cleaning_function" ]
3
[ [ "convert_csv_to_parquet", "process_csv_file" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
86b93beecc9e2141a5bf05d1c1495b1c65df581a
9ec4fbe899d02a6f61b111c399ef49afea3cee93
v1.0
instruct
Filter
Filter_38127_I
Develop a Python function that generates the first 10 prime numbers that are also Fibonacci numbers. Then, extend the function to check if those numbers are also palindrome. The function should return a dictionary where the keys are the prime Fibonacci numbers and the values are Boolean indicating if the number is a pa...
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def is_palindrome(n): return str(n) == str(n)[::-1] def fibonacci_primes_palindromes(): fibs = [0, 1] primes = [] while len(primes) < 10: ...
from solution import is_prime, is_palindrome, fibonacci_primes_palindromes 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(0) == False assert is_prime(1) == False d...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_palindrome(n):", "function_name": "is_palindrome", "parameter_list": "(n)" }, { "docstring": null,...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00038127", "row_id": 38127, "seed_ids": "['Qwen2-72B-Instruct_84287']" }
0.620122
Filter_38127
I
[ "is_prime", "is_palindrome", "fibonacci_primes_palindromes" ]
3
[ [ "fibonacci_primes_palindromes", "is_palindrome" ], [ "fibonacci_primes_palindromes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c3a437d81f2895d7112b7b78fe99339ce207f963
cc55153b14420a51db1659836559bc73610af69f
v1.0
instruct
Filter
Filter_38157_I
Given a list of strings, write a function that filters out all strings that are palindromes and have a prime number length. The function should return the filtered list in reverse order.
def is_palindrome(s): return s == s[::-1] 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 filter_and_reverse(strings): filtered_list = [s for s in strings if not (is_palindrome(s) and is_prime(len(...
from solution import filter_and_reverse def test_no_palindromes_or_primes(): assert filter_and_reverse(["hello", "world", "python"]) == ["python", "world", "hello"] def test_all_palindrome_primes(): assert filter_and_reverse(["aba", "racecar", "civic", "radar"]) == [] def test_mixed_list(): assert filter...
[ { "docstring": null, "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00038157", "row_id": 38157, "seed_ids": "['Qwen2-72B-Instruct_84335']" }
0.619961
Filter_38157
I
[ "is_palindrome", "is_prime", "filter_and_reverse" ]
3
[ [ "filter_and_reverse", "is_palindrome" ], [ "filter_and_reverse", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4e67b071ff0475790a26c964738ab3dfffac77ea
bd7b07555bce0782ec760e344e48d9c73c0c419a
v1.0
instruct
Filter
Filter_38232_I
Following is my 2 files: admin\_route.json and detect.py. I want to detect anomalies or black spots from video camera that is streams online. Can you modify the detect.py file in a way so that it will only detect motion anomalies and black spots anomalies based on the configuration defined in the admin\_route.json file...
import cv2 import numpy as np import json from datetime import datetime def load_config(config_path): with open(config_path, 'r') as config_file: config = json.load(config_file) return config def is_within_detection_hours(config): current_hour = datetime.now().hour return config["detection_sta...
import json import pytest from unittest.mock import patch, MagicMock from datetime import datetime from solution import load_config, is_within_detection_hours, detect_anomalies # Sample configuration sample_config = { "video_source": "sample_video.mp4", "detection_start_hour": 9, "detection_end_hour": 17 }...
[ { "docstring": null, "function_declaration": "def load_config(config_path):", "function_name": "load_config", "parameter_list": "(config_path)" }, { "docstring": null, "function_declaration": "def is_within_detection_hours(config):", "function_name": "is_within_detection_hours", ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\nimport numpy as np\nimport json\nfrom datetime import datetime\n\n# Load configuration from admin_route.json\nwith open('admin_route.json') as config_file:\n config = json.load(...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00038232", "row_id": 38232, "seed_ids": "['Qwen2-72B-Instruct_84480']" }
0.348825
Filter_38232
I
[ "load_config", "is_within_detection_hours", "detect_anomalies" ]
3
[ [ "detect_anomalies", "is_within_detection_hours" ] ]
1
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
44de7a49bcf9e2268b303d7235933044dfdca818
e18e175287e84cc49e387dfc3f248fef81a5c0c6
v1.0
instruct
Filter
Filter_38243_I
Develop a subroutine labelled顽强的狐狸 that accepts a singular input, a string, and its return value is a boolean. The subroutine determines if the string, considered as a palindrome when ignoring all case sensitivity and non-alphanumeric elements, has a length that exactly matches the golden ratio value (approximately 1.6...
import re def is_fibonacci(n): """ Determine if a given number n is a Fibonacci number """ x, y = 0, 1 while y < n: x, y = y, x + y return y == n def calculate_golden_ratio_length(length): """ Calculate the golden ratio related length given an initial length """ golden_...
from solution import stubbón_狐狸 def test_stubbón_狐狸_valid_palindrome(): assert stubbón_狐狸("A man, a plan, a canal, Panama") == False # The adjusted string length isn't equal to golden ratio length def test_stubbón_狐狸_non_fibonacci_length(): assert stubbón_狐狸("abc") == False # 'abc' doesn't have Fibona...
[ { "docstring": "Determine if a given number n is a Fibonacci number", "function_declaration": "def is_fibonacci(n):", "function_name": "is_fibonacci", "parameter_list": "(n)" }, { "docstring": "Calculate the golden ratio related length given an initial length", "function_declaration": "d...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nimport math\n\ndef is_fibonacci(n):\n \"\"\"\n Checks if a given number n is a Fibonacci number.\n \"\"\"\n # A number is Fibonacci if and only if one or both of (5*n^2 ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00038243", "row_id": 38243, "seed_ids": "['Qwen2-72B-Instruct_84496']" }
0.618754
Filter_38243
I
[ "is_fibonacci", "calculate_golden_ratio_length", "is_valid_palindrome", "stubbón_狐狸" ]
4
[ [ "stubbón_狐狸", "calculate_golden_ratio_length" ], [ "stubbón_狐狸", "is_fibonacci" ], [ "stubbón_狐狸", "is_valid_palindrome" ] ]
3
[]
false
[]
false
pytest
true
[]
true
392b1dc51a51f03d267394ca8f60551e60aff033
5755c1ab881df0fde2e69e6d31c0b87f3364531d
v1.0
instruct
Filter
Filter_38261_I
Code a Python program that accepts three integers and prints out their least common multiple (LCM) and the greatest common divisor (GCD). Additionally, ensure that your program can handle large numbers efficiently.
import math def gcd(a, b): """ Returns the greatest common divisor (GCD) of a and b. """ while b: a, b = b, a % b return a def lcm(a, b): """ Returns the least common multiple (LCM) of a and b. """ return a * b // gcd(a, b) def gcd_three_numbers(a, b, c): """ Retur...
from solution import gcd_three_numbers, lcm_three_numbers, calculate_gcd_and_lcm def test_gcd_three_numbers(): assert gcd_three_numbers(12, 15, 21) == 3 assert gcd_three_numbers(5, 10, 25) == 5 assert gcd_three_numbers(101, 103, 107) == 1 assert gcd_three_numbers(27, 36, 45) == 9 def test_lcm_three_nu...
[ { "docstring": "Returns the greatest common divisor (GCD) of a and b.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the least common multiple (LCM) of a and b.", "function_declaration": "def lcm(a, b):", "fun...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom functools import reduce\n\ndef gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b.\n \"\"\"\n return math.gcd(a, b)\n\ndef lcm(a, b):\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00038261", "row_id": 38261, "seed_ids": "['Qwen2-72B-Instruct_84535']" }
0.665579
Filter_38261
I
[ "gcd", "lcm", "gcd_three_numbers", "lcm_three_numbers", "calculate_gcd_and_lcm" ]
5
[ [ "calculate_gcd_and_lcm", "gcd_three_numbers" ], [ "calculate_gcd_and_lcm", "lcm_three_numbers" ], [ "gcd_three_numbers", "gcd" ], [ "lcm", "gcd" ], [ "lcm_three_numbers", "lcm" ] ]
5
[]
false
[]
false
pytest
true
[]
true
ca1408d15bd0f433b169be5dce2888061862e2de
4a77dc5c2b753859e725732cf3ea3b96a9a92e6b
v1.0
instruct
Filter
Filter_38392_I
Write a Python function `get_count` that receives an array of integers and returns the total count of even numbers in the array. Additionally, create another function called `check_arrays_match` which takes two arrays as input, uses `get_count` to check the quantity of even numbers in both arrays, and outputs 'YES' if ...
def get_count(arr): """ Returns the count of even numbers in the array. """ return sum(1 for x in arr if x % 2 == 0) def check_arrays_match(arr1, arr2): """ Uses get_count to check if the quantity of even numbers in both arrays is identical. Returns 'YES' if the counts are identical and 'NO...
from solution import get_count, check_arrays_match def test_get_count_no_evens(): assert get_count([1, 3, 5, 7]) == 0 def test_get_count_all_evens(): assert get_count([2, 4, 6, 8]) == 4 def test_get_count_mixed_numbers(): assert get_count([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5 def test_get_count_empty_ar...
[ { "docstring": "Returns the count of even numbers in the array.", "function_declaration": "def get_count(arr):", "function_name": "get_count", "parameter_list": "(arr)" }, { "docstring": "Uses get_count to check if the quantity of even numbers in both arrays is identical.\nReturns 'YES' if t...
[ 0, 0, 0, 0, 1, 0, 1, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def get_count(arr):\n \"\"\"\n Returns the count of even numbers in the array.\n \"\"\"\n return sum(1 for x in arr if x % 2 == 0)\n\ndef check_arrays_match(arr1, arr2):\n \"\"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00038392", "row_id": 38392, "seed_ids": "['Qwen2-72B-Instruct_84766']" }
0.670663
Filter_38392
I
[ "get_count", "check_arrays_match" ]
2
[ [ "check_arrays_match", "get_count" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7ff7fa8711e56cbcde699a33879ce7960578a2c3
5c6dad247714e42751f700a58c2e0a03cf270177
v1.0
instruct
Filter
Filter_38413_I
Given two strings inputted by a user, write a Python program that creates a 2D array with the length of each string as the dimensions. Each element in the array should contain a substring that is formed by starting from the corresponding index in the loop. If the substring matches a palindrome, append "True" in the res...
def is_palindrome(s): """ Helper function to check if a string is a palindrome. """ return s == s[::-1] def create_2d_palindrome_array(str1, str2): """ Creates a 2D array with the lengths of str1 and str2 as dimensions. Each cell contains "True" if the substring starting from that index in ...
from solution import create_2d_palindrome_array, is_palindrome def test_is_palindrome(): assert is_palindrome("racecar") == True assert is_palindrome("hello") == False assert is_palindrome("madam") == True assert is_palindrome("a") == True assert is_palindrome("") == True def test_create_2d_palind...
[ { "docstring": "Helper function to check if a string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Creates a 2D array with the lengths of str1 and str2 as dimensions.\nEach cell contains \"True...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_palindrome_matrix(string1, string2):\n \"\"\"\n Creates a 2D array where each element contains a substring starting\n from the corresponding index in loops of string1 and s...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00038413", "row_id": 38413, "seed_ids": "['Qwen2-72B-Instruct_84805']" }
0.780895
Filter_38413
I
[ "is_palindrome", "create_2d_palindrome_array", "main_loop" ]
3
[ [ "create_2d_palindrome_array", "is_palindrome" ], [ "main_loop", "create_2d_palindrome_array" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7d88df1cec4c89adf513898020a0aa86af2a75d4
a3142e04b60ec622ba9846b25d5e442f57cade1f
v1.0
instruct
Filter
Filter_38427_I
Create an input function in Python that prompts the user to enter a list of integers. The user should be allowed to enter as many integers as they want. However, the list must contain at least one integer and the sum of all the integers must be a prime number. Your program should validate the input and ask the user to ...
def is_prime(number): if number <= 1: return False for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def get_int_list(): while True: try: user_input = input("Enter a list of integers separated by spaces: ") ...
import pytest from unittest import mock from solution import is_prime, get_int_list # Tests for is_prime function def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(1) == False assert is_prime(0) == F...
[ { "docstring": null, "function_declaration": "def is_prime(number):", "function_name": "is_prime", "parameter_list": "(number)" }, { "docstring": null, "function_declaration": "def get_int_list():", "function_name": "get_int_list", "parameter_list": "()" } ]
[ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Check if a number is a prime.\"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00038427", "row_id": 38427, "seed_ids": "['Qwen2-72B-Instruct_84828']" }
0.606894
Filter_38427
I
[ "is_prime", "get_int_list" ]
2
[ [ "get_int_list", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c48e6f55554ee2cf81a48285686ed904b05ac608
8375079acf06ed2c717ba2a2ac9c14df9ea8c54c
v1.0
instruct
Filter
Filter_38443_I
Given a string s, write a Python function to print the number of times each character in the string appears, but only for characters that are prime numbers. The function should ignore any non-prime characters in the string.
def is_prime(n): """ Returns True if n is a prime number, else False. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i...
from solution import count_prime_characters, is_prime from io import StringIO import sys 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...
[ { "docstring": "Returns True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Prints the number of times each prime number character appears in the string s.\nOnly considers prime number ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Returns True if n is a prime number, False otherwise.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 =...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00038443", "row_id": 38443, "seed_ids": "['Qwen2-72B-Instruct_84862']" }
0.72563
Filter_38443
I
[ "is_prime", "count_prime_characters" ]
2
[ [ "count_prime_characters", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
343b49694a01c4b66a108042ca872356a99a60fb
d2b5236771433eb4b9b45458e553db6761b7a581
v1.0
instruct
Filter
Filter_38472_I
Extend the given prompt by creating a more complex function that not only determines whether a number is prime or not but also calculates the sum of the prime factors of a number. The function should take an integer as input and return a tuple containing the boolean value indicating whether the input number is prime or...
import math from functools import lru_cache def is_prime(n): """ Determines if the given number is a prime number. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i...
from solution import is_prime, prime_factors_sum def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(18) == False assert is_prime(19) == True assert is_prime(1) == False def test_prime_factors_su...
[ { "docstring": "Determines if the given number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculates the prime factors of the given number and returns their sum.\nOnly considers prime factors less t...
[ 0, 0, 0, 0, 1, 0, 1, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef decorate_primes_plus_memoize_decorator(func):\n \"\"\"\n This decorator is designed to enhance the given function with two main features:\n 1. Memoization: This hel...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00038472", "row_id": 38472, "seed_ids": "['Qwen2-72B-Instruct_84913']" }
0.67516
Filter_38472
I
[ "is_prime", "prime_factors_sum" ]
2
[ [ "prime_factors_sum", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e3390b5606bc5e8daed300b30d1f0b77af7e654
cd48bfdf1cb9e6cbfecb6b6ac9aab04f546a583c
v1.0
instruct
Filter
Filter_38543_I
Given an array of integers, implement insertion sort to sort the array in descending order. Also, calculate and return the number of shifts made during the sorting process. You should also implement a check to use a binary search to find the correct position for the inserted item.
def binary_search(arr, item, low, high): """Helper function to perform binary search within subarray""" if high <= low: return low + 1 if item < arr[low] else low mid = (low + high) // 2 if item == arr[mid]: return mid + 1 if item < arr[mid]: return binary_search(arr, item...
from solution import binary_search, insertion_sort_desc_with_shifts def test_binary_search(): assert binary_search([5, 2], 4, 0, 1) == 1 assert binary_search([5, 2], 6, 0, 1) == 0 assert binary_search([5, 2], 1, 0, 1) == 2 def test_insertion_sort_desc_with_shifts_empty(): arr, shifts = insertion_sort_...
[ { "docstring": "Helper function to perform binary search within subarray", "function_declaration": "def binary_search(arr, item, low, high):", "function_name": "binary_search", "parameter_list": "(arr, item, low, high)" }, { "docstring": "Sorts the array in descending order using insertion s...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Use binary search to find the position to insert val in the array slice arr[start:end+1].\n \"\"\"\n if start == end:\n i...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00038543", "row_id": 38543, "seed_ids": "['Qwen2-72B-Instruct_85022']" }
0.646455
Filter_38543
I
[ "binary_search", "insertion_sort_desc_with_shifts" ]
2
[ [ "insertion_sort_desc_with_shifts", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
894e7135aad64e745a10a3c169ca665851fad4c5
f3d4ee5b7351209e3f9a11ea96370b8b31532792
v1.0
instruct
Filter
Filter_38633_I
Increase the difficulty by adding a specific requirement: In addition to generating an AlexNet model for image classification, also implement a data augmentation technique such as random cropping or flipping to improve the model's performance. Write a function that performs the data augmentation and integrate it into t...
import torch import torch.nn as nn import torchvision.transforms as transforms import torchvision.models as models def get_alexnet_model(pretrained=True, num_classes=1000): """ Returns an AlexNet model. If pretrained is True, returns a model pre-trained on ImageNet. The num_classes parameter specifies the ...
from solution import get_alexnet_model, get_data_transforms, get_dataloader import torchvision.datasets as datasets def test_get_alexnet_model_structure(): model = get_alexnet_model(pretrained=False, num_classes=100) assert isinstance(model, models.AlexNet) assert model.classifier[6].out_features == 100 d...
[ { "docstring": "Returns an AlexNet model. If pretrained is True, returns a model pre-trained on ImageNet.\nThe num_classes parameter specifies the number of classes for the classifier layer.", "function_declaration": "def get_alexnet_model(pretrained=True, num_classes=1000):", "function_name": "get_alex...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms, models\n\ndef get_data_loaders(batch_size=32, data_dir='./data'):\n \"\"\"\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00038633", "row_id": 38633, "seed_ids": "['Qwen2-72B-Instruct_85156']" }
0.305557
Filter_38633
I
[ "get_alexnet_model", "get_data_transforms", "get_dataloader" ]
3
[ [ "get_dataloader", "get_data_transforms" ] ]
1
[]
false
[]
false
pytest
true
[ "torch", "torchvision" ]
false
370c1b93c35b3e937178872f21c6f6616eb21476
37ae9077633b2cfba6866d8274eee7809b22e9a3
v1.0
instruct
Filter
Filter_38822_I
I have a problem in my application right now where there is no EQ button or lie filter option. This is causing some issues when trying to adjust the sound quality. Can you propose a solution that would involve using both a button and a slider to manipulate the bass levels? Preferably in Python.
import tkinter as tk from tkinter import ttk def adjust_bass(value): """ Adjusts the bass level based on the slider value. """ bass_level = int(value) print(f"Bass level set to: {bass_level}") # Here you would add code to process the bass level adjustment def create_eq_interface(): """ ...
import pytest from unittest.mock import patch from solution import adjust_bass, create_eq_interface @patch('builtins.print') def test_adjust_bass(mock_print): adjust_bass(60) mock_print.assert_called_with("Bass level set to: 60") @patch('tkinter.Tk') @patch('tkinter.ttk.Button') @patch('tkinter.ttk.Scale') d...
[ { "docstring": "Adjusts the bass level based on the slider value.", "function_declaration": "def adjust_bass(value):", "function_name": "adjust_bass", "parameter_list": "(value)" }, { "docstring": "Creates a GUI window with a button and a slider to manipulate bass levels.", "function_dec...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from tkinter import Tk, Scale, Button, HORIZONTAL\n\ndef change_bass(value):\n \"\"\"\n Adjust the bass level based on slider value.\n \"\"\"\n print(f\"Adjusting bass level to {va...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00038822", "row_id": 38822, "seed_ids": "['Qwen2-72B-Instruct_85471']" }
0.236655
Filter_38822
I
[ "adjust_bass", "create_eq_interface" ]
2
[ [ "create_eq_interface", "adjust_bass" ] ]
1
[]
false
[]
false
pytest
true
[]
true
66cb46809e0d48e69089e9f880eb25b27492b798
882688554a96e4dfd6a43cea549416255d047f4b
v1.0
instruct
Filter
Filter_38867_I
Build a Python function that, given two lists of floating point numbers, identifies and retains the smallest prime number from each list, and calculates the third root of each. The function should handle exceptions for values not in number format and return a list composed of these third roots. Ensure that you import n...
import math def is_prime(n): """Check if a number is prime.""" if n <= 1: return False if n == 2: return True # 2 is the only even prime number if n % 2 == 0: return False max_divisor = math.isqrt(n) for d in range(3, max_divisor + 1, 2): if n % d == 0: ...
from solution import smallest_prime_root import math import pytest def test_small_list(): list1 = [2.0, 3.0, 5.0] list2 = [11.0, 13.0, 17.0] result = smallest_prime_root(list1, list2) expected = [2.0 ** (1/3), 11.0 ** (1/3)] assert math.isclose(result[0], expected[0], rel_tol=1e-9) assert math....
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculate the third root of a number.", "function_declaration": "def third_root(n):", "function_name": "third_root", "...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(num):\n \"\"\"Check if the given number is a prime number.\"\"\"\n if num <= 1:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00038867", "row_id": 38867, "seed_ids": "['Qwen2-72B-Instruct_85558']" }
0.567465
Filter_38867
I
[ "is_prime", "third_root", "smallest_prime_root" ]
3
[ [ "smallest_prime_root", "is_prime" ], [ "smallest_prime_root", "third_root" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d0bdbe0a76991becfab8b28e2690d8752a000a22
601f91e18aba197bf540574900cb0dcae6292271
v1.0
instruct
Filter
Filter_38922_I
Develop a Python program to analyze a given list of URL requests and count the number of unique requests. Additionally, your solution should be able to handle and correct erroneous URLs by removing incorrect symbols that are not part of standard URL structures and then count the unique requests again.
import re def sanitize_url(url): """ Remove incorrect symbols from the URL. """ return re.sub(r'[^a-zA-Z0-9\:/\.\-_]', '', url) def count_unique_requests(urls): """ Analyze a given list of URL requests and count the number of unique requests. """ sanitized_urls = [sanitize_url(url) for...
from solution import count_unique_requests def test_count_unique_requests_with_clean_urls(): urls = [ "https://example.com/requestA", "https://example.com/requestB", "https://example.com/requestC" ] assert count_unique_requests(urls) == 3 def test_count_unique_requests_with_duplica...
[ { "docstring": "Remove incorrect symbols from the URL.", "function_declaration": "def sanitize_url(url):", "function_name": "sanitize_url", "parameter_list": "(url)" }, { "docstring": "Analyze a given list of URL requests and count the number of unique requests.", "function_declaration":...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef clean_url(url):\n \"\"\"\n Removes incorrect symbols from the URL that are not part of standard URL structures.\n \"\"\"\n return re.sub(r'[^a-zA-Z0-9\\-._~:/?#\\[...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00038922", "row_id": 38922, "seed_ids": "['Qwen2-72B-Instruct_85661']" }
0.566476
Filter_38922
I
[ "sanitize_url", "count_unique_requests" ]
2
[ [ "count_unique_requests", "sanitize_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
770d9d41e2bd1d9e755c22fd7b7c0a5890020010
670235ef1cde15f20b87d656e1ce197ec083dbda
v1.0
instruct
Filter
Filter_39004_I
Create a Python function to measure similarity between two strings based on Jaccard Similarity Index, Cosine Similarity, and also Levenshtein Distance with normalization. Besides, add functionality to choose which similarity measure(s) to use via function parameter.
import math from collections import Counter from typing import List, Tuple def jaccard_similarity(str1: str, str2: str) -> float: set1 = set(str1) set2 = set(str2) intersection = len(set1 & set2) union = len(set1 | set2) return intersection / union if union != 0 else 0 def cosine_similarity(str1: ...
from solution import jaccard_similarity, cosine_similarity, levenshtein_distance, string_similarity def test_jaccard_similarity(): assert jaccard_similarity("abc", "abc") == 1.0 assert jaccard_similarity("abc", "def") == 0.0 assert jaccard_similarity("abc", "ab") == 2/3 assert jaccard_similarity("aaa",...
[ { "docstring": null, "function_declaration": "def jaccard_similarity(str1, str2):", "function_name": "jaccard_similarity", "parameter_list": "(str1, str2)" }, { "docstring": null, "function_declaration": "def cosine_similarity(str1, str2):", "function_name": "cosine_similarity", ...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import Counter\nfrom math import sqrt\nfrom Levenshtein import distance as levenshtein_distance\n\ndef jaccard_similarity(str1, str2):\n set1, set2 = set(str1), set(str2)\n...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00039004", "row_id": 39004, "seed_ids": "['Qwen2-72B-Instruct_85798']" }
0.774509
Filter_39004
I
[ "jaccard_similarity", "cosine_similarity", "levenshtein_distance", "string_similarity" ]
4
[ [ "string_similarity", "cosine_similarity" ], [ "string_similarity", "jaccard_similarity" ], [ "string_similarity", "levenshtein_distance" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6e7528176f5db40d95d3d0b9ee8bdd7b8ec2471e
b0bd6f99ecbedbd4416bd1bee9a9cd0cbd08b09e
v1.0
instruct
Filter
Filter_39102_I
Write Python code for the theorem that considers any convex quadrilateral whose diagonals intersect at a point which is also the orthocenter. This convex quadrilateral is represented as a 2D list. The code needs to validate if the angles formed at this intersection point are right angles. Moreover, it should confirm wh...
import math def dot_product(v1, v2): return sum(a * b for a, b in zip(v1, v2)) def vector_from_points(P1, P2): return [P2[0] - P1[0], P2[1] - P1[1]] def is_right_angle(v1, v2): return dot_product(v1, v2) == 0 def area_of_triangle(P1, P2, P3): return abs(P1[0]*(P2[1] - P3[1]) + P2[0]*(P3[1] - P1[1]) ...
import math from solution import validate_convex_quadrilateral def test_validate_convex_quadrilateral_right_angle(): quadrilateral = [ [0, 0], # Point A [0, 4], # Point B [4, 4], # Point C [4, 0] # Point D ] assert validate_convex_quadrilateral(quadrilateral) == True d...
[ { "docstring": null, "function_declaration": "def dot_product(v1, v2):", "function_name": "dot_product", "parameter_list": "(v1, v2)" }, { "docstring": null, "function_declaration": "def vector_from_points(P1, P2):", "function_name": "vector_from_points", "parameter_list": "(P1, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef are_diagonals_orthocenter(diagonal1, diagonal2):\n \"\"\"\n Returns True if the diagonals intersect at right angles and\n each diagonal divides the quadrilateral in...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00039102", "row_id": 39102, "seed_ids": "['Qwen2-72B-Instruct_85957']" }
0.481758
Filter_39102
I
[ "dot_product", "vector_from_points", "is_right_angle", "area_of_triangle", "validate_convex_quadrilateral" ]
5
[ [ "is_right_angle", "dot_product" ], [ "validate_convex_quadrilateral", "area_of_triangle" ], [ "validate_convex_quadrilateral", "is_right_angle" ], [ "validate_convex_quadrilateral", "vector_from_points" ] ]
4
[]
false
[]
false
pytest
true
[]
true
3428eabcb268fd0d7960a4c9048c0ca1083865bb
ed578228a691091511a375f3fc8b890cc005f440
v1.0
instruct
Filter
Filter_39292_I
Write code that determines not only if a string is a palindrome, but also a perfect square palindrome. The string should consist only of digits. If the number the string represents is not a perfect square, or it isn't a palindrome, the function should return false.
import math def is_palindrome(s): """ Returns True if the string s is a palindrome, False otherwise. """ return s == s[::-1] def is_perfect_square(n): """ Returns True if n is a perfect square, False otherwise. """ root = int(math.sqrt(n)) return root * root == n def is_perfect_sq...
from solution import is_perfect_square_palindrome def test_palindrome_and_perfect_square(): # "121" is a palindrome and 121 is a perfect square (11^2) assert is_perfect_square_palindrome("121") == True def test_palindrome_not_perfect_square(): # "22" is a palindrome but 22 is not a perfect square asse...
[ { "docstring": "Returns True if the string s is a palindrome, False otherwise.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Returns True if n is a perfect square, False otherwise.", "function_declaration":...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_palindrome(s):\n \"\"\"\n Checks if a given string s is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef is_perfect_square(n):\n \"\"\"\n Checks if a...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00039292", "row_id": 39292, "seed_ids": "['Qwen2-72B-Instruct_86302']" }
0.681357
Filter_39292
I
[ "is_palindrome", "is_perfect_square", "is_perfect_square_palindrome" ]
3
[ [ "is_perfect_square_palindrome", "is_palindrome" ], [ "is_perfect_square_palindrome", "is_perfect_square" ] ]
2
[]
false
[]
false
pytest
true
[]
true
613d7245d9b12e5d38fa06527699759d9362449e
001ec0e9d159748195566bc59b24fe067bc04721
v1.0
instruct
Filter
Filter_39376_I
Write a python function which takes a list of 2-D points [[x1,y1],[x2,y2],...,[xn,yn]] and a point [x,y]. The function should find the smallest circle which intersects at least 3 points and passes through the point [x,y]. The function should return the center (a,b) and radius r of this circle.
import math from itertools import combinations def dist(p1, p2): """Calculate the Euclidean distance between two points.""" return math.hypot(p1[0] - p2[0], p1[1] - p2[1]) def circle_from_points(p1, p2, p3): """Return the center (a, b) and radius r of the circle through p1, p2, p3.""" A = p1[0] - p2[0...
import pytest from solution import find_smallest_circle def test_basic_case(): points = [[0, 0], [1, 0], [0, 1], [1, 1]] point = [0.5, 0.5] circle = find_smallest_circle(points, point) assert circle is not None assert round(circle[2], 2) == 0.71 def test_three_points_circle(): points = [[0, 0]...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def dist(p1, p2):", "function_name": "dist", "parameter_list": "(p1, p2)" }, { "docstring": "Return the center (a, b) and radius r of the circle through p1, p2, p3.", "function_declaration": "...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import combinations\nfrom math import sqrt\n\ndef circle_from_points(p1, p2, p3):\n \"\"\"\n Return the center (a,b) and radius r of the circle passing through points p1, ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00039376", "row_id": 39376, "seed_ids": "['Qwen2-72B-Instruct_86436']" }
0.533034
Filter_39376
I
[ "dist", "circle_from_points", "is_point_inside_circle", "find_smallest_circle" ]
4
[ [ "circle_from_points", "dist" ], [ "find_smallest_circle", "circle_from_points" ], [ "find_smallest_circle", "is_point_inside_circle" ], [ "is_point_inside_circle", "dist" ] ]
4
[]
false
[]
false
pytest
true
[]
true
8e8fead30c62539766e2dc1e6fc6047c115fc9d9
3ae49e428e378b2cc684fe660b5f508b92fcc051
v1.0
instruct
Filter
Filter_39394_I
Construct a code that dissects, inspects, modifies if necessary, and ultimately reintegrates specific data in a number series presented as an array. The code should find prime numbers in the array and replace them with the next fibinacci number in their place. The interval should be defined by the provided start and en...
def is_prime(n): """ Checks 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 Tru...
from solution import process_series def test_basic_case(): arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] start, end = 0, 9 expected = [1, 3, 5, 4, 8, 6, 8, 8, 9, 10] assert process_series(arr, start, end) == expected def test_out_of_bounds(): arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] start, end = -5, 15 ...
[ { "docstring": "Checks if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generator to produce Fibonacci numbers indefinitely.", "function_declaration": "def fibonacci_gen():", "function_name": "...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def next_fibonacci(num):\n \"\"\"\n Returns the next Fibonacci number after 'num'.\n \"\"\"\n a, b = 0, 1\n while b <= num:\n a, b = b, a + b\n return b\n\ndef is_prim...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00039394", "row_id": 39394, "seed_ids": "['Qwen2-72B-Instruct_86477']" }
0.558358
Filter_39394
I
[ "is_prime", "fibonacci_gen", "find_next_fibonacci", "process_series" ]
4
[ [ "find_next_fibonacci", "fibonacci_gen" ], [ "process_series", "find_next_fibonacci" ], [ "process_series", "is_prime" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6b0e8d34d7d76ff11c43515e2456594288e6995e
cb104fc85111e0f0b7da2193122e5f3a40edbdbd
v1.0
instruct
Filter
Filter_39497_I
Write a polar plot interpreter in Python. Given a polar representation of a complex number in the form (radius, angle), the program should plot it on a polar graph and also return the x and y Cartesian coordinates. Additionally, the interpreter should be able to handle multiple points plotted on the same graph.
import matplotlib.pyplot as plt import numpy as np def polar_to_cartesian(radius, angle): """ Converts polar coordinates to Cartesian coordinates. Parameters: radius (float): The radius (distance from the origin) angle (float): The angle in radians Returns: (float, float): The Cartesian c...
from solution import polar_to_cartesian, plot_polar_points def test_polar_to_cartesian(): assert polar_to_cartesian(1, 0) == (1, 0) assert np.isclose(polar_to_cartesian(1, np.pi / 2), (0, 1)).all() assert np.isclose(polar_to_cartesian(1, np.pi), (-1, 0)).all() assert np.isclose(polar_to_cartesian(1, 3 ...
[ { "docstring": "Converts polar coordinates to Cartesian coordinates.\n\nParameters:\nradius (float): The radius (distance from the origin)\nangle (float): The angle in radians\n\nReturns:\n(float, float): The Cartesian coordinates (x, y)", "function_declaration": "def polar_to_cartesian(radius, angle):", ...
[ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\nimport numpy as np\n\ndef polar_to_cartesian(radius, angle):\n \"\"\"\n Converts polar coordinates (radius, angle) to Cartesian coordinates (x, y).\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00039497", "row_id": 39497, "seed_ids": "['Qwen2-72B-Instruct_86647']" }
0.789175
Filter_39497
I
[ "polar_to_cartesian", "plot_polar_points" ]
2
[ [ "plot_polar_points", "polar_to_cartesian" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
21f885da78d507303edad831ebe52f48cdf11c8d
5194869a4146446207628f0f8d72214a297cca41
v1.0
instruct
Filter
Filter_39598_I
Suppose I have a list of words and I want to find their anagrams. Specifically, I want to find all the anagrams for the word "elbow" that are listed in the Global相当Words dataset. How can I do this using Python code and pandas library?
import pandas as pd def find_anagrams(target_word, word_list): """ Finds all anagrams of the target word from the given word list. :param target_word: The word to find anagrams for. :param word_list: List of words to search through. :return: List of anagrams found in the word list. """ ...
import pandas as pd from solution import find_anagrams, find_anagrams_in_dataframe def test_find_anagrams(): word_list = ["elbow", "below", "bellow", "bow", "hello", "world"] target_word = "elbow" expected_anagrams = ["elbow", "below"] assert find_anagrams(target_word, word_list) == expected_anagrams ...
[ { "docstring": "Finds all anagrams of the target word from the given word list.\n\n:param target_word: The word to find anagrams for.\n:param word_list: List of words to search through.\n:return: List of anagrams found in the word list.", "function_declaration": "def find_anagrams(target_word, word_list):",...
[ 0, 0, 0, 1, 1, 0, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\n\ndef find_anagrams(word, dataset):\n \"\"\"\n Returns a list of anagrams of the given word from the specified dataset.\n \n Args:\n word (str): The word fo...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00039598", "row_id": 39598, "seed_ids": "['Qwen2-72B-Instruct_86830']" }
0.509233
Filter_39598
I
[ "find_anagrams", "find_anagrams_in_dataframe" ]
2
[ [ "find_anagrams_in_dataframe", "find_anagrams" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
6d9c824b9cefab8b11e44c6ed295bb0e88d0130c
2021ab1d7aab28d51fe3dd5614dee19255783466
v1.0
instruct
Filter
Filter_39662_I
Based on the FastAPI and Nicoco/yahoo-finance-cli2 library, create a price_change_percentage function that calculates percentage of price change of a particular stock within specific time X (take this value as an input) and compare it with a volatility value (also an input) obtained from a specific API (that a user imp...
import requests from datetime import datetime, timedelta class StockTickerError(Exception): """Custom exception class for stock ticker errors.""" pass def get_stock_price_on(isin, date): """ Function to get stock price on a specific date using Nicoco/yahoo-finance-cli2. """ try: # Sim...
import pytest from unittest.mock import patch from datetime import datetime, timedelta from solution import price_change_percentage, StockTickerError def mock_get_stock_price_on(isin, date): # Mock function to return stock prices based on the date prices = { '2023-10-01': 100, '2023-09-01': 90,...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from fastapi import FastAPI\nfrom nicoco.yahoofinance import Stock\nfrom typing import Union\n\napp = FastAPI()\n\nclass StockTickerError(Exception):\n pass\n\n@app.get(\"/price_change_perc...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00039662", "row_id": 39662, "seed_ids": "['Qwen2-72B-Instruct_86962']" }
0.417224
Filter_39662
I
[ "get_stock_price_on", "get_volatility", "price_change_percentage" ]
3
[ [ "price_change_percentage", "get_stock_price_on" ], [ "price_change_percentage", "get_volatility" ] ]
2
[]
false
[ "StockTickerError" ]
true
pytest
true
[ "requests" ]
false
218955f34bbb3a693df1571c658c805d307b099d
c0f4bd56eace62d7644ddbdbd5133c4f6a03c6bc
v1.0
instruct
Filter
Filter_39768_I
Write a function in Python that generates a Markov chain based on a given text and uses it to generate new text by allowing the next word to be influenced not only by the previous word, but also by the second previous word. In addition to printing the generated text, save it to a text file with an option for the user t...
import random from collections import defaultdict def generate_markov_chain(text): """ Generate a Markov chain based on the given text. """ words = text.split() markov_chain = defaultdict(list) for i in range(len(words) - 2): markov_chain[(words[i], words[i+1])].append(words[i+2]) ...
from solution import generate_markov_chain, generate_text, save_text_to_file, generate_and_save_text import os def test_generate_markov_chain(): text = "hello world hello universe hello world universe" markov_chain = generate_markov_chain(text) expected_chain = { ('hello', 'world'): ['hello', 'univ...
[ { "docstring": "Generate a Markov chain based on the given text.", "function_declaration": "def generate_markov_chain(text):", "function_name": "generate_markov_chain", "parameter_list": "(text)" }, { "docstring": "Generate new text based on the Markov chain, using the provided seed word and...
[ 0, 0, 0, 1, 0, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport re\n\ndef generate_markov_chain(text):\n \"\"\"\n This function generates a Markov chain based on a given text.\n It takes the previous two words to predict the ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00039768", "row_id": 39768, "seed_ids": "['Qwen2-72B-Instruct_87148']" }
0.608506
Filter_39768
I
[ "generate_markov_chain", "generate_text", "save_text_to_file", "generate_and_save_text" ]
4
[ [ "generate_and_save_text", "generate_markov_chain" ], [ "generate_and_save_text", "generate_text" ], [ "generate_and_save_text", "save_text_to_file" ] ]
3
[]
false
[]
false
pytest
true
[]
true
a40da60742dccf212f251b758dd41bacd589f1f0
63c3160bcfcd657a3cd3f318ba240fc954820040
v1.0
instruct
Filter
Filter_39874_I
Please write a parallel Python function to download multiple content from a list of urls based on given query keys, save them to a predefined folder, and extract specific data using a simple query on the saved files. Your function should efficiently handle multiple downloads and extractions concurrently to optimize the...
import os import aiohttp import asyncio from concurrent.futures import ThreadPoolExecutor from bs4 import BeautifulSoup # Define folder to save the downloaded content SAVE_FOLDER = 'downloads' if not os.path.exists(SAVE_FOLDER): os.makedirs(SAVE_FOLDER) async def download_content(session, url, filename): """ ...
import os import pytest import shutil from solution import download_and_extract, SAVE_FOLDER def setup_module(module): """Setup any state specific to the execution of the given module.""" if not os.path.exists(SAVE_FOLDER): os.makedirs(SAVE_FOLDER) def teardown_module(module): """Teardown any stat...
[ { "docstring": "Extract specific data from the saved file based on the query. \nFor simplicity, use BeautifulSoup to query HTML content.", "function_declaration": "def extract_data_from_file(filename, query):", "function_name": "extract_data_from_file", "parameter_list": "(filename, query)" }, {...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport aiohttp\nimport asyncio\nimport aiofiles\n\nasync def download(url, session, folder_path):\n \"\"\"\n Async function to download content from a single url and save to a...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00039874", "row_id": 39874, "seed_ids": "['Qwen2-72B-Instruct_87343']" }
0.634956
Filter_39874
I
[ "download_content", "download_all", "extract_data_from_file", "main", "download_and_extract" ]
5
[ [ "download_all", "download_content" ], [ "download_and_extract", "main" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp", "bs4" ]
false
e03fa0d74012bb3c0a19ccd7cd5db268ec7c60f9
689c62feb9787ad9eba9c2568f1b44514f304110
v1.0
instruct
Filter
Filter_40018_I
/Game_theory.py: Generate a list of all possible strategy profiles (tuples) given a list of strategy sets, and return the strategy profiles that can achieve equilibrium under the given condition. The function should take two arguments, a list of strategy sets and a function that defines the condition for equilibrium fo...
from itertools import product def generate_strategy_profiles(strategy_sets): """ Generates all possible strategy profiles given a list of strategy sets. Parameters: strategy_sets (list of lists): A list where each element is a list of strategies for a player. Returns: list of tuples: All poss...
from solution import generate_strategy_profiles, find_equilibrium_profiles def test_generate_strategy_profiles(): strategy_sets = [[1, 2], ['A', 'B']] expected_profiles = [ (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B'), ] assert generate_strategy_profiles(strategy_sets) == expe...
[ { "docstring": "Generates all possible strategy profiles given a list of strategy sets.\n\nParameters:\nstrategy_sets (list of lists): A list where each element is a list of strategies for a player.\n\nReturns:\nlist of tuples: All possible strategy profiles.", "function_declaration": "def generate_strategy...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef generate_all_strategy_profiles(strategy_sets):\n \"\"\"\n Given a list of strategy sets, generate all possible strategy profiles.\n \n Args:\n strategy_s...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00040018", "row_id": 40018, "seed_ids": "['Qwen2-72B-Instruct_87615']" }
0.434096
Filter_40018
I
[ "generate_strategy_profiles", "find_equilibrium_profiles" ]
2
[ [ "find_equilibrium_profiles", "generate_strategy_profiles" ] ]
1
[]
false
[]
false
pytest
true
[]
true
762d79b36693a515e18b295ddd90ff6b59e96578
6052696121932ff55f63a3dc55a98971d77f2063
v1.0
instruct
Filter
Filter_40020_I
Develop a transaction digest algorithm that not only replaces all alphabetic characters in a given transaction ID with a unique alphanumeric symbol, but also includes a timestamp to add chronological context to the encryption. For added complexity, implement an additional function that transforms the transaction ID bas...
import hashlib from datetime import datetime def generate_unique_symbols(): symbols = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' return {chr(i): symbols[i % len(symbols)] for i in range(256)} def replace_characters(transaction_id, symbol_map): return ''.join(symbol_map.get(c, c) for ...
from solution import transaction_digest, generate_unique_symbols, replace_characters, add_timestamp, transform_transaction_id import re def test_generate_symbol_map_length(): symbol_map = generate_unique_symbols() assert len(symbol_map) == 256 def test_replace_characters(): symbol_map = {'a': '1', 'b': '2...
[ { "docstring": null, "function_declaration": "def generate_unique_symbols():", "function_name": "generate_unique_symbols", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def replace_characters(transaction_id, symbol_map):", "function_name": "replace_character...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import string\nimport time\n\n# Mapping dictionary for alphanumeric substitution\nsubstitution_map = {\n **{char: str(index + 1).zfill(2) for index, char in enumerate(string.ascii_lowercase...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040020", "row_id": 40020, "seed_ids": "['Qwen2-72B-Instruct_87624']" }
0.478229
Filter_40020
I
[ "generate_unique_symbols", "replace_characters", "add_timestamp", "transform_transaction_id", "transaction_digest" ]
5
[ [ "transaction_digest", "add_timestamp" ], [ "transaction_digest", "generate_unique_symbols" ], [ "transaction_digest", "replace_characters" ], [ "transaction_digest", "transform_transaction_id" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ccdd3c758e242820284184400f85d56a4b460e71
4e0eed2098deca03cf44da81464e692a28583f43
v1.0
instruct
Filter
Filter_40093_I
Create a Python function that solves the task of determining the net score of a set of semi-prime values. The net score is calculated by applying the specific operator, provided as op, to reduce the semi-prime values list into a single result value. Before performing this operation, validate each number to ensure they ...
import operator import math def is_semiprime(n): """ Determines if a number is a semi-prime. A semi-prime is a natural number that is the product of two prime numbers. """ count = 0 for i in range(2, int(math.sqrt(n)) + 1): while n % i == 0: n //= i count += 1 ...
import pytest from solution import net_score def test_net_score_sum(): assert net_score([4, 6, 9, 10], 'sum') == 29 def test_net_score_mul(): assert net_score([4, 6, 9, 10], 'mul') == 2160 def test_net_score_sub(): assert net_score([4, 6, 9, 10], 'sub') == -21 def test_net_score_truediv(): assert ne...
[ { "docstring": "Determines if a number is a semi-prime.\nA semi-prime is a natural number that is the product of two prime numbers.", "function_declaration": "def is_semiprime(n):", "function_name": "is_semiprime", "parameter_list": "(n)" }, { "docstring": "Determines the net score of a list...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import operator\nfrom math import isqrt\n\ndef is_semi_prime(n):\n \"\"\"\n Validates if a number is a semi-prime.\n A semi-prime number is a product of exactly two prime numbers.\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00040093", "row_id": 40093, "seed_ids": "['Qwen2-72B-Instruct_87772']" }
0.553245
Filter_40093
I
[ "is_semiprime", "net_score" ]
2
[ [ "net_score", "is_semiprime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
556b8f36632ea56093a54924f69a8a04179267e3
bec6e347a72312400a5056769a261cd1cafc86f6
v1.0
instruct
Filter
Filter_40219_I
You were tasked to develop and code a decision tree classifier from scratch in python without use of any library other than numpy for mathematical operations. You should also write the functions for data set splitting, information gain, gini index, and entropy calculation. Ensure the code is well-commented for easy und...
import numpy as np def entropy(y): """ Calculate the entropy of a label array y. """ values, counts = np.unique(y, return_counts=True) probabilities = counts / len(y) return -np.sum([p * np.log2(p) for p in probabilities if p > 0]) def gini_index(y): """ Calculate the Gini index of a l...
import numpy as np from solution import entropy, gini_index, information_gain, split_dataset, DecisionTreeClassifier def test_entropy(): y = np.array([0, 0, 1, 1]) assert np.isclose(entropy(y), 1) def test_gini_index(): y = np.array([0, 0, 1, 1]) assert np.isclose(gini_index(y), 0.5) def test_informa...
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\nclass DecisionTreeClassifier:\n def __init__(self, min_samples_split=2, max_depth=100):\n self.min_samples_split = min_samples_split\n self.max_depth = m...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040219", "row_id": 40219, "seed_ids": "['Qwen2-72B-Instruct_88012']" }
0.459761
Filter_40219
I
[ "entropy", "gini_index", "information_gain", "split_dataset" ]
4
[ [ "information_gain", "entropy" ], [ "information_gain", "gini_index" ] ]
2
[]
false
[ "Node", "DecisionTreeClassifier" ]
true
pytest
true
[ "numpy" ]
false
92222365d5fbd300239976f9a3d36b41eb4bd2b9
f9bf8d8b96da6118405d188b2f78482366d4e33a
v1.0
instruct
Filter
Filter_40226_I
Develop a Python program that tests if a string is a palindrome. However, to make it more challenging, your program should not just check the most common palindrome cases like 'madam' or 'racecar'; it should be capable of judging whether or not longer strings, up to 1000 characters in length and in reverse, and phrases...
import re def is_palindrome(s): """ Checks if a given string s is a palindrome considering only alphanumeric characters and ignoring cases. """ # Remove non-alphanumeric characters and convert to lowercase filtered_string = re.sub(r'[^A-Za-z0-9]', '', s).lower() # Check if filtered string is eq...
from solution import check_palindromes def test_check_palindromes_all_palindromes(): strings = [ "A man, a plan, a canal, Panama!", "Was it a car or a cat I saw?", "Madam, in Eden, I'm Adam", "Able was I, I saw elbA", ] expected = [True, True, True, True] assert check_pa...
[ { "docstring": "Checks if a given string s is a palindrome considering only alphanumeric characters and ignoring cases.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Checks an array of strings and returns a lis...
[ 0, 0, 0, 1, 0, 0, 1, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef is_palindrome(s):\n \"\"\"\n Returns True if the string s is a palindrome, ignoring punctuation,\n spaces, and case. Otherwise, returns False.\n \"\"\"\n s = re...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00040226", "row_id": 40226, "seed_ids": "['Qwen2-72B-Instruct_88028']" }
0.819828
Filter_40226
I
[ "is_palindrome", "check_palindromes" ]
2
[ [ "check_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
76e085adbffde7c85938e386f11f97952ad25893
bacfbc7bc5d47a8d830c73a9a29fdba0a6fd6d11
v1.0
instruct
Filter
Filter_40272_I
Implement a backtracking algorithm to solve a sudoku puzzle with the additional constraints that the solution must be found within a specified time limit of 5 seconds and the algorithm must be able to handle puzzles of size N x N, where N is a positive integer less than or equal to 9. Additionally, the algorithm must o...
import time SIZE = 9 # Standard size of Sudoku puzzle is 9x9 def is_valid(board, row, col, num): """ Check if it's legal to assign num to the given row/col position. """ # Check row for x in range(SIZE): if board[row][x] == num: return False # Check column for x in ra...
from solution import solve_sudoku def test_sudoku_returns_correct_solution(): board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], ...
[ { "docstring": "Check if it's legal to assign num to the given row/col position.", "function_declaration": "def is_valid(board, row, col, num):", "function_name": "is_valid", "parameter_list": "(board, row, col, num)" }, { "docstring": "Uses backtracking to solve the Sudoku puzzle.\nAddition...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef is_safe(board, row, col, num, N):\n # Check if 'num' is not in given row \n for x in range(N): \n if board[row][x] == num: \n return False\n \n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00040272", "row_id": 40272, "seed_ids": "['Qwen2-72B-Instruct_88117']" }
0.523122
Filter_40272
I
[ "is_valid", "solve_sudoku" ]
2
[ [ "solve_sudoku", "is_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
06cb006ff391288345caa4e5eac289b4f332a47f
4fefe6957ab4fa607ad544d63f0a8005fd238b5f
v1.0
instruct
Filter
Filter_40454_I
Develop a Python code snippet that expresses the algorithm of linear search in a non-ordered list. You must also implement input validation for ensuring that the given list is actually non-ordered. Your code should also efficently handle large data inputs up to 10,000 elements.
def is_non_ordered_list(lst): """ Checks if the given list is non-ordered. A list is considered non-ordered if it is neither entirely non-decreasing nor non-increasing. """ if len(lst) < 2: return True # A list with fewer than 2 elements is trivially non-ordered is_non_decreasing = all...
from solution import is_non_ordered_list, linear_search def test_is_non_ordered_list(): assert is_non_ordered_list([3, 1, 4, 2]) == True assert is_non_ordered_list([1, 2, 3, 4]) == False assert is_non_ordered_list([4, 3, 2, 1]) == False assert is_non_ordered_list([1, 1, 1, 1]) == False assert is_no...
[ { "docstring": "Checks if the given list is non-ordered.\nA list is considered non-ordered if it is neither entirely non-decreasing nor non-increasing.", "function_declaration": "def is_non_ordered_list(lst):", "function_name": "is_non_ordered_list", "parameter_list": "(lst)" }, { "docstring...
[ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_non_ordered(arr):\n \"\"\"\n Checks if the list is non-ordered (neither strictly increasing nor strictly decreasing).\n \"\"\"\n is_inc = is_dec = True\n\n for i in range...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040454", "row_id": 40454, "seed_ids": "['Qwen2-72B-Instruct_88443']" }
0.54724
Filter_40454
I
[ "is_non_ordered_list", "linear_search" ]
2
[ [ "linear_search", "is_non_ordered_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8ed18aec6ff3d4c8570c26fe3f1d50a6f0e22227
5348f46e07e0b90975c466ff1e5b594a7f7812e7
v1.0
instruct
Filter
Filter_40521_I
function \* takes a and b, which are both positive integers, and creates a Fibonacci sequence based on them. Moreover, write a filter function such that it returns even numbers in the Fibonacci sequence in descending order. Specifically, the function should identify the a^b Fibonacci number, create the Fibonacci sequen...
def fibonacci(n): """ Generates a Fibonacci sequence up to the nth number. """ sequence = [0, 1] while len(sequence) < n: next_value = sequence[-1] + sequence[-2] sequence.append(next_value) return sequence def filter_even_descending(sequence): """ Filters even numbers f...
from solution import fibonacci_even_descending def test_fibonacci_even_descending(): result = fibonacci_even_descending(2, 5) # The 2^5 = 32nd Fibonacci number # Fibonacci sequence up to 32nd number: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17...
[ { "docstring": "Generates a Fibonacci sequence up to the nth number.", "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": "Filters even numbers from the sequence and returns them in descending order.", "function_declaratio...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def fibonacci(a, b):\n \"\"\"\n Generates a Fibonacci sequence until the a^b Fibonacci number,\n then filters out and returns the even numbers in descending order.\n \"\"\"\n n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00040521", "row_id": 40521, "seed_ids": "['Qwen2-72B-Instruct_88566']" }
0.676644
Filter_40521
I
[ "fibonacci", "filter_even_descending", "fibonacci_even_descending" ]
3
[ [ "fibonacci_even_descending", "fibonacci" ], [ "fibonacci_even_descending", "filter_even_descending" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b38122db459a0ce34fa49f320e643aca7d518e78
51e3e8be1768f3a7ac18accff008d70b094a7d82
v1.0
instruct
Filter
Filter_40556_I
Use Python generators to implement a function that returns the first 'n' prime numbers. After the initial 'n' primes have been generated, the function should continue to generate the next prime number one at a time, only when it is called again. The function should demonstrate the efficiency of generators in handling p...
def is_prime(n): """ Helper function to check if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % i + 2 == 0: return False i += ...
from solution import is_prime, prime_generator, first_n_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(1) == False assert is_prime(-7) == False def test_first_n_primes(): assert f...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generator function to yield prime numbers one by one.", "function_declaration": "def prime_generator():", ...
[ 0, 0, 0, 1, 1, 1, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00040556", "row_id": 40556, "seed_ids": "['Qwen2-72B-Instruct_88628']" }
0.669704
Filter_40556
I
[ "is_prime", "prime_generator", "first_n_primes" ]
3
[ [ "first_n_primes", "prime_generator" ], [ "prime_generator", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
296c73350547d472d012c16a9600c7af39726be7
448cd0dd18a837b47a494f3d6da60a4e514c8f6d
v1.0
instruct
Filter
Filter_40567_I
In the provided input, there are two lists: list_of_trees and list_of_itineraries. Each tree is represented as a node with a unique name, neighbors, type (wood or concrete) and scenic value. Our goal is to create a breadth-first search function that finds the shortest path to visit all the trees with the highest scenic...
from collections import deque, defaultdict class Tree: def __init__(self, name, neighbors, tree_type, scenic_value): self.name = name self.neighbors = neighbors self.tree_type = tree_type self.scenic_value = scenic_value def bfs_highest_scenic_value(trees, start): visited = set...
from solution import trip_to_trees def test_trip_to_trees_simple(): list_of_trees = [ {'name': 'A', 'neighbors': ['B'], 'type': 'wood', 'scenic_value': 5}, {'name': 'B', 'neighbors': ['A', 'C'], 'type': 'wood', 'scenic_value': 8}, {'name': 'C', 'neighbors': ['B'], 'type': 'concrete', 'sceni...
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import deque, defaultdict\n\nclass TreeNode:\n def __init__(self, name, neighbors, tree_type, scenic_value):\n self.name = name\n self.neighbors...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00040567", "row_id": 40567, "seed_ids": "['Qwen2-72B-Instruct_88644']" }
0.58261
Filter_40567
I
[ "bfs_highest_scenic_value", "trip_to_trees" ]
2
[ [ "trip_to_trees", "bfs_highest_scenic_value" ] ]
1
[]
false
[ "Tree" ]
true
pytest
true
[]
true
b83bcccd213db548280a94589dc1f0e7e6283f10
c8878c9637b0ad02f96b465437a413bb9d61483d
v1.0
instruct
Filter
Filter_40569_I
Construct a违纪违法multi-threaded code in Python to generate a sequence of n prime numbers utilising the Sieve of Eratosthenes method. This task will also require you to optimise your code to efficiently handle large values of n, for instance, generating the first 10,000 prime numbers. You should implement, concurrent, par...
import threading def sieve_of_eratosthenes(limit): primes = [True] * (limit + 1) p = 2 while (p * p <= limit): if primes[p]: for i in range(p * p, limit + 1, p): primes[i] = False p += 1 prime_numbers = [p for p in range(2, limit + 1) if primes[p]] return...
from solution import generate_n_primes, verification def test_generate_first_10_primes(): primes = generate_n_primes(10) assert primes == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] assert verification(primes) def test_generate_first_100_primes(): primes = generate_n_primes(100) assert len(primes) == 100...
[ { "docstring": null, "function_declaration": "def sieve_of_eratosthenes(limit):", "function_name": "sieve_of_eratosthenes", "parameter_list": "(limit)" }, { "docstring": null, "function_declaration": "def generate_primes(n, result):", "function_name": "generate_primes", "paramete...
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nimport threading\n\ndef sieve(n):\n \"\"\"\n Generate n prime numbers using Sieve of Eratosthenes in a multi-threaded manner.\n \"\"\"\n if n < 1:\n return []\n...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00040569", "row_id": 40569, "seed_ids": "['Qwen2-72B-Instruct_88650']" }
0.557401
Filter_40569
I
[ "sieve_of_eratosthenes", "generate_primes", "verification", "generate_n_primes" ]
4
[ [ "generate_primes", "sieve_of_eratosthenes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e782fd4f5035f81737359f40ba1eea7c0fc1bfd0
369a62a347e0d38bb71a2aebdc78910f9cfb03c7
v1.0
instruct
Filter
Filter_40576_I
Engender an intricate Python program which, by employing dictionary comprehensions, generates a dictionary with keys as prime numbers starting from 1 and going up to a user given limit N, and corresponding values as the product of two specified base numbers x and y, supposed to be less than the key and coprime with eac...
import math from sympy import primerange def gcd(a, b): while b: a, b = b, a % b return a def primes_and_coprime_products(limit, x, y): """ Generates a dictionary with keys as prime numbers starting from 1 and going up to a given limit N, and values as the product of two specified base num...
from solution import gcd, primes_and_coprime_products import pytest def test_gcd(): assert gcd(54, 24) == 6 assert gcd(20, 8) == 4 assert gcd(17, 5) == 1 assert gcd(1, 1) == 1 def test_primes_and_coprime_products(): assert primes_and_coprime_products(10, 3, 4) == {2: 12, 3: 12, 5: 12, 7: 12} ...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Generates a dictionary with keys as prime numbers starting from 1 and going up to a given limit N,\nand values as the product of two specified base numbers x a...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import gcd\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00040576", "row_id": 40576, "seed_ids": "['Qwen2-72B-Instruct_88663']" }
0.575113
Filter_40576
I
[ "gcd", "primes_and_coprime_products" ]
2
[ [ "primes_and_coprime_products", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[ "sympy" ]
false
51c7e0b8eb92d12aab44a91ed2b3a493830b3fac
28b7d7559cb5f288eb952cda9a847e16323094fa
v1.0
instruct
Filter
Filter_40631_I
How do I use recursion to draw a maze-like structure using Python? The structure should have a start point, end point, and walls, and should be solvable from start to end without hitting any walls.
import random def create_maze(width, height): # Initializing the maze with walls maze = [['#'] * width for _ in range(height)] # Utility functions for recursion def carve_passage(x, y): directions = [(2, 0), (-2, 0), (0, 2), (0, -2)] random.shuffle(directions) for ...
from solution import generate_solvable_maze def test_maze_size(): maze = generate_solvable_maze(5, 5) assert len(maze) == 5 assert len(maze[0]) == 5 assert maze[1][1] == 'S' assert maze[3][3] == 'E' def test_maze_elements(): maze = generate_solvable_maze(10, 10) assert maze[1][1] == 'S' ...
[ { "docstring": null, "function_declaration": "def create_maze(width, height):", "function_name": "create_maze", "parameter_list": "(width, height)" }, { "docstring": null, "function_declaration": "def print_maze(maze):", "function_name": "print_maze", "parameter_list": "(maze)" ...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef create_maze(width, height):\n \"\"\"\n Uses recursion to create a maze-like structure with start and end points.\n \"\"\"\n maze = [['#' for _ in range(width)]...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040631", "row_id": 40631, "seed_ids": "['Qwen2-72B-Instruct_88748']" }
0.508089
Filter_40631
I
[ "create_maze", "print_maze", "generate_solvable_maze" ]
3
[ [ "generate_solvable_maze", "create_maze" ], [ "generate_solvable_maze", "print_maze" ] ]
2
[]
false
[]
false
pytest
true
[]
true
be80c4baa10bb7dabfc752e6b187415f70cdcdff
b0339fc5a48fa1905a623d3f28f894f3a91c5720
v1.0
instruct
Filter
Filter_40675_I
Write a Python program to process receipt data. The program should accept as command line arguments: the directory that has the receipts files and a json configuration file. The config json file specifies the data quality validation methods to run. These receipts files are are in json format and named as download-yyyy_...
import os import json import sys from datetime import datetime import glob def process_receipts(directory, config_file): receipts = [] # Load the configuration file with open(config_file, 'r') as f: config = json.load(f) # Process files in the directory files = sorted(glob.glob(os...
from solution import process_receipts, generate_receipt_id import json import os def test_process_receipts(tmpdir): # Setup temporary directory and files data = [ {"sold_quantity": 10, "timestamp": ["2023-10-04T10:00:00.000Z"]}, {"sold_quantity": 5, "timestamp": ["2023-10-04T10:01:00.000Z"]} ...
[ { "docstring": null, "function_declaration": "def process_receipts(directory, config_file):", "function_name": "process_receipts", "parameter_list": "(directory, config_file)" }, { "docstring": null, "function_declaration": "def generate_receipt_id(timestamp):", "function_name": "gen...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import json\nimport os\nimport sys\nfrom datetime import datetime\n\ndef process_receipt_files(receipts_directory, config_file):\n receipts = []\n config = load_config(config_file)\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00040675", "row_id": 40675, "seed_ids": "['Qwen2-72B-Instruct_88830']" }
0.449745
Filter_40675
I
[ "process_receipts", "generate_receipt_id" ]
2
[ [ "process_receipts", "generate_receipt_id" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c48f090ea3c3c14a36667875ab2fc0e36c681496
00029f3727ea9664f126e3b23e50f833398debd9
v1.0
instruct
Filter
Filter_40679_I
Can you write a function that checks if two given Binary Search Trees (BSTs) have the same leaf node values?
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def get_leaf_values(root): if root is None: return [] if root.left is None and root.right is None: return [root.val] return get_leaf_values(root.l...
from solution import TreeNode, same_leaf_values def test_same_leaf_values_same_trees(): # Tree 1 root1 = TreeNode(1) root1.left = TreeNode(2) root1.right = TreeNode(3) root1.left.left = TreeNode(4) root1.left.right = TreeNode(5) root1.right.left = TreeNode(6) root1.right.right = TreeNod...
[]
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef leaf_values(root):\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00040679", "row_id": 40679, "seed_ids": "['Qwen2-72B-Instruct_88837']" }
0.585373
Filter_40679
I
[ "get_leaf_values", "same_leaf_values" ]
2
[ [ "same_leaf_values", "get_leaf_values" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
72a61cff7c1f817dfc596b81a1dbfcbf8393c950
00be8ac497e85ff7dc38996a6054dc9cd94626e4
v1.0
instruct
Filter
Filter_40808_I
In the Python programming language, write a script to calculate the geometric mean of a series of numerical values present in a tuple data structure. Additionally, extend the functionality of your script to handle arbitrary tuple nesting. Your solution should be able to handle not only a tuple of numbers (example: (2, ...
import math def flatten_tuple(nested_tuple): """ Flatten a nested tuple. """ flat_list = [] def flatten(current_tuple): for item in current_tuple: if isinstance(item, tuple): flatten(item) else: flat_list.append(item) fla...
from solution import geometric_mean def test_geometric_mean_single_level(): assert geometric_mean((2, 4, 6, 8)) == (2*4*6*8) ** 0.25 def test_geometric_mean_double_level_nested(): assert geometric_mean(((2, 4), (6, 8))) == (2*4*6*8) ** 0.25 def test_geometric_mean_mixed_nested(): assert geometric_mean((2...
[ { "docstring": "Flatten a nested tuple.", "function_declaration": "def flatten_tuple(nested_tuple):", "function_name": "flatten_tuple", "parameter_list": "(nested_tuple)" }, { "docstring": "Returns the geometric mean of numbers present in a nested tuple.", "function_declaration": "def ge...
[ 0, 0, 0, 1, 1, 0, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import exp, log\nfrom functools import reduce\n\ndef flatten_tuple(data):\n \"\"\"\n Flattens a nested tuple into a single list of values.\n \"\"\"\n flat_list = []\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040808", "row_id": 40808, "seed_ids": "['Qwen2-72B-Instruct_89059']" }
0.646332
Filter_40808
I
[ "flatten_tuple", "geometric_mean" ]
2
[ [ "geometric_mean", "flatten_tuple" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bb4c4fe241c17ffcac1d1a352b6e60a6f8b44ee8
370f524a9777b6936be8bd5d8905bbebdac02d70
v1.0
instruct
Filter
Filter_40952_I
Revamp the provided function so that it not only exhibits a 'zaire fruit' inspired output when executed, but does so by recursively generating and connecting string elements in a binary tree structure. The string "I love coding in Python!" should be the root from which left and right branches stem, with the left branch...
class BinaryTree: def __init__(self, value): self.left = None self.right = None self.value = value def construct_tree(string): """ Constructs a binary tree recursively from a given string and returns its root. """ if len(string) <= 1: return BinaryTree(string) ...
from solution import zaire_fruit, construct_tree, traverse_tree def test_zaire_fruit_output(): assert zaire_fruit() == "I love coding in Python!" def test_construct_tree(): tree = construct_tree("hello") assert tree.value == "hello" assert tree.left.value == "he" assert tree.right.value == "llo" ...
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_tree_split(s):\n \"\"\"\n Splits a string into its binary tree representation, each leaf node presents a single character.\n :param s: Input string\n :return: A list rep...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00040952", "row_id": 40952, "seed_ids": "['Qwen2-72B-Instruct_89330']" }
0.575402
Filter_40952
I
[ "construct_tree", "traverse_tree", "zaire_fruit" ]
3
[ [ "zaire_fruit", "construct_tree" ], [ "zaire_fruit", "traverse_tree" ] ]
2
[]
false
[ "BinaryTree" ]
true
pytest
true
[]
true
0bc30fd67d35254397257c93e9c7572f825b2962
4e11de57889a639aa4aa501b488bb9ceef9709ab
v1.0
instruct
Filter
Filter_40984_I
Generate a distributed dictionary with a GUI to allow a user to enter data that should be stored in the dictionary. Then, implement a function that allows the user to execute search queries on the dictionary in parallel using multiple cores or threads. Track the number of search attempts and print it for each query att...
import tkinter as tk from concurrent.futures import ThreadPoolExecutor import threading class DistributedDictionary: def __init__(self): self.data = {} self.lock = threading.Lock() self.search_count = 0 def add_entry(self, key, value): with self.lock: self.data[key]...
import pytest from solution import DistributedDictionary, run_search_in_parallel def test_add_entry(): d = DistributedDictionary() d.add_entry('key1', 'value1') assert d.data['key1'] == 'value1' def test_parallel_search_existing_key(): d = DistributedDictionary() d.add_entry('key1', 'value1') ...
[]
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\nfrom tkinter import messagebox\nfrom concurrent.futures import ThreadPoolExecutor\nimport threading\n\n# Distributed dictionary\ndata_store = {}\nsearch_attempt_lock = th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00040984", "row_id": 40984, "seed_ids": "['Qwen2-72B-Instruct_89382']" }
0.401855
Filter_40984
I
[ "run_search_in_parallel", "add_data_to_dict", "create_interface" ]
3
[ [ "create_interface", "add_data_to_dict" ] ]
1
[]
false
[ "DistributedDictionary" ]
true
pytest
true
[]
true
203e4ab0809a8fe31d2aed221fe3852466bfceab
fc2ad15306b073714c6beda202ee0fd5e82cf881
v1.0
instruct
Filter
Filter_41179_I
I have a list of tuples representing a binary tree in Python. Each tuple has three elements: the value of the node, and two nested trees which represent the node's left and right children. Note these trees themselves are represented as tuples in the same way. I want to write a recursive function that returns the deepes...
def deepest_left_node(tree, is_left=False, depth=0): if tree is None: return (None, depth) value, left, right = tree if left is None and right is None: return (value, depth) if is_left else (None, depth) left_result, left_depth = deepest_left_node(left, True, depth + 1) rig...
import pytest from solution import find_deepest_left_node def test_deepest_left_node_single_node(): assert find_deepest_left_node((1, None, None)) == None def test_deepest_left_node_simple_tree(): assert find_deepest_left_node((1, (2, None, None), (3, None, None))) == 2 def test_deepest_left_node_only_left_s...
[ { "docstring": null, "function_declaration": "def deepest_left_node(tree, is_left=False, depth=0):", "function_name": "deepest_left_node", "parameter_list": "(tree, is_left=False, depth=0)" }, { "docstring": null, "function_declaration": "def find_deepest_left_node(tree):", "function...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def deepest_left_node(tree, level=1, is_left=False, deepest_node=None):\n if not tree:\n return deepest_node\n \n value, left, right = tree\n \n # Check if this is a left...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00041179", "row_id": 41179, "seed_ids": "['Qwen2-72B-Instruct_89723']" }
0.474269
Filter_41179
I
[ "deepest_left_node", "find_deepest_left_node" ]
2
[ [ "find_deepest_left_node", "deepest_left_node" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6991669daf83f51aa91bb4a0377aa1c8354da54f
eff719ace84494e7ccc925d84a09346fcff34920
v1.0
instruct
Filter
Filter_41197_I
I am currently in downloading videos and saving to a log with confirmed and missed events detected. I'd love to input the events from confirmed log and send emails to recipients on email log. The script needs to display title, link, and description of each video event that occurred in the email. Can you write a python ...
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(subject, body, to_emails, from_email, smtp_server, smtp_port, smtp_user, smtp_password): """ Sends an email with the given subject and body to a list of recipient emails. """ # Setup MIME ...
import pytest from unittest.mock import patch, call from solution import send_video_event_emails, build_email_body def test_build_email_body(): events = [ {"title": "Event 1", "link": "http://link1.com", "description": "Description 1"}, {"title": "Event 2", "link": "http://link2.com", "description...
[ { "docstring": "Sends an email with the given subject and body to a list of recipient emails.", "function_declaration": "def send_email(subject, body, to_emails, from_email, smtp_server, smtp_port, smtp_user, smtp_password):", "function_name": "send_email", "parameter_list": "(subject, body, to_emai...
[ 0, 0, 0, 0, 0, 1, 1, 0, 1 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef load_event_log(log_path):\n \"\"\"\n Load events from the provided log file.\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041197", "row_id": 41197, "seed_ids": "['Qwen2-72B-Instruct_89759']" }
0.537375
Filter_41197
I
[ "send_email", "build_email_body", "send_video_event_emails" ]
3
[ [ "send_video_event_emails", "build_email_body" ], [ "send_video_event_emails", "send_email" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8bb111c8b5a8df5eee25f20df40ac8df24577868
0c6aef0e3f150057d6ba62c352bfc4a8b1acf533
v1.0
instruct
Filter
Filter_41223_I
How do you solve logistic regression using Newton's method in Python? Please include the code for the implementation.
import numpy as np def sigmoid(z): return 1 / (1 + np.exp(-z)) def logistic_regression_newton_method(X, y, num_iterations=10, tol=1e-6): """ Performs logistic regression using Newton's method. Parameters: X : ndarray Feature matrix of shape (n_samples, n_features) y : ndarray ...
from solution import logistic_regression_newton_method import numpy as np def test_logistic_regression_newton_method_simple(): X = np.array([[1, 0], [1, 1], [1, 2]]) y = np.array([0, 1, 1]) w = logistic_regression_newton_method(X, y) assert w is not None assert w.shape == (2,) def test_logisti...
[ { "docstring": null, "function_declaration": "def sigmoid(z):", "function_name": "sigmoid", "parameter_list": "(z)" }, { "docstring": "Performs logistic regression using Newton's method.\n\nParameters:\nX : ndarray\n Feature matrix of shape (n_samples, n_features)\ny : ndarray\n Target...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef logistic_regression_newton(X, y, num_steps, epsilon=1e-5):\n \"\"\"\n Logistic Regression using Newton's Met...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041223", "row_id": 41223, "seed_ids": "['Qwen2-72B-Instruct_89813']" }
0.473509
Filter_41223
I
[ "sigmoid", "logistic_regression_newton_method" ]
2
[ [ "logistic_regression_newton_method", "sigmoid" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
dc394362275a9f77aa68e906810caa9f5001632a
a83df4383a75aab2b8ebfb478c3be5075649dacc
v1.0
instruct
Filter
Filter_41282_I
Construct a computational program in Python that can accept two unique sequences of alphabetical characters and determine if they are anagrammatic variations of one another. Additionally, ensure that each character's frequency is prime number.
def is_prime(num): """Returns True if the number is a prime number, else 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: return ...
from solution import is_anagrammatic_variation def test_anagrammatic_variation_prime_frequencies(): seq1 = "aabb" seq2 = "bbaa" assert is_anagrammatic_variation(seq1, seq2) == True def test_not_anagrammatic_variation(): seq1 = "aabc" seq2 = "abcc" assert is_anagrammatic_variation(seq1, seq2) =...
[ { "docstring": "Returns True if the number is a prime number, else False.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns True if seq1 and seq2 are anagrammatic variations of each other \nand each character's f...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import Counter\n\ndef is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041282", "row_id": 41282, "seed_ids": "['Qwen2-72B-Instruct_89917']" }
0.614876
Filter_41282
I
[ "is_prime", "is_anagrammatic_variation" ]
2
[ [ "is_anagrammatic_variation", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
460bdb52dcae6385a386750145ce511e435e4ff9
be0a280c6755aad2e85ad3699ed8673f172fb981
v1.0
instruct
Filter
Filter_41334_I
Implement the stochastic gradient descent algorithm for a linear regression model. Additionally, include L2 regularization (also known as Ridge regression) and provide an option for mini-batch gradient descent. Compare the performance of these methods to the standard linear regression using a synthetic dataset with pre...
import numpy as np def generate_synthetic_data(num_samples=100, noise_std=0.1): np.random.seed(42) X = 2 * np.random.rand(num_samples, 1) y = 4 + 3 * X + noise_std * np.random.randn(num_samples, 1) return X, y def standardize_data(X): mean = np.mean(X, axis=0) std = np.std(X, axis=0) retur...
import numpy as np from solution import generate_synthetic_data, standardize_data, sgd, linear_regression, add_bias, compute_mse def test_generate_synthetic_data(): X, y = generate_synthetic_data() assert X.shape == (100, 1) assert y.shape == (100, 1) def test_standardize_data(): X = np.array([[1], [2...
[ { "docstring": null, "function_declaration": "def generate_synthetic_data(num_samples=100, noise_std=0.1):", "function_name": "generate_synthetic_data", "parameter_list": "(num_samples=100, noise_std=0.1)" }, { "docstring": null, "function_declaration": "def standardize_data(X):", "f...
[ 0, 0, 0, 0, 1, 1, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\nclass LinearRegressionSGD:\n def __init__(self, lr=0.01, epochs=1000, batch_size=1, lambda_l2=0.0):\n self.lr = lr\n self.epochs = epochs\n self.b...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00041334", "row_id": 41334, "seed_ids": "['Qwen2-72B-Instruct_90008']" }
0.438197
Filter_41334
I
[ "generate_synthetic_data", "standardize_data", "predict", "compute_mse", "gradient_step", "sgd", "linear_regression", "add_bias" ]
8
[ [ "gradient_step", "predict" ], [ "sgd", "gradient_step" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
8669af201fca4af767c2c4b2342f7028c418932d
245dc00365ab45d8d05caee973f8c8018d84107e
v1.0
instruct
Filter
Filter_41475_I
Create a recursive function to assess whether a given word constitutes a palindrome when its characters are arranged in their reverse order. The function should accomplish this without utilizing any built-in reverse functions. Furthermore, extend the function to determine if the palindrome remains intact when the word ...
def is_palindrome(word): """ Checks if a given word is a palindrome. """ def helper(s, left, right): if left >= right: return True if s[left] != s[right]: return False return helper(s, left + 1, right - 1) return helper(word, 0, len(word) - 1) de...
from solution import is_palindrome, is_palindrome_after_vowel_removal def test_is_palindrome(): assert is_palindrome("racecar") assert is_palindrome("madam") assert not is_palindrome("hello") assert is_palindrome("a") assert is_palindrome("") def test_is_vowel(): assert is_vowel('a') asser...
[ { "docstring": "Checks if a given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Checks if a character is a vowel.", "function_declaration": "def is_vowel(c):", "function_name...
[ 0, 0, 0, 0, 1, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome_recursive(word):\n \"\"\"\n Checks if a word is a palindrome using recursion.\n \"\"\"\n if len(word) <= 1:\n return True\n if word[0] != word[-1]:\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041475", "row_id": 41475, "seed_ids": "['Qwen2-72B-Instruct_90288']" }
0.737498
Filter_41475
I
[ "is_palindrome", "is_vowel", "remove_vowels", "is_palindrome_after_vowel_removal" ]
4
[ [ "is_palindrome_after_vowel_removal", "is_palindrome" ], [ "is_palindrome_after_vowel_removal", "remove_vowels" ], [ "remove_vowels", "is_vowel" ] ]
3
[]
false
[]
false
pytest
true
[]
true
b811d430155eb53b2977ebc870c09fba519fe160
d46662052b767f6c607afb1acc5fa1e012e24f43
v1.0
instruct
Filter
Filter_41489_I
Write me a Python script that toggles if WSL 2 update-manager is Enabled or Disabled and do not cause Ubuntu Server to prompt towards the end of the checking for updates. Additionally, check in the beginning if it's already in the desired state, if true then script should do nothing. In dry-run mode ($1), the script sh...
import subprocess def check_update_manager_status(): """ Check if update-manager is enabled or disabled. """ try: status = subprocess.check_output(["systemctl", "is-enabled", "update-manager"], text=True).strip() return status == "enabled" except subprocess.CalledProcessError: ...
import subprocess from solution import check_update_manager_status, toggle_update_manager def test_check_update_manager_status_enabled(monkeypatch): def mock_check_output(cmd, text=True): return "enabled" monkeypatch.setattr(subprocess, "check_output", mock_check_output) assert check_update_manage...
[ { "docstring": "Check if update-manager is enabled or disabled.", "function_declaration": "def check_update_manager_status():", "function_name": "check_update_manager_status", "parameter_list": "()" }, { "docstring": "Toggles the update-manager between enabled and disabled states.\n\n:param ...
[ 0, 0, 0, 0, 0, 1, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import subprocess\n\ndef is_update_manager_enabled():\n \"\"\"\n Checks if the update-manager is enabled.\n \"\"\"\n result = subprocess.run(\n [\"systemctl\", \"is-enabled\...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041489", "row_id": 41489, "seed_ids": "['Qwen2-72B-Instruct_90314']" }
0.312446
Filter_41489
I
[ "check_update_manager_status", "toggle_update_manager" ]
2
[ [ "toggle_update_manager", "check_update_manager_status" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a98a7cf4b8ef15db8bc9e87f114c6c1caf12898
a60c110e02f198d8cfae9e0a6bdf4e29a063a1d4
v1.0
instruct
Filter
Filter_41520_I
Design a Python function that not only accepts a list of integers as input and returns a list where each element is the product of all the elements in the original list except the element at the current index, but also a list indicating the occurrence of each unique prime factor found within the product calculation for...
from collections import defaultdict def prime_factors(n): """ Returns a dictionary with prime factors of n as keys and their frequency as values. """ def recurse_factors(n, factor, factors): if n < 2: return while n % factor == 0: factors[factor] += 1 ...
from solution import prime_factors, product_except_self_with_prime_factors def test_prime_factors(): assert prime_factors(18) == {2: 1, 3: 2} assert prime_factors(60) == {2: 2, 3: 1, 5: 1} assert prime_factors(19) == {19: 1} assert prime_factors(1) == {} assert prime_factors(0) == {} def test_prod...
[ { "docstring": "Returns a dictionary with prime factors of n as keys and their frequency as values.", "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { "docstring": "Given a list of integers nums, returns a tuple containing:\n- A ...
[ 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict\n\ndef find_prime_factors(n, factors=None):\n \"\"\"\n Recursively find all prime factors of a number.\n \"\"\"\n if factors is None:\n f...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00041520", "row_id": 41520, "seed_ids": "['Qwen2-72B-Instruct_90367']" }
0.828001
Filter_41520
I
[ "prime_factors", "product_except_self_with_prime_factors" ]
2
[ [ "product_except_self_with_prime_factors", "prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c904bdd0f2682c0a0195609141f332c65bad0021
80308059b4af58a7fc317f55d944543876568f94
v1.0
instruct
Filter
Filter_41527_I
Formulate an adversarial attack strategy on a Machine Learning model using the Gradient ascent methodology and Python programming. Explain your strategy, implementation steps and how it impacts model performance.
import numpy as np def adversarial_attack(model, x, y, epsilon=0.01, iterations=10): """ Performs an adversarial attack using gradient ascent on the given model. Parameters: model (function): The machine learning model's prediction function. x (numpy array): The input data to be attacked. ...
import numpy as np from solution import adversarial_attack, compute_loss_and_gradient def dummy_model(x): """ A simple linear dummy model for testing purposes. """ return np.dot(x, np.array([1.0, 2.0])) def test_adversarial_attack_shape(): x = np.array([0.5, -0.2]) y = 1 x_adv = adversaria...
[ { "docstring": "Performs an adversarial attack using gradient ascent on the given model.\n\nParameters:\n model (function): The machine learning model's prediction function.\n x (numpy array): The input data to be attacked.\n y (int): The true label of the input data.\n epsilon (float): The step siz...
[ 0, 0, 0, 0, 1, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef adversarial_attack(model, input, target_label, epsilon=0.01, steps=100):\n \"\"\"\n Performs a...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041527", "row_id": 41527, "seed_ids": "['Qwen2-72B-Instruct_90379']" }
0.279477
Filter_41527
I
[ "adversarial_attack", "compute_loss_and_gradient" ]
2
[ [ "adversarial_attack", "compute_loss_and_gradient" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
9f3b7e588e85be418c46ba672c956d703ae933ac
81770af998bd07d1bc95d2161f4b75624c174d87
v1.0
instruct
Filter
Filter_41531_I
Write an optimized Python function that calculates the surface area of a given 3D object, where the object is represented by multiple planar vertices. The data structure is composed of a list of tuples, such that (x, y, z) is a point on the 3D plane represented in Cartesian coordinates. Assume that the surface area cal...
import math def triangle_area(a, b, c): """ Calculate the area of a triangle given its vertices in 3D space using Heron's formula. """ side_length = lambda p1, p2: math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2) ab = side_length(a, b) bc = side_length(b, c) ca ...
from solution import surface_area def test_simple_triangle(): vertices = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] assert math.isclose(surface_area(vertices), 0.5, rel_tol=1e-9) def test_square_pyramid_base(): # (0,0,0), (1,0,0), (0,1,0), (1,1,0) with apex at (0.5,0.5,1) vertices = [(0, 0, 0), (1, 0, 0), (0.5...
[ { "docstring": "Calculate the area of a triangle given its vertices in 3D space using Heron's formula.", "function_declaration": "def triangle_area(a, b, c):", "function_name": "triangle_area", "parameter_list": "(a, b, c)" }, { "docstring": "Calculate the surface area of a 3D object given i...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.spatial import ConvexHull\n\ndef surface_area(vertices):\n \"\"\"\n Calculate the surface area of a 3D object represented by vertices.\n\n Parameters:\n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00041531", "row_id": 41531, "seed_ids": "['Qwen2-72B-Instruct_90388']" }
0.506074
Filter_41531
I
[ "triangle_area", "surface_area" ]
2
[ [ "surface_area", "triangle_area" ] ]
1
[]
false
[]
false
pytest
true
[]
true
60526b533c1bda645c08f840a4764371a871b432
6b5eb82e2355248f0a72e33c26d524b3ce354261
v1.0
instruct
Filter
Filter_41599_I
Please rewrite the web scraping algorithm in Python using the BeautifulSoup and requests libraries to gather data from a secure website. The website requires a user to log in before accessing the information. The data should be stored in a SQLite database and each article should also have a thumbnail image which must b...
import requests from bs4 import BeautifulSoup import sqlite3 import os import hashlib from datetime import datetime import smtplib from email.mime.text import MIMEText def login_to_website(session, login_url, username, password): payload = { 'username': username, 'password': password } resp...
import sqlite3 import os import pytest from solution import save_to_db, search_articles, download_image # Sample data for testing sample_articles = [ {'title': 'Test Title 1', 'content': 'Test Content 1', 'thumbnail_url': 'http://example.com/image1.jpg', 'date': '2021-05-01'}, {'title': 'Test Title 2', 'conten...
[ { "docstring": null, "function_declaration": "def login_to_website(session, login_url, username, password):", "function_name": "login_to_website", "parameter_list": "(session, login_url, username, password)" }, { "docstring": null, "function_declaration": "def get_articles(session, artic...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\nimport sqlite3\nimport os\n\ndef login_and_get_session(login_url, login_data):\n session = requests.Session()\n session.post(login_url, da...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041599", "row_id": 41599, "seed_ids": "['Qwen2-72B-Instruct_90508']" }
0.678514
Filter_41599
I
[ "login_to_website", "get_articles", "download_image", "save_to_db", "search_articles", "send_email_notification", "main" ]
7
[ [ "save_to_db", "download_image" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
ccf844a1b7895e618c90843e99f4b05bbda4f9b0
4019d0cd6cedafe65fcc2a74c256544c2d6931e9
v1.0
instruct
Filter
Filter_41623_I
Develop a collaborative filtering algorithm for movie recommendation. Your function should take in a movie title, a user's movie ratings in a dictionary format, and a list of all user ratings in a matrix format. It should return a list of recommended movies based on user-item similarity. However, you're encouraged to t...
from collections import defaultdict import numpy as np def cosine_similarity(vec1, vec2): """ Compute the cosine similarity between two vectors. """ dot_product = np.dot(vec1, vec2) norm_vec1 = np.linalg.norm(vec1) norm_vec2 = np.linalg.norm(vec2) if norm_vec1 == 0 or norm_vec2 == 0: ...
from solution import recommend_movies def test_recommend_movies(): user_ratings = { "Movie A": 5, "Movie B": 3, "Movie C": 4 } all_user_ratings = [ [5, 3, 4], [3, 5, 1], [4, 2, 5], [2, 5, 3], [5, 4, 4] ] target_movie = "Movie A" ...
[ { "docstring": "Compute the cosine similarity between two vectors.", "function_declaration": "def cosine_similarity(vec1, vec2):", "function_name": "cosine_similarity", "parameter_list": "(vec1, vec2)" }, { "docstring": "Recommend movies based on user-item collaborative filtering.", "fun...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def collaborative_filtering(movie_title, user_ratings, all_user_ratings):\n \"\"\"\n Returns a list of recommended movies based on user-item similarity.\n\n :param movie_title: The ti...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00041623", "row_id": 41623, "seed_ids": "['Qwen2-72B-Instruct_90562']" }
0.479869
Filter_41623
I
[ "cosine_similarity", "recommend_movies" ]
2
[ [ "recommend_movies", "cosine_similarity" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
eada7aab7c9c6df9347b48e4f921b6ffdf9e6d78
3ad668cd80dde337eddf5da532e5ed1e66ccd3a4
v1.0
instruct
Filter
Filter_41630_I
Given an erroneous piece of code, debug and extract the geographical coordinates of multiple locations, then decipher the least travel distance between these locations. Use geographical coordinates provided for five global cities: New York, Los Angeles, Tokyo, Sydney and Paris.
import math def haversine(lat1, lon1, lat2, lon2): """ Calculate the great-circle distance between two points on the Earth surface. Parameters: - lat1, lon1: latitude and longitude of the first point. - lat2, lon2: latitude and longitude of the second point. Returns: - distance be...
from solution import haversine, locations, minimal_distance_between_cities def test_haversine(): # distance between New York and Los Angeles assert math.isclose(haversine(40.7128, -74.0060, 34.0522, -118.2437), 3940, abs_tol=10) # distance between Tokyo and Sydney assert math.isclose(haversine(35.6762,...
[ { "docstring": "Calculate the great-circle distance between two points on the Earth surface.\n\nParameters:\n- lat1, lon1: latitude and longitude of the first point.\n- lat2, lon2: latitude and longitude of the second point.\n\nReturns:\n- distance between the two points in kilometers.", "function_declarati...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\n# Geographical coordinates of the cities\ncoordinates = {\n 'New York': (40.7128, -74.0060),\n 'Los Angeles': (34.0522, -118.2437),\n 'Tokyo': (35.6895, 139.6917),\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041630", "row_id": 41630, "seed_ids": "['Qwen2-72B-Instruct_90575']" }
0.569295
Filter_41630
I
[ "haversine", "minimal_distance_between_cities" ]
2
[ [ "minimal_distance_between_cities", "haversine" ] ]
1
[]
false
[]
false
pytest
true
[]
true
37c6594c1068d51f5d3a38a588247d0627573ef9
dca7f3032b1660678050ee7686cf6fc6b4eab8dd
v1.0
instruct
Filter
Filter_41777_I
To resolve nested shortened URLs while browsing on an Android device, could you provide guidance on what steps need to be taken to develop a script using the requested regex patterns and environments? Please detail the regex patterns required for handling various forms of shortened URLs, the shell command for running t...
import re import requests def resolve_url(url): """ Resolve a given shortened URL to its final destination URL. Args: url (str): The shortened URL to resolve. Returns: str: The final destination URL. """ try: response = requests.head(url, allow_redirects=True) re...
from solution import resolve_url, resolve_nested_urls, extract_shortened_urls def test_resolve_url(): # Mock requests.head to simulate URL resolution in tests from requests.models import Response from unittest.mock import patch def mock_head(url, allow_redirects): response = Response() ...
[ { "docstring": "Resolve a given shortened URL to its final destination URL.\nArgs:\n url (str): The shortened URL to resolve.\nReturns:\n str: The final destination URL.", "function_declaration": "def resolve_url(url):", "function_name": "resolve_url", "parameter_list": "(url)" }, { "d...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nimport re\n\n# Define regex patterns for common URL shorteners.\nURL_PATTERNS = [\n re.compile(r'(https?://bit\\.ly/\\S+)'),\n re.compile(r'(https?://goo\\.gl/\\S+)'),\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00041777", "row_id": 41777, "seed_ids": "['Qwen2-72B-Instruct_90849']" }
0.406908
Filter_41777
I
[ "resolve_url", "resolve_nested_urls", "extract_shortened_urls" ]
3
[ [ "resolve_nested_urls", "resolve_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
eaa54e3066de3eccd5c90c2ffe49f8a1ca9b1f08
c72245c40b5f476fe8263ecf46f879affd9e4ee1
v1.0
instruct
Filter
Filter_41819_I
Create a python script that reads a multilingual csv file (with a defined encoding) containing inconsistent column and row data, and converts it into a well-structured xml file. The script should include comprehensive error handling.
import csv import xml.etree.ElementTree as ET import sys def read_csv(file_path, encoding): try: with open(file_path, encoding=encoding) as f: reader = csv.reader(f) data = [row for row in reader] return data except Exception as e: print(f"Error reading CSV: {e}"...
import pytest from solution import read_csv, csv_to_dict, dict_to_xml, write_xml, csv_to_xml import os import xml.etree.ElementTree as ET def test_read_csv(): sample_csv = "test.csv" with open(sample_csv, "w", encoding="utf-8") as f: f.write("Name,Age,City\nJohn,23,New York\nAnna,30,London\n") ...
[ { "docstring": null, "function_declaration": "def read_csv(file_path, encoding):", "function_name": "read_csv", "parameter_list": "(file_path, encoding)" }, { "docstring": null, "function_declaration": "def csv_to_dict(data):", "function_name": "csv_to_dict", "parameter_list": "(...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nimport xml.etree.ElementTree as ET\nimport chardet\n\ndef detect_encoding(file_path):\n \"\"\"\n Detects the encoding of a file.\n \"\"\"\n with open(file_path, 'rb') a...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00041819", "row_id": 41819, "seed_ids": "['Qwen2-72B-Instruct_90929']" }
0.606082
Filter_41819
I
[ "read_csv", "csv_to_dict", "dict_to_xml", "write_xml", "csv_to_xml" ]
5
[ [ "csv_to_xml", "csv_to_dict" ], [ "csv_to_xml", "dict_to_xml" ], [ "csv_to_xml", "read_csv" ], [ "csv_to_xml", "write_xml" ] ]
4
[]
false
[]
false
pytest
true
[]
true
4e47f48fdefa2fb47a85f8f35092ebfd20d761ba
1633641f9c2f136bc736e772af8f230c93ed0e40
v1.0
instruct
Filter
Filter_41830_I
Given a list of N messages of length L, each message can be compressed using one of two algorithms: Algorithm A with a compression ratio of 5:1 or Algorithm B with a compression ratio of 10:1. Given this, create a program that outputs the total size of the messages after compression using both algorithms, mentioning wh...
def compress_messages(messages): """ Given a list of messages, calculate the total size after compression using Algorithm A and Algorithm B. Parameters: messages (list of str): List of messages to be compressed Returns: dict: A dictionary containing the total compressed size for both algorithm...
from solution import compress_messages def test_compression_algorithm_a(): messages = ["This is a message.", "Another message.", "Yet another message."] result = compress_messages(messages) expected_size_a = len("This is a message.") + len("Another message.") + len("Yet another message.") assert result...
[ { "docstring": "Given a list of messages, calculate the total size after compression using Algorithm A and Algorithm B.\n\nParameters:\nmessages (list of str): List of messages to be compressed\n\nReturns:\ndict: A dictionary containing the total compressed size for both algorithms with human-readable formats."...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def convert_size(size_bytes):\n \"\"\"\n Convert a size in bytes to a more human-readable format.\n \"\"\"\n if size_bytes == 0:\n return \"0 bytes\"\n size_name = (\"byt...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00041830", "row_id": 41830, "seed_ids": "['Qwen2-72B-Instruct_90951']" }
0.530021
Filter_41830
I
[ "compress_messages", "human_readable_size" ]
2
[ [ "compress_messages", "human_readable_size" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f3589bcce60a8f6dda2241359799213501f97aff
1d2bba757ec200535aa45294a07c7bc5067ab23f
v1.0
instruct
Filter
Filter_41878_I
Write a python3 code using list comprehension to get the power of 3 of the numbers between 1 to 20, but only if the numbers are prime.
def primes_up_to(n): """ Returns a list of all prime numbers up to n. """ primes = [] for num in range(2, n + 1): is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: ...
from solution import primes_up_to, prime_cubes def test_primes_up_to_10(): assert primes_up_to(10) == [2, 3, 5, 7] def test_primes_up_to_20(): assert primes_up_to(20) == [2, 3, 5, 7, 11, 13, 17, 19] def test_prime_cubes(): assert prime_cubes() == [8, 27, 125, 343, 1331, 2197, 4913, 6859]
[ { "docstring": "Returns a list of all prime numbers up to n.", "function_declaration": "def primes_up_to(n):", "function_name": "primes_up_to", "parameter_list": "(n)" }, { "docstring": "Returns a list of the cubes of prime numbers between 1 to 20.", "function_declaration": "def prime_cu...
[ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041878", "row_id": 41878, "seed_ids": "['Qwen2-72B-Instruct_91047']" }
0.678334
Filter_41878
I
[ "primes_up_to", "prime_cubes" ]
2
[ [ "prime_cubes", "primes_up_to" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9fee03f5b007cc1dd491ba8132fe799b82e89790
674d7b74690fe305c6881bbda8a833c30ad2d9aa
v1.0
instruct
Filter
Filter_41927_I
Develop a simple sentiment-analysis model using NLP. Your model should be able to classify a sentence as having positive or negative sentiment. Don't just use a pre-built model, but try to implement it with your own understanding from scratch. You may use libraries for NLP tasks, but you must explain every part of your...
import re from collections import Counter from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def preprocess_text(text): """ Preprocesses the input text by converting to lowercase, removing non-alphabetic characters, and tokenizing. """ text = text.lower...
from solution import preprocess_text, build_vocabulary, text_to_features, simple_sentiment_analysis_model, evaluate_model def test_preprocess_text(): assert preprocess_text("This is an Example!") == ["this", "is", "an", "example"] def test_build_vocabulary(): corpus = ["This is a test", "This is another test"...
[ { "docstring": "Preprocesses the input text by converting to lowercase, removing non-alphabetic characters, \nand tokenizing.", "function_declaration": "def preprocess_text(text):", "function_name": "preprocess_text", "parameter_list": "(text)" }, { "docstring": "Builds a vocabulary from the...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\n\n# Sample data for ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00041927", "row_id": 41927, "seed_ids": "['Qwen2-72B-Instruct_91125']" }
0.584649
Filter_41927
I
[ "preprocess_text", "build_vocabulary", "text_to_features", "simple_sentiment_analysis_model", "evaluate_model" ]
5
[ [ "build_vocabulary", "preprocess_text" ], [ "simple_sentiment_analysis_model", "build_vocabulary" ], [ "simple_sentiment_analysis_model", "preprocess_text" ], [ "simple_sentiment_analysis_model", "text_to_features" ], [ "text_to_features", "preprocess_text" ...
5
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
fc8179c936481b9bd490e01b8a5a7070e7051fc2
6bb007e796201abbb730210a6acd3615cb9dac95
v1.0
instruct
Filter
Filter_41965_I
Write a code segment that generates a Fibonacci sequence until the sum is greater than a given limit and also only includes even numbers in the sequence. Additionally, the code should compute and print the average of the even numbers in the sequence.
def generate_even_fibonacci_until_limit(limit): """ Generates a list of even Fibonacci numbers where the cumulative sum is less than or equal to the limit and returns the list. """ fib_sequence = [0, 1] # Starting Fibonacci sequence even_fibs = [] while fib_sequence[-1] <= limit: ...
from solution import generate_even_fibonacci_until_limit, average_even_fibonacci def test_generate_even_fibonacci_until_limit(): assert generate_even_fibonacci_until_limit(10) == [2, 8] assert generate_even_fibonacci_until_limit(34) == [2, 8, 34] assert generate_even_fibonacci_until_limit(1) == [] asse...
[ { "docstring": "Generates a list of even Fibonacci numbers where the cumulative sum \nis less than or equal to the limit and returns the list.", "function_declaration": "def generate_even_fibonacci_until_limit(limit):", "function_name": "generate_even_fibonacci_until_limit", "parameter_list": "(limi...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_even_fibonacci_sequence(limit):\n \"\"\"\n Generates Fibonacci sequence with only even numbers until the sum is greater than the given limit and computes the average of thes...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00041965", "row_id": 41965, "seed_ids": "['Qwen2-72B-Instruct_91189']" }
0.578147
Filter_41965
I
[ "generate_even_fibonacci_until_limit", "average_even_fibonacci", "even_fibonacci_avg_until_limit" ]
3
[ [ "even_fibonacci_avg_until_limit", "average_even_fibonacci" ], [ "even_fibonacci_avg_until_limit", "generate_even_fibonacci_until_limit" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5882376854ede9eab0cbfc986d291c8ade680b03
2e069bc50a695a5b7c5d745eeea930b5336cf53e
v1.0
instruct
Filter
Filter_42017_I
Download an HTML page and extract all the <h2> tags and their corresponding text content using BeautifulSoup. Additionally, the program should also remove any HTML tags present within the extracted text content. The program should be able to handle cases where the HTML page is large (e.g., multiple MBs) and contain a l...
import requests from bs4 import BeautifulSoup import re def fetch_and_extract_h2(url): """ Fetches the HTML content from the given URL, extracts all <h2> tags and their corresponding text content, and removes any HTML tags present within the extracted text content. Parameters: url (str): The U...
from solution import fetch_and_extract_h2 def test_fetch_and_extract_h2(): # Mock URL and HTML content for testing url = 'http://example.com' html_content = ''' <html> <body> <h2>Title 1</h2> <h2><b>Title 2</b></h2> <h2>Title 3</h2> <div>Some othe...
[ { "docstring": "Fetches the HTML content from the given URL, extracts all <h2> tags and their corresponding text content,\nand removes any HTML tags present within the extracted text content.\n\nParameters:\nurl (str): The URL of the HTML page.\n\nReturns:\nlist: A list of strings, each representing the text co...
[ 0, 0, 0, 0, 1, 0, 1, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\nimport re\n\ndef fetch_html(url):\n \"\"\"\n Fetches the HTML content from the given URL.\n \"\"\"\n response = requests.get(url)\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042017", "row_id": 42017, "seed_ids": "['Qwen2-72B-Instruct_91304']" }
0.585108
Filter_42017
I
[ "fetch_and_extract_h2", "clean_html_tags" ]
2
[ [ "fetch_and_extract_h2", "clean_html_tags" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
bf9e248d3089846f132544e400ec2f2502479c4d
006fd66c748bab56a48c530407b01046df308432
v1.0
instruct
Filter
Filter_42052_I
Create a python script that runs a shell command to not only list all JPG files in a given directory, but also counts the number of pixels in each image, and finally categorizes images by their predominant color.
import os import subprocess from PIL import Image from collections import Counter def execute_shell_command(command): """ Execute a shell command and return the output. """ result = subprocess.run(command, shell=True, capture_output=True, text=True) return result.stdout.strip() def list_jpg_files(...
import pytest from solution import list_jpg_files, count_pixels, get_predominant_color, categorize_images def test_list_jpg_files(monkeypatch): def mock_execute_shell_command(command): return '/path/to/image1.jpg\n/path/to/image2.jpg' monkeypatch.setattr('solution.execute_shell_command', mock_exec...
[ { "docstring": "Execute a shell command and return the output.", "function_declaration": "def execute_shell_command(command):", "function_name": "execute_shell_command", "parameter_list": "(command)" }, { "docstring": "Lists all JPG files in the given directory.", "function_declaration":...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport subprocess\nfrom PIL import Image\nfrom collections import Counter\n\ndef list_jpg_files(directory):\n \"\"\"\n Lists all JPG files in a given directory.\n \"\"\"\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042052", "row_id": 42052, "seed_ids": "['Qwen2-72B-Instruct_91367']" }
0.455379
Filter_42052
I
[ "execute_shell_command", "list_jpg_files", "count_pixels", "get_predominant_color", "categorize_images" ]
5
[ [ "categorize_images", "count_pixels" ], [ "categorize_images", "get_predominant_color" ], [ "categorize_images", "list_jpg_files" ], [ "list_jpg_files", "execute_shell_command" ] ]
4
[]
false
[]
false
pytest
true
[ "PIL" ]
false
e1363ea4c1c287fefe7fe9150be2b92c3149095a
7e09665e3dff67911c61b83739ecef1cd8710fe1
v1.0
instruct
Filter
Filter_42139_I
Given a function that calculates the power of a number in Python, implement the bisection method for root finding algorithm where in specific the function power(x,n) is the input. If done correctly, using the bisection method should eventually result in the number that when raised to the power of n, results in x. This ...
def power(x, n): """ Calculate x raised to the power n. """ return x ** n def bisect_root(x, n, tol=1e-6): """ Use the bisection method to find the n-th root of x. :param x: The number to find the root of. :param n: The degree of the root. :param tol: The tolerance for converge...
from solution import bisect_root def test_bisect_root(): result = bisect_root(16, 4) assert abs(result - (16**(1/4))) < 1e-6 def test_bisect_root_small_number(): result = bisect_root(0.001, 3) assert abs(result - (0.001**(1/3))) < 1e-6 def test_bisect_root_perfect_square(): result = bisect_root(8...
[ { "docstring": "Calculate x raised to the power n.", "function_declaration": "def power(x, n):", "function_name": "power", "parameter_list": "(x, n)" }, { "docstring": "Use the bisection method to find the n-th root of x.\n\n:param x: The number to find the root of.\n:param n: The degree of ...
[ 0, 0, 0, 1, 1, 1, 0, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def power(base, exponent):\n \"\"\"\n This function returns the base raised to the power of exponent.\n \"\"\"\n return base ** exponent\n\ndef bisection_method_for_root(x, n, tole...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042139", "row_id": 42139, "seed_ids": "['Qwen2-72B-Instruct_91531']" }
0.598524
Filter_42139
I
[ "power", "bisect_root" ]
2
[ [ "bisect_root", "power" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c8e517153f5510444008c5f9f51572e812aec0db
271c16c0ee977b9bd2fa1d63e9e520e55df9b1fe
v1.0
instruct
Filter
Filter_42163_I
As an environmental consultant, you have a lot of import data in CSV file format, such as noise measurements from various locations in a city. Write a Python program using pandas that reads the CSV, filters out locations with noise levels above a certain decibel (dB) threshold specified by the user as a command line ar...
import pandas as pd import sys import os def filter_noise_data(input_file, threshold): """ Reads the CSV, filters out locations with noise levels above a certain dB threshold, and outputs the remaining data to a new CSV file. Parameters: input_file (str): The path to the input CSV file. t...
import os import pandas as pd import pytest from solution import filter_noise_data, append_threshold_to_filename @pytest.fixture def create_csv_file(tmp_path): data = { 'location': ['Location1', 'Location2', 'Location3', 'Location4'], 'noise_level': ['45.5', '67.8', 'invalid_data', '54.2'] } ...
[ { "docstring": "Reads the CSV, filters out locations with noise levels above a certain dB threshold, \nand outputs the remaining data to a new CSV file.\n\nParameters:\ninput_file (str): The path to the input CSV file.\nthreshold (float): The decibel (dB) threshold for filtering the noise levels.", "functio...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport sys\n\ndef filter_noise_data(input_file, threshold):\n try:\n df = pd.read_csv(input_file)\n\n # Check if 'NoiseLevel' column exists\n if 'N...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042163", "row_id": 42163, "seed_ids": "['Qwen2-72B-Instruct_91572']" }
0.538037
Filter_42163
I
[ "filter_noise_data", "append_threshold_to_filename" ]
2
[ [ "filter_noise_data", "append_threshold_to_filename" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
3b0b4b4b017833d3695e8fe39f02d8af252fbeaa
ab7b908d7e73df8fdca2cc37b869fdbdff670382
v1.0
instruct
Filter
Filter_42189_I
Sort the given list of numbers in non-decreasing order with selection sort. Additionally, keep track of the number of swaps made during the sorting process. Finally, implement a function that returns the median value of the sorted list. You are not allowed to use any built-in sorting functions or libraries.
def selection_sort(arr): """ Sorts the list arr using selection sort and returns the sorted list along with the swap count. """ swap_count = 0 n = len(arr) for i in range(n): min_index = i for j in range(i+1, n): if arr[j] < arr[min_index]: min_in...
from solution import selection_sort, find_median def test_selection_sort(): arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_arr, swap_count = selection_sort(arr) assert sorted_arr == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] assert swap_count > 0 def test_selection_sort_no_swaps_needed(): arr = [1, 2, 3, 4...
[ { "docstring": "Sorts the list arr using selection sort and returns the sorted list along with the swap count.", "function_declaration": "def selection_sort(arr):", "function_name": "selection_sort", "parameter_list": "(arr)" }, { "docstring": "Finds and returns the median of the given list ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def selection_sort(arr):\n \"\"\"\n Sort the given list of numbers in non-decreasing order using selection sort.\n Keep track of the number of swaps made during the sorting process.\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00042189", "row_id": 42189, "seed_ids": "['Qwen2-72B-Instruct_91610']" }
0.646564
Filter_42189
I
[ "selection_sort", "find_median" ]
2
[ [ "find_median", "selection_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bb523834979bf1e70d63f457a2777e5cf85a9454
9259e720006aae48f398ca09ba84d1fe66e01e0b
v1.0
instruct
Filter
Filter_42207_I
Can we use a recursive approach to navigate through a maze in Python? Also, provide an implementation that demonstrates the usage of recursive calls in solving the maze problem efficiently.
def is_safe(maze, x, y): """ A utility function to check if x, y is valid index for N*N maze """ return 0 <= x < len(maze) and 0 <= y < len(maze[0]) and maze[x][y] == 1 def solve_maze_util(maze, x, y, sol): """ A recursive utility function to solve Maze problem """ # if (x, y is goal) r...
from solution import solve_maze def test_solve_maze_with_solution(): maze = [ [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1] ] success, sol = solve_maze(maze) expected_solution = [ [1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1...
[ { "docstring": "A utility function to check if x, y is valid index for N*N maze", "function_declaration": "def is_safe(maze, x, y):", "function_name": "is_safe", "parameter_list": "(maze, x, y)" }, { "docstring": "A recursive utility function to solve Maze problem", "function_declaration...
[ 0, 0, 0, 0, 1, 1, 1, 1, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def navigate_maze(maze, start, end):\n \"\"\"\n Uses a recursive approach to navigate through a maze from start to end.\n \n :param maze: List of list denoting the maze grid (1 is ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00042207", "row_id": 42207, "seed_ids": "['Qwen2-72B-Instruct_91638']" }
0.539132
Filter_42207
I
[ "is_safe", "solve_maze_util", "solve_maze" ]
3
[ [ "solve_maze", "solve_maze_util" ], [ "solve_maze_util", "is_safe" ] ]
2
[]
false
[]
false
pytest
true
[]
true
57b5872b1bce55b72bb6746cd8e8778d66bffc21
40d022ab94c5f9656634a2bdc175b2e0aef372ec
v1.0
instruct
Filter
Filter_42263_I
Given a set of strings, write a Python program to determine if the set is a palindrome set. A palindrome set is defined as a set where each string in the set is a palindrome and all strings have the same length. Also, create a function to generate all possible palindrome sets of size 'n'.
def is_palindrome(s): """ Checks if a given string is a palindrome. """ return s == s[::-1] def is_palindrome_set(string_set): """ Checks if a given set of strings is a palindrome set. A palindrome set is defined as a set where: - Each string in the set is a palindrome - All strin...
from solution import is_palindrome_set, generate_palindrome_sets def test_is_palindrome_set(): assert is_palindrome_set({"a", "b", "c"}) == True assert is_palindrome_set({"aa", "bb", "cc"}) == True assert is_palindrome_set({"a", "aa", "ba"}) == False assert is_palindrome_set({"aa", "b", "cc"}) == False...
[ { "docstring": "Checks if a given string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Checks if a given set of strings is a palindrome set.\nA palindrome set is defined as a set where:\n - Eac...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(s):\n \"\"\"\n Returns True if the string s is a palindrome, False otherwise.\n \"\"\"\n return s == s[::-1]\n\ndef is_palindrome_set(sset):\n \"\"\"\n Retu...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00042263", "row_id": 42263, "seed_ids": "['Qwen2-72B-Instruct_91735']" }
0.701704
Filter_42263
I
[ "is_palindrome", "is_palindrome_set", "generate_palindrome_sets" ]
3
[ [ "is_palindrome_set", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb348633369c3973333eebb032565ddce8644bfe
8bc360e2fe8652b5d449aec8d707a610da82472b