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_14867_I | A binary tree is a tree-like structure in which each node has at most two children (i.e., left child and right child). Given two binary trees and an integer `K`, return the `K`th smallest element in the in-order traversal of the merged binary tree.
Example:
Input:
First tree 100
/ \
... | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def in_order_traversal(root):
if root is None:
return []
return in_order_traversal(root.left) + [root.value] + in_order_traversal(root.right)
def merge... | from solution import TreeNode, find_Kth_smallest
def build_tree(values, index=0):
if index < len(values):
node = None
if values[index] is not None:
node = TreeNode(values[index])
node.left = build_tree(values, 2 * index + 1)
node.right = build_tree(values, 2 * in... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef kth_smallest_combined_inorder(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014867",
"row_id": 14867,
"seed_ids": "['Llama-3.3-70B-Instruct_38180']"
} | 0.543112 | Filter_14867 | I | [
"in_order_traversal",
"merge_in_order_traversals",
"find_Kth_smallest"
] | 3 | [
[
"find_Kth_smallest",
"in_order_traversal"
],
[
"find_Kth_smallest",
"merge_in_order_traversals"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | e60883b0dffa2c150e20fc34442dd5722186ad32 | 7bdfc6e992cbef8d0eb927b52a890f83024ad990 | |||
v1.0 | instruct | Filter | Filter_14903_I | ### Game Program With 5 Questions
Create a simple game program with the following requirements:
* The program should ask the user 5 questions.
* Each question should have 4 possible answers (A, B, C, D).
* The user should be able to select only one answer for each question.
* The program should check if the us... | def ask_question(question, options, correct_answer):
"""
Asks the user a question and returns if the answer was correct.
:param question: The question to ask.
:param options: A dictionary of options with keys A, B, C, D.
:param correct_answer: The correct answer option (A, B, C, or D).
:return:... | def test_ask_question_correct(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: 'B')
assert ask_question("What is 2+2?", {"A": "3", "B": "4", "C": "5", "D": "6"}, "B")
def test_ask_question_incorrect(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: 'A')
assert not ask_question(... | [
{
"docstring": "Asks the user a question and returns if the answer was correct.\n\n:param question: The question to ask.\n:param options: A dictionary of options with keys A, B, C, D.\n:param correct_answer: The correct answer option (A, B, C, or D).\n:return: True if correct, False otherwise.",
"function_d... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def game():\n questions = [\n {\n \"question\": \"What is 2+2?\",\n \"options\": [\"A: 3\", \"B: 4\", \"C: 5\", \"D: 6\"],\n \"answer\": \"B\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00014903",
"row_id": 14903,
"seed_ids": "['Llama-3.3-70B-Instruct_38271']"
} | 0.493692 | Filter_14903 | I | [
"ask_question",
"game"
] | 2 | [
[
"game",
"ask_question"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d408872cf74e35e0313dd1b0566d7cc6c08cbe22 | 3c0867ec62296caef42709ae8e9baed64190f632 | |||
v1.0 | instruct | Filter | Filter_14908_I | I want to make a password reset tool that allows users to reset their password for their account. How can I implement a password reset feature in a web application? | from flask import Flask, request, jsonify, redirect, url_for
from werkzeug.security import generate_password_hash
from datetime import datetime, timedelta
import os
import hashlib
app = Flask(__name__)
# Mock database
users_db = {
"test@example.com": {
"password": generate_password_hash("old_password"),
... | import pytest
from solution import app, users_db, generate_password_hash
from datetime import datetime, timedelta
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_request_password_reset(client):
response = client.post('/request_password_reset', json={"email": "test... | [
{
"docstring": null,
"function_declaration": "def send_reset_email(email, token):",
"function_name": "send_reset_email",
"parameter_list": "(email, token)"
},
{
"docstring": null,
"function_declaration": "def request_password_reset():",
"function_name": "request_password_reset",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, url_for, render_template_string\nfrom itsdangerous import URLSafeTimedSerializer\nimport smtplib\n\napp = Flask(__name__)\napp.secret_key = 'YOUR_SECRET_KEY'\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014908",
"row_id": 14908,
"seed_ids": "['Llama-3.3-70B-Instruct_38288']"
} | 0.313064 | Filter_14908 | I | [
"send_reset_email",
"request_password_reset",
"reset_password"
] | 3 | [
[
"request_password_reset",
"send_reset_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"werkzeug"
] | false | 53975d8166bdb4506f64521d1b8e66b76bb00d62 | bf46f0aaa6321550b2a2004db7d1eee68b148df8 | |||
v1.0 | instruct | Filter | Filter_14928_I | I want to encrypt/decrypt a text file. The encryption method should be simple, like a substitution cipher where each letter is replaced with the one "n" places down the alphabet.
Here are my requirements:
1. The user should be able to choose between encryption and decryption
2. The user should be able to input the t... | def shift_char(c, n):
if 'a' <= c <= 'z':
return chr((ord(c) - ord('a') + n) % 26 + ord('a'))
elif 'A' <= c <= 'Z':
return chr((ord(c) - ord('A') + n) % 26 + ord('A'))
return c
def encrypt_decrypt(text, n):
return ''.join(shift_char(c, n) for c in text)
def process_file(file_name, n, m... | import os
from solution import shift_char, encrypt_decrypt, process_file
def test_shift_char():
assert shift_char('a', 1) == 'b'
assert shift_char('z', 1) == 'a'
assert shift_char('A', 1) == 'B'
assert shift_char('Z', 1) == 'A'
assert shift_char('!', 1) == '!'
def test_encrypt_decrypt():
asser... | [
{
"docstring": null,
"function_declaration": "def shift_char(c, n):",
"function_name": "shift_char",
"parameter_list": "(c, n)"
},
{
"docstring": null,
"function_declaration": "def encrypt_decrypt(text, n):",
"function_name": "encrypt_decrypt",
"parameter_list": "(text, n)"
},
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def shift_char(char, n):\n if 'a' <= char <= 'z':\n return chr((ord(char) - ord('a') + n) % 26 + ord('a'))\n elif 'A' <= char <= 'Z':\n return chr((ord(char) - ord('A') + n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014928",
"row_id": 14928,
"seed_ids": "['Llama-3.3-70B-Instruct_38327']"
} | 0.612166 | Filter_14928 | I | [
"shift_char",
"encrypt_decrypt",
"process_file"
] | 3 | [
[
"encrypt_decrypt",
"shift_char"
],
[
"process_file",
"encrypt_decrypt"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 51863765b6cb8b8f3c3fdc74447656e97adf5ef6 | ccad48043fbb6d688495c675fe539f7453d4f35b | |||
v1.0 | instruct | Filter | Filter_14950_I | Given a list of integers, return True if any two adjacent elements are equal. AreEqualNeighbors function.
def AreEqualNeighbors(lst):
for i in range(len(lst) - 1):
if lst[i] == lst[i + 1]:
return True
return False
# Test the function
print(AreEqualNeighbors([1, 2, 3, 4])) # False
print(AreEqualNeighbor... | def AreEqualNeighbors(lst):
"""
Returns True if any two adjacent elements in the list are equal, False otherwise.
"""
result = AreEqualNeighborsHelper(lst)
return result is not None
def AreEqualNeighborsEnhanced(lst):
"""
Returns the indices of the first pair of equal adjacent elements in t... | from solution import AreEqualNeighbors, AreEqualNeighborsEnhanced
def test_AreEqualNeighbors_no_equal_neighbors():
assert AreEqualNeighbors([1, 2, 3, 4]) == False
def test_AreEqualNeighbors_one_pair_equal_neighbors():
assert AreEqualNeighbors([1, 1, 3, 4]) == True
def test_AreEqualNeighbors_end_pair_equal_ne... | [
{
"docstring": "Returns True if any two adjacent elements in the list are equal, False otherwise.",
"function_declaration": "def AreEqualNeighbors(lst):",
"function_name": "AreEqualNeighbors",
"parameter_list": "(lst)"
},
{
"docstring": "Returns the indices of the first pair of equal adjacen... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def AreEqualNeighbors(lst):\n \"\"\"\n Returns True if any two adjacent elements are equal, else False.\n \"\"\"\n return AreEqualNeighborsEnhanced(lst) is not None\n\ndef AreEqual... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00014950",
"row_id": 14950,
"seed_ids": "['Llama-3.3-70B-Instruct_38396']"
} | 0.524291 | Filter_14950 | I | [
"AreEqualNeighbors",
"AreEqualNeighborsEnhanced",
"AreEqualNeighborsHelper"
] | 3 | [
[
"AreEqualNeighbors",
"AreEqualNeighborsHelper"
],
[
"AreEqualNeighborsEnhanced",
"AreEqualNeighborsHelper"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 188137a4307ce370685cd9b3eb0bd450cc5e8604 | 2526d039267952b06ee295ad99a481d55bbd5b55 | |||
v1.0 | instruct | Filter | Filter_14952_I | I am given a random number as the input and I have to find the first two distinct prime factors of the random number, starting from the lowest prime number.
For example, if the input is 100, the first two distinct prime factors are 2 and 5.
If the input is 67, the first two distinct prime factors are 67 and -1, becau... | 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 first_two_prime_factors(n):
"""
Returns a tuple of the first two distinct prime factors of n.
If n has only one prime factor, the second element of... | from solution import is_prime, first_two_prime_factors
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
def test_first_two_pr... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a tuple of the first two distinct prime factors of n.\nIf n has only one prime factor, the second element of the tuple will be -1.",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef first_two_distinct_prim... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014952",
"row_id": 14952,
"seed_ids": "['Llama-3.3-70B-Instruct_38406']"
} | 0.714089 | Filter_14952 | I | [
"is_prime",
"first_two_prime_factors"
] | 2 | [
[
"first_two_prime_factors",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 59a78fab8dcc8949bde35db0f659d4a97af4e6f4 | 3cc2f1e8b9cf4df8a73da7027dae6cae9135dafd | |||
v1.0 | instruct | Filter | Filter_14954_I | ### Task 1: Create a Hangman Game
Create a game of Hangman where the player has to guess a letter, and if they guess correctly, the letter is revealed in the word. If they guess incorrectly, a part of a hangman's gallows appears. The game continues until the word is guessed or the gallows is complete and the player wh... | import random
def get_word(difficulty):
easy_words = ['cat', 'dog', 'bat']
medium_words = ['apple', 'banana', 'cherry']
hard_words = ['rhapsody', 'quizzical', 'juxtapose']
if difficulty == 'easy':
return random.choice(easy_words)
elif difficulty == 'medium':
return random.choice(me... | import pytest
from solution import get_word, hangman_game, display_gallows
def test_get_word_easy():
assert get_word('easy') in ['cat', 'dog', 'bat']
def test_get_word_medium():
assert get_word('medium') in ['apple', 'banana', 'cherry']
def test_get_word_hard():
assert get_word('hard') in ['rhapsody', 'q... | [
{
"docstring": null,
"function_declaration": "def get_word(difficulty):",
"function_name": "get_word",
"parameter_list": "(difficulty)"
},
{
"docstring": null,
"function_declaration": "def display_gallows(stage):",
"function_name": "display_gallows",
"parameter_list": "(stage)"
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_word(difficulty):\n easy_words = ['cat', 'dog', 'bat']\n medium_words = ['apple', 'banana', 'cherry']\n hard_words = ['rhapsody', 'quizzical', 'juxtapose']\n\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00014954",
"row_id": 14954,
"seed_ids": "['Llama-3.3-70B-Instruct_38409']"
} | 0.584468 | Filter_14954 | I | [
"get_word",
"display_gallows",
"hangman_game"
] | 3 | [
[
"hangman_game",
"display_gallows"
],
[
"hangman_game",
"get_word"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 619cb55d562678573049503e31a858135b83e060 | c024d357bb089f6807ce3a89a4090b35fd7721a2 | |||
v1.0 | instruct | Filter | Filter_14955_I | I am running a mathematical modeling project at a student competition, and I have been assigned to use Python. For my project, I have a set of ordinary differential equations (ODEs) that describe the population dynamics of a system. I want to use Python to numerically integrate these ODEs and generate plots to analyze ... | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def population_model(y, t, a, b, c, d):
"""
Defines the system of ODEs for the population dynamics model.
Parameters:
y : array, list of population levels [prey, predator]
t : float, time point
... | # Unit Test Code in Python
from solution import population_model, integrate_ode
def test_population_model():
# Test with known inputs and outputs
y = [40, 9]
t = 0
params = (0.1, 0.02, 0.3, 0.01)
prey, predator = y
dydt = population_model(y, t, *params)
expected_dydt = [prey * 0.1 - prey * ... | [
{
"docstring": "Defines the system of ODEs for the population dynamics model.\n\nParameters:\n y : array, list of population levels [prey, predator]\n t : float, time point\n a : float, growth rate of prey\n b : float, rate at which prey is consumed by predator\n c : float, death rate of predator... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import solve_ivp\nimport matplotlib.pyplot as plt\n\ndef system_of_odes(t, y, a, b, c):\n \"\"\"\n Defines a system of ODEs.\n \n Parameter... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014955",
"row_id": 14955,
"seed_ids": "['Llama-3.3-70B-Instruct_38411']"
} | 0.41962 | Filter_14955 | I | [
"population_model",
"integrate_ode",
"plot_population_dynamics"
] | 3 | [
[
"integrate_ode",
"population_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 53d491d6a529587230826fb1f470fbd006b36b1c | 2edab9a8c9c7d7d70e2a2768261fdd04777c3af2 | |||
v1.0 | instruct | Filter | Filter_14962_I | ### Exploding Dice
In this problem, we will create a simple game of exploding dice. The rules are as follows:
* The game is played with six-sided dice.
* Each player rolls the dice until they choose to stop or they roll a 6.
* If the player rolls a 6, their turn is over and their score for that turn is 0.
* If a play... | import random
def roll_dice():
"""Roll a six-sided dice"""
return random.randint(1, 6)
def game():
"""
Main game loop for the exploding dice game.
Players take turns to roll a dice until one of them achieves a score of 20 or more to win.
"""
player1_score = 0
player2_score = 0
turn... | from solution import roll_dice
def test_roll_dice():
roll = roll_dice()
assert 1 <= roll <= 6
def test_roll_dice_distribution():
results = [roll_dice() for _ in range(6000)]
counts = [results.count(i) for i in range(1, 7)]
for count in counts:
assert 900 <= count <= 1100 # Rough check for... | [
{
"docstring": "Roll a six-sided dice",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Main game loop for the exploding dice game.\nPlayers take turns to roll a dice until one of them achieves a score of 20 or more to win."... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"Roll a six-sided dice\"\"\"\n return random.randint(1, 6)\n\ndef take_turn(player_name):\n \"\"\"Simulate a player's turn\"\"\"\n turn_sco... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014962",
"row_id": 14962,
"seed_ids": "['Llama-3.3-70B-Instruct_38429']"
} | 0.531093 | Filter_14962 | I | [
"roll_dice",
"game"
] | 2 | [
[
"game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a73449fbd8b85dc1bcd5dec32c9a9d0559ea07b8 | 9ccc9f28b907e029bd8e3473bfe37e0f01924d82 | |||
v1.0 | instruct | Filter | Filter_14974_I | I would like to ask for a script that takes a list of code files on the local machine and checks for every file in that list if it has an import statement. Is this possible to check programmatically? | import os
def has_import_statement(file_path):
"""
Check if a file contains any import statement.
Args:
file_path (str): Path to the file to be checked.
Returns:
bool: True if the file contains an import statement, False otherwise.
"""
if not os.path.isfile(file_path):
... | import pytest
from solution import has_import_statement, check_files_for_import_statements
def test_has_import_statement():
# Create a temp file to test
with open('temp_with_import.py', 'w') as file:
file.write('import os\n')
with open('temp_without_import.py', 'w') as file:
file.write... | [
{
"docstring": "Check if a file contains any import statement.\n\nArgs:\nfile_path (str): Path to the file to be checked.\n\nReturns:\nbool: True if the file contains an import statement, False otherwise.",
"function_declaration": "def has_import_statement(file_path):",
"function_name": "has_import_stat... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef has_import_statement(file_path):\n \"\"\"\n Checks if the given file contains an import statement.\n \n Args:\n file_path (str): The path to the code file.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00014974",
"row_id": 14974,
"seed_ids": "['Llama-3.3-70B-Instruct_38454']"
} | 0.444994 | Filter_14974 | I | [
"has_import_statement",
"check_files_for_import_statements"
] | 2 | [
[
"check_files_for_import_statements",
"has_import_statement"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0d5fe671819d0440b53cd1129b93f86c17bc46c7 | 0502dc29361db0151c123423320cfa0c5ff4d982 | |||
v1.0 | instruct | Filter | Filter_15006_I | ### Background
The Blum-Blum-Shub (BBS) pseudorandom number generator (PRNG) is a cryptographically secure PRNG defined as follows:
1. Choose two large prime numbers, $p$ and $q$, such that $p \equiv q \equiv 3 \pmod{4}$.
2. Compute $n = p \cdot q$.
3. Choose a random integer $x$ such that $x \in \mathbb{Z}_n^*$ and $x... | import random
def is_prime(num, k=5):
"""Test if a number is prime using the Miller-Rabin primality test"""
if num < 2: # 0, 1, and negatives are not prime
return False
for p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]:
if num < p * p:
return True
if num % p == 0:
... | from solution import generate_primes, generate_seed, bbs_prng, is_prime
def test_is_prime():
assert is_prime(3)
assert is_prime(7)
assert not is_prime(1)
assert not is_prime(4)
assert is_prime(97)
def test_generate_primes():
p, q = generate_primes(16) # smaller bit size for faster testing
... | [
{
"docstring": "Test if a number is prime using the Miller-Rabin primality test",
"function_declaration": "def is_prime(num, k=5):",
"function_name": "is_prime",
"parameter_list": "(num, k=5)"
},
{
"docstring": "Generate a large prime number p such that p ≡ 3 (mod 4)",
"function_declarat... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(num, k=5): # The Miller-Rabin primality test\n if num < 2:\n return False\n if num % 2 == 0:\n return num == 2\n s, d = 0, num - 1\n wh... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015006",
"row_id": 15006,
"seed_ids": "['Llama-3.3-70B-Instruct_38514']"
} | 0.503744 | Filter_15006 | I | [
"is_prime",
"generate_prime",
"generate_primes",
"bbs_prng",
"generate_seed",
"main"
] | 6 | [
[
"generate_prime",
"is_prime"
],
[
"generate_primes",
"generate_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 09a0c6a91188014f27847e4d920ed56ea3c57215 | ea4519ff2dece4bf37ddc1498c51f20e3b8d1533 | |||
v1.0 | instruct | Filter | Filter_15024_I | How can I create a function that meets the following requirements:
- It takes in a list of integers as input
- It calculates the median of the list
- It compares the median to a predefined threshold (let's say 5)
- If the median is less than the threshold, the function returns True, otherwise it returns False
Here's a... | import random
def quickselect_median(lst):
if len(lst) % 2 == 1:
return quickselect(lst, len(lst) // 2)
else:
return 0.5 * (quickselect(lst, len(lst) // 2 - 1) +
quickselect(lst, len(lst) // 2))
def quickselect(lst, k):
if len(lst) == 1:
return lst[0]
piv... | from solution import check_median, quickselect_median, quickselect
def test_check_median_less_than_threshold():
assert check_median([1, 2, 3, 4, 5]) == True # Median is 3
assert check_median([4, 4, 4, 4, 4]) == True # Median is 4
assert check_median([1, 2, 2, 3, 4]) == True # Median is 2
def test... | [
{
"docstring": null,
"function_declaration": "def quickselect_median(lst):",
"function_name": "quickselect_median",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def quickselect(lst, k):",
"function_name": "quickselect",
"parameter_list": "(lst, k)"
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef quickselect_median(lst):\n if len(lst) % 2 == 1:\n return quickselect(lst, len(lst) // 2)\n else:\n return 0.5 * (quickselect(lst, len(lst) // 2 - 1) +... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015024",
"row_id": 15024,
"seed_ids": "['Llama-3.3-70B-Instruct_38554']"
} | 0.782638 | Filter_15024 | I | [
"quickselect_median",
"quickselect",
"check_median"
] | 3 | [
[
"check_median",
"quickselect_median"
],
[
"quickselect_median",
"quickselect"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 00b51fe26e784e0cfbd564f022794288b49a1f62 | 0776b8d3de93cc3650859d97d6bbedc4b7846466 | |||
v1.0 | instruct | Filter | Filter_15050_I | Given the following Python code:
```python
from math import gcd
from functools import reduce
def calculate_gcd(numbers):
return reduce(gcd, numbers)
```
How would you implement a function to calculate the least common multiple (LCM) of a list of numbers using the provided GCD function? | from math import gcd
from functools import reduce
def calculate_gcd(numbers):
return reduce(gcd, numbers)
def lcm(a, b):
return abs(a * b) // gcd(a, b)
def calculate_lcm(numbers):
return reduce(lcm, numbers) | from solution import calculate_gcd, calculate_lcm
def test_calculate_gcd():
assert calculate_gcd([12, 15, 21]) == 3
assert calculate_gcd([4, 8, 16]) == 4
assert calculate_gcd([27, 9, 3]) == 3
assert calculate_gcd([44, 88, 121]) == 11
assert calculate_gcd([14, 25, 35]) == 1
def test_calculate_lcm()... | [
{
"docstring": null,
"function_declaration": "def calculate_gcd(numbers):",
"function_name": "calculate_gcd",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\nfrom functools import reduce\n\ndef calculate_gcd(numbers):\n return reduce(gcd, numbers)\n\ndef calculate_lcm(numbers):\n def lcm(a, b):\n return abs(a * b)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015050",
"row_id": 15050,
"seed_ids": "['Llama-3.3-70B-Instruct_38610']"
} | 0.609752 | Filter_15050 | I | [
"calculate_gcd",
"lcm",
"calculate_lcm"
] | 3 | [
[
"calculate_lcm",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | acc3ee389c5eda0daf567e5542aedcc64025ed0c | 98b7647155a79653ba60454f940fb3ec35b9678c | |||
v1.0 | instruct | Filter | Filter_15056_I | Write a code block using Python that calculates the total cost of a customer's order, including a discount for bulk purchases of a specific product.
```python
# Define the function
def calculate_total_cost():
# Define and initialize variables
product_price = 9.99
discount_percentage = 0.1 # 10% discount
... | product_info = {
"price": 9.99,
"discount_percentage": 0.1,
"bulk_quantity": 10
}
def get_product_info():
"""
Returns the product price and discount percentage from the dictionary.
"""
return product_info["price"], product_info["discount_percentage"], product_info["bulk_quantity"]
def calc... | from solution import calculate_total_cost
def test_calculate_total_cost_no_bulk_discount():
assert calculate_total_cost(5) == round(5 * 9.99, 2)
def test_calculate_total_cost_bulk_discount():
original_price = 10 * 9.99
discount_amount = original_price * 0.1
expected_price = original_price - discount_a... | [
{
"docstring": "Returns the product price and discount percentage from the dictionary.",
"function_declaration": "def get_product_info():",
"function_name": "get_product_info",
"parameter_list": "()"
},
{
"docstring": "Calculates the total cost of the customer order, including a discount for... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "product_info = {\n \"price\": 9.99,\n \"discount_percentage\": 0.1,\n \"bulk_quantity\": 10\n}\n\ndef get_product_info():\n \"\"\"\n Retrieve the product price and discount perc... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015056",
"row_id": 15056,
"seed_ids": "['Llama-3.3-70B-Instruct_38631']"
} | 0.502743 | Filter_15056 | I | [
"get_product_info",
"calculate_total_cost"
] | 2 | [
[
"calculate_total_cost",
"get_product_info"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 623ab73a27840a96ec929364c68b4aca75682f2a | c96a057a74b2c0736d0d0490fec83ee6859f558e | |||
v1.0 | instruct | Filter | Filter_15087_I | ### Basic Blackjack Game
#### Game Rules:
- The deck has 50 cards: 4 Aces, 16 num cards (4 suits of 2-10, excluding 5), 10 face cards (Jack, Queen, King), and 20 'action' cards (4 suits of 5 special cards: Reverse, Skip, +2, +5).
- Numbered cards are worth their number value.
- Face cards are worth 10 points.
- Ace can... | from random import shuffle
# Define card ranks and suits
card_ranks = ['2', '3', '4', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
card_suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
action_ranks = ['Reverse', 'Skip', '+2', '+5']
# Initialize deck
deck = []
for suit in card_suits:
for rank in card... | def test_card_value():
assert card_value(('2', 'Hearts')) == 2
assert card_value(('King', 'Spades')) == 10
assert card_value(('Ace', 'Diamonds')) == 11
assert card_value(('+2', 'Clubs')) == 0
def test_calculate_score_without_ace():
hand = [('2', 'Hearts'), ('King', 'Spades')]
assert calculate_s... | [
{
"docstring": null,
"function_declaration": "def card_value(card):",
"function_name": "card_value",
"parameter_list": "(card)"
},
{
"docstring": null,
"function_declaration": "def calculate_score(hand):",
"function_name": "calculate_score",
"parameter_list": "(hand)"
},
{
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from random import shuffle\n\n# Define card ranks and suits\ncard_ranks = ['2', '3', '4', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']\ncard_suits = ['Hearts', 'Diamonds', 'Clubs'... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015087",
"row_id": 15087,
"seed_ids": "['Llama-3.3-70B-Instruct_38687']"
} | 0.59898 | Filter_15087 | I | [
"card_value",
"calculate_score",
"basic_blackjack_game"
] | 3 | [
[
"basic_blackjack_game",
"calculate_score"
],
[
"calculate_score",
"card_value"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 0f668c0eefc817b215ab1b738c50396721590e2a | 8f8b86a2231f6728a79797dffdb6177d5b502c68 | |||
v1.0 | instruct | Filter | Filter_15089_I | I am writing a script to automate the download of music from YouTube. My script should use the `youtube-dl` command, which is located on my system, but it is not in the default path.
I need a way to construct the full path of `youtube-dl` command so that it can be used by the `subprocess` module.
Here are the scena... | import os
import shutil
import subprocess
def get_youtube_dl_path(user_provided_path=None):
"""
This function gets the path to youtube-dl.
If the path is provided by the user, it will be returned.
If the path is not provided, it will check if youtube-dl is in the default path.
If it's not in t... | import os
import pytest
import subprocess
from unittest import mock
from solution import get_youtube_dl_path, download_music
def test_get_youtube_dl_path_user_provided():
user_path = "/custom/path/to/youtube-dl"
with mock.patch("os.path.exists", return_value=True):
result = get_youtube_dl_path(user_pa... | [
{
"docstring": "This function gets the path to youtube-dl.\n\nIf the path is provided by the user, it will be returned.\nIf the path is not provided, it will check if youtube-dl is in the default path.\nIf it's not in the default path, it will search for it in certain directories.\n\nArgs:\n user_provided_pa... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport subprocess\nimport sys\n\ndef get_youtube_dl_path(user_provided_path=None):\n \"\"\"\n This function gets the path to youtube-dl.\n \n If the path ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015089",
"row_id": 15089,
"seed_ids": "['Llama-3.3-70B-Instruct_38691']"
} | 0.571591 | Filter_15089 | I | [
"get_youtube_dl_path",
"download_music"
] | 2 | [
[
"download_music",
"get_youtube_dl_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ad64dbdc47f6859642624a33b0311e82389710d | ccc8365b8001aa794ad9f773775c345947af0580 | |||
v1.0 | instruct | Filter | Filter_15102_I | I have a large number of input files, all in CSV format. They all have a header row, but no index column. Each file describes the same dataset but has a different number of rows (some are more complete than others). I'd like to write a script that merges these files together, keeping the unique rows from each file and ... | import pandas as pd
import glob
def merge_csv_files(file_pattern):
"""
Merge multiple CSV files into a single DataFrame, keeping unique rows and removing duplicates.
Parameters:
file_pattern (str): A glob pattern to match the input CSV files.
Returns:
pd.DataFrame: Merged DataFrame wi... | import os
import pandas as pd
import pytest
from solution import merge_csv_files, save_merged_csv
def create_temp_csv_files(file_contents):
for filename, content in file_contents.items():
with open(filename, 'w') as f:
f.write(content)
def remove_temp_csv_files(file_contents):
for filename... | [
{
"docstring": "Merge multiple CSV files into a single DataFrame, keeping unique rows and removing duplicates.\n\nParameters:\nfile_pattern (str): A glob pattern to match the input CSV files.\n\nReturns:\npd.DataFrame: Merged DataFrame with unique rows.",
"function_declaration": "def merge_csv_files(file_pa... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport glob\n\ndef merge_csv_files(file_pattern, output_file):\n \"\"\"\n Merges multiple CSV files into one, ensuring unique rows and removing duplicates.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015102",
"row_id": 15102,
"seed_ids": "['Llama-3.3-70B-Instruct_38720']"
} | 0.643507 | Filter_15102 | I | [
"merge_csv_files",
"save_merged_csv"
] | 2 | [
[
"save_merged_csv",
"merge_csv_files"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | c9616a88888cd61b0418130a149c6e5254aac642 | 8564ee283bc018914205d7f984e02df83cd7aa1a | |||
v1.0 | instruct | Filter | Filter_15112_I | ### Part 1: Create a Python Script for Calculating the Total Cost of Groceries
#### Objective:
Create a Python script that will allow a user to calculate the total cost of their groceries. The script should:
- Prompt the user to enter the number of items they wish to purchase.
- Ask the user for the name and price of e... | def get_item_input():
"""
Prompts user to input the name and price of an item.
Returns:
tuple: containing the name of the item and its price.
"""
while True:
try:
item_name = input("Enter the name of the item: ")
item_price = float(input(f"Enter the price of {... | import os
from solution import add_items, read_items_from_file
def test_add_items(monkeypatch):
inputs = iter(["3", "Apple", "1.25", "Banana", "0.5", "Orange", "1.0"])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
expected_output = 2.75
assert add_items() == expected_output
assert o... | [
{
"docstring": "Prompts user to input the name and price of an item.\nReturns:\n tuple: containing the name of the item and its price.",
"function_declaration": "def get_item_input():",
"function_name": "get_item_input",
"parameter_list": "()"
},
{
"docstring": "Prompts the user to add a ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_items():\n total_cost = 0.0\n num_items = input(\"Enter the number of items you wish to purchase: \")\n \n try:\n num_items = int(num_items)\n if num_items <=... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015112",
"row_id": 15112,
"seed_ids": "['Llama-3.3-70B-Instruct_38743']"
} | 0.540927 | Filter_15112 | I | [
"get_item_input",
"add_items",
"read_items_from_file",
"main"
] | 4 | [
[
"add_items",
"get_item_input"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da8f594d7266e335ccdec5be76ef8b688f61544e | d2069e8952d4d097b0e2c2351244af221c8c83a1 | |||
v1.0 | instruct | Filter | Filter_15144_I | Provide a code that reads a text file that contains a list of words, one word per line, and prints out each word along with the number of vowels in the word. | def count_vowels(word):
"""
Returns the number of vowels in the given word.
"""
vowels = 'aeiouAEIOU'
return sum(1 for char in word if char in vowels)
def read_and_process_file(filename):
"""
Reads a file containing a list of words, one word per line,
and prints out each word along with... | from solution import count_vowels, read_and_process_file
import tempfile
def test_count_vowels():
assert count_vowels("hello") == 2
assert count_vowels("world") == 1
assert count_vowels("bcdfghjklmnpqrstvwxyz") == 0
assert count_vowels("AEIOUaeiou") == 10
assert count_vowels("") == 0
def test_read... | [
{
"docstring": "Returns the number of vowels in the given word.",
"function_declaration": "def count_vowels(word):",
"function_name": "count_vowels",
"parameter_list": "(word)"
},
{
"docstring": "Reads a file containing a list of words, one word per line,\nand prints out each word along with... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_vowels(word):\n \"\"\"\n Returns the number of vowels in the given word.\n \"\"\"\n vowels = 'aeiouAEIOU'\n return sum(1 for char in word if char in vowels)\n\ndef pri... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015144",
"row_id": 15144,
"seed_ids": "['Llama-3.3-70B-Instruct_38819']"
} | 0.697184 | Filter_15144 | I | [
"count_vowels",
"read_and_process_file"
] | 2 | [
[
"read_and_process_file",
"count_vowels"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5339849ce981229609db985dcca506633bb016f2 | 8b4352f24c47af7786a4b8f1d1799684ac605a0a | |||
v1.0 | instruct | Filter | Filter_15152_I | I have written a code to upload CSV and parse it, and I want to enhance it so that it can handle multiple files. The current implementation only works for single file upload.
Below is my current implementation:
```python
import pandas as pd
import os
# Function to parse CSV
def parse_csv(file_path):
try:
... | import pandas as pd
import os
# Function to parse CSV
def parse_csv(file_path):
try:
# Read the csv file
df = pd.read_csv(file_path)
# Print the data frame
print(df)
return df
except Exception as e:
print(f"Failed to parse CSV: {str(e)}")
... | import os
import pandas as pd
from solution import parse_csv, parse_multiple_csv
def test_parse_csv():
test_file = 'test.csv'
df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
df.to_csv(test_file, index=False)
result = parse_csv(test_file)
assert result.equals(df)
os.remove(test_fil... | [
{
"docstring": null,
"function_declaration": "def parse_csv(file_path):",
"function_name": "parse_csv",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def parse_multiple_csv(file_paths):",
"function_name": "parse_multiple_csv",
"parameter_list": ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport os\n\n# Function to parse CSV\ndef parse_csv(file_path):\n try:\n # Read the csv file\n df = pd.read_csv(file_path)\n \n # Print the ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015152",
"row_id": 15152,
"seed_ids": "['Llama-3.3-70B-Instruct_38831']"
} | 0.643925 | Filter_15152 | I | [
"parse_csv",
"parse_multiple_csv",
"main"
] | 3 | [
[
"parse_multiple_csv",
"parse_csv"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 631a8dfce41b9c6d3af6e6ce9e102a6753087aca | bc086f9975f14392d5d1499dc83b99fffe2057f8 | |||
v1.0 | instruct | Filter | Filter_15158_I | I wrote a code that gets the number of days in a given month. However I need to modify the code such that it should also consider leap year conditions.
Here is the sample code:
```python
def get_days_in_month(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month == 2:
return 2... | def is_leap_year(year):
"""
Returns True if the given year is a leap year, otherwise False.
"""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
return False
def get_days_in_month(year, month):
"""
Returns the number of days in the specified month of the give... | from solution import get_days_in_month, is_leap_year
def test_is_leap_year():
assert is_leap_year(2020) == True
assert is_leap_year(1900) == False
assert is_leap_year(2000) == True
assert is_leap_year(2021) == False
def test_days_in_january():
assert get_days_in_month(2021, 1) == 31
def test_days... | [
{
"docstring": "Returns True if the given year is a leap year, otherwise False.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"docstring": "Returns the number of days in the specified month of the given year, considering... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_days_in_month(year, month):\n \"\"\"\n Returns the number of days in a given month of a given year, \n considering leap year conditions.\n \"\"\"\n if month in [1, 3, 5,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015158",
"row_id": 15158,
"seed_ids": "['Llama-3.3-70B-Instruct_38844']"
} | 0.566783 | Filter_15158 | I | [
"is_leap_year",
"get_days_in_month"
] | 2 | [
[
"get_days_in_month",
"is_leap_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 609a82cf65901d8c0c048ea4603c492e510012eb | 92bda3dcc56daef14c0e5523f88fc59044444118 | |||
v1.0 | instruct | Filter | Filter_15214_I | I have a list of long strings, and I would like to iterate through them and perform processing on each string. I want to know if there are any specific recommendations for processing strings in Python, especially if the strings are very long.
Here's an example of what I have now:
```
my_list = ["string1", "string2",... | def process_strings(long_string_list):
"""
Processes a list of long strings.
Parameters:
long_string_list (list): List of strings to be processed.
Returns:
list: A list of processed strings.
"""
processed_list = []
for s in long_string_list:
# Simulate some pro... | from solution import process_strings, process_string
def test_process_string():
assert process_string("hello") == 5
assert process_string("") == 0
assert process_string("a"*1000) == 1000
def test_process_strings():
input_list = ["abc", "defg", "hi"]
expected_output = [3, 4, 2]
assert process_s... | [
{
"docstring": "Processes a list of long strings.\n\nParameters:\nlong_string_list (list): List of strings to be processed.\n\nReturns:\nlist: A list of processed strings.",
"function_declaration": "def process_strings(long_string_list):",
"function_name": "process_strings",
"parameter_list": "(long... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_string(s):\n \"\"\"\n Placeholder function to represent string processing.\n \"\"\"\n return s[::-1]\n\ndef process_long_strings(my_list):\n \"\"\"\n Processes ea... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015214",
"row_id": 15214,
"seed_ids": "['Llama-3.3-70B-Instruct_38957']"
} | 0.451861 | Filter_15214 | I | [
"process_strings",
"process_string"
] | 2 | [
[
"process_strings",
"process_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77bebcdca35c2c05bd031c819dbd2914fc00a96b | 2a8823b1e5c8d7ebd719f9f25e2793986a67d85a | |||
v1.0 | instruct | Filter | Filter_15216_I | I have the following Python function:
```python
def get_text():
return "Hello, World!"
```
Now I want to be able to modify the output of the `get_text` function by adding a new function that can be used to decorate the `get_text` function. The idea is to be able to add some prefix or suffix or modify the text in ... | import functools
def add_prefix(prefix):
def decorator(func):
@functools.wraps(func) # preserves metadata
def wrapper(*args, **kwargs):
text = func(*args, **kwargs)
return prefix + text
return wrapper
return decorator
@add_prefix("NEW PREFIX: ")
def get_text():... | from solution import get_text, get_custom_text, MyGreeter
def test_get_text():
assert get_text() == "NEW PREFIX: Hello, World!"
def test_get_custom_text():
assert get_custom_text("Hello") == "Hello!!!"
assert get_custom_text("Goodbye") == "Goodbye!!!"
def test_my_greeter_greet():
greeter = MyGreeter(... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import wraps\n\ndef add_prefix(prefix):\n \"\"\"\n Decorator to add a prefix to the return value of a function.\n \n Args:\n prefix (str): The prefix to add to th... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015216",
"row_id": 15216,
"seed_ids": "['Llama-3.3-70B-Instruct_38959']"
} | 0.378627 | Filter_15216 | I | [
"add_prefix",
"get_text",
"add_suffix",
"get_custom_text"
] | 4 | [
[
"get_custom_text",
"add_suffix"
],
[
"get_text",
"add_prefix"
]
] | 2 | [] | false | [
"MyGreeter"
] | true | pytest | true | [] | true | a9bfa4b394d345da7daa0531de276c2ac751c7c8 | 90cbdc8bdd4d2f9c7e19810c294589c98bc0332b | |||
v1.0 | instruct | Filter | Filter_15219_I | ### Heads or Tails Game
You have to write a program to simulate a Heads or Tails game. The user will input their choice. Then the computer will randomly select either Heads or Tails. If the user's choice is the same as the computer's choice, the user wins; otherwise, the user loses. Finally, the program will print out ... | import random
def coin_flip():
"""Simulates a coin flip."""
# Use random.choice to select either 'Heads' or 'Tails'
return random.choice(['Heads', 'Tails'])
def heads_or_tails(user_choice):
"""Determines if user wins the Heads or Tails game."""
# Validate user input
if user_choice not in ['Hea... | from solution import heads_or_tails
# Mocking coin_flip for consistent testing results
def test_heads_or_tails_win(monkeypatch):
def mock_coin_flip():
return 'Heads'
monkeypatch.setattr('solution.coin_flip', mock_coin_flip)
assert heads_or_tails('Heads') == "You win!"
def test_heads_or_tails_loss(... | [
{
"docstring": "Simulates a coin flip.",
"function_declaration": "def coin_flip():",
"function_name": "coin_flip",
"parameter_list": "()"
},
{
"docstring": "Determines if user wins the Heads or Tails game.",
"function_declaration": "def heads_or_tails(user_choice):",
"function_name":... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef coin_flip():\n \"\"\"Simulates a coin flip.\"\"\"\n # Use random.choice to select either 'Heads' or 'Tails'\n return random.choice(['Heads', 'Tails'])\n\ndef head... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015219",
"row_id": 15219,
"seed_ids": "['Llama-3.3-70B-Instruct_38965']"
} | 0.50953 | Filter_15219 | I | [
"coin_flip",
"heads_or_tails"
] | 2 | [
[
"heads_or_tails",
"coin_flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f879fababba0701df13bf8bbf1b987112254b87c | f95e5e506203a4d181b65b3d76564f059f67542c | |||
v1.0 | instruct | Filter | Filter_15223_I | How can I create a function in python that starts a new process and writes a text file with an initial byte size of 450MB? | import os
def create_large_file(file_name='large_file.txt', size_in_mb=450):
"""
Create a file with the specified file name and initial size in MB.
Default file size is 450MB.
"""
size_in_bytes = size_in_mb * 1024 * 1024
# Create a file with the specified size
with open(file_name, 'wb') as ... | from solution import create_large_file, start_new_process
import os
def test_create_large_file():
file_name = 'test_large_file.txt'
# Before ensuring file does not exist
if os.path.exists(file_name):
os.remove(file_name)
create_large_file(file_name, 1) # Create 1MB file for testing
# Check... | [
{
"docstring": "Create a file with the specified file name and initial size in MB.\nDefault file size is 450MB.",
"function_declaration": "def create_large_file(file_name='large_file.txt', size_in_mb=450):",
"function_name": "create_large_file",
"parameter_list": "(file_name='large_file.txt', size_i... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef create_large_file(file_name='large_file.txt', size_in_mb=450):\n \"\"\"\n Create a file with the specified file name and initial size in MB.\n Default file size is 45... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015223",
"row_id": 15223,
"seed_ids": "['Llama-3.3-70B-Instruct_38970']"
} | 0.484918 | Filter_15223 | I | [
"create_large_file",
"start_new_process"
] | 2 | [
[
"start_new_process",
"create_large_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 51e7219d22fa9b0dd220923d51b26e5501bc078f | 6f9242efb90af6cda7c8f8f75ab22da2bc9605a6 | |||
v1.0 | instruct | Filter | Filter_15229_I | I've got a text file containing a list of urls in one column, I want to read it and extract the domain from each url using python.
Example:
```
https://www.example.com
https://subdomain.example.com
https://example.co.uk
```
Would result in the following output:
```
example.com
example.com
example.co.uk
```
How wou... | from urllib.parse import urlparse
def extract_domain_from_url(url):
"""
Extracts and returns the domain from a given URL.
"""
parsed_url = urlparse(url)
domain = parsed_url.netloc
if domain.startswith('www.'):
domain = domain[4:]
return domain
def extract_domains_from_file(file_pat... | from solution import extract_domain_from_url, extract_domains_from_file
def test_extract_domain_from_url():
assert extract_domain_from_url('https://www.example.com') == 'example.com'
assert extract_domain_from_url('https://subdomain.example.com') == 'subdomain.example.com'
assert extract_domain_from_url('h... | [
{
"docstring": "Extracts and returns the domain from a given URL.",
"function_declaration": "def extract_domain_from_url(url):",
"function_name": "extract_domain_from_url",
"parameter_list": "(url)"
},
{
"docstring": "Extracts and returns a list of domains from a file containing URLs.",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from urllib.parse import urlparse\n\ndef extract_domain_from_url(url):\n \"\"\"\n Extracts and returns the domain from a given URL.\n \"\"\"\n parsed_url = urlparse(url)\n domai... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015229",
"row_id": 15229,
"seed_ids": "['Llama-3.3-70B-Instruct_38986']"
} | 0.647161 | Filter_15229 | I | [
"extract_domain_from_url",
"extract_domains_from_file"
] | 2 | [
[
"extract_domains_from_file",
"extract_domain_from_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38d35a17ba88ae7287eeb2d91d70380e7356ad42 | 2cf4af0481931e958f993fc8b468b2454283d5ec | |||
v1.0 | instruct | Filter | Filter_15234_I | I have a standard TikTok video and I want to apply several effects to it that are commonly used on TikTok, such as zooming, panning, and fading. I was thinking about using Python and the OpenCV library for this task, but I am not sure where to start.
Can you provide a basic example of how I can use OpenCV to apply the... | import cv2
import numpy as np
def zoom_effect(frame, zoom_factor=1.2):
height, width = frame.shape[:2]
new_height, new_width = int(height / zoom_factor), int(width / zoom_factor)
y1, x1 = (height - new_height) // 2, (width - new_width) // 2
zoomed_frame = frame[y1:y1+new_height, x1:x1+new_width]
re... | import cv2
import numpy as np
from solution import zoom_effect, pan_effect, fade_effect
def test_zoom_effect():
frame = np.ones((100, 100, 3), dtype=np.uint8) * 255
zoomed_frame = zoom_effect(frame, 1.2)
assert zoomed_frame.shape == frame.shape
assert np.all(zoomed_frame[:10, :10] == 255) # Ensuring t... | [
{
"docstring": null,
"function_declaration": "def zoom_effect(frame, zoom_factor=1.2):",
"function_name": "zoom_effect",
"parameter_list": "(frame, zoom_factor=1.2)"
},
{
"docstring": null,
"function_declaration": "def pan_effect(frame, direction='right', pan_factor=0.02):",
"functio... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport numpy as np\n\ndef apply_zoom_effect(frame, zoom_scale=1.2):\n \"\"\"\n Apply zoom effect to the frame.\n \"\"\"\n height, width = frame.shape[:2]\n center_x,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015234",
"row_id": 15234,
"seed_ids": "['Llama-3.3-70B-Instruct_38998']"
} | 0.401857 | Filter_15234 | I | [
"zoom_effect",
"pan_effect",
"fade_effect",
"apply_effects"
] | 4 | [
[
"apply_effects",
"fade_effect"
],
[
"apply_effects",
"pan_effect"
],
[
"apply_effects",
"zoom_effect"
]
] | 3 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | fbac50d813d65afd11f3fe39730c192b60598256 | 38b8561d4bd12c87ed5d1db3fe141072c607ed99 | |||
v1.0 | instruct | Filter | Filter_15245_I | Here is a Python code for a Huffman coding:
```python
import heapq
from collections import defaultdict
import os
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq <... | import heapq
from collections import defaultdict
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def calculate_frequency(message):
frequency = de... | import pytest
from solution import (Node, calculate_frequency, build_huffman_tree,
build_code, huffman_encoding, huffman_decoding)
def test_calculate_frequency():
message = "test message"
expected = {'t': 2, 'e': 3, 's': 3, ' ': 1, 'm': 1, 'a': 1, 'g': 1}
assert calculate_frequency(m... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import defaultdict\n\nclass Node:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n self.left = None\n sel... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015245",
"row_id": 15245,
"seed_ids": "['Llama-3.3-70B-Instruct_39029']"
} | 0.416981 | Filter_15245 | I | [
"calculate_frequency",
"build_huffman_tree",
"build_code_helper",
"build_code",
"huffman_encoding",
"huffman_decoding"
] | 6 | [
[
"build_code",
"build_code_helper"
],
[
"huffman_encoding",
"build_code"
],
[
"huffman_encoding",
"build_huffman_tree"
],
[
"huffman_encoding",
"calculate_frequency"
]
] | 4 | [] | false | [
"Node"
] | true | pytest | true | [] | true | eb6e268debfcbc17daf70047f7f0cc4c4d648a24 | f9252c6e768cc0dcd6ff5a14ce7b1e008f467535 | |||
v1.0 | instruct | Filter | Filter_15254_I | Consider a population of animals in a preserve. The change in population over time can be modeled using the logistic growth equation, given by
dp/dt = rP(1 - P/K)
where:
- dp/dt is the rate of change of the population
- P is the population size at time t
- r is the intrinsic growth rate
- K is the carrying capacity o... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def logistic_growth(P, t, r, K):
"""
Logistic growth differential equation.
Parameters:
P (float): current population
t (float): time
r (float): intrinsic growth rate
K (float): carrying capacity
... | import numpy as np
from solution import logistic_growth, model_population_growth
def test_logistic_growth():
r = 0.5
K = 1000
P = 500 # Population size in the middle of the carrying capacity
t = 0 # Time is irrelevant for the function
rate_of_change = logistic_growth(P, t, r, K)
expected_valu... | [
{
"docstring": "Logistic growth differential equation.\n\nParameters:\nP (float): current population\nt (float): time\nr (float): intrinsic growth rate\nK (float): carrying capacity\n\nReturns:\nfloat: rate of change of the population",
"function_declaration": "def logistic_growth(P, t, r, K):",
"functi... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\ndef logistic_growth(P, t, r, K):\n \"\"\"\n Logistic growth differential equation.\n \n P... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015254",
"row_id": 15254,
"seed_ids": "['Llama-3.3-70B-Instruct_39053']"
} | 0.377602 | Filter_15254 | I | [
"logistic_growth",
"model_population_growth"
] | 2 | [
[
"model_population_growth",
"logistic_growth"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 957f991e5a4bc479efe4116a4834a4d51b851b4e | 8692b0175df0150dcd8269ba61b94c0762d0fa75 | |||
v1.0 | instruct | Filter | Filter_15271_I | Here is the Python solution to find the LCM of two numbers. However, it can only accept two arguments. If the user wants to find the LCM of 3 or more numbers, then it doesn't work.
```
def find_lcm(num1, num2):
# compute gcd
def compute_gcd(a, b):
while b:
a, b = b, a % b
return a
... | from math import gcd
def find_lcm(num1, num2):
"""
Returns the LCM (Least Common Multiple) of two numbers.
"""
return num1 * num2 // gcd(num1, num2)
def find_lcm_general(*args):
"""
Returns the LCM (Least Common Multiple) of multiple numbers.
"""
if len(args) < 2:
raise ValueEr... | from solution import find_lcm, find_lcm_general
def test_find_lcm():
assert find_lcm(15, 20) == 60
assert find_lcm(12, 18) == 36
assert find_lcm(7, 5) == 35
assert find_lcm(21, 6) == 42
def test_find_lcm_general_two_numbers():
assert find_lcm_general(15, 20) == 60
assert find_lcm_general(12, 1... | [
{
"docstring": "Returns the LCM (Least Common Multiple) of two numbers.",
"function_declaration": "def find_lcm(num1, num2):",
"function_name": "find_lcm",
"parameter_list": "(num1, num2)"
},
{
"docstring": "Returns the LCM (Least Common Multiple) of multiple numbers.",
"function_declara... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_lcm(num1, num2):\n \"\"\"\n Returns the LCM (Least Common Multiple) of two numbers.\n \"\"\"\n def compute_gcd(a, b):\n while b:\n a, b = b, a % b\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015271",
"row_id": 15271,
"seed_ids": "['Llama-3.3-70B-Instruct_39088']"
} | 0.668476 | Filter_15271 | I | [
"find_lcm",
"find_lcm_general"
] | 2 | [
[
"find_lcm_general",
"find_lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fdfd7f94c312be670861083e36cc6b04a724900d | bfed9c0c9f469c52be1d23c9e2097e8a0df8729f | |||
v1.0 | instruct | Filter | Filter_15305_I | Here's a tricky problem I've been trying to solve:
Write a Python program to find all prime numbers up to a given number `n`.
However, here's the catch: you must use a **primality test** based on the **Miller-Rabin test**. The method should be able to handle large inputs and should be sufficient for cryptographic ap... | import random
def _miller_rabin_pass(a, s, d, n):
"""
Perform the Miller-Rabin test pass with base 'a'.
"""
a_to_power = pow(a, d, n)
if a_to_power == 1:
return True
for i in range(s - 1):
if a_to_power == n - 1:
return True
a_to_power = (a_to_power * a_to_po... | from solution import find_primes_up_to, is_prime
def test_small_primes():
assert find_primes_up_to(10) == [2, 3, 5, 7]
def test_no_primes_under_two():
assert find_primes_up_to(1) == []
def test_large_prime_list():
primes_up_to_50 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
assert find_... | [
{
"docstring": "Perform the Miller-Rabin test pass with base 'a'.",
"function_declaration": "def _miller_rabin_pass(a, s, d, n):",
"function_name": "_miller_rabin_pass",
"parameter_list": "(a, s, d, n)"
},
{
"docstring": "Determine if a number n is prime using the Miller-Rabin test.",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef miller_rabin(n, k=5):\n \"\"\"\n Perform the Miller-Rabin primality test to check if n is a prime number.\n \n Parameters:\n n (int): The number to test for... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015305",
"row_id": 15305,
"seed_ids": "['Llama-3.3-70B-Instruct_39169']"
} | 0.59399 | Filter_15305 | I | [
"_miller_rabin_pass",
"is_prime",
"find_primes_up_to"
] | 3 | [
[
"find_primes_up_to",
"is_prime"
],
[
"is_prime",
"_miller_rabin_pass"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2e8f42dfc7b5efc711426e8d6587fa02dc689c3e | 353bacb7fb96f25a859d10cd897984339f4cc4d9 | |||
v1.0 | instruct | Filter | Filter_15325_I | I'm trying to implement the simplest form of RSA encryption, where encryption and decryption are simple multiplication and division, respectively, with mod n. However, I've encountered a problem with the decryption process.
Specifically, the decrypted result is either zero or a large number. This could be because I'm... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def modinv(a, m):
m0, y, x = m, 0, 1
if m == 1:
return 0
while a > 1:
q = a // m
t = m
m = a % m
a = t
t = y
y = x - q * y
x = t
if x < 0:
x = x + m0
return x
de... | from solution import generate_keys, encrypt, decrypt
def test_rsa():
p = 61
q = 53
n, e, d = generate_keys(p, q)
plaintext = 1234
ciphertext = encrypt(plaintext, n, e)
decrypted_text = decrypt(ciphertext, d, n)
assert decrypted_text == plaintext
def test_gcd():
assert gcd(54,... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def modinv(a, m):",
"function_name": "modinv",
"parameter_list": "(a, m)"
},
{
"docstring": null,
"functi... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_keys(p, q):\n n = p * q\n phi = (p - 1) * (q - 1)\n e = 65537 # commonly used prime for RSA\n d = pow(e, -1, phi)\n return n, e, d\n\ndef encrypt(plaintext, n, e):... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015325",
"row_id": 15325,
"seed_ids": "['Llama-3.3-70B-Instruct_39227']"
} | 0.489949 | Filter_15325 | I | [
"gcd",
"modinv",
"generate_keys",
"encrypt",
"decrypt",
"main"
] | 6 | [
[
"generate_keys",
"modinv"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0f8c9ba728c571fa7f1fbd469b57c5e8b2c5368 | 623a02e8d2fcffd31a1906cece8fb7c02cbb9f73 | |||
v1.0 | instruct | Filter | Filter_15340_I | Given a list of integers, return `True` if any integer appears at least twice in the list and `False` otherwise.
Here is the code for this problem:
```
def contains_duplicate(nums):
seen = {}
for num in nums:
if num in seen:
return True
seen[num] = None
return False
```
However,... | def make_hashable(x):
if isinstance(x, list):
return tuple(make_hashable(y) for y in x)
elif isinstance(x, dict):
return frozenset((make_hashable(k), make_hashable(v)) for k, v in x.items())
elif isinstance(x, set):
return frozenset(make_hashable(y) for y in x)
else:
retu... | def test_contains_duplicate_no_duplicates():
assert not contains_duplicate([1, 2, 3, 4, 5, 6])
def test_contains_duplicate_with_duplicates():
assert contains_duplicate([1, 2, 3, 4, 2])
def test_contains_duplicate_unhashable_elements_no_duplicates():
assert not contains_duplicate([[1, 2], 1, [3, 4]])
... | [
{
"docstring": null,
"function_declaration": "def make_hashable(x):",
"function_name": "make_hashable",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def contains_duplicate(nums):",
"function_name": "contains_duplicate",
"parameter_list": "(nums)"
}
] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def make_hashable(x):\n if isinstance(x, list):\n return tuple(make_hashable(y) for y in x)\n elif isinstance(x, dict):\n return frozenset((make_hashable(k), make_hashable(... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015340",
"row_id": 15340,
"seed_ids": "['Llama-3.3-70B-Instruct_39268']"
} | 0.610016 | Filter_15340 | I | [
"make_hashable",
"contains_duplicate"
] | 2 | [
[
"contains_duplicate",
"make_hashable"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 80d530f64bc213ca36ce5a61ade34bc44fc0a3ce | f6518c1c52aa9e9b0b4b509be4a40eb51d47bac5 | |||
v1.0 | instruct | Filter | Filter_15360_I | I'm trying to implement a binary search in a sorted array and a linear search in a unsorted array. I've started by writing a linear search algorithm and a binary search algorithm, but I'm not sure how to implement it for both sorted and unsorted arrays.
Here is my code:
```python
def linear_search(arr, target):
... | def search_in_sorted_array(arr, target):
"""
Searches for the target in a sorted array using binary search.
Parameters:
arr (list): Sorted list of elements
target (int/float): The element to search for in the array
Returns:
int: The index of the found element, or -1 if not found
""... | def test_search_in_sorted_array():
arr = [1, 2, 3, 4, 5]
assert search_in_sorted_array(arr, 3) == 2
assert search_in_sorted_array(arr, 1) == 0
assert search_in_sorted_array(arr, 5) == 4
assert search_in_sorted_array(arr, 6) == -1
def test_search_in_unsorted_array():
arr = [3, 1, 4, 5, 2]
as... | [
{
"docstring": "Searches for the target in a sorted array using binary search.\n\nParameters:\narr (list): Sorted list of elements\ntarget (int/float): The element to search for in the array\n\nReturns:\nint: The index of the found element, or -1 if not found",
"function_declaration": "def search_in_sorted_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search(arr, target, sorted_array=False):\n \"\"\"\n Search for a target in the array. Uses binary search if array is sorted.\n \"\"\"\n if sorted_array:\n return binary_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015360",
"row_id": 15360,
"seed_ids": "['Llama-3.3-70B-Instruct_39302']"
} | 0.626092 | Filter_15360 | I | [
"search_in_sorted_array",
"search_in_unsorted_array",
"linear_search",
"binary_search"
] | 4 | [
[
"search_in_sorted_array",
"binary_search"
],
[
"search_in_unsorted_array",
"linear_search"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 5d66686f061a5cf1248f18daf353a6f0393750f5 | e2723927795cc5eb1ff424913cd48a258ec83ea9 | |||
v1.0 | instruct | Filter | Filter_15362_I | I'm looking for a simple simulation of a tennis match. I'd like to see the basic structures of the game and use a random number generator to determine the winner of each point. I'm looking for the best of three sets to win.
I'm most interested in this for understanding scoring and basic game structure rather than a d... | import random
def play_game():
score_a = 0
score_b = 0
while True:
if random.random() > 0.5:
score_a += 1
else:
score_b += 1
if score_a >= 4 and score_a - score_b >= 2:
return "A"
elif score_b >= 4 and score_b - score_a >= 2:
... | from solution import play_game, play_tiebreaker, play_set, play_match
def test_play_game():
result = play_game()
assert result in ["A", "B"]
def test_play_tiebreaker():
result = play_tiebreaker()
assert result in ["A", "B"]
def test_play_set():
result = play_set()
assert result in ["A", "B"]
... | [
{
"docstring": null,
"function_declaration": "def play_game():",
"function_name": "play_game",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def play_tiebreaker():",
"function_name": "play_tiebreaker",
"parameter_list": "()"
},
{
"docstring": nul... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef play_game():\n score_a = 0\n score_b = 0\n while True:\n if random.random() > 0.5:\n score_a += 1\n else:\n score_b += 1\n\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015362",
"row_id": 15362,
"seed_ids": "['Llama-3.3-70B-Instruct_39304']"
} | 0.493986 | Filter_15362 | I | [
"play_game",
"play_tiebreaker",
"play_set",
"play_match"
] | 4 | [
[
"play_match",
"play_set"
],
[
"play_set",
"play_game"
],
[
"play_set",
"play_tiebreaker"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e92b173780a584dbdfe18d6c67a4802d6627c784 | b9134c096e3d71adea154590b33a6859a014d3b7 | |||
v1.0 | instruct | Filter | Filter_15399_I | I have a list of numbers and I want to write a function that will calculate the greatest common divisor (GCD) of two numbers and use that function to find the GCD of all the numbers in the list.
Here is the code that I have written so far:
```
def gcd(a, b):
# Use Euclid's algorithm to find GCD
while b != 0:
... | def gcd(a, b):
"""
Use Euclid's algorithm to find the GCD of two numbers.
"""
while b != 0:
a, b = b, a % b
return a
def find_gcd_of_list(numbers):
"""
Find the GCD of all the numbers in the list using the gcd function.
"""
if not numbers:
raise ValueError("The list ... | from solution import gcd, find_gcd_of_list
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(7, 3) == 1
assert gcd(100, 10) == 10
assert gcd(13, 13) == 13
def test_find_gcd_of_list_single_element():
assert find_gcd_of_list([7]) == 7
def test_find_gcd_of_list_multiple_elements():
assert find_... | [
{
"docstring": "Use Euclid's algorithm to find the GCD of two numbers.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Find the GCD of all the numbers in the list using the gcd function.",
"function_declaration": "def find... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Use Euclid's algorithm to find GCD of two numbers a and b.\n \"\"\"\n while b != 0:\n a, b = b, a % b\n return a\n\ndef find_gcd_of_list(numbers... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015399",
"row_id": 15399,
"seed_ids": "['Llama-3.3-70B-Instruct_39385']"
} | 0.741361 | Filter_15399 | I | [
"gcd",
"find_gcd_of_list"
] | 2 | [
[
"find_gcd_of_list",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd282650596734959313d8e915eeb7956724b7a9 | d08a3f510a3c792e70a5c2857c229391b214e126 | |||
v1.0 | instruct | Filter | Filter_15405_I | I have a need for a function that takes a list of points in 3D space, and determines whether these points are coplanar. This function should return True if the points are coplanar, and False otherwise.
Here is a basic idea of what I'm looking for:
```python
def are_coplanar(points):
# Calculate normal vector to pl... | import numpy as np
def are_coplanar(points):
"""
Determines if a list of points in 3D space are coplanar.
Args:
points (list of tuple): List of points in 3D space. Each point is a tuple of 3 coordinates.
Returns:
bool: True if points are coplanar, False otherwise.
"""
if len(p... | from solution import are_coplanar
def test_coplanar_points():
points = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
assert are_coplanar(points) == True
def test_non_coplanar_points():
points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 1, 1)]
assert are_coplanar(points) == False
def test_three_points_coplanar():
... | [
{
"docstring": "Determines if a list of points in 3D space are coplanar.\n\nArgs:\npoints (list of tuple): List of points in 3D space. Each point is a tuple of 3 coordinates.\n\nReturns:\nbool: True if points are coplanar, False otherwise.",
"function_declaration": "def are_coplanar(points):",
"function... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def are_coplanar(points):\n \"\"\"\n Determines if a set of points in 3D space are coplanar.\n \n Parameters:\n points (list of tuples): List of points, each represented as a tu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015405",
"row_id": 15405,
"seed_ids": "['Llama-3.3-70B-Instruct_39398']"
} | 0.595041 | Filter_15405 | I | [
"are_coplanar",
"calculate_normal_vector",
"is_point_on_plane"
] | 3 | [
[
"are_coplanar",
"calculate_normal_vector"
],
[
"are_coplanar",
"is_point_on_plane"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 85e310a4cfe291b4aef0402605b18c2963f94d4b | 6995d4893a3368daadfc077dceef2343be23658a | |||
v1.0 | instruct | Filter | Filter_15424_I | I've been given the task to develop a simple, console-based, Rock, Paper, Scissors game in Python. The game should allow two players or a single player against the computer.
Here's a basic implementation that I used as a starting point:
```python
import random
def game():
while True:
user = input("Enter ... | import random
def play_round(user_choice, computer_choice):
winning_cases = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
if user_choice == computer_choice:
return "It's a tie!"
elif winning_cases[user_choice] == computer_choice:
return "You w... | from solution import play_round
def test_play_round_tie():
assert play_round("rock", "rock") == "It's a tie!"
assert play_round("paper", "paper") == "It's a tie!"
assert play_round("scissors", "scissors") == "It's a tie!"
def test_play_round_user_wins():
assert play_round("rock", "scissors") == "You w... | [
{
"docstring": null,
"function_declaration": "def play_round(user_choice, computer_choice):",
"function_name": "play_round",
"parameter_list": "(user_choice, computer_choice)"
},
{
"docstring": null,
"function_declaration": "def game():",
"function_name": "game",
"parameter_list"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef play_round(user_choice, computer_choice):\n winning_cases = {\n \"rock\": \"scissors\",\n \"scissors\": \"paper\",\n \"paper\": \"rock\"\n }\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015424",
"row_id": 15424,
"seed_ids": "['Llama-3.3-70B-Instruct_39458']"
} | 0.539917 | Filter_15424 | I | [
"play_round",
"game"
] | 2 | [
[
"game",
"play_round"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ab0ab42c88dd73857b8848f92fcded81b042bde | 57d1a1d9189868b11e9a67a04fac21048c3b5a15 | |||
v1.0 | instruct | Filter | Filter_15429_I | Can I get the code to calculate the list of the first few Fibonacci numbers using recursion? | def fibonacci_recursive(n):
"""
Returns the nth Fibonacci number using recursion.
Parameters:
n (int): The position in the Fibonacci sequence.
Returns:
int: The nth Fibonacci number.
"""
if n <= 0:
raise ValueError("n must be a positive integer")
elif n == 1:
... | from solution import fibonacci_recursive, fibonacci_list
def test_fibonacci_recursive():
assert fibonacci_recursive(1) == 0
assert fibonacci_recursive(2) == 1
assert fibonacci_recursive(3) == 1
assert fibonacci_recursive(4) == 2
assert fibonacci_recursive(5) == 3
assert fibonacci_recursive(6) =... | [
{
"docstring": "Returns the nth Fibonacci number using recursion.\n\nParameters:\nn (int): The position in the Fibonacci sequence.\n\nReturns:\nint: The nth Fibonacci number.",
"function_declaration": "def fibonacci_recursive(n):",
"function_name": "fibonacci_recursive",
"parameter_list": "(n)"
},... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_recursive(n):\n \"\"\"\n Returns the Fibonacci sequence up to the n-th term using recursion.\n \"\"\"\n if n <= 0:\n return []\n elif n == 1:\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015429",
"row_id": 15429,
"seed_ids": "['Llama-3.3-70B-Instruct_39468']"
} | 0.689873 | Filter_15429 | I | [
"fibonacci_recursive",
"fibonacci_list"
] | 2 | [
[
"fibonacci_list",
"fibonacci_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15cca3b5b7cf42854ea8df31c3960527b2a23b68 | 47b62d6b4374b6974726870228eb9a274e0ddfcd | |||
v1.0 | instruct | Filter | Filter_15444_I | I have a Python function that I've been using to steer a robot. This function takes in a list of angles (in radians) for the robot to turn and a list of distances for the robot to travel after each turn. The function works by iterating over the angles and distances, and for each pair, it turns the robot by the given an... | import math
def navigate_robot(angles, distances, checkpoints):
total_distance = 0
checkpoints = sorted(checkpoints)
checkpoint_index = 0
for angle, distance in zip(angles, distances):
# Turn the robot by the given angle
turn_robot(angle)
# Move the robot by the given dista... | from solution import navigate_robot
def test_navigate_robot_no_checkpoints(capsys):
angles = [math.radians(90)]
distances = [10]
checkpoints = []
navigate_robot(angles, distances, checkpoints)
captured = capsys.readouterr()
assert "Turning 90.0 degrees" in captured.out
assert "Mov... | [
{
"docstring": null,
"function_declaration": "def navigate_robot(angles, distances, checkpoints):",
"function_name": "navigate_robot",
"parameter_list": "(angles, distances, checkpoints)"
},
{
"docstring": null,
"function_declaration": "def turn_robot(angle):",
"function_name": "turn... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import math\n\ndef navigate_robot(angles, distances, checkpoints):\n total_distance_travelled = 0\n checkpoint_index = 0\n\n for angle, distance in zip(angles... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015444",
"row_id": 15444,
"seed_ids": "['Llama-3.3-70B-Instruct_39502']"
} | 0.452575 | Filter_15444 | I | [
"navigate_robot",
"turn_robot",
"move_robot"
] | 3 | [
[
"navigate_robot",
"move_robot"
],
[
"navigate_robot",
"turn_robot"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 107618f37752dbbe92992bd2cc92f53b2d9095f2 | 5b38e03df2c5d40631f6e9fe2d68ef5083916a6f | |||
v1.0 | instruct | Filter | Filter_15445_I | I have a grid of pixels, and I want to determine whether each point in a grid is fully or partially contained within a rectangle.
I would like a Python function to iterate through the grid and check for the pixel's coordinates against the rectangle's.
Here is a starter code for creating a grid:
```python
import nump... | import numpy as np
def is_point_in_rectangle(x, y, rect):
"""
Check if point (x, y) is within the rectangle defined by rect.
rect is defined by (x1, y1, x2, y2) where:
(x1, y1) - bottom left corner
(x2, y2) - top right corner
"""
(x1, y1, x2, y2) = rect
return x1 <= x <= x2 and y1 ... | from solution import is_point_in_rectangle, check_grid_against_rectangle
import numpy as np
# Unit test for is_point_in_rectangle
def test_is_point_in_rectangle():
assert is_point_in_rectangle(1, 1, (0, 0, 2, 2)) == True
assert is_point_in_rectangle(3, 3, (0, 0, 2, 2)) == False
assert is_point_in_rectangle... | [
{
"docstring": "Check if point (x, y) is within the rectangle defined by rect.\n\nrect is defined by (x1, y1, x2, y2) where:\n(x1, y1) - bottom left corner\n(x2, y2) - top right corner",
"function_declaration": "def is_point_in_rectangle(x, y, rect):",
"function_name": "is_point_in_rectangle",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef check_pixel_in_rectangle(x, y, rect):\n \"\"\"\n Check if the pixel (x, y) is inside the given rectangle.\n \n Args:\n x (int): The x-coordinate of the... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015445",
"row_id": 15445,
"seed_ids": "['Llama-3.3-70B-Instruct_39504']"
} | 0.5635 | Filter_15445 | I | [
"is_point_in_rectangle",
"check_grid_against_rectangle"
] | 2 | [
[
"check_grid_against_rectangle",
"is_point_in_rectangle"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 5a5b213507e31b55926366422cffb502cc289f4f | 452e1830d91e4adcbad7d8784621246e877576d2 | |||
v1.0 | instruct | Filter | Filter_15460_I | I've got a web application that, when the user clicks a button, triggers a series of algorithms that ultimately return a (potentially very large) collection of results. The results need to be displayed on the webpage, but I don't want to wait for the entire collection to be generated and returned before displaying anyt... | from flask import Flask, Response
import time
app = Flask(__name__)
def generate_results():
for i in range(1, 101):
time.sleep(0.1) # Simulate time-consuming computation
yield f"data: Result {i}\n\n"
@app.route('/results')
def results():
return Response(generate_results(), mimetype='text/eve... | import pytest
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_generate_results(client):
response = client.get('/results')
assert response.status_code == 200
assert response.mimetype == 'text/event-stream'
# Read line by line t... | [
{
"docstring": null,
"function_declaration": "def generate_results():",
"function_name": "generate_results",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def results():",
"function_name": "results",
"parameter_list": "()"
}
] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, Response\nimport time\n\napp = Flask(__name__)\n\ndef generate_results():\n for i in range(1, 101):\n time.sleep(0.1) # Simulate time-consuming computation\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015460",
"row_id": 15460,
"seed_ids": "['Llama-3.3-70B-Instruct_39534']"
} | 0.266473 | Filter_15460 | I | [
"generate_results",
"results"
] | 2 | [
[
"results",
"generate_results"
]
] | 1 | [
"generate_results"
] | false | [] | false | pytest | true | [
"flask"
] | false | c3d127af53a5c65f6324ff223e568d172a284d82 | 33b3b85123ea7615bcae5bbee0f1b6f2ad791a69 | |||
v1.0 | instruct | Filter | Filter_15472_I | In this problem, you will implement a method to play a simplified version of the popular game "Hangman". The game will start with a secret word that will be given to your method as an input parameter. The method should then prompt the user to guess a letter. If the letter is in the secret word, it should print the corr... | def display_word(secret_word, guessed_letters):
return ''.join([letter if letter in guessed_letters else '_' for letter in secret_word])
def hangman(secret_word):
guessed_letters = set()
wrong_guesses = 0
max_wrong_guesses = 6
gallows = [
' O ',
' | ',
' /| '... | from unittest.mock import patch
from solution import hangman
def test_hangman_win():
word = "test"
guesses = ['t', 'e', 's']
with patch('builtins.input', side_effect=guesses):
assert hangman(word) == True
def test_hangman_lose():
word = "test"
guesses = ['a', 'b', 'c', 'd', 'f', 'g', 'h']
... | [
{
"docstring": null,
"function_declaration": "def display_word(secret_word, guessed_letters):",
"function_name": "display_word",
"parameter_list": "(secret_word, guessed_letters)"
},
{
"docstring": null,
"function_declaration": "def hangman(secret_word):",
"function_name": "hangman",... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def play_hangman(secret_word):\n \"\"\"\n Function to play a simplified version of Hangman game.\n \n Parameters:\n secret_word (str): The word to be guessed.\n \n Ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015472",
"row_id": 15472,
"seed_ids": "['Llama-3.3-70B-Instruct_39562']"
} | 0.528331 | Filter_15472 | I | [
"display_word",
"hangman"
] | 2 | [
[
"hangman",
"display_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6bdc0ba16e797c1c973b214b737b525a70a064f0 | 037652be1bb2ceaea9572a56961082fae5d7cdaa | |||
v1.0 | instruct | Filter | Filter_15494_I | I have two matrices:
```
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
```
I would like to rotate the first matrix by 90 degrees counterclockwise and then add the resulting matrix to the second matrix.
Here is the code I am currently using:
```
def rotate(matrix):
n = len... | import numpy as np
def rotate(matrix):
"""
Rotate the given matrix 90 degrees counterclockwise.
"""
n = len(matrix)
new_matrix = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[n - j - 1][i] = matrix[i][j]
return new_matrix
def add... | import pytest
from solution import rotate, add_matrices, rotate_and_add_matrices
def test_rotate():
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
expected_rotated = [[3, 6, 9], [2, 5, 8], [1, 4, 7]]
assert rotate(matrix) == expected_rotated
def test_add_matrices():
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8,... | [
{
"docstring": "Rotate the given matrix 90 degrees counterclockwise.",
"function_declaration": "def rotate(matrix):",
"function_name": "rotate",
"parameter_list": "(matrix)"
},
{
"docstring": "Return the sum of two matrices.",
"function_declaration": "def add_matrices(matrix1, matrix2):"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef rotate_90_counterclockwise(matrix):\n \"\"\"\n Rotates a given matrix by 90 degrees counterclockwise.\n \"\"\"\n return list(map(list, zip(*matrix)))[::-1... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015494",
"row_id": 15494,
"seed_ids": "['Llama-3.3-70B-Instruct_39604']"
} | 0.442232 | Filter_15494 | I | [
"rotate",
"add_matrices",
"rotate_and_add_matrices",
"rotate_and_add_using_numpy"
] | 4 | [
[
"rotate_and_add_matrices",
"add_matrices"
],
[
"rotate_and_add_matrices",
"rotate"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 14b13309e6fa9e4318c738e54f89b5db85010550 | e5f65d0a77616f32365c7220929b72f60168073e | |||
v1.0 | instruct | Filter | Filter_15506_I | I have a large JSON file that contains a list of objects. I want to iterate through this list and perform some operations on each object. However, I'm facing an issue where the JSON file is too large to fit into memory, and I'm looking for an approach to process the file in chunks.
Can you provide a way to parse a JS... | import json
def process_json_in_chunks(file_path, chunk_size):
"""
Processes a large JSON file in chunks.
Args:
file_path (str): The path to the JSON file.
chunk_size (int): The number of objects to process at a time.
Yields:
list: A list of JSON objects.
"""
with open(fil... | import os
import json
from solution import process_json_in_chunks
def test_process_json_in_chunks():
# Setup: Create a test JSON file.
test_data = [
json.dumps({"id": 1, "value": "a"}),
json.dumps({"id": 2, "value": "b"}),
json.dumps({"id": 3, "value": "c"}),
json.dumps({"id": 4... | [
{
"docstring": "Processes a large JSON file in chunks.\n\nArgs:\nfile_path (str): The path to the JSON file.\nchunk_size (int): The number of objects to process at a time.\n\nYields:\nlist: A list of JSON objects.",
"function_declaration": "def process_json_in_chunks(file_path, chunk_size):",
"function_... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef process_json_in_chunks(file_path, chunk_size):\n \"\"\"\n Processes a large JSON file in chunks.\n \n Args:\n file_path (str): The path to the JSON file.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015506",
"row_id": 15506,
"seed_ids": "['Llama-3.3-70B-Instruct_39627']"
} | 0.546418 | Filter_15506 | I | [
"process_json_in_chunks",
"parse_json_objects"
] | 2 | [
[
"process_json_in_chunks",
"parse_json_objects"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b078d8aa35eb299f120a233187ea3e021aa4e0e7 | 07c179fa49d2fa183c037c0012b228926b111232 | |||
v1.0 | instruct | Filter | Filter_15513_I | Can I have the Python code for a basic CLI calculator that can perform the four basic arithmetic operations? | def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def calculator(operation, a, b):
if operation == 'add':
return add(a, b)
elif operation == 'su... | from solution import add, subtract, multiply, divide, calculator
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(2, 1) == 1
assert subtract(1, 1) == 0
assert subtract(0, 1) == -1
def test_multiply():
assert multiply(2... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015513",
"row_id": 15513,
"seed_ids": "['Llama-3.3-70B-Instruct_39647']"
} | 0.508676 | Filter_15513 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | d9436b5eb9240492f2b5b49e61254180a66e5509 | 75b588c853a4f058770d565729939453784c3ce0 | |||
v1.0 | instruct | Filter | Filter_15519_I | I was trying to write a Python program to find all the prime numbers in a given range, but I stumbled upon a problem when it came to the function that generates prime numbers. I have written the following:
```
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
... | def is_prime(num):
"""
Check if a number is prime.
"""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def find_primes_in_range(start, end):
"""
Finds all prime numbers in a given range [start, end).
... | from solution import is_prime, find_primes_in_range
def test_is_prime():
# Test primes
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
# Test non-primes
assert is_prime(1) == False
assert is_prime(4) == False
assert is_prime(10) == False
def test_find_p... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Finds all prime numbers in a given range [start, end).",
"function_declaration": "def find_primes_in_range(start, end):",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Returns True if num is a prime number, False otherwise.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015519",
"row_id": 15519,
"seed_ids": "['Llama-3.3-70B-Instruct_39659']"
} | 0.650494 | Filter_15519 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a8590d0a24a08136c3cf7a46e01936730a5ec0d | d436c0d9a7b17ef082ef3e5b7b46255533dd52ef | |||
v1.0 | instruct | Filter | Filter_15594_I | I have a problem where I need to use a Python script to move only certain files from one directory to another. Which files to move depends on user input and certain conditions based on file name.
The script will ask the user for the path of the source directory and the destination directory. Then it will ask for the ... | import os
import shutil
def get_path(prompt):
while True:
user_input = input(prompt)
if os.path.exists(user_input):
return user_input
else:
print("Invalid path. Please enter a valid path.")
def get_extension():
while True:
user_input = input("Enter file ... | import os
import shutil
import tempfile
from solution import move_files, get_path, get_extension, get_move_choice
def setup_module(module):
"""
Create a temporary source and destination directory for testing.
"""
global temp_source_dir, temp_dest_dir
temp_source_dir = tempfile.mkdtemp()
temp_de... | [
{
"docstring": null,
"function_declaration": "def get_path(prompt):",
"function_name": "get_path",
"parameter_list": "(prompt)"
},
{
"docstring": null,
"function_declaration": "def get_extension():",
"function_name": "get_extension",
"parameter_list": "()"
},
{
"docstring... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\n\ndef get_path(prompt):\n while True:\n user_input = input(prompt)\n if os.path.exists(user_input):\n return user_input\n else:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015594",
"row_id": 15594,
"seed_ids": "['Llama-3.3-70B-Instruct_39829']"
} | 0.750347 | Filter_15594 | I | [
"get_path",
"get_extension",
"get_move_choice",
"move_files"
] | 4 | [
[
"move_files",
"get_extension"
],
[
"move_files",
"get_move_choice"
],
[
"move_files",
"get_path"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | acbefd90d017e4f5b7631a214c6d61743ab1ab1a | 82de010505b5df49ee52eca05c165e74c90a08c7 | |||
v1.0 | instruct | Filter | Filter_15595_I | I am trying to add functionality to a legacy system that records timestamps for certain events. The timestamp is currently recorded as a string in the format "YYYY-MM-DD HH:MM:SS". I want to update the system to be able to parse these timestamps and perform basic time-related calculations, such as calculating the diffe... | from datetime import datetime
def parse_timestamp(timestamp_str):
"""
Parses a timestamp string in the format 'YYYY-MM-DD HH:MM:SS' to a datetime object.
:param timestamp_str: The timestamp string to parse.
:return: A datetime object representing the parsed timestamp.
"""
return datetime.s... | from solution import parse_timestamp, calculate_time_difference
from datetime import datetime, timedelta
def test_parse_timestamp():
timestamp_str = "2023-10-01 12:34:56"
expected_datetime = datetime(2023, 10, 1, 12, 34, 56)
assert parse_timestamp(timestamp_str) == expected_datetime
def test_calculate_tim... | [
{
"docstring": "Parses a timestamp string in the format 'YYYY-MM-DD HH:MM:SS' to a datetime object.\n\n:param timestamp_str: The timestamp string to parse.\n:return: A datetime object representing the parsed timestamp.",
"function_declaration": "def parse_timestamp(timestamp_str):",
"function_name": "pa... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef parse_timestamp(timestamp):\n \"\"\"\n Parses a timestamp string in the format \"YYYY-MM-DD HH:MM:SS\" to a datetime object.\n \n :param timest... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015595",
"row_id": 15595,
"seed_ids": "['Llama-3.3-70B-Instruct_39831']"
} | 0.622969 | Filter_15595 | I | [
"parse_timestamp",
"calculate_time_difference"
] | 2 | [
[
"calculate_time_difference",
"parse_timestamp"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0cebc18468f4f00ca88f4df9d548fe62b91e8460 | 79e76fc239d37b327c2066534a1dffd025ff8764 | |||
v1.0 | instruct | Filter | Filter_15633_I | My mother is getting a little forgetful and I want to help her remember her grandchildren's birthdays. I have a piece of paper with her grandkids names and birthdays written on it, and she has been misplacing it. To help her, I would like to write a simple Python script that will store the names and birthdays in a file... | import re
# Constants
FILENAME = "birthdays.txt"
def get_all_birthdays(filename):
"""Return a dictionary of all birthdays in the file"""
birthdays = {}
try:
with open(filename, 'r') as file:
for line in file:
name, birthday = line.strip().split('|')
birt... | import os
import pytest
from solution import get_all_birthdays, add_birthday, delete_birthday
FILENAME = "test_birthdays.txt"
def setup_module(module):
with open(FILENAME, 'w') as f:
f.write("Alice|1995-02-12\n")
f.write("Bob|2001-08-25\n")
@pytest.fixture(autouse=True)
def run_before_and_after_t... | [
{
"docstring": "Return a dictionary of all birthdays in the file",
"function_declaration": "def get_all_birthdays(filename):",
"function_name": "get_all_birthdays",
"parameter_list": "(filename)"
},
{
"docstring": "Add a birthday to the file",
"function_declaration": "def add_birthday(fi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\n# Constants\nFILENAME = \"birthdays.txt\"\n\ndef get_all_birthdays(filename):\n \"\"\"Return a dictionary of all birthdays in the file\"\"\"\n birthdays = {}\n try:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015633",
"row_id": 15633,
"seed_ids": "['Llama-3.3-70B-Instruct_39923']"
} | 0.482884 | Filter_15633 | I | [
"get_all_birthdays",
"add_birthday",
"delete_birthday",
"main"
] | 4 | [
[
"delete_birthday",
"get_all_birthdays"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f167e644ecb94f469313cb1d1817f57561442a9 | c07614cc13f54899dbb3449c4d2eed34ae8acee6 | |||
v1.0 | instruct | Filter | Filter_15646_I | I have a 'data' folder containing a list of text files, each with a unique name (e.g. 'file1.txt', 'file2.txt', etc.). The files contain a list of words, one word per line.
I want to write a Python program that will read each file, convert all the words to lowercase, count the frequency of each word across all the fil... | import os
from collections import Counter
def count_words_in_file(file_name):
with open(file_name, 'r') as f:
words = [line.strip().lower() for line in f]
return Counter(words)
def count_words_in_folder(folder_path):
all_word_counts = Counter()
for file_name in os.listdir(folder_path):
... | import os
from solution import count_words_in_file, count_words_in_folder, write_word_counts_to_file
def test_count_words_in_file(tmp_path):
file_path = tmp_path / 'test_file.txt'
file_path.write_text('Word\nword\nAnother\nword\n')
expected = {'word': 3, 'another': 1}
result = count_words_in_file(... | [
{
"docstring": null,
"function_declaration": "def count_words_in_file(file_name):",
"function_name": "count_words_in_file",
"parameter_list": "(file_name)"
},
{
"docstring": null,
"function_declaration": "def count_words_in_folder(folder_path):",
"function_name": "count_words_in_fold... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom collections import Counter\n\ndef count_words_in_file(file_name):\n with open(file_name, 'r') as f:\n words = [line.strip().lower() for line in f]\n return Counter... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015646",
"row_id": 15646,
"seed_ids": "['Llama-3.3-70B-Instruct_39954']"
} | 0.706374 | Filter_15646 | I | [
"count_words_in_file",
"count_words_in_folder",
"write_word_counts_to_file",
"main"
] | 4 | [
[
"count_words_in_folder",
"count_words_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 762f4df19352df93c3fd386c175940288de37ab5 | ebc87906254ec885fe18e28aba395ac0747b1573 | |||
v1.0 | instruct | Filter | Filter_15667_I | ### Functions
```python
def create_timer(start_time, duration):
"""
Creates a timer that starts at a certain time and lasts for a certain duration.
Args:
start_time (int): The time at which the timer starts.
duration (int): The duration of the timer.
Returns:
list: A list of ti... | def create_timer(start_time, duration):
"""
Creates a timer that starts at a certain time and lasts for a certain duration.
Args:
start_time (int): The time at which the timer starts.
duration (int): The duration of the timer.
Returns:
list: A list of timestamps representing th... | from solution import create_reverse_timer_and_add_transactions
def test_create_reverse_timer_and_add_transactions():
# Test with given example
current_time = 10
transactions = [(1, 'buy', 100), (2, 'sell', 50), (3, 'buy', 200)]
reverse_timer, total_transaction_time = create_reverse_timer_and_add_transa... | [
{
"docstring": "Creates a timer that starts at a certain time and lasts for a certain duration.\n\nArgs:\n start_time (int): The time at which the timer starts.\n duration (int): The duration of the timer.\n\nReturns:\n list: A list of timestamps representing the timer.",
"function_declaration": "d... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Assuming the provided functions are already available\n\ndef find_last_transaction_timestamp(transactions):\n \"\"\"\n Finds the last transaction timestamp from a list of transactions.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015667",
"row_id": 15667,
"seed_ids": "['Llama-3.3-70B-Instruct_40004']"
} | 0.596294 | Filter_15667 | I | [
"create_timer",
"add_time_stamps",
"process_transactions",
"create_reverse_timer_and_add_transactions"
] | 4 | [
[
"create_reverse_timer_and_add_transactions",
"add_time_stamps"
],
[
"create_reverse_timer_and_add_transactions",
"create_timer"
],
[
"create_reverse_timer_and_add_transactions",
"process_transactions"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7b4b9a5f7a356c670c43d29e9d98b53304be0035 | 93faee7e13162299aa7ccf1c80f88d03bd24c4ae | |||
v1.0 | instruct | Filter | Filter_15736_I | I'm working on a Hidden Markov Model (HMM) and I want to evaluate its performance on a test set using the Viterbi algorithm. I've implemented the Viterbi algorithm and the HMM, but I'm having trouble understanding how to use them to evaluate the model's performance.
Can you explain how to evaluate the performance of a... | def viterbi(obs, states, start_p, trans_p, emit_p):
"""
Viterbi algorithm to find the most likely sequence of states.
"""
V = [{}]
path = {}
# Initialize the base cases (t == 0)
for y in states:
V[0][y] = start_p[y] * emit_p[y][obs[0]]
path[y] = [y]
# Build the Viterbi ... | def test_viterbi():
hmm_model = (states, start_probability, transition_probability, emission_probability)
obs_seq = ['normal', 'cold', 'dizzy']
predicted_seq = viterbi(obs_seq, states, start_probability, transition_probability, emission_probability)
assert predicted_seq == ['Healthy', 'Healthy', 'Fever'... | [
{
"docstring": "Viterbi algorithm to find the most likely sequence of states.",
"function_declaration": "def viterbi(obs, states, start_p, trans_p, emit_p):",
"function_name": "viterbi",
"parameter_list": "(obs, states, start_p, trans_p, emit_p)"
},
{
"docstring": "Evaluate the HMM model usi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef viterbi_algorithm(observations, states, start_prob, trans_prob, emit_prob):\n \"\"\"\n Viterbi Algorithm to find the most probable sequence of hidden states.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015736",
"row_id": 15736,
"seed_ids": "['Llama-3.3-70B-Instruct_40157']"
} | 0.254318 | Filter_15736 | I | [
"viterbi",
"evaluate_hmm"
] | 2 | [
[
"evaluate_hmm",
"viterbi"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 03bec8795adcc8fbbde30afe435edc18642fe0cb | 22a63083454e4fdd9db70a5aac71fb88ac7ac865 | |||
v1.0 | instruct | Filter | Filter_15741_I | You have a test that checks the functionality of the billing system. This test consists of a positive and negative integer value that are translated into billing cycles. One billing cycle equals 30 days.
Here is the example of the test:
Input: [14, -30]
Output: [1, -1]
Here's how it translates:
- The first number, ... | import math
def translate_to_billing_cycle(days):
"""
Translates days into billing cycles.
:param days: integer representing days
:return: integer representing billing cycles
"""
cycle = days / 30
if days > 0:
return math.ceil(cycle)
elif days < 0:
return math.floor(cycl... | from solution import translate_to_billing_cycle, translate_days_list
def test_translate_to_billing_cycle():
assert translate_to_billing_cycle(14) == 1
assert translate_to_billing_cycle(-30) == -1
assert translate_to_billing_cycle(31) == 2
assert translate_to_billing_cycle(0) == 0
assert translate_t... | [
{
"docstring": "Translates days into billing cycles.\n:param days: integer representing days\n:return: integer representing billing cycles",
"function_declaration": "def translate_to_billing_cycle(days):",
"function_name": "translate_to_billing_cycle",
"parameter_list": "(days)"
},
{
"docstr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef translate_to_billing_cycle(days):\n \"\"\"\n Translates number of days into billing cycles.\n One billing cycle equals 30 days.\n \"\"\"\n cycle = days / 30\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015741",
"row_id": 15741,
"seed_ids": "['Llama-3.3-70B-Instruct_40164']"
} | 0.56724 | Filter_15741 | I | [
"translate_to_billing_cycle",
"translate_days_list"
] | 2 | [
[
"translate_days_list",
"translate_to_billing_cycle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85836963c51a73641c497aae1b676ffea78404bb | ca69c148b629dfd6ea1bd48b5ffde37591d9ce49 | |||
v1.0 | instruct | Filter | Filter_15743_I | I'm trying to create a Python program that can solve Sudoku puzzles. I want to choose a random puzzle from a predefined list, then fill it in according to Sudoku rules. | import random
def solve_sudoku(board):
"""
Solve the given Sudoku puzzle using backtracking algorithm.
"""
empty = find_empty(board)
if not empty:
return True
row, col = empty
for num in range(1, 10):
if is_valid(board, num, row, col):
board[row][col] = num
... | from solution import solve_sudoku, is_valid, get_random_puzzle, find_empty
def test_solve_sudoku():
puzzle = [
[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... | [
{
"docstring": "Solve the given Sudoku puzzle using backtracking algorithm.",
"function_declaration": "def solve_sudoku(board):",
"function_name": "solve_sudoku",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def find_empty(board):",
"function_name": "f... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_valid(board, row, col, num):\n \"\"\"\n Check if num can be placed at board[row][col].\n \"\"\"\n # Check the row\n for i in range(9):\n if board[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015743",
"row_id": 15743,
"seed_ids": "['Llama-3.3-70B-Instruct_40167']"
} | 0.486746 | Filter_15743 | I | [
"solve_sudoku",
"find_empty",
"is_valid",
"get_random_puzzle"
] | 4 | [
[
"solve_sudoku",
"find_empty"
],
[
"solve_sudoku",
"is_valid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7a52e48056311419b54527fbb2d466de362172c1 | 12b50aaf4bdd8e09e9db85d00726c06e86b313f8 | |||
v1.0 | instruct | Filter | Filter_15751_I | I have a 9-digit number and I need to write a function that checks whether the number is a valid ISBN (10 or 13) or not.
Here is what I've got so far:
```python
def is_isbn(number):
if len(number) == 10:
return validate_isbn_10(number)
elif len(number) == 13:
return validate_isbn_13(number)
... | def is_isbn(number):
"""
Checks if the given number is a valid ISBN-10 or ISBN-13.
Parameters:
number (str): The ISBN number to check.
Returns:
bool: True if valid, False otherwise.
"""
if len(number) == 10:
return validate_isbn_10(number)
elif len(number) == 13:
... | def test_is_isbn_10_valid():
assert is_isbn("0306406152") == True # Correct ISBN-10
def test_is_isbn_10_invalid():
assert is_isbn("0306406153") == False # Incorrect ISBN-10
def test_is_isbn_13_valid():
assert is_isbn("9780306406157") == True # Correct ISBN-13
def test_is_isbn_13_invalid():
asser... | [
{
"docstring": "Checks if the given number is a valid ISBN-10 or ISBN-13.\n\nParameters:\nnumber (str): The ISBN number to check.\n\nReturns:\nbool: True if valid, False otherwise.",
"function_declaration": "def is_isbn(number):",
"function_name": "is_isbn",
"parameter_list": "(number)"
},
{
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_isbn(number):\n if len(number) == 10:\n return validate_isbn_10(number)\n elif len(number) == 13:\n return validate_isbn_13(number)\n else:\n return False\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015751",
"row_id": 15751,
"seed_ids": "['Llama-3.3-70B-Instruct_40186']"
} | 0.545247 | Filter_15751 | I | [
"is_isbn",
"validate_isbn_10",
"validate_isbn_13"
] | 3 | [
[
"is_isbn",
"validate_isbn_10"
],
[
"is_isbn",
"validate_isbn_13"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | fa7875c7b3cef988033c3af43d7af2d1be340bfa | 1641487d74a6bb1e18e524c8a5c9861df0d853f6 | |||
v1.0 | instruct | Filter | Filter_15754_I | I have a board game where I need to roll a dice, and the result needs to be multiplied by 2. I want to develop a code that simulates this dice roll and the result multiplication.
Can you help me write a Python code for this?
If yes, what are the code steps?
1. Define the function for simulating the dice roll
2. W... | import random
def roll_dice():
"""
Simulates rolling a dice and returns a number between 1 and 6.
"""
return random.randint(1, 6)
def multiply_by_2(n):
"""
Multiplies the given number by 2.
"""
return n * 2
def roll_and_multiply():
"""
Rolls a dice and multiplies the result by... | from solution import roll_dice, multiply_by_2, roll_and_multiply
def test_roll_dice():
result = roll_dice()
assert 1 <= result <= 6, "Dice roll should be between 1 and 6"
def test_multiply_by_2():
assert multiply_by_2(1) == 2
assert multiply_by_2(6) == 12
assert multiply_by_2(-3) == -6
def test_r... | [
{
"docstring": "Simulates rolling a dice and returns a number between 1 and 6.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Multiplies the given number by 2.",
"function_declaration": "def multiply_by_2(n):",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided dice and returns the result.\n \"\"\"\n return random.randint(1, 6)\n\ndef multiply_by_2(number):\n \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015754",
"row_id": 15754,
"seed_ids": "['Llama-3.3-70B-Instruct_40193']"
} | 0.532721 | Filter_15754 | I | [
"roll_dice",
"multiply_by_2",
"roll_and_multiply"
] | 3 | [
[
"roll_and_multiply",
"multiply_by_2"
],
[
"roll_and_multiply",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1e4d73667a0ea185241b12c78b0f9a043ba8ed6a | 6cb51eb37ce2194818a122842dd62acdcf270b7b | |||
v1.0 | instruct | Filter | Filter_15789_I | Here's a new piece of code for you to work with:
```python
import numpy as np
import pandas as pd
def calculate_new_position(row, velocity):
new_position = np.array([row['x'], row['y']])
new_position += np.array(velocity)
return pd.Series(new_position, index=['x', 'y'])
def run_simulation(particles, veloc... | import numpy as np
import pandas as pd
def calculate_new_position(row, velocity):
"""
Given a row with 'x' and 'y' coordinates, and a velocity vector,
compute the new position by adding the velocity to the current position.
"""
new_position = np.array([row['x'], row['y']])
new_position += np.ar... | import pytest
import numpy as np
import pandas as pd
from solution import calculate_new_position, run_simulation
def test_calculate_new_position():
row = pd.Series({'x': 2, 'y': 3})
velocity = [1, -1]
result = calculate_new_position(row, velocity)
assert result['x'] == 3
assert result['y'] == 2
de... | [
{
"docstring": "Given a row with 'x' and 'y' coordinates, and a velocity vector,\ncompute the new position by adding the velocity to the current position.",
"function_declaration": "def calculate_new_position(row, velocity):",
"function_name": "calculate_new_position",
"parameter_list": "(row, veloc... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\n\ndef calculate_new_position(row, velocity):\n new_position = np.array([row['x'], row['y']])\n new_position += np.array(velocity)\n return pd.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015789",
"row_id": 15789,
"seed_ids": "['Llama-3.3-70B-Instruct_40264']"
} | 0.453986 | Filter_15789 | I | [
"calculate_new_position",
"run_simulation"
] | 2 | [
[
"run_simulation",
"calculate_new_position"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 0fb9f74e1aa141c066a2850e15089bbc08f6849a | ef8d998c47f2cb018ab2456b7730a7fd1fe4dbdc | |||
v1.0 | instruct | Filter | Filter_15801_I | I was tasked to create a Python program to compare the execution time of different sorting algorithms.
Here is my code:
```python
import random
import time
from typing import List
import matplotlib.pyplot as plt
def bubble_sort(lst: List[int]) -> List[int]:
n = len(lst)
for i in range(n):
for j in ... | import random
import time
from typing import List
import matplotlib.pyplot as plt
def bubble_sort(lst: List[int]) -> List[int]:
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
def merge_sort(... | from solution import bubble_sort, merge_sort, quick_sort, insertion_sort, selection_sort
def test_bubble_sort():
assert bubble_sort([3, 2, 1]) == [1, 2, 3]
assert bubble_sort([]) == []
assert bubble_sort([1]) == [1]
assert bubble_sort([2, 3, 1]) == [1, 2, 3]
def test_merge_sort():
assert merge_sor... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(lst):",
"function_name": "bubble_sort",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(lst):",
"function_name": "merge_sort",
"parameter_list": "(lst)"
},
{
"docstring... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport time\nfrom typing import List\nimport matplotlib.pyplot as plt\n\ndef bubble_sort(lst: List[int]) -> List[int]:\n n = len(lst)\n for i in range(n):\n for j i... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015801",
"row_id": 15801,
"seed_ids": "['Llama-3.3-70B-Instruct_40303']"
} | 0.506823 | Filter_15801 | I | [
"bubble_sort",
"merge_sort",
"merge",
"quick_sort",
"insertion_sort",
"selection_sort",
"measure_sorting_times"
] | 7 | [
[
"measure_sorting_times",
"bubble_sort"
],
[
"measure_sorting_times",
"insertion_sort"
],
[
"measure_sorting_times",
"merge_sort"
],
[
"measure_sorting_times",
"quick_sort"
],
[
"measure_sorting_times",
"selection_sort"
],
[
"merge_sort",
"merge"
... | 6 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | 9f93c9d7f19e31d056b89c83efc51189ee8f27c7 | fcc947bb30346754c0e1e4197d734071a6bb3ee9 | |||
v1.0 | instruct | Filter | Filter_15812_I | I've been trying to implement merge sort, but I need some help understanding some specific parts of it.
Here's my attempt at implementing merge sort in Python:
```
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
left_half... | def merge_sort(arr):
"""
Perform merge sort on a list of elements.
Parameters:
arr (list): List of elements to be sorted.
Returns:
list: Sorted list of elements.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid... | 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]) == [1, 2, 3]
def test_merge_sort_reverse_sorted_list():
assert merge_sort(... | [
{
"docstring": "Perform merge sort on a list of elements.\n\nParameters:\narr (list): List of elements to be sorted.\n\nReturns:\nlist: Sorted list of elements.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n\n left_half = merge_sort(left_half)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015812",
"row_id": 15812,
"seed_ids": "['Llama-3.3-70B-Instruct_40328']"
} | 0.563826 | Filter_15812 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 94521859f1f77f07c18e3724d050a0b4454cacff | 45bb5b028abebb315ecb351a6e180a55889db206 | |||
v1.0 | instruct | Filter | Filter_15834_I | I have a function that is trying to calculate the number of ways to arrange a set of items into groups of a specified size. The items are distinct, and the order of the groups does matter.
I've tried to implement this using recursion, but I keep getting errors when the input size is large. I think it may have an issue... | from math import comb
def calculate_arrangements(n, k):
"""
Calculates the number of ways to arrange n distinct items into groups of size k.
"""
if n < k or k < 1:
return 0
return comb(n, k) * factorial(k)
def factorial(n):
"""
Computes the factorial of n.
"""
result = 1
... | from solution import calculate_arrangements
def test_basic_combinations():
assert calculate_arrangements(5, 3) == 60 # 5 choose 3 * 3!
def test_infeasible_combinations():
assert calculate_arrangements(3, 5) == 0 # Can't choose more than you have
assert calculate_arrangements(5, 0) == 0 # Group size can... | [
{
"docstring": "Calculates the number of ways to arrange n distinct items into groups of size k.",
"function_declaration": "def calculate_arrangements(n, k):",
"function_name": "calculate_arrangements",
"parameter_list": "(n, k)"
},
{
"docstring": "Computes the factorial of n.",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import factorial\n\ndef count_arrangements(n, k):\n \"\"\"\n Calculate the number of ways to arrange `n` distinct items into groups of size `k`.\n This is equivalent to calc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015834",
"row_id": 15834,
"seed_ids": "['Llama-3.3-70B-Instruct_40371']"
} | 0.536162 | Filter_15834 | I | [
"calculate_arrangements",
"factorial"
] | 2 | [
[
"calculate_arrangements",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0dae337c93efaf79aabcab5f81e13e0f4ee0984b | 4ad35f4efa0541a5a556ae813e6c7930e5cab22d | |||
v1.0 | instruct | Filter | Filter_15869_I | Here is the code to solve a Queens problem using backtracking:
```python
def solve_n_queens(n):
def is_valid(board, row, col):
for i in range(row):
if board[i] == col or board[i] - i == col - row or board[i] + i == col + row:
return False
return True
def solve(board,... | def solve_n_queens(n):
def is_valid(board, row, col):
for i in range(row):
if board[i] == col or board[i] - i == col - row or board[i] + i == col + row:
return False
return True
def solve(board, row):
if row == n:
return [board[:]]
solutio... | from solution import solve_n_queens
def test_solve_n_queens_4():
expected_solutions = [
[".Q..", # Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", # Solution 2
"Q...",
"...Q",
".Q.."]
]
assert solve_n_queens(4) == expected_soluti... | [
{
"docstring": null,
"function_declaration": "def solve_n_queens(n):",
"function_name": "solve_n_queens",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def format_solutions(solutions, n):",
"function_name": "format_solutions",
"parameter_list": "(soluti... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def solve_n_queens(n):\n def is_valid(board, row, col):\n \"\"\"\n Check if a queen can be placed at board[row][col].\n \"\"\"\n for i in range(row):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00015869",
"row_id": 15869,
"seed_ids": "['Llama-3.3-70B-Instruct_40453']"
} | 0.474307 | Filter_15869 | I | [
"solve_n_queens",
"format_solutions"
] | 2 | [
[
"solve_n_queens",
"format_solutions"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | afa64942bb8a0862a643c3ce1a1e826afe78c80b | aafabac0975513dfcc0bd8a552eaa12ab9e458f0 | |||
v1.0 | instruct | Filter | Filter_15895_I | In this problem, we will create a simple Vigenère cipher that can encrypt and decrypt messages using a keyword. The Vigenère cipher is a polyalphabetic substitution cipher that uses a keyword to determine the substitution for each letter. Here is a detailed explanation of how the Vigenère cipher works, along with a sam... | def generate_table():
table = []
for i in range(26):
row = []
for j in range(26):
row.append(chr(((i + j) % 26) + ord('A')))
table.append(row)
return table
def encrypt(message, keyword):
table = generate_table()
encrypted_message = ""
keyword_index = 0
fo... | from solution import encrypt, decrypt
def test_encrypt_with_keyword():
assert encrypt("ATTACKATDAWN", "LEMON") == "LXFOPVEFRNHR"
def test_encrypt_with_non_alpha():
assert encrypt("HELLO, WORLD!", "KEY") == "RIJVS, UYVJN!"
def test_encrypt_with_lowercase():
assert encrypt("hello", "key") == "RIJVS"
def t... | [
{
"docstring": null,
"function_declaration": "def generate_table():",
"function_name": "generate_table",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def encrypt(message, keyword):",
"function_name": "encrypt",
"parameter_list": "(message, keyword)"
}... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_table():\n table = []\n for i in range(26):\n row = []\n for j in range(26):\n row.append(chr(((i + j) % 26) + ord('A')))\n table.append(row)... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015895",
"row_id": 15895,
"seed_ids": "['Llama-3.3-70B-Instruct_40521']"
} | 0.598683 | Filter_15895 | I | [
"generate_table",
"encrypt",
"decrypt"
] | 3 | [
[
"decrypt",
"generate_table"
],
[
"encrypt",
"generate_table"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cdb20a90c1b6b4b0259b0a7f76f5bf5d949e1f72 | 75bc122ddd830e006491ca6fb604f37bf58ad003 | |||
v1.0 | instruct | Filter | Filter_15897_I | I'm trying to generate random uppercase English letters at the specified rate of 10 letters per second.
I can generate random uppercase English letters in sequence but they are generated at a fixed rate without pause.
Any ideas on how to generate the letters with a random pause of about 10 letters per second average... | import random
import string
import time
def generate_random_letter():
"""
Generates a random uppercase English letter.
"""
return random.choice(string.ascii_uppercase)
def letters_with_rate(rate):
"""
Yields random uppercase English letters at the specified rate (letters per second).
"""
... | import time
from solution import generate_random_letter, letters_with_rate
def test_generate_random_letter():
letter = generate_random_letter()
assert letter in string.ascii_uppercase
assert len(letter) == 1
def test_letters_with_rate():
rate = 10 # 10 letters per second
generator = letters_with_... | [
{
"docstring": "Generates a random uppercase English letter.",
"function_declaration": "def generate_random_letter():",
"function_name": "generate_random_letter",
"parameter_list": "()"
},
{
"docstring": "Yields random uppercase English letters at the specified rate (letters per second).",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\nimport time\n\ndef generate_random_uppercase_letters(rate=10, duration=1):\n \"\"\"\n Generates random uppercase English letters at an average rate of 'rate... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015897",
"row_id": 15897,
"seed_ids": "['Llama-3.3-70B-Instruct_40526']"
} | 0.536766 | Filter_15897 | I | [
"generate_random_letter",
"letters_with_rate"
] | 2 | [
[
"letters_with_rate",
"generate_random_letter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f7acc687160c44a56690856a0aab84b37dee7ec1 | 175247a75e98a6a0533cc7ac880aa3cf600237c0 | |||
v1.0 | instruct | Filter | Filter_15926_I | I have a binary tree where each node may or may not have a parent method. The node class is defined as follows.
```python
from typing import Any, Optional
class Node:
def __init__(self, key: Any, value: Any, parent: Optional['Node'] = None):
self.key = key
self.value = value
self.left: Op... | class Node:
def __init__(self, key, value, parent=None):
self.key = key
self.value = value
self.left = None
self.right = None
self.parent = parent
def find_path_to_root(node):
path = []
while node:
path.append(node)
node = node.parent
return path
... | def test_lowest_common_ancestor():
root = Node('root', 1)
left = Node('left', 2, root)
right = Node('right', 3, root)
root.left = left
root.right = right
left_left = Node('left_left', 4, left)
left.right = Node('left_right', 5, left)
left.left = left_left
right_left = Node(... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_path_to_root(node):\n \"\"\"\n Helper function to find path from a node to the root.\n \"\"\"\n path = []\n while node:\n path.append(node)\n node = node.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015926",
"row_id": 15926,
"seed_ids": "['Llama-3.3-70B-Instruct_40590']"
} | 0.412629 | Filter_15926 | I | [
"find_path_to_root",
"lowest_common_ancestor"
] | 2 | [
[
"lowest_common_ancestor",
"find_path_to_root"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | false | [] | true | be8bea7f8b73d62a12b121850ac9a2cd2416b38a | a96e39b038d3fe92afb54f4d083cd2fbdf3a77bd | |||
v1.0 | instruct | Filter | Filter_15939_I | I'm new to programming, I'm trying to create a simple command-line calculator in Python. I need some help with the logic of the calculator.
I have the following code:
```python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:... | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: Division by zero is not allowed"
else:
return x / y
def calculator():
while True:
print("Select operation:")
print("1.Add"... | def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(2, 1) == 1
assert subtract(-1, -1) == 0
assert subtract(0, 1) == -1
def test_multiply():
assert multiply(2, 3) == 6
assert multiply(-1, 1) == -1
assert multiply(0... | [
{
"docstring": null,
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def subtract(x, y):",
"function_name": "subtract",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"fu... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef multiply(x, y):\n return x * y\n\ndef divide(x, y):\n if y == 0:\n return \"Error: Division by zer... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00015939",
"row_id": 15939,
"seed_ids": "['Llama-3.3-70B-Instruct_40619']"
} | 0.543152 | Filter_15939 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 79f0d37c018d8a3f79c0eddd0a582a6cfbfcbe14 | 340d1fdb306e9a45869e6d7467e9940c958eaf3f | |||
v1.0 | instruct | Filter | Filter_15956_I | In this exercise, we will write a Python script to encrypt and decrypt data using the Caesar Cipher encryption technique. The Caesar Cipher is a type of substitution cipher in which each character in the plaintext is 'shifted' a certain number of places down the alphabet. | def caesar_encrypt(plaintext, shift):
"""
Encrypts the given plaintext using the Caesar Cipher with the specified shift.
Parameters:
plaintext (str): The text to be encrypted.
shift (int): The number of positions to shift each character.
Returns:
str: The encrypted text.
"""
... | from solution import caesar_encrypt, caesar_decrypt
def test_encrypt_basic():
assert caesar_encrypt("ABC", 1) == "BCD"
assert caesar_encrypt("abc", 1) == "bcd"
def test_encrypt_with_wrapping():
assert caesar_encrypt("XYZ", 3) == "ABC"
assert caesar_encrypt("xyz", 3) == "abc"
def test_encrypt_with_non... | [
{
"docstring": "Encrypts the given plaintext using the Caesar Cipher with the specified shift.\n\nParameters:\nplaintext (str): The text to be encrypted.\nshift (int): The number of positions to shift each character.\n\nReturns:\nstr: The encrypted text.",
"function_declaration": "def caesar_encrypt(plainte... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_encrypt(plaintext, shift):\n \"\"\"\n Encrypts the plaintext using the Caesar Cipher technique with a given shift.\n \n Parameters:\n plaintext (str): The text to be ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015956",
"row_id": 15956,
"seed_ids": "['Llama-3.3-70B-Instruct_40661']"
} | 0.634148 | Filter_15956 | I | [
"caesar_encrypt",
"caesar_decrypt"
] | 2 | [
[
"caesar_decrypt",
"caesar_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 404dcb69be1a76d28d164f7e3fc0555d53efcbf6 | c898c1d4fdfa0e97777ff5785bcb5823b04eb856 | |||
v1.0 | instruct | Filter | Filter_15962_I | Can you walk me through the process of creating a pathfinding algorithm in Python, specifically using the A* algorithm? | import heapq
def heuristic(a, b):
"""
Calculate the Manhattan distance between points a and b.
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star(start, goal, neighbors_fn):
"""
Implements the A* algorithm.
:param start: The start node (tuple of coordinates).
:param goal: T... | from solution import a_star, heuristic
def test_heuristic():
assert heuristic((0, 0), (1, 1)) == 2
assert heuristic((1, 2), (4, 6)) == 7
def test_reconstruct_path():
came_from = {
(1, 1): (0, 0),
(2, 2): (1, 1)
}
assert reconstruct_path(came_from, (2, 2)) == [(0, 0), (1, 1), (2, 2)... | [
{
"docstring": "Calculate the Manhattan distance between points a and b.",
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": "Implements the A* algorithm.\n\n:param start: The start node (tuple of coordinates).\n:param ... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "from queue import PriorityQueue\n\ndef heuristic(a, b):\n \"\"\"\n Heuristic function used by A* algorithm.\n This implementation uses the Manhattan distance ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00015962",
"row_id": 15962,
"seed_ids": "['Llama-3.3-70B-Instruct_40672']"
} | 0.405431 | Filter_15962 | I | [
"heuristic",
"a_star",
"reconstruct_path"
] | 3 | [
[
"a_star",
"heuristic"
],
[
"a_star",
"reconstruct_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 01607c8f598dc0b757104737faee4bd6018e7d81 | da340024ddb5f0e224734c952f24eaba4fe07e51 | |||
v1.0 | instruct | Filter | Filter_16031_I | Here's my code to find the shortest odd prime in a list of integers:
```python
def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def find_shortest_odd_prime(nums):
"""Find... | def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def find_shortest_odd_prime(nums):
"""Find the shortest odd prime in a list of integers."""
primes = [n for n in nums... | from solution import is_prime, find_shortest_odd_prime
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
assert is_prime(-5) == False
def test_find_short... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the shortest odd prime in a list of integers.",
"function_declaration": "def find_shortest_odd_prime(nums):",
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016031",
"row_id": 16031,
"seed_ids": "['Llama-3.3-70B-Instruct_40827']"
} | 0.63888 | Filter_16031 | I | [
"is_prime",
"find_shortest_odd_prime"
] | 2 | [
[
"find_shortest_odd_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c704c6f84a8dbd0903212fb9526b0d9ec8bb3f4 | f5cf9ae15c50b3ed384f4744f0a5f666f7bb4584 | |||
v1.0 | instruct | Filter | Filter_16032_I | I'll need a script to simulate the behavior of a action that helps mitigate the spread of COVID-19. The action is wearing a mask.
Here is an example input data:
```json
{
"number_of_people": 10,
"infection_rate": 0.1,
"recovery_rate": 0.05,
"mask_wearing_percentage": 0.7,
"days": 30
}
```
Here is a descr... | import json
import numpy as np
from scipy.integrate import odeint
def validate_input(data):
if not isinstance(data["number_of_people"], (int, float)) or data["number_of_people"] <= 0:
raise ValueError("number_of_people must be a positive number.")
if not 0 <= data["infection_rate"] <= 1:
raise ... | import pytest
import json
from solution import validate_input, simulate
def test_validate_input_valid():
data = {
"number_of_people": 10,
"infection_rate": 0.1,
"recovery_rate": 0.05,
"mask_wearing_percentage": 0.7,
"days": 30
}
try:
validate_input(data)
... | [
{
"docstring": null,
"function_declaration": "def validate_input(data):",
"function_name": "validate_input",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def sir_model(state, t, beta_masked, beta_non_masked, gamma, N, mask_percentage):",
"function_name"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport numpy as np\nfrom scipy.integrate import odeint\n\ndef sir_model(state, t, beta_no_mask, beta_mask, gamma, N, mask_wearing_percentage):\n S, I, R = state\n dSdt = -((... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016032",
"row_id": 16032,
"seed_ids": "['Llama-3.3-70B-Instruct_40828']"
} | 0.461241 | Filter_16032 | I | [
"validate_input",
"sir_model",
"simulate"
] | 3 | [
[
"simulate",
"sir_model"
],
[
"simulate",
"validate_input"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 3a5f290ae4794c05601dbdab5a82888de1014d2f | a09b6a22c7db3f69d3e08d6445c7fd124b73dce9 | |||
v1.0 | instruct | Filter | Filter_16041_I | I'll provide you with a dataset of graphs. The task is to provide a function that calculates the shortest path between two nodes in a graph using the A (A-star) algorithm. | import heapq
def heuristic(a, b):
"""
Returns the heuristic cost estimate to reach node b from node a.
For simplicity, this implementation assumes the heuristics always returns 1 if a != b
"""
return 1
def a_star(graph, start, goal):
"""
Implements the A* algorithm to find the shortes... | from solution import a_star
def test_a_star_simple():
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1},
}
assert a_star(graph, 'A', 'D') == ['A', 'B', 'C', 'D']
def test_a_star_no_path():
graph = {
... | [
{
"docstring": "Returns the heuristic cost estimate to reach node b from node a.\n\nFor simplicity, this implementation assumes the heuristics always returns 1 if a != b",
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from heapq import heappop, heappush\n\ndef a_star(graph, start, goal, heuristic):\n \"\"\"\n A* algorithm to find the shortest path in a graph.\n \n Parameters:\n - graph: dict,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016041",
"row_id": 16041,
"seed_ids": "['Llama-3.3-70B-Instruct_40847']"
} | 0.493095 | Filter_16041 | I | [
"heuristic",
"a_star",
"reconstruct_path"
] | 3 | [
[
"a_star",
"heuristic"
],
[
"a_star",
"reconstruct_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b7fccbb75fda69d9aff076e8f7916f7063aee373 | 069db0b20487b45db2aa50f63a8497543eecc241 | |||
v1.0 | instruct | Filter | Filter_16071_I | Here are the instructions for a recent homework assignment in a freshman-level computer science course:
In this assignment, you will create a Python program to simulate an online store. The store sells books. The online store has three different types of customers: 'A', 'S', and 'P'. Customers of type 'A' get 10% disc... | def read_pricelist(filename='pricelist.txt'):
price_dict = {}
with open(filename, 'r') as file:
for line in file:
book, price = line.strip().split(',')
price_dict[book] = float(price)
return price_dict
def calculate_discounted_price(price, customer_type):
discounts = {'A... | from solution import read_pricelist, calculate_discounted_price, add_to_cart, view_cart
def test_read_pricelist(tmpdir):
pricelist = tmpdir.join('pricelist.txt')
pricelist.write("The Hunger Games,9.99\nTo Kill a Mockingbird,10.99\nPride and Prejudice,12.99\nThe Great Gatsby,8.99")
price_dict = read_priceli... | [
{
"docstring": null,
"function_declaration": "def read_pricelist(filename='pricelist.txt'):",
"function_name": "read_pricelist",
"parameter_list": "(filename='pricelist.txt')"
},
{
"docstring": null,
"function_declaration": "def calculate_discounted_price(price, customer_type):",
"fu... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_pricelist(filename):\n pricelist = {}\n with open(filename, 'r') as file:\n for line in file:\n title, price = line.strip().split(',')\n pricelist[t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00016071",
"row_id": 16071,
"seed_ids": "['Llama-3.3-70B-Instruct_40918']"
} | 0.57434 | Filter_16071 | I | [
"read_pricelist",
"calculate_discounted_price",
"add_to_cart",
"view_cart",
"main"
] | 5 | [
[
"add_to_cart",
"calculate_discounted_price"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79cd249cbdf08b395d9672838f4c001eeeaf6c3e | ae8faf9ac56906ad10c0f684bf7925ac08d15785 | |||
v1.0 | instruct | Filter | Filter_16087_I | Solution Strategy
====================
To solve this problem, we will use the divide and conquer approach.
## Step 1: Divide
We will divide the problem into smaller sub-problems. Each sub-problem will represent a smaller instance of the same problem.
## Step 2: Conquer
We will solve each sub-problem using a similar a... | def merge_sort(arr):
"""
Sorts an array using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
# Divide
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# Conquer
left_sorted = merge_sort(left_half)
right_sorted = merge_sort(right_h... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([5]) == [5]
def test_merge_sort_two_elements():
assert merge_sort([5, 2]) == [2, 5]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) =... | [
{
"docstring": "Sorts an array using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array.",
"function_declaration": "def merge(left, right):"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_max(arr):\n \"\"\"\n Finds the maximum element in the list using divide and conquer approach.\n \"\"\"\n # Base case: if the array has only one element\n if len(arr) ==... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00016087",
"row_id": 16087,
"seed_ids": "['Llama-3.3-70B-Instruct_40952']"
} | 0.481496 | Filter_16087 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 066f60e1b266f7cae09cb89beca8d634df0b885e | 40a9a5faf9dc29cac54d7060564a911ca15d77eb | |||
v1.0 | instruct | Filter | Filter_16091_I | I have many (over 10,000) XML files and would like to automate the task of extracting some specific XML elements. I suggest writing a Python program that does this.
Here are the elements I would like to extract:
* `third_party_code` which is the text inside the `third_party_code` XML element.
* `third_party_name` wh... | import os
import xml.etree.ElementTree as ET
def extract_elements_from_xml(file_path):
tree = ET.parse(file_path)
root = tree.getroot()
third_party_code = root.find('third_party_code').text if root.find('third_party_code') is not None else None
third_party_name = root.find('third_party_name').text if ... | import os
import tempfile
from solution import extract_elements_from_xml, extract_elements_from_directory
def create_temp_xml_file(content, dir_path):
fd, temp_path = tempfile.mkstemp(suffix=".xml", dir=dir_path)
with os.fdopen(fd, 'w') as tmp:
tmp.write(content)
return temp_path
def test_extract_... | [
{
"docstring": null,
"function_declaration": "def extract_elements_from_xml(file_path):",
"function_name": "extract_elements_from_xml",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def extract_elements_from_directory(directory_path):",
"function_na... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport xml.etree.ElementTree as ET\n\ndef extract_xml_elements(file_path):\n \"\"\"\n Extracts the 'third_party_code', 'third_party_name' elements text and the 'employee_id' a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016091",
"row_id": 16091,
"seed_ids": "['Llama-3.3-70B-Instruct_40958']"
} | 0.583685 | Filter_16091 | I | [
"extract_elements_from_xml",
"extract_elements_from_directory"
] | 2 | [
[
"extract_elements_from_directory",
"extract_elements_from_xml"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f5ad7da8eaf571cd633840cd02966ba4b90df476 | dc3486fee72333e0f752b98359b5b2c11262c88d | |||
v1.0 | instruct | Filter | Filter_16120_I | I am trying to create a Python program that can calculate the gcd of two integers using the Euclidean algorithm. Here is my code so far:
```python
def gcd(a, b):
r = b % a
if r == 0:
return a
elif a > b:
return gcd(b, a)
else:
return gcd(a, r)
```
I'm not sure why this code doe... | def gcd(a, b):
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def gcd_list(numbers):
"""
Calculate the gcd of a list of numbers.
"""
from functools import reduce
return reduce(gcd, numbers)
# Testi... | from solution import gcd, gcd_list
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(101, 103) == 1
assert gcd(54, 24) == 6
assert gcd(35, 10) == 5
def test_gcd_list():
assert gcd_list([6, 10, 15, 24, 30, 36, 42]) == 1
assert gcd_list([21, 28, 35, 42]) == 7
assert gcd_list([12, 15, 18]) =... | [
{
"docstring": "Returns the greatest common divisor of a and b using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the gcd of a list of numbers.",
"function_declaration": "def gcd_list(... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Calculate the gcd of two integers using the Euclidean algorithm.\n \"\"\"\n while b != 0:\n a, b = b, a % b\n return a\n\ndef find_gcd_of_list(n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016120",
"row_id": 16120,
"seed_ids": "['Llama-3.3-70B-Instruct_41037']"
} | 0.829931 | Filter_16120 | I | [
"gcd",
"gcd_list"
] | 2 | [
[
"gcd_list",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7fbda22bb8f31d47f87156315409d3b06d454c94 | 729ccabd7c52bd3f582240c77a13b0430672d269 | |||
v1.0 | instruct | Filter | Filter_16133_I | Please create a scoring program for a quiz that includes three types of questions: multiple-choice questions, fill-in-the-blank questions, and true/false questions.
The program should contain the following features:
1. The program should ask each type of question in the quiz.
2. The quiz will have at least 3 questi... | def ask_multiple_choice(question, options, correct_answer):
print(question)
for idx, option in enumerate(options, start=1):
print(f"{idx}. {option}")
answer = input("Please select the correct option (1-4): ")
if options[int(answer) - 1].lower() == correct_answer.lower():
print("Correct!\... | import pytest
from unittest.mock import patch
from solution import ask_multiple_choice, ask_fill_in_blank, ask_true_false
def test_ask_multiple_choice():
with patch('builtins.input', return_value='3'):
assert ask_multiple_choice("What is the capital of France?", ["Berlin", "London", "Paris", "Madrid"], "P... | [
{
"docstring": null,
"function_declaration": "def ask_multiple_choice(question, options, correct_answer):",
"function_name": "ask_multiple_choice",
"parameter_list": "(question, options, correct_answer)"
},
{
"docstring": null,
"function_declaration": "def ask_fill_in_blank(question, cor... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Quiz:\n def __init__(self):\n self.score = 0\n self.questions = [\n (\"multiple_choice\", \"What is the capital of France?\", [\"A. Paris\", \"B. London\", \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016133",
"row_id": 16133,
"seed_ids": "['Llama-3.3-70B-Instruct_41066']"
} | 0.478831 | Filter_16133 | I | [
"ask_multiple_choice",
"ask_fill_in_blank",
"ask_true_false",
"run_quiz"
] | 4 | [
[
"run_quiz",
"ask_fill_in_blank"
],
[
"run_quiz",
"ask_multiple_choice"
],
[
"run_quiz",
"ask_true_false"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 653685d0c0d7aabd53f1a9d0f9b8cac8ae201278 | 59c68342cf0643c7595a0455878c6cf2ff1ba9bc | |||
v1.0 | instruct | Filter | Filter_16143_I | I'm trying to create a python script that can be used to monitor the RAM usage of my system and send a notification to my email when it crosses a certain threshold. | import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def check_ram_usage(threshold):
"""
Checks the system's RAM usage and returns True if it exceeds the given threshold.
"""
memory_info = psutil.virtual_memory()
usage_percent = memory_inf... | from unittest.mock import patch
import pytest
from solution import check_ram_usage, send_notification_email
@patch('psutil.virtual_memory')
def test_check_ram_usage_above_threshold(mock_virtual_memory):
mock_virtual_memory.return_value.percent = 85
assert check_ram_usage(80) == True
@patch('psutil.virtual_mem... | [
{
"docstring": "Checks the system's RAM usage and returns True if it exceeds the given threshold.",
"function_declaration": "def check_ram_usage(threshold):",
"function_name": "check_ram_usage",
"parameter_list": "(threshold)"
},
{
"docstring": "Sends an email notification if the RAM usage e... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import psutil\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_ram_usage(threshold):\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016143",
"row_id": 16143,
"seed_ids": "['Llama-3.3-70B-Instruct_41095']"
} | 0.61632 | Filter_16143 | I | [
"check_ram_usage",
"send_notification_email"
] | 2 | [
[
"send_notification_email",
"check_ram_usage"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | ebd463916349c469671d4aa5464fb4516556b266 | 7dd0a316c1a96373007988e7948bfe70a4528b79 | |||
v1.0 | instruct | Filter | Filter_16155_I | I have a binary search tree (BST) with the following structure:
```
4
/ \
2 6
/ \ \
1 3 7
```
I want to implement a recursive function that checks if the BST is balanced for each node. A balanced BST is defined as a BST where the height of the left subtree and the height of the right subtree of every ... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_balanced(node):
if node is None:
return True
left_height = get_height(node.left)
right_height = get_height(node.right)
return abs(left_height - right_height) <= 1 an... | import pytest
from solution import Node, is_balanced
def test_empty_tree():
assert is_balanced(None) == True
def test_single_node():
root = Node(1)
assert is_balanced(root) == True
def test_balanced_tree():
root = Node(4)
root.left = Node(2)
root.right = Node(6)
root.left.left = Node(1)
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef is_balanced(node):\n if node is None:\n return Tru... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016155",
"row_id": 16155,
"seed_ids": "['Llama-3.3-70B-Instruct_41137']"
} | 0.707756 | Filter_16155 | I | [
"is_balanced",
"get_height"
] | 2 | [
[
"is_balanced",
"get_height"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 261dce18cfc79b8dd352c0bdc341c41589494b4d | 34eb3fd991349f42267234e03b84b691312d36d1 | |||
v1.0 | instruct | Filter | Filter_16170_I | You have been tasked with creating a simple program that can take a directory path and a search term as input and return a list of files that contain the search term.
The program should search through all the files in the directory and its subdirectories.
Here's a sample implementation:
```python
import os
def find_... | import os
def is_text_file(file_path):
"""
Checks if a file is a text file.
"""
try:
with open(file_path, 'rb') as f:
chunk = f.read(1024)
if b'\0' in chunk:
return False
return True
except Exception as e:
print(f"Error checking file t... | import os
import tempfile
import pytest
from solution import find_files
def create_test_file(directory, file_name, content):
file_path = os.path.join(directory, file_name)
with open(file_path, 'w') as f:
f.write(content)
return file_path
def test_find_files():
with tempfile.TemporaryDirectory(... | [
{
"docstring": "Checks if a file is a text file.",
"function_declaration": "def is_text_file(file_path):",
"function_name": "is_text_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Searches for files containing the search term within the specified directory.\nSearches line by line,... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef is_text_file(file_path):\n \"\"\"Checks if the file is a text file by reading the first 1024 bytes.\"\"\"\n try:\n with open(file_path, 'rb') as file:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00016170",
"row_id": 16170,
"seed_ids": "['Llama-3.3-70B-Instruct_41176']"
} | 0.679726 | Filter_16170 | I | [
"is_text_file",
"find_files"
] | 2 | [
[
"find_files",
"is_text_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b3ec453e1b3d5b40bf5bff3600cfdf8c35c87543 | e88adabe9693592a1efe9b676775f9525658ed7f | |||
v1.0 | instruct | Filter | Filter_16177_I | I have a large graph in a CSV file and I want to find the shortest path between two nodes. The graph is weighted and directed. For example, my graph looks something like the below.
| Source | Target | Weight |
|--------|--------|--------|
| A | B | 1 |
| B | C | 2 |
| C | D | 1 ... | import heapq
import csv
class Graph:
def __init__(self):
self.edges = {}
self.weights = {}
def add_edge(self, from_node, to_node, weight):
if from_node not in self.edges:
self.edges[from_node] = []
self.edges[from_node].append(to_node)
self.weights[(from_nod... | from solution import Graph, astar
def test_graph_add_edge():
graph = Graph()
graph.add_edge('A', 'B', 1)
assert graph.edges == {'A': ['B']}
assert graph.weights == {('A', 'B'): 1}
def test_graph_neighbors():
graph = Graph()
graph.add_edge('A', 'B', 1)
assert graph.neighbors('A') == ['B']
... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef heuristic(a, b):\n \"\"\"\n Heuristic function for A* algorithm.\n \"\"\"\n return 0 # As we do not have coordinates, set heuristic to 0 (Dijkstra's)\n\n\ndef ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016177",
"row_id": 16177,
"seed_ids": "['Llama-3.3-70B-Instruct_41188']"
} | 0.556849 | Filter_16177 | I | [
"heuristic",
"astar",
"load_graph_from_csv"
] | 3 | [
[
"astar",
"heuristic"
]
] | 1 | [] | false | [
"Graph"
] | true | pytest | true | [] | true | 6e580db5b187ee011ea36e03807873b8728739bb | 6d5b9f48237f1221dcba1b4cd021b2f9e48f982c | |||
v1.0 | instruct | Filter | Filter_16193_I | I have a text file named `scores.txt`. The file contains the names of students along with their respective scores. The format of the file is like this:
`Name:Score`
For example:
`John:80`
`Alice:90`
`Bob:70`
I want to write a Python program that reads this file, calculates the average score of each studen... | def read_scores(file_path):
"""
Reads the scores from the given file and returns a dictionary
with student names as keys and their scores as values.
Arguments:
file_path -- the path to the file containing the scores
Returns:
A dictionary with student names as keys and scores as val... | from solution import read_scores, calculate_average_score, sort_students_by_score, process_scores
def test_read_scores(tmp_path):
test_file = tmp_path / "scores.txt"
test_file.write_text("John:80\nAlice:90\nBob:70\n")
expected = {'John': 80, 'Alice': 90, 'Bob': 70}
assert read_scores(test_file) ==... | [
{
"docstring": "Reads the scores from the given file and returns a dictionary\nwith student names as keys and their scores as values.\n\nArguments:\nfile_path -- the path to the file containing the scores\n\nReturns:\nA dictionary with student names as keys and scores as values.",
"function_declaration": "d... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_average_score(file_path):\n \"\"\"\n Reads the scores from the file and calculates the average score for each student,\n then returns a list of tuples (name, average_sco... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016193",
"row_id": 16193,
"seed_ids": "['Llama-3.3-70B-Instruct_41228']"
} | 0.580057 | Filter_16193 | I | [
"read_scores",
"calculate_average_score",
"sort_students_by_score",
"process_scores"
] | 4 | [
[
"process_scores",
"calculate_average_score"
],
[
"process_scores",
"read_scores"
],
[
"process_scores",
"sort_students_by_score"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0f3d6c5dcea56e51f00e2be4ff30cde21e5780c1 | 6acfb1c03a543e0969e15a3a34b279160607d799 | |||
v1.0 | instruct | Filter | Filter_16209_I | I have a game that can load and render a OBJ 3D model, and animate it just fine, but it only has one material, and thus only looks like it's made of one type of material. To support multiple materials I'll need to split my 3D model into multiple meshes, one for each material.
However, I currently have no idea how to ... | def parse_obj(obj_file):
"""
Parses an OBJ file and returns vertices, texture coordinates, normals, and faces by material.
"""
vertices = []
textures = []
normals = []
faces = {}
current_material = None
with open(obj_file, 'r') as f:
for line in f:
parts = line.... | import os
def test_parse_obj():
# Use a small sample OBJ file content for testing
obj_content = """
v 1.000000 1.000000 1.000000
v 1.000000 1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 1.000000 1.000000
... | [
{
"docstring": "Parses an OBJ file and returns vertices, texture coordinates, normals, and faces by material.",
"function_declaration": "def parse_obj(obj_file):",
"function_name": "parse_obj",
"parameter_list": "(obj_file)"
},
{
"docstring": "Splits the OBJ model into separate meshes based ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pywavefront\n\ndef split_obj_by_material(file_path):\n \"\"\"\n Splits an OBJ file into multiple meshes based on materials.\n\n Args:\n file_path (str): The path to the ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016209",
"row_id": 16209,
"seed_ids": "['Llama-3.3-70B-Instruct_41276']"
} | 0.296496 | Filter_16209 | I | [
"parse_obj",
"split_by_material"
] | 2 | [
[
"split_by_material",
"parse_obj"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | e9f4a9b653ebf97ce6722e62fff3543812934690 | dcc70cdea5ca895dcface2c763fc4fb0645fee40 | |||
v1.0 | instruct | Filter | Filter_16218_I | Design a program that can print the prime numbers in a given range [a, b] (including a and b). The program should check if a and b are valid integers and if a is less than or equal to b, and then calculates the prime numbers in the range. If a or b is not an integer, or if a > b, the program should print an error mess... | def is_prime(n):
"""
Returns True if the number n is a prime number, else False.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
p = 3
while p**2 <= n:
if n % p == 0:
return False
p += 2
return True
d... | from solution import is_prime, print_primes_in_range
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert not is_prime(1)
assert is_prime(5)
assert not is_prime(9)
assert is_prime(11)
def test_print_primes_positive_range():
assert print_primes_in_ran... | [
{
"docstring": "Returns True if the number n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Prints all prime numbers in the range [a, b] inclusive.\nAlso checks if a and b are valid integers... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is a prime number.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016218",
"row_id": 16218,
"seed_ids": "['Llama-3.3-70B-Instruct_41291']"
} | 0.600506 | Filter_16218 | I | [
"is_prime",
"print_primes_in_range"
] | 2 | [
[
"print_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 68d2f2414b37c1bb2fe22da38580c1f28fc84acf | 4a3897438e9ae723d1234421349443231e07ca3e | |||
v1.0 | instruct | Filter | Filter_16268_I | Here is a code that generates a matrix of random numbers and another one that generates a Gaussian distribution of random numbers.
```python
import numpy as np
def generate_random_matrix(n, m):
return np.random.rand(n, m)
def generate_gaussian_distribution_matrix(n, m, mean, sigma):
return np.random.normal(l... | import numpy as np
def generate_random_matrix(n, m):
return np.random.rand(n, m)
def generate_gaussian_distribution_matrix(n, m, mean, sigma):
return np.random.normal(loc=mean, scale=sigma, size=(n, m))
def generate_full_workload(n, m, mean, sigma, num_random_matrices, num_gaussian_matrices):
"""
Gen... | from solution import generate_full_workload, generate_random_matrix, generate_gaussian_distribution_matrix
def test_generate_random_matrix_shape():
matrix = generate_random_matrix(3, 4)
assert matrix.shape == (3, 4)
def test_generate_gaussian_distribution_matrix_shape():
matrix = generate_gaussian_distrib... | [
{
"docstring": null,
"function_declaration": "def generate_random_matrix(n, m):",
"function_name": "generate_random_matrix",
"parameter_list": "(n, m)"
},
{
"docstring": null,
"function_declaration": "def generate_gaussian_distribution_matrix(n, m, mean, sigma):",
"function_name": "g... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef generate_random_matrix(n, m):\n return np.random.rand(n, m)\n\ndef generate_gaussian_distribution_matrix(n, m, mean, sigma):\n return np.random.normal(loc=mean,... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00016268",
"row_id": 16268,
"seed_ids": "['Llama-3.3-70B-Instruct_41407']"
} | 0.642932 | Filter_16268 | I | [
"generate_random_matrix",
"generate_gaussian_distribution_matrix",
"generate_full_workload"
] | 3 | [
[
"generate_full_workload",
"generate_gaussian_distribution_matrix"
],
[
"generate_full_workload",
"generate_random_matrix"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 7296d514118d5c9879a06c08786db8335d793696 | 3c1a5e44f9a692a92e5f069f9b4b88e8b7a90fae | |||
v1.0 | instruct | Filter | Filter_16287_I | Can I implement a k-nearest neighbors (KNN) algorithm without the help of a library? | import math
from collections import Counter
def euclidean_distance(point1, point2):
"""
Compute the Euclidean distance between two data points.
"""
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def knn(train_set, train_labels, test_point, k):
"""
Perform K-Nearest Neighbo... | import pytest
from solution import euclidean_distance, knn
def test_euclidean_distance():
assert euclidean_distance([0, 0], [3, 4]) == 5.0
assert euclidean_distance([1, 1], [4, 5]) == 5.0
assert math.isclose(euclidean_distance([2, 3], [5, 7]), 5.0, rel_tol=1e-9)
assert euclidean_distance([0, 0, 0], [1,... | [
{
"docstring": "Compute the Euclidean distance between two data points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Perform K-Nearest Neighbors classification.\n\n:param tr... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Computes the Euclidean distance between two points.\n \"\"\"\n distance = 0.0\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016287",
"row_id": 16287,
"seed_ids": "['Llama-3.3-70B-Instruct_41469']"
} | 0.410325 | Filter_16287 | I | [
"euclidean_distance",
"knn"
] | 2 | [
[
"knn",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4ee349b9e59faedb0742bbb5fbde6da01bfdf0a0 | 8576bfcbc9f273c80da0fc82bc75e443c18e26de | |||
v1.0 | instruct | Filter | Filter_16326_I | ### Enhanced Rock, Paper, Scissors
**Overview**
The code provided is a simple implementation of the Rock, Paper, Scissors game in Python. However, we need to enhance it with additional features such as the ability to play against the computer, play against another player, keep track of the score, and display the game ... | import random
def get_winner(choice1, choice2):
if choice1 == choice2:
return "tie"
elif (choice1 == "rock" and choice2 == "scissors") or \
(choice1 == "paper" and choice2 == "rock") or \
(choice1 == "scissors" and choice2 == "paper"):
return "player1"
else:
return... | import random
from solution import get_winner, play_round
def test_get_winner():
assert get_winner("rock", "scissors") == "player1"
assert get_winner("rock", "paper") == "player2"
assert get_winner("scissors", "paper") == "player1"
assert get_winner("paper", "rock") == "player1"
assert get_winner("... | [
{
"docstring": null,
"function_declaration": "def get_winner(choice1, choice2):",
"function_name": "get_winner",
"parameter_list": "(choice1, choice2)"
},
{
"docstring": null,
"function_declaration": "def play_round(player1, player2):",
"function_name": "play_round",
"parameter_l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_winner(choice1, choice2):\n if choice1 == choice2:\n return \"tie\"\n elif (choice1 == \"rock\" and choice2 == \"scissors\") or \\\n (choice1 == \... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00016326",
"row_id": 16326,
"seed_ids": "['Llama-3.3-70B-Instruct_41566']"
} | 0.565213 | Filter_16326 | I | [
"get_winner",
"play_round",
"enhanced_game"
] | 3 | [
[
"enhanced_game",
"play_round"
],
[
"play_round",
"get_winner"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ec03cad4b24cc9266c744ad5dbd459c13cbdaf9d | 6985c723b20b86bf67a2d38af566d2ddc2db6e45 | |||
v1.0 | instruct | Filter | Filter_16377_I | I'll give you 2 text files, `file1.txt` and `file2.txt`, each containing a list of names separated by newline characters. I want you to write a Python script that reads both files, splits each line into a list, and then finds the common names between the two lists. The script should print the common names.
Here are th... | def read_file_and_split(filename):
"""
Reads a file and returns a list of names (each line is a name).
"""
with open(filename, 'r') as file:
lines = file.read().splitlines()
return lines
def find_common_names(file1, file2):
"""
Reads two files and returns a list of common names betw... | from solution import read_file_and_split, find_common_names
# Mocking file reading using tempfile and StringIO
import tempfile
import pytest
@pytest.fixture
def create_temp_files():
file1_content = "John\nAlice\nBob\nEve\n"
file2_content = "Alice\nBob\nCharlie\nDavid\n"
file1 = tempfile.NamedTemporar... | [
{
"docstring": "Reads a file and returns a list of names (each line is a name).",
"function_declaration": "def read_file_and_split(filename):",
"function_name": "read_file_and_split",
"parameter_list": "(filename)"
},
{
"docstring": "Reads two files and returns a list of common names between... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_file_and_split(filename):\n \"\"\"\n Reads a file and returns a list of names (each line is a name).\n \"\"\"\n with open(filename, 'r') as file:\n lines = file.rea... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00016377",
"row_id": 16377,
"seed_ids": "['Llama-3.3-70B-Instruct_41701']"
} | 0.580482 | Filter_16377 | I | [
"read_file_and_split",
"find_common_names",
"print_common_names"
] | 3 | [
[
"find_common_names",
"read_file_and_split"
],
[
"print_common_names",
"find_common_names"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b25b8b61e457a371e9c7548fc145dbebcdd2f73e | d02d5abb294089a2f94e938603c39ddad6b2d971 | |||
v1.0 | instruct | Filter | Filter_16449_I | Here's a problem:
"Write a program to input a number and find all its divisors, then write another program to find the number of divisors for any given number."
I'd like to solve this problem in Python.
Here's a code written in Python that solves the first part of the problem.
```python
def find_divisors(num):
... | def find_divisors(num):
"""
Returns a list of all divisors of num.
"""
divisors = []
for i in range(1, num + 1):
if num % i == 0:
divisors.append(i)
return divisors
def count_divisors(num):
"""
Returns the number of divisors of num.
"""
return len(find_diviso... | from solution import find_divisors, count_divisors
def test_find_divisors():
assert find_divisors(1) == [1]
assert find_divisors(6) == [1, 2, 3, 6]
assert find_divisors(12) == [1, 2, 3, 4, 6, 12]
assert find_divisors(17) == [1, 17]
assert find_divisors(25) == [1, 5, 25]
def test_count_divisors():
... | [
{
"docstring": "Returns a list of all divisors of num.",
"function_declaration": "def find_divisors(num):",
"function_name": "find_divisors",
"parameter_list": "(num)"
},
{
"docstring": "Returns the number of divisors of num.",
"function_declaration": "def count_divisors(num):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_number_of_divisors(num):\n \"\"\"\n Returns the number of divisors for the given number.\n \"\"\"\n count = 0\n for i in range(1, num + 1):\n if num % i == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016449",
"row_id": 16449,
"seed_ids": "['Llama-3.3-70B-Instruct_41890']"
} | 0.7994 | Filter_16449 | I | [
"find_divisors",
"count_divisors"
] | 2 | [
[
"count_divisors",
"find_divisors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4b62141fb5c54c425b31fb19054375389a3afb4 | c3b314c19ab2cec7c5a6303e8e04edeea14da5fa | |||
v1.0 | instruct | Filter | Filter_16462_I | I have a function `my_function` which takes a single argument `arg1`. I want to create new functions `my_function_a` and `my_function_b` that wrap around `my_function` with different default arguments.
How do I implement these wrapper functions in Python? | def my_function(arg1):
"""
A placeholder function that takes a single argument and returns it.
"""
return arg1
def my_function_a():
"""
Wrapper function around my_function with a default argument.
"""
return my_function('a')
def my_function_b():
"""
Wrapper function around my_f... | from solution import my_function, my_function_a, my_function_b
def test_my_function():
assert my_function('test') == 'test'
def test_my_function_a():
assert my_function_a() == 'a'
def test_my_function_b():
assert my_function_b() == 'b'
def test_my_function_with_other_arguments():
assert my_function(... | [
{
"docstring": "A placeholder function that takes a single argument and returns it.",
"function_declaration": "def my_function(arg1):",
"function_name": "my_function",
"parameter_list": "(arg1)"
},
{
"docstring": "Wrapper function around my_function with a default argument.",
"function_d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def my_function(arg1):\n \"\"\"\n Processes the given argument and returns a result.\n In a real scenario, replace the code in this function with actual logic.\n \"\"\"\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016462",
"row_id": 16462,
"seed_ids": "['Llama-3.3-70B-Instruct_41922']"
} | 0.452654 | Filter_16462 | I | [
"my_function",
"my_function_a",
"my_function_b"
] | 3 | [
[
"my_function_a",
"my_function"
],
[
"my_function_b",
"my_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 80dd8c08ef226006988104f19f095b0830e249b2 | 106c5d540b44e164846829b4b77fa06491824ec2 | |||
v1.0 | instruct | Filter | Filter_16471_I | Deoxyribonucleic acid (DNA) is a complex molecule that contains genetic instructions used in the development and function of all living organisms. The building blocks of DNA are four nucleotide bases: adenine (A), thymine (T), cytosine (C), and guanine (G). These bases pair up in a specific manner: A always pairs with ... | def get_complement(base):
"""
This function takes a single base as input and returns its complementary base.
:param base: A single nucleotide base (A, C, G, or T)
:return: The complementary base
"""
base_pairs = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C'
}
... | from solution import get_complementary_sequence, get_complement
def test_get_complement():
assert get_complement('A') == 'T'
assert get_complement('T') == 'A'
assert get_complement('C') == 'G'
assert get_complement('G') == 'C'
try:
get_complement('X')
except ValueError as e:
ass... | [
{
"docstring": "This function takes a single base as input and returns its complementary base.\n\n:param base: A single nucleotide base (A, C, G, or T)\n:return: The complementary base",
"function_declaration": "def get_complement(base):",
"function_name": "get_complement",
"parameter_list": "(base)... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_complement(base):\n \"\"\"\n This function takes a single base as input and returns its complementary base.\n\n :param base: A single nucleotide base (A, C, G, or T)\n :ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016471",
"row_id": 16471,
"seed_ids": "['Llama-3.3-70B-Instruct_41938']"
} | 0.552233 | Filter_16471 | I | [
"get_complement",
"get_complementary_sequence"
] | 2 | [
[
"get_complementary_sequence",
"get_complement"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f29ffea691dd5d42b2081d7abd612aaead518a51 | 2e6a57a40970ba5adaa6f8b1eacaff610fcfab64 | |||
v1.0 | instruct | Filter | Filter_16481_I | Can you create a functional simple text-based Tic Tac Toe program in Python where two players 'X' and 'O' can play together? | def print_board(board):
"""
Prints the current state of the tic-tac-toe board.
"""
for row in board:
print(' | '.join(row))
print('-' * 5)
def check_winner(board, player):
"""
Checks if the given player has won the game.
"""
# Check rows
for row in board:
if ... | def test_check_winner_row():
board = [
['X', 'X', 'X'],
['O', ' ', 'O'],
[' ', ' ', ' ']
]
assert check_winner(board, 'X') == True
assert check_winner(board, 'O') == False
def test_check_winner_column():
board = [
['X', 'O', ' '],
['X', 'O', ' '],
['X... | [
{
"docstring": "Prints the current state of the tic-tac-toe board.",
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": "Checks if the given player has won the game.",
"function_declaration": "def check_winner(... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def print_board(board):\n \"\"\"\n Prints the Tic Tac Toe board.\n \"\"\"\n for row in board:\n print(\" | \".join(row))\n print(\"-\" * 5)\n\ndef check_winner(board)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00016481",
"row_id": 16481,
"seed_ids": "['Llama-3.3-70B-Instruct_41956']"
} | 0.387301 | Filter_16481 | I | [
"print_board",
"check_winner",
"check_draw",
"make_move",
"tic_tac_toe"
] | 5 | [
[
"tic_tac_toe",
"check_draw"
],
[
"tic_tac_toe",
"check_winner"
],
[
"tic_tac_toe",
"make_move"
],
[
"tic_tac_toe",
"print_board"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 27e0e72c2df825487486cd10a517006d3c813df7 | a5dab65d2402717941f075446f11355c8edfcf12 | |||
v1.0 | instruct | Filter | Filter_16489_I | I want to carry out a backtest for a statistical arbitrage strategy that aims to exploit the spread between two highly correlated assets. The strategy will be based on a linear regression model that will generate a z-score for each asset, and then use this z-score to determine whether to buy or sell the asset.
Below ... | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
# Generate sample data
np.random.seed(0)
n_samples = 1000
x = np.random.normal(0, 1, n_samples)
y = 2 + 0.5 * x + np.random.normal(0, 1, n_samples)
# Create a dataframe
df = pd.DataFrame({'x': x, 'y': y})
# Define a function to ... | from solution import generate_trading_signals
def test_generate_trading_signals():
np.random.seed(0)
n_samples = 1000
x = np.random.normal(0, 1, n_samples)
y = 2 + 0.5 * x + np.random.normal(0, 1, n_samples)
df = pd.DataFrame({'x': x, 'y': y})
result = generate_trading_signals(df, 2, 0.5)
... | [
{
"docstring": null,
"function_declaration": "def calculate_zscore(x, mean, std):",
"function_name": "calculate_zscore",
"parameter_list": "(x, mean, std)"
},
{
"docstring": null,
"function_declaration": "def generate_trading_signals(df, entry_threshold=2, exit_threshold=0.5):",
"fun... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\n# Generate sample data\nnp.random.seed(0)\nn_samples = 1000\nx = np.random.normal(0, 1, n_samples)... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00016489",
"row_id": 16489,
"seed_ids": "['Llama-3.3-70B-Instruct_41967']"
} | 0.490742 | Filter_16489 | I | [
"calculate_zscore",
"generate_trading_signals"
] | 2 | [
[
"generate_trading_signals",
"calculate_zscore"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | ebeacd82e0fddcabef5ad5ac4687824886dd1b44 | ac9b3de7e50d09abdc9725b464779e131abbbd76 | |||
v1.0 | instruct | Filter | Filter_16500_I | In this problem, we will adjust the previous problem a bit. Instead of processing the whole file, we will be processing the file in chunks, one chunk at a time. This will be an on-the-fly processing manner. We will not load the whole file into memory but instead, we will load a small chunk of the file into memory, proc... | def get_chunk(file_object, chunk_size=1024):
if chunk_size <= 0:
raise ValueError("Chunk size must be greater than zero.")
while True:
chunk = file_object.read(chunk_size)
if not chunk:
break
yield chunk
def process_chunk(chunk):
# This function should r... | import pytest
from solution import get_chunk, process_chunk, process_file
def test_get_chunk_valid_chunk_size():
with open("test_file.txt", "w") as f:
f.write("This is a test")
with open("test_file.txt", "r") as f:
chunks = list(get_chunk(f, chunk_size=4))
assert chunks == ["This", " is ", ... | [
{
"docstring": null,
"function_declaration": "def get_chunk(file_object, chunk_size=1024):",
"function_name": "get_chunk",
"parameter_list": "(file_object, chunk_size=1024)"
},
{
"docstring": null,
"function_declaration": "def process_chunk(chunk):",
"function_name": "process_chunk",... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_chunk(file_object, chunk_size=1024):\n if chunk_size <= 0:\n raise ValueError(\"Chunk size must be greater than zero.\")\n while True:\n chunk = file_object.read(ch... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016500",
"row_id": 16500,
"seed_ids": "['Llama-3.3-70B-Instruct_41993']"
} | 0.518198 | Filter_16500 | I | [
"get_chunk",
"process_chunk",
"process_file"
] | 3 | [
[
"process_file",
"get_chunk"
],
[
"process_file",
"process_chunk"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 53660960ada8a61249951c1bf477885205ae8cdd | ae8a9bd15c6d789e816d593d3cb1a01f1f28b18f | |||
v1.0 | instruct | Filter | Filter_16501_I | I've got a list of map coordinates in the following format:
`[(60.2, 50.7), (70.1, 60.5), ...]`.
I want to write a function in python that calculates the great-circle distance between each pair of consecutive points in the list and a function that calculates the cumulative sum of these distances.
Here is the code I ha... | import math
def haversine(lat1, lon1, lat2, lon2):
"""
Calculate the great-circle distance between two points
on a sphere given their longitudes and latitudes.
Parameters:
lat1, lon1 - latitude and longitude of point 1 (in decimal degrees)
lat2, lon2 - latitude and longitude of point 2 (i... | from solution import haversine, calculate_distances, cumulative_distance
def test_haversine():
# Test case1: Known distance between two points
assert math.isclose(haversine(0, 0, 0, 1), 111.195, rel_tol=1e-2)
# Test case2: Same points should have 0 distance
assert math.isclose(haversine(0, 0, 0, 0... | [
{
"docstring": "Calculate the great-circle distance between two points \non a sphere given their longitudes and latitudes.\n\nParameters:\nlat1, lon1 - latitude and longitude of point 1 (in decimal degrees)\nlat2, lon2 - latitude and longitude of point 2 (in decimal degrees)\n\nReturns:\nDistance between the tw... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef haversine(lat1, lon1, lat2, lon2):\n \"\"\"\n Calculate the great-circle distance between two points\n on a sphere (such as the Earth) given their longitudes\n a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016501",
"row_id": 16501,
"seed_ids": "['Llama-3.3-70B-Instruct_42003']"
} | 0.648859 | Filter_16501 | I | [
"haversine",
"calculate_distances",
"cumulative_distance"
] | 3 | [
[
"calculate_distances",
"haversine"
],
[
"cumulative_distance",
"calculate_distances"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ffc156b5f96fa5f4db64a49fe8911fc02beb0ba4 | f97475ba5c71b8417b53a34143263ecc7010d07d | |||
v1.0 | instruct | Filter | Filter_16504_I | I have a function `func` that takes in 3 parameters: `a`, `b`, and `c`. `a` and `b` are integers, and `c` is a string. I want to write a decorator that checks if `c` is either of two specific strings. If `c` is not one of these two, then the function should not be run, and an error should be raised.
Here's a basic ex... | def check_c_decorator(valid_strings):
def decorator(func):
def wrapper(a, b, c):
if c not in valid_strings:
raise ValueError(f"Invalid string. Must be one of {valid_strings}.")
return func(a, b, c)
return wrapper
return decorator
@check_c_decorator(["spec... | import pytest
from solution import check_c_decorator, func
@check_c_decorator(["valid_str1", "valid_str2"])
def sample_func(a, b, c):
return a * b
def test_func_with_valid_strings():
assert func(1, 2, "specific_string1") == 3
assert func(3, 4, "specific_string2") == 7
def test_func_with_invalid_string():... | [
{
"docstring": null,
"function_declaration": "def check_c_decorator(valid_strings):",
"function_name": "check_c_decorator",
"parameter_list": "(valid_strings)"
},
{
"docstring": null,
"function_declaration": "def func(a, b, c):",
"function_name": "func",
"parameter_list": "(a, b,... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def check_c(allowed_strings):\n def decorator(func):\n def wrapper(a, b, c):\n if c not in allowed_strings:\n raise ValueError(f\"Invalid string. Must be on... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00016504",
"row_id": 16504,
"seed_ids": "['Llama-3.3-70B-Instruct_42007']"
} | 0.454744 | Filter_16504 | I | [
"check_c_decorator",
"func"
] | 2 | [
[
"func",
"check_c_decorator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd01d5af70789e1bf00cdfa3ca3a548d7828f9e3 | e94151757d58a632d6375e81c6cec7e21b96b945 | |||
v1.0 | instruct | Filter | Filter_16508_I | Here is the Python code that I wrote to solve the problem of finding the first N prime numbers:
```python
def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
def find_primes(n):
"""Find t... | def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def find_primes(n):
"""Find the first N prime numbers."""
primes = []
num = 2
while len(primes) < n:
... | from solution import is_prime, find_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(1) == False
assert is_prime(13) == True
assert is_prime(0) == False
def test_find_primes():
assert find_primes(0) == []
asse... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the first N prime numbers.",
"function_declaration": "def find_primes(n):",
"function_name": "find_primes",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n < 2:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016508",
"row_id": 16508,
"seed_ids": "['Llama-3.3-70B-Instruct_42016']"
} | 0.763469 | Filter_16508 | I | [
"is_prime",
"find_primes"
] | 2 | [
[
"find_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d95071f9ea5a3b00c4c071882708ddffb7444dc9 | c52670156c10139a0f3f3441fca8496c6fa7f80c | |||
v1.0 | instruct | Filter | Filter_16511_I | You've been tasked with automating some of the routing work in your company's network. The current routing table for your company is as follows:
- There are three routers: Router A, Router B, and Router C.
- Router A is connected to Router B and Router C.
- Router B is connected to Router A and Router D.
- Router C is ... | import sys
import heapq
class Graph:
def __init__(self):
self.routers = {}
def add_router(self, router):
if router not in self.routers:
self.routers[router] = {}
def add_connection(self, router1, router2):
if router1 in self.routers and router2 in self.routers:
... | from solution import shortest_path
def test_shortest_path_a_to_d():
assert shortest_path('A', 'D') in [['A', 'B', 'D'], ['A', 'C', 'D']]
def test_shortest_path_a_to_f():
assert shortest_path('A', 'F') in [['A', 'B', 'D', 'F'], ['A', 'C', 'D', 'F']]
def test_shortest_path_c_to_f():
assert shortest_pat... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport heapq\n\nclass Graph:\n def __init__(self):\n self.routers = {}\n\n def add_router(self, router):\n if router not in self.routers:\n self.rout... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00016511",
"row_id": 16511,
"seed_ids": "['Llama-3.3-70B-Instruct_42032']"
} | 0.614416 | Filter_16511 | I | [
"create_company_network",
"shortest_path"
] | 2 | [
[
"shortest_path",
"create_company_network"
]
] | 1 | [] | false | [
"Graph"
] | true | pytest | true | [] | true | 247630fa2f964ae776ca4d34ea2c3933f32158d1 | 2421fc50b5863993ea26b2dc3ca790e9ff1f3045 | |||
v1.0 | instruct | Filter | Filter_16514_I | Let's do a lot of nesting in Python. Let's create a function that nests 10 levels deep. Each level will be a separate function. We'll have `level1`, `level2`, ..., `level10`. Each function should call the next level's function and pass the number of the current level as an argument. | def level10(level):
return f"Level {level}"
def level9(level):
return level10(level + 1)
def level8(level):
return level9(level + 1)
def level7(level):
return level8(level + 1)
def level6(level):
return level7(level + 1)
def level5(level):
return level6(level + 1)
def level4(level):
re... | from solution import level1
def test_level1():
assert level1(1) == "Level 10"
def test_level1_with_different_start():
assert level1(3) == "Level 12" | [
{
"docstring": null,
"function_declaration": "def level10(level):",
"function_name": "level10",
"parameter_list": "(level)"
},
{
"docstring": null,
"function_declaration": "def level9(level):",
"function_name": "level9",
"parameter_list": "(level)"
},
{
"docstring": null,... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def level10(n):\n return n\n\ndef level9(n):\n return level10(n + 1)\n\ndef level8(n):\n return level9(n + 1)\n\ndef level7(n):\n return level8(n + 1)\n\ndef level6(n):\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016514",
"row_id": 16514,
"seed_ids": "['Llama-3.3-70B-Instruct_42038']"
} | 0.461011 | Filter_16514 | I | [
"level10",
"level9",
"level8",
"level7",
"level6",
"level5",
"level4",
"level3",
"level2",
"level1"
] | 10 | [
[
"level1",
"level2"
],
[
"level2",
"level3"
],
[
"level3",
"level4"
],
[
"level4",
"level5"
],
[
"level5",
"level6"
],
[
"level6",
"level7"
],
[
"level7",
"level8"
],
[
"level8",
"level9"
],
[
"level9",
"level10... | 9 | [] | false | [] | false | pytest | true | [] | true | 55410aaa57fa2f6b541d0fb3e9097738d69bfa10 | 5069fffab62291386f47425c9e96346723cb4132 | |||
v1.0 | instruct | Filter | Filter_16544_I | It's a while since I started working on this project and I have now come across a
requirement to add / remove devices from my existing project. I need a script to
add or remove device from an existing set of devices in the project. When adding
a new device I will provide the device details such as device_id, device_... | # Devices dictionary
devices = {
"device1": {"device_id": "device1", "device_type": "thermostat", "connection_details": "some details"},
"device2": {"device_id": "device2", "device_type": "light", "connection_details": "some details"},
"device3": {"device_id": "device3", "device_type": "fan", "connection_de... | import pytest
from solution import get_device, update_device, remove_device, add_device, devices
def setup_function():
"""
Resets the devices dictionary to its initial state before each test.
"""
devices.clear()
devices.update({
"device1": {"device_id": "device1", "device_type": "thermostat... | [
{
"docstring": "Retrieves a device by its ID.\n\nArgs:\n- device_id (str): The ID of the device to retrieve.\n\nReturns:\n- dict or None: The device dictionary if found, otherwise None.",
"function_declaration": "def get_device(device_id):",
"function_name": "get_device",
"parameter_list": "(device_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Devices dictionary\ndevices = {\n \"device1\": {\"device_id\": \"device1\", \"device_type\": \"thermostat\", \"connection_details\": \"some details\"},\n \"device2\": {\"device_id\": \... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00016544",
"row_id": 16544,
"seed_ids": "['Llama-3.3-70B-Instruct_42110']"
} | 0.475482 | Filter_16544 | I | [
"get_device",
"update_device",
"remove_device",
"add_device"
] | 4 | [
[
"update_device",
"get_device"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0eb8f6a9451ef4b0886a5898d4f97ff97b126f7 | 50e690e4ce87d18d9463b32f5065e63f1cdb15d5 | |||
v1.0 | instruct | Filter | Filter_16582_I | Can you create a short Python script to generate employee records as XML files, assuming each record contains an employee ID, name, department, and job title? | import xml.etree.ElementTree as ET
def create_employee_record(employee_id, name, department, job_title):
"""
Create an XML representation of an employee record.
Parameters:
employee_id (str): The unique ID of the employee.
name (str): The name of the employee.
department (str):... | from solution import create_employee_record, save_employee_record_to_file
import xml.etree.ElementTree as ET
def test_create_employee_record():
employee_id = "12345"
name = "John Doe"
department = "Engineering"
job_title = "Software Engineer"
expected_xml = '<employee><id>12345</id><name>John ... | [
{
"docstring": "Create an XML representation of an employee record.\n\nParameters:\n employee_id (str): The unique ID of the employee.\n name (str): The name of the employee.\n department (str): The department the employee works in.\n job_title (str): The job title of the employee.\n \nReturns:\n... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\n\ndef create_employee_record(employee_id, name, department, job_title):\n \"\"\"\n Creates an XML representation of an employee record.\n \n :pa... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00016582",
"row_id": 16582,
"seed_ids": "['Llama-3.3-70B-Instruct_42223']"
} | 0.498416 | Filter_16582 | I | [
"create_employee_record",
"save_employee_record_to_file"
] | 2 | [
[
"save_employee_record_to_file",
"create_employee_record"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 381ea04a59fe7d6d8542185ec106872d56c4c3e7 | 4777e79ee837328b6d1d888724f25eb0aaf694e3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.