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_11529_I | I am trying to write a program that will intersect two sets. When a user enters two sets, I want the program to find the common elements and store the result in a new set.
Here's what I have so far:
```python
def intersect_sets():
# Get user input for the two sets
set1 = input("Enter the elements of the first ... | def convert_to_int_set(input_str):
"""
Converts a space-separated string of numbers to a set of integers.
Raises ValueError if any value is not a valid integer.
"""
elements = input_str.split()
if not elements:
raise ValueError("Set is empty.")
return set(int(x) for x in elements)
d... | import pytest
from solution import convert_to_int_set, intersect_sets
def test_convert_to_int_set_valid_input():
assert convert_to_int_set("1 2 3") == {1, 2, 3}
assert convert_to_int_set("10 20 30") == {10, 20, 30}
def test_convert_to_int_set_empty_input():
with pytest.raises(ValueError, match="Set is emp... | [
{
"docstring": "Converts a space-separated string of numbers to a set of integers.\nRaises ValueError if any value is not a valid integer.",
"function_declaration": "def convert_to_int_set(input_str):",
"function_name": "convert_to_int_set",
"parameter_list": "(input_str)"
},
{
"docstring": ... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_user_input(prompt):\n \"\"\"\n Get the input from the user and split it into a list of elements.\n \"\"\"\n return input(prompt).split()\n\ndef validate_and_convert_to_set(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011529",
"row_id": 11529,
"seed_ids": "['Llama-3.3-70B-Instruct_30528']"
} | 0.577305 | Filter_11529 | I | [
"convert_to_int_set",
"intersect_sets"
] | 2 | [
[
"intersect_sets",
"convert_to_int_set"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cbc5934af6ccca405983f702e19cae1e8988810d | 38f51caae3bde1fb401b562927946585aad4c9ca | |||
v1.0 | instruct | Filter | Filter_11540_I | Here is a problem.
Let's call the problem "Divide and Conquer the Integer".
Given an integer N. If N is prime then print it and exit.
If N is not prime, then find the largest prime factor and divide N by that number and repeat the process until N becomes 1.
Provide a solution in python code. | def is_prime(n):
"""
Check if an integer n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return ... | from solution import is_prime, largest_prime_factor, divide_and_conquer_integer
def test_is_prime():
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(9)
assert is_prime(11)
def test_largest_prime_factor():
assert... | [
{
"docstring": "Check if an integer n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the largest prime factor of n.",
"function_declaration": "def largest_prime_factor(n):",
"function_name": "larges... | [
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 is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011540",
"row_id": 11540,
"seed_ids": "['Llama-3.3-70B-Instruct_30551']"
} | 0.717964 | Filter_11540 | I | [
"is_prime",
"largest_prime_factor",
"divide_and_conquer_integer"
] | 3 | [
[
"divide_and_conquer_integer",
"is_prime"
],
[
"divide_and_conquer_integer",
"largest_prime_factor"
],
[
"largest_prime_factor",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 822f7f4b4a9dc1ef5bad4efb887117d4e6c108e1 | 187910752cd73f75d9e4b7791adcaa8dc49dfb1a | |||
v1.0 | instruct | Filter | Filter_11602_I | ### Overview
In this assignment, you will implement a Python program that can display the first 'n' prime numbers.
### Requirements
1. Define a function `is_prime(num)` that checks whether a number is prime or not.
2. Define another function `get_primes(n)` that generates the first 'n' prime numbers.
3. In the `main`... | def is_prime(num):
"""
Check whether a number is prime or not.
Parameters:
num (int): The number to check.
Returns:
bool: True if the number is prime, otherwise False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0... | from solution import is_prime, get_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
def test_get_primes():
assert... | [
{
"docstring": "Check whether a number is prime or not.\n\nParameters:\nnum (int): The number to check.\n\nReturns:\nbool: True if the number is prime, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "G... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011602",
"row_id": 11602,
"seed_ids": "['Llama-3.3-70B-Instruct_30698']"
} | 0.756836 | Filter_11602 | I | [
"is_prime",
"get_primes",
"main"
] | 3 | [
[
"get_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b8c7fe95e18134e30fcb8adf16cd3d90a307fb4a | 2210b06df8df5eeb6a031573d4bdb693eb077d39 | |||
v1.0 | instruct | Filter | Filter_11604_I | I have a dataset of 1000 entries that contains a column with emails, and I want to extract the domain name from each email. The domain name is what comes after the "@" symbol. How can I achieve this in Python? | def extract_domain(email):
"""
Extract the domain name from an email address.
:param email: str, the email address
:return: str, the domain part of the email
"""
try:
return email.split('@')[1]
except IndexError:
return None
def extract_domains(email_list):
"""
... | from solution import extract_domain, extract_domains
def test_extract_domain():
assert extract_domain('user@example.com') == 'example.com'
assert extract_domain('john.doe@gmail.com') == 'gmail.com'
assert extract_domain('jane@company.co.uk') == 'company.co.uk'
assert extract_domain('no_at_symbol.com') ... | [
{
"docstring": "Extract the domain name from an email address.\n\n:param email: str, the email address\n:return: str, the domain part of the email",
"function_declaration": "def extract_domain(email):",
"function_name": "extract_domain",
"parameter_list": "(email)"
},
{
"docstring": "Extract... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def extract_domain(email):\n \"\"\"\n Extracts and returns the domain name from an email address.\n\n :param email: str, email address to extract the domain from\n :return: str, do... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011604",
"row_id": 11604,
"seed_ids": "['Llama-3.3-70B-Instruct_30703']"
} | 0.491609 | Filter_11604 | I | [
"extract_domain",
"extract_domains"
] | 2 | [
[
"extract_domains",
"extract_domain"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b423e5608a12bb74640c45fcca09446270e5afa6 | 0d83dc5c81d05086327fa4a97f45b09aea874fb3 | |||
v1.0 | instruct | Filter | Filter_11614_I | ### Card Game: BlackJack
#### Problem Statement
The objective of this problem is to create a simple console-based BlackJack game. The game should allow two players to play against the dealer. The rules of BlackJack are as follows:
- The game starts with each player being dealt two cards.
- The cards 2-10 are worth thei... | import random
# Define card ranks and suits
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
# Function to create deck
def create_deck():
deck = [{'rank': r, 'suit': s} for r in ranks for s in suits]
random.shuffle(deck)
return de... | import pytest
from solution import create_deck, deal_card, calculate_card_value, calculate_total_value, simulate_blackjack
def test_create_deck():
deck = create_deck()
assert len(deck) == 52
assert all(card in [{'rank': r, 'suit': s} for r in ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A... | [
{
"docstring": null,
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def deal_card(deck):",
"function_name": "deal_card",
"parameter_list": "(deck)"
},
{
"docstring": nul... | [
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\n# Define card ranks and suits\nranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nsuits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n\n# Function to c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011614",
"row_id": 11614,
"seed_ids": "['Llama-3.3-70B-Instruct_30724']"
} | 0.613559 | Filter_11614 | I | [
"create_deck",
"deal_card",
"calculate_card_value",
"calculate_total_value",
"simulate_blackjack"
] | 5 | [
[
"calculate_total_value",
"calculate_card_value"
],
[
"simulate_blackjack",
"calculate_total_value"
],
[
"simulate_blackjack",
"deal_card"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6089d4fd86cfefa3cea98cc5863268947cc2f439 | 0c93a2694cff716ffb3e3c2070f0758d5cb46fff | |||
v1.0 | instruct | Filter | Filter_11618_I | ### Algorithm description
Write a program that implements the Rock, Paper, Scissors game.
### Constraints
1. The program should allow two modes of gameplay:
- Mode 1: User vs Computer
- Mode 2: User vs User
2. The program should keep track of the score for each player.
3. The program should validate user inputs... | import random
def validate_choice(choice):
"""
Validates that the choice is one of rock, paper, or scissors.
"""
return choice in ["rock", "paper", "scissors"]
def determine_winner(player1, player2):
"""
Determines the winner between two choices: rock, paper, and scissors.
"""
if playe... | from solution import rock_paper_scissors, determine_winner, validate_choice
def test_validate_choice():
assert validate_choice("rock") == True
assert validate_choice("paper") == True
assert validate_choice("scissors") == True
assert validate_choice("lizard") == False
def test_determine_winner():
a... | [
{
"docstring": "Validates that the choice is one of rock, paper, or scissors.",
"function_declaration": "def validate_choice(choice):",
"function_name": "validate_choice",
"parameter_list": "(choice)"
},
{
"docstring": "Determines the winner between two choices: rock, paper, and scissors.",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_user_choice(input_func=input):\n \"\"\"\n Get the user's choice, ensuring it is valid.\n Args:\n - input_func: a function that takes no arguments and retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011618",
"row_id": 11618,
"seed_ids": "['Llama-3.3-70B-Instruct_30734']"
} | 0.619774 | Filter_11618 | I | [
"validate_choice",
"determine_winner",
"rock_paper_scissors"
] | 3 | [
[
"rock_paper_scissors",
"determine_winner"
],
[
"rock_paper_scissors",
"validate_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 83e34b80f044831973ff298a06c5c5c6af5e4947 | d0fc4e2033678608eeda3070abd9f8175640a3d6 | |||
v1.0 | instruct | Filter | Filter_11635_I | Can you make a library that has functions to convert between string and array of integers.
Here are the specifications:
* The library should have a function named `string_to_array` that takes a string, separates it by a comma and converts each substring to an integer. The function should return an array of integers.
... | def string_to_array(s):
if s.strip() == "":
return []
try:
return [int(x) for x in s.split(",")]
except ValueError:
return None # Return None to indicate that conversion failed
def array_to_string(arr):
if not arr:
return ""
return ",".join(map(str, arr))
def is_va... | from solution import string_to_array, array_to_string, is_valid_array, is_valid_string
from solution import string_to_array_with_error_handling, array_to_string_with_error_handling
def test_string_to_array():
assert string_to_array("1,2,3") == [1, 2, 3]
assert string_to_array("10,20,30") == [10, 20, 30]
as... | [
{
"docstring": null,
"function_declaration": "def string_to_array(s):",
"function_name": "string_to_array",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def array_to_string(arr):",
"function_name": "array_to_string",
"parameter_list": "(arr)"
},
{
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def string_to_array(s):\n if not s:\n return []\n try:\n return [int(x) for x in s.split(\",\")]\n except ValueError:\n raise ValueError(\"Error: Input string con... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011635",
"row_id": 11635,
"seed_ids": "['Llama-3.3-70B-Instruct_30780']"
} | 0.565038 | Filter_11635 | I | [
"string_to_array",
"array_to_string",
"is_valid_array",
"is_valid_string",
"string_to_array_with_error_handling",
"array_to_string_with_error_handling"
] | 6 | [
[
"array_to_string_with_error_handling",
"array_to_string"
],
[
"array_to_string_with_error_handling",
"is_valid_array"
],
[
"string_to_array_with_error_handling",
"is_valid_string"
],
[
"string_to_array_with_error_handling",
"string_to_array"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 00a55d37fe8f3ab8102b36d7d6a1035fba12b6f8 | 43d4ebd9a8c2a52a8265dbc47d4c7393a24461bc | |||
v1.0 | instruct | Filter | Filter_11654_I | I want to create a Python script that generates a specified number of random passwords. Here are the details I have so far:
- The passwords will be 12 characters long
- The passwords will contain at least one lowercase letter, one uppercase letter, one digit, and one special character
- The passwords will be randomly g... | import random
import string
def generate_password(length=12):
if length < 12:
raise ValueError("Length must be at least 12")
lowercase_letters = string.ascii_lowercase
uppercase_letters = string.ascii_uppercase
digits = string.digits
special_characters = string.punctuation
# Ensure at... | from solution import generate_password, generate_multiple_passwords
def test_generate_password_length():
assert len(generate_password(12)) == 12
def test_generate_password_contains_lowercase():
pwd = generate_password(12)
assert any(c.islower() for c in pwd)
def test_generate_password_contains_uppercase(... | [
{
"docstring": null,
"function_declaration": "def generate_password(length=12):",
"function_name": "generate_password",
"parameter_list": "(length=12)"
},
{
"docstring": null,
"function_declaration": "def generate_multiple_passwords(num_passwords, length=12):",
"function_name": "gene... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_password(length=12):\n if length < 4:\n print(\"Length must be at least 4\")\n return None\n lowercase_letters = string.ascii_l... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011654",
"row_id": 11654,
"seed_ids": "['Llama-3.3-70B-Instruct_30825']"
} | 0.669111 | Filter_11654 | I | [
"generate_password",
"generate_multiple_passwords"
] | 2 | [
[
"generate_multiple_passwords",
"generate_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9b9f2d524f263032173673ef23c72b0a43e618b5 | 6301e6cea47a80fd493c65055fb66e4f812c10ad | |||
v1.0 | instruct | Filter | Filter_11660_I | I have a binary tree where each node has a value and a pointer to left child and right child. My task is to convert the binary tree to a doubly linked list in-place, meaning no extra space is allowed. | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class DoublyLinkedListNode:
def __init__(self, val=0, prev=None, next=None):
self.val = val
self.prev = prev
self.next = next
def tree_to_doubly_... | from solution import TreeNode, DoublyLinkedListNode, convert_tree_to_doubly_linked_list
def test_convert_empty_tree():
assert convert_tree_to_doubly_linked_list(None) is None
def test_convert_single_node():
tree = TreeNode(1)
dll = convert_tree_to_doubly_linked_list(tree)
assert dll.val == 1
asser... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef tree_to_doubly_linked_list(roo... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011660",
"row_id": 11660,
"seed_ids": "['Llama-3.3-70B-Instruct_30837']"
} | 0.375586 | Filter_11660 | I | [
"tree_to_doubly_linked_list",
"convert_tree_to_doubly_linked_list"
] | 2 | [
[
"convert_tree_to_doubly_linked_list",
"tree_to_doubly_linked_list"
]
] | 1 | [] | false | [
"TreeNode",
"DoublyLinkedListNode"
] | true | pytest | true | [] | true | 20fdb52a05e52e391fabfc75c0e93ed21b34a2d8 | 9d54fae6aa1e4d346ee27df0e4157ebe14b3af42 | |||
v1.0 | instruct | Filter | Filter_11709_I | I have a list of 2500 phone numbers. And I need to check if they all have a valid format. I want to create a function that checks if the number has a valid format and also I want to add a country code if it's not present.
Here is the format that I want the phone numbers to have:
+1 XXX-XXX-XXXX
Here is an example of... | import re
def check_phone_number_format(phone_number):
"""
Check if the phone number has a valid format and add country code if not present.
"""
valid_pattern = r'^\+1 \d{3}-\d{3}-\d{4}$'
basic_pattern = r'\d{3}-\d{3}-\d{4}'
if re.match(valid_pattern, phone_number):
return phone_nu... | def test_valid_number_with_country_code():
assert check_phone_number_format("+1 123-456-7890") == "+1 123-456-7890"
def test_valid_number_without_country_code():
assert check_phone_number_format("123-456-7890") == "+1 123-456-7890"
def test_number_without_dashes():
assert check_phone_number_format("123456... | [
{
"docstring": "Check if the phone number has a valid format and add country code if not present.",
"function_declaration": "def check_phone_number_format(phone_number):",
"function_name": "check_phone_number_format",
"parameter_list": "(phone_number)"
},
{
"docstring": "Takes a list of phon... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef check_phone_number_format(phone_number):\n \"\"\"\n Check if the phone number has a valid format and add country code if not present.\n \"\"\"\n valid_pattern = r'... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011709",
"row_id": 11709,
"seed_ids": "['Llama-3.3-70B-Instruct_30942']"
} | 0.510856 | Filter_11709 | I | [
"check_phone_number_format",
"format_phone_numbers"
] | 2 | [
[
"format_phone_numbers",
"check_phone_number_format"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | fa2bb9b65bbc600b940f611be38b1ce8e097ae7f | dd32afb524ebf1b59e1191eceb9e4a29442741d3 | |||
v1.0 | instruct | Filter | Filter_11741_I | Imagine you've been tasked with implementing a sorting algorithm for an array of integers that must satisfy the following constraints:
- The array can be of any size.
- The array can contain duplicate integers.
- The algorithm must be stable, i.e., the order of equal elements should be preserved.
- The algorithm must ... | def merge_sort(arr):
"""
Implementation of Merge Sort, a stable and efficient sorting algorithm.
It recursively divides the array in half, sorts each half, and merges them back together.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A new sorted list of in... | from solution import merge_sort
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_array():
ass... | [
{
"docstring": "Implementation of Merge Sort, a stable and efficient sorting algorithm.\nIt recursively divides the array in half, sorts each half, and merges them back together.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A new sorted list of integers.\n\nExample Usage:\nsor... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Perform a stable merge sort on an array of integers.\n \n Parameters:\n arr (list of int): The array to sort.\n \n Returns:\n list of in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011741",
"row_id": 11741,
"seed_ids": "['Llama-3.3-70B-Instruct_31011']"
} | 0.593448 | Filter_11741 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2d0ab3ce93a4dc6633d940092809ed3bd908c32f | 6aa87cd36c4ac77200ce7ac44042ebbefa4aea49 | |||
v1.0 | instruct | Filter | Filter_11749_I | Here is the code:
```python
import random
import time
def generate_random_number(min_value, max_value):
"""
This function generates a random integer within the specified range.
Args:
min_value (int): The minimum value of the range.
max_value (int): The maximum value of the range.
... | import random
def generate_random_number(min_value, max_value):
"""
This function generates a random integer within the specified range.
Args:
min_value (int): The minimum value of the range.
max_value (int): The maximum value of the range.
Returns:
int: A random integ... | from solution import (generate_random_number, generate_random_float,
generate_random_string, generate_random_boolean,
generate_random_list)
import pytest
def test_generate_random_number():
result = generate_random_number(1, 100)
assert 1 <= result <= 100
def test_... | [
{
"docstring": "This function generates a random integer within the specified range.\n\nArgs:\n min_value (int): The minimum value of the range.\n max_value (int): The maximum value of the range.\n\nReturns:\n int: A random integer between min_value and max_value (inclusive).",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_number(min_value, max_value):\n \"\"\"\n This function generates a random integer within the specified range.\n \n Args:\n min_value (in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011749",
"row_id": 11749,
"seed_ids": "['Llama-3.3-70B-Instruct_31035']"
} | 0.661882 | Filter_11749 | I | [
"generate_random_number",
"generate_random_float",
"generate_random_string",
"generate_random_boolean",
"generate_random_list"
] | 5 | [
[
"generate_random_list",
"generate_random_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c29a3256dfffa18cf26d2a1e3345cfd9e18d21d9 | 9ca82cc4266074a19715e211ad71e75979f3f905 | |||
v1.0 | instruct | Filter | Filter_11766_I | I have written a program in Python which contains two functions, `add` and `subtract`, each of which take two arguments, `x` and `y`, and return the sum and difference of `x` and `y` respectively. I now want to write a new function that can take in any two arguments and any mathematical operation as an input and apply ... | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def apply_operation(x, y, operation):
"""
Applies the given operation to x and y.
Parameters:
- x: The first operand
- y: The second operand
- operation: The operation to apply. It can be "add", "subtract", or any other oper... | from solution import add, subtract, apply_operation
def test_add():
assert add(3, 5) == 8
assert add(-1, 1) == 0
assert add(1, -1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(-1, 1) == -2
assert subtract(1, -1) == 2
assert subtract(0, 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": "Applies the ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(x, y):\n \"\"\"\n Returns the sum of x and y.\n \"\"\"\n return x + y\n\ndef subtract(x, y):\n \"\"\"\n Returns the difference between x and y.\n \"\"\"\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011766",
"row_id": 11766,
"seed_ids": "['Llama-3.3-70B-Instruct_31074']"
} | 0.625653 | Filter_11766 | I | [
"add",
"subtract",
"apply_operation"
] | 3 | [
[
"apply_operation",
"add"
],
[
"apply_operation",
"subtract"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a91838890e7f5504d186f2340099f6040c08709a | 8a920587718ebe4243260490cc1621832dc41a4b | |||
v1.0 | instruct | Filter | Filter_11834_I | You can use the following code to make a function that calculates the greatest common divisor of two integers by using the Euclidean algorithm:
```python
def gcd(a, b):
while b:
a, b = b, a % b
return a
```
This function works by repeatedly replacing `a` and `b` with `b` and `a % b` until `b` is zero, a... | def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm_of_two():
a = 12
b = 15
return abs(a * b) // gcd(a, b)
def lcm_of_three():
a = 12
b = 15
c = 20
lcm_ab = abs(a * b) // gcd(a, b)
return abs(lcm_ab * c) // gcd(lcm_ab, c) | from solution import gcd, lcm_of_two, lcm_of_three
def test_gcd():
assert gcd(12, 15) == 3
assert gcd(100, 10) == 10
assert gcd(17, 13) == 1
def test_lcm_of_two():
assert lcm_of_two() == 60
def test_lcm_of_three():
assert lcm_of_three() == 60
# Additional tests for a comprehensive check
def test... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def lcm_of_two():",
"function_name": "lcm_of_two",
"parameter_list": "()"
},
{
"docstring": null,
"functi... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm_2_numbers():\n # Define the two numbers a and b\n a = 15\n b = 20\n # Calculate LCM using the formula... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011834",
"row_id": 11834,
"seed_ids": "['Llama-3.3-70B-Instruct_31215']"
} | 0.75117 | Filter_11834 | I | [
"gcd",
"lcm_of_two",
"lcm_of_three"
] | 3 | [
[
"lcm_of_three",
"gcd"
],
[
"lcm_of_two",
"gcd"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e9a96081b416b00b7e00330fba51c5c645094612 | 653bed44852748482105d83879b53ec1fa7e57bb | |||
v1.0 | instruct | Filter | Filter_11866_I | I have a scenario where I need to verify the checksum of a file before processing it. I want to use Python to calculate and verify the checksum. How can I use the `hashlib` library in Python to calculate the checksum of a file? | import hashlib
def calculate_checksum(file_path, algorithm='sha256'):
"""
Calculate the checksum of a file using the specified hashing algorithm.
:param file_path: Path to the file.
:param algorithm: Hashing algorithm to use ('md5', 'sha1', 'sha256', etc.)
:return: The hexdigest of the checksu... | from solution import calculate_checksum, verify_checksum
import tempfile
def create_temp_file(contents):
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(contents)
temp_file.seek(0)
temp_file.close()
return temp_file
def test_calculate_checksum():
temp_file = create_temp_f... | [
{
"docstring": "Calculate the checksum of a file using the specified hashing algorithm.\n\n:param file_path: Path to the file.\n:param algorithm: Hashing algorithm to use ('md5', 'sha1', 'sha256', etc.)\n:return: The hexdigest of the checksum.",
"function_declaration": "def calculate_checksum(file_path, alg... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef calculate_checksum(file_path, algorithm='md5'):\n \"\"\"\n Calculates the checksum of a given file using the specified algorithm.\n\n Parameters:\n - file_pat... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011866",
"row_id": 11866,
"seed_ids": "['Llama-3.3-70B-Instruct_31285']"
} | 0.58221 | Filter_11866 | I | [
"calculate_checksum",
"verify_checksum"
] | 2 | [
[
"verify_checksum",
"calculate_checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b795139cd55b519ba6278ef0deb7e7c818e1f3f | 0d4b0e226de5d91114a5fd519c1f1b110aa49e8b | |||
v1.0 | instruct | Filter | Filter_11893_I | I've been trying to code an app that implements the Dijkstra algorithm for finding the shortest path in a graph. I've been stuck at implementing the algorithm itself.
Here's my implementation in Python:
```python
import sys
import heapq
def dijkstra(graph, start):
distances = {node: sys.maxsize for node in graph... | import sys
import heapq
def dijkstra(graph, start):
distances = {node: sys.maxsize for node in graph}
distances[start] = 0
queue = [(0, start)]
shortest_path = {start: None}
while queue:
current_distance, current_node = heapq.heappop(queue)
if current_distance > distances[current_n... | from solution import dijkstra
def test_dijkstra():
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}
}
start_node = 'A'
expected_distances = {'A': 0, 'B': 1, 'C': 3, 'D': 4}
expected_paths = {
... | [
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start):",
"function_name": "dijkstra",
"parameter_list": "(graph, start)"
},
{
"docstring": null,
"function_declaration": "def reconstruct_path(shortest_path, start, end):",
"function_name": "reconstruct_path",
"pa... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport heapq\n\ndef reconstruct_path(shortest_path, start, end):\n \"\"\"\n Reconstructs the full path from start to end using the shortest_path dictionary.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011893",
"row_id": 11893,
"seed_ids": "['Llama-3.3-70B-Instruct_31342']"
} | 0.520817 | Filter_11893 | I | [
"dijkstra",
"reconstruct_path"
] | 2 | [
[
"dijkstra",
"reconstruct_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b64b4d22b95eda0f65603fbfa9b124cc80abb1e0 | 3ba7ef77831b5ebcaba49d9d2c214c21358348b0 | |||
v1.0 | instruct | Filter | Filter_11905_I | I have the following code:
```python
import json
import os
def load_json_file(file_path):
"""
Loads a JSON file and returns its contents.
Args:
file_path (str): The path to the JSON file.
Returns:
dict: The contents of the JSON file.
"""
try:
with open(file_path, 'r')... | import json
import os
from datetime import datetime
def load_json_file(file_path):
"""
Loads a JSON file and returns its contents.
Args:
file_path (str): The path to the JSON file.
Returns:
dict: The contents of the JSON file.
"""
try:
with open(file_path, 'r') as file... | import os
import pytest
import json
from datetime import datetime, timedelta
from solution import load_json_file, save_json_file, get_all_files, get_file_names, get_json_files, get_sorted_json_files, get_latest_json_file
TEST_DIRECTORY = 'test_dir/'
def setup_module(module):
""" setup any state specific to the ex... | [
{
"docstring": "Loads a JSON file and returns its contents.\n\nArgs:\nfile_path (str): The path to the JSON file.\n\nReturns:\ndict: The contents of the JSON file.",
"function_declaration": "def load_json_file(file_path):",
"function_name": "load_json_file",
"parameter_list": "(file_path)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport os\nfrom datetime import datetime\n\ndef load_json_file(file_path):\n \"\"\"\n Loads a JSON file and returns its contents.\n \n Args:\n file_path (str): The ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00011905",
"row_id": 11905,
"seed_ids": "['Llama-3.3-70B-Instruct_31373']"
} | 0.738157 | Filter_11905 | I | [
"load_json_file",
"save_json_file",
"get_all_files",
"get_file_names",
"get_json_files",
"get_sorted_json_files",
"get_latest_json_file",
"main"
] | 8 | [
[
"get_file_names",
"get_all_files"
],
[
"get_json_files",
"get_all_files"
],
[
"get_latest_json_file",
"get_json_files"
],
[
"get_sorted_json_files",
"get_json_files"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 673b2f823ac38c4d4eb0e6f333c8fd9215ade41c | 7fb90069323ff757ec1fe1e392290b67d0b7afc1 | |||
v1.0 | instruct | Filter | Filter_11915_I | I've been given an exercise to find the kth smallest element in an unsorted array. However, I need to implement this without using the built-in sort function.
Here's a simple example of how to use the built-in sort function to solve this problem:
```python
def find_kth_smallest(nums, k):
nums.sort()
return num... | def partition(arr, left, right):
pivot = arr[right]
p_idx = left
for i in range(left, right):
if arr[i] <= pivot:
arr[i], arr[p_idx] = arr[p_idx], arr[i]
p_idx += 1
arr[p_idx], arr[right] = arr[right], arr[p_idx]
return p_idx
def quick_select(arr, left, right, k):
... | from solution import find_kth_smallest
def test_find_kth_smallest_basic():
assert find_kth_smallest([3, 1, 2, 5, 4], 2) == 2
def test_find_kth_smallest_single_element():
assert find_kth_smallest([1], 1) == 1
def test_find_kth_smallest_negative_numbers():
assert find_kth_smallest([-1, -3, -2, -5, -4], 4) ... | [
{
"docstring": null,
"function_declaration": "def partition(arr, left, right):",
"function_name": "partition",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def quick_select(arr, left, right, k):",
"function_name": "quick_select",
"parame... | [
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 partition(arr, low, high):\n pivot = arr[high]\n i = low - 1\n \n for j in range(low, high):\n if arr[j] <= pivot:\n i += 1\n arr[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011915",
"row_id": 11915,
"seed_ids": "['Llama-3.3-70B-Instruct_31395']"
} | 0.52685 | Filter_11915 | I | [
"partition",
"quick_select",
"find_kth_smallest"
] | 3 | [
[
"find_kth_smallest",
"quick_select"
],
[
"quick_select",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e8994e1bbfd85b7e1c27f50ad7bfb23ecb8feedd | b788329a01bb864f149e39392ad80fe10f4df121 | |||
v1.0 | instruct | Filter | Filter_11932_I | I have a network with the following structure:
* The network is an undirected graph
* There are 10 nodes
* Each node has a maximum of 5 connections
* Each connection has a weight
* The weight is unique between any two nodes
I'm trying to find the shortest path between two nodes in the network. Since eac... | import heapq
def dijkstra(graph, start):
queue = []
heapq.heappush(queue, (0, start))
distances = {node: float('infinity') for node in graph}
distances[start] = 0
shortest_paths = {node: [] for node in graph}
while queue:
current_distance, current_node = heapq.heappop(queue)
... | from solution import find_shortest_path
def test_find_shortest_path_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}
}
distance, path = find_shortest_path(graph, 'A', 'D')
assert distance == 4
... | [
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start):",
"function_name": "dijkstra",
"parameter_list": "(graph, start)"
},
{
"docstring": null,
"function_declaration": "def find_shortest_path(graph, start, end):",
"function_name": "find_shortest_path",
"parame... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(graph, start):\n queue = []\n heapq.heappush(queue, (0, start))\n distances = {node: float('infinity') for node in graph}\n distances[start] = 0\n s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011932",
"row_id": 11932,
"seed_ids": "['Llama-3.3-70B-Instruct_31441']"
} | 0.54612 | Filter_11932 | I | [
"dijkstra",
"find_shortest_path"
] | 2 | [
[
"find_shortest_path",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7fa2aff9b61cbcb363817425a54f6a81ba0bda8d | 436e5451d7e28a0cfac0f347e479b26d8df5c91a | |||
v1.0 | instruct | Filter | Filter_11957_I | I have two CSV files, one for routes and another for stops. I have written a program in Python that parses those files, creates Route and Stop objects, and stores them in a dictionary. Now I would like to find the shortest path between two given stops.
To implement this, I would like to use Dijkstra's algorithm. Howev... | import csv
import heapq
from collections import defaultdict
class Route:
def __init__(self, route_id, stop1_id, stop2_id, distance):
self.route_id = route_id
self.stop1_id = stop1_id
self.stop2_id = stop2_id
self.distance = float(distance)
class Stop:
def __init__(self, stop_id... | import os
import pytest
from solution import Route, Stop, parse_routes, parse_stops, create_graph, dijkstra, shortest_path
def test_parse_routes():
routes = parse_routes('test_routes.csv')
assert len(routes) == 3
assert routes[0].route_id == '1'
assert routes[0].stop1_id == 'A'
assert routes[0].sto... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport heapq\n\nclass Stop:\n def __init__(self, stop_id, name):\n self.id = stop_id\n self.name = name\n\nclass Route:\n def __init__(self, start_stop, end_sto... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00011957",
"row_id": 11957,
"seed_ids": "['Llama-3.3-70B-Instruct_31491']"
} | 0.469424 | Filter_11957 | I | [
"parse_routes",
"parse_stops",
"create_graph",
"dijkstra",
"shortest_path"
] | 5 | [
[
"shortest_path",
"create_graph"
],
[
"shortest_path",
"dijkstra"
],
[
"shortest_path",
"parse_routes"
],
[
"shortest_path",
"parse_stops"
]
] | 4 | [] | false | [
"Route",
"Stop"
] | true | pytest | true | [] | true | deaed3f1bbb517e98d51e344c70d74a772cdbb80 | 01cfeadc52817dacfde791b88d560026049ae63b | |||
v1.0 | instruct | Filter | Filter_11984_I | Imagine a domain-specific language (DSL) for financial modeling. This DSL is used to define a set of rules that determine whether a loan is approved or rejected. The DSL consists of the following components:
- A set of variables, which can be either numeric or categorical.
- A set of operations, which can be combined t... | def greater_than(a, b):
"""
Returns True if a is greater than b
"""
return a > b
def less_than(a, b):
"""
Returns True if a is less than b
"""
return a < b
def equals(a, b):
"""
Returns True if a is equal to b
"""
return a == b
def in_category(a, b):
"""
Return... | from solution import greater_than, less_than, equals, in_category, approve_loan
def test_greater_than():
assert greater_than(5, 3) == True
assert greater_than(3, 5) == False
assert greater_than(3, 3) == False
def test_less_than():
assert less_than(3, 5) == True
assert less_than(5, 3) == False
... | [
{
"docstring": "Returns True if a is greater than b",
"function_declaration": "def greater_than(a, b):",
"function_name": "greater_than",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns True if a is less than b",
"function_declaration": "def less_than(a, b):",
"function_name": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greater_than(a, b):\n return a > b\n\ndef less_than(a, b):\n return a < b\n\ndef equals(a, b):\n return a == b\n\ndef in_category(a, b):\n return a in b\n\ndef loan_approval_ru... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00011984",
"row_id": 11984,
"seed_ids": "['Llama-3.3-70B-Instruct_31552']"
} | 0.462546 | Filter_11984 | I | [
"greater_than",
"less_than",
"equals",
"in_category",
"approve_loan"
] | 5 | [
[
"approve_loan",
"equals"
],
[
"approve_loan",
"greater_than"
],
[
"approve_loan",
"less_than"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a06ec2d71b08ce6e647374a8a681074d8edb9f39 | a055bee30e5becd5b7052d65e571eecee82a8088 | |||
v1.0 | instruct | Filter | Filter_12000_I | What is the process to create a system in Python that can take in user input in a text-based interface and then generate a response to this input? | def handle_user_input(prompt):
"""
Takes a prompt, asks the user for input, and returns a response.
"""
user_input = input(prompt)
response = generate_response(user_input)
return response
def generate_response(user_input):
"""
Generates a response based on the user input.
This ... | def test_generate_response():
assert generate_response("Hello") == "You said: Hello"
assert generate_response("How are you?") == "You said: How are you?"
assert generate_response("") == "You said: "
def test_handle_user_input(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: "Hello")
as... | [
{
"docstring": "Takes a prompt, asks the user for input, and returns a response.",
"function_declaration": "def handle_user_input(prompt):",
"function_name": "handle_user_input",
"parameter_list": "(prompt)"
},
{
"docstring": "Generates a response based on the user input.\n\nThis is a simple... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_response(user_input):\n \"\"\"\n Generates a response based on user input.\n \"\"\"\n if user_input.lower() in ['hi', 'hello']:\n return \"Hello! How can I help... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012000",
"row_id": 12000,
"seed_ids": "['Llama-3.3-70B-Instruct_31591']"
} | 0.429071 | Filter_12000 | I | [
"handle_user_input",
"generate_response"
] | 2 | [
[
"handle_user_input",
"generate_response"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | cd5833253aaa3296838e05a5a885e7ea8311d4bd | 4d2ce73eaf0a86f310829721425d33f2b5418487 | |||
v1.0 | instruct | Filter | Filter_12059_I | I have a list of files with .zip, .rar, .7z, .tar, and .tar.gz extensions. I want to extract these archives into a directory, but only if they are not empty. I'm looking for a solution that is flexible, allowing me to add or remove archive types as needed, and also handling different extraction commands.
Here's an exa... | import os
import subprocess
# List of files to extract
files = ['file1.zip', 'file2.rar', 'file3.7z', 'file4.tar', 'file5.tar.gz']
# Dictionary with archive types and their corresponding extraction commands
extraction_commands = {
'.zip': 'unzip {}',
'.rar': 'unrar x {}',
'.7z': '7z x {}',
'.tar': 'ta... | import os
from unittest.mock import patch, mock_open
from solution import extract_archive, extract_all_archives
def test_extract_archive_zip():
with patch('os.path.getsize', return_value=1024):
with patch('subprocess.run') as mock_run:
extract_archive('file1.zip', {
'.zip': 'unz... | [
{
"docstring": null,
"function_declaration": "def extract_archive(file_path, extraction_commands):",
"function_name": "extract_archive",
"parameter_list": "(file_path, extraction_commands)"
},
{
"docstring": null,
"function_declaration": "def extract_all_archives(files, extraction_comman... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport subprocess\n\n# List of files to extract\nfiles = ['file1.zip', 'file2.rar', 'file3.7z', 'file4.tar', 'file5.tar.gz']\n\n# Dictionary with archive types and their correspondi... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012059",
"row_id": 12059,
"seed_ids": "['Llama-3.3-70B-Instruct_31734']"
} | 0.620142 | Filter_12059 | I | [
"extract_archive",
"extract_all_archives"
] | 2 | [
[
"extract_all_archives",
"extract_archive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | df2cea248ed1941e0e705d95e29c960842e74565 | 06bf07e65e2796a48fe7590c25283abfe9ed525f | |||
v1.0 | instruct | Filter | Filter_12112_I | ### Creating a Simple Game: Hangman
#### Game Overview
Hangman is a guessing game where one player thinks of a word, and the other player tries to guess it by suggesting letters. For each letter that is not in the word, the first player draws a part of a hangman's gallows. The game continues until the word is guessed o... | import random
HANGMAN_PICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O ... | import pytest
from solution import getRandomWord, getGuess, displayBoard
def test_getRandomWord():
word = getRandomWord(WORDS)
assert word in WORDS
def test_getGuess(monkeypatch):
monkeypatch.setattr('builtins.input', lambda: 'a')
guess = getGuess('bcdef')
assert guess == 'a'
def test_displayBoar... | [
{
"docstring": "Returns a random word from the word list.",
"function_declaration": "def getRandomWord(wordList):",
"function_name": "getRandomWord",
"parameter_list": "(wordList)"
},
{
"docstring": "Displays the current state of the Hangman board.",
"function_declaration": "def displayB... | [
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\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012112",
"row_id": 12112,
"seed_ids": "['Llama-3.3-70B-Instruct_31859']"
} | 0.521826 | Filter_12112 | I | [
"getRandomWord",
"displayBoard",
"getGuess",
"playAgain",
"hangman"
] | 5 | [
[
"hangman",
"displayBoard"
],
[
"hangman",
"getGuess"
],
[
"hangman",
"getRandomWord"
],
[
"hangman",
"playAgain"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | ae7ea5c7f3453164c03c4c5496dd369228dd4fff | e4e075009ef058254e11b4767638fbc4061ab0c6 | |||
v1.0 | instruct | Filter | Filter_12131_I | I have a function that takes in a 2D numpy array and returns a 1D numpy array. This function uses standard libraries only. Can I use this function with a list comprehension to create a new 2D numpy array from an existing 2D numpy array? | import numpy as np
def flatten_row(row):
"""
Flattens a 2D numpy array row into a 1D numpy array.
"""
return row.flatten()
def transform_2d_array(arr):
"""
Transforms each row of the 2D numpy array using the flatten_row function.
"""
return np.array([flatten_row(row) for row in arr]) | import numpy as np
from solution import flatten_row, transform_2d_array
def test_flatten_row():
arr = np.array([[1, 2], [3, 4]])
assert np.array_equal(flatten_row(arr[0]), np.array([1, 2]))
assert np.array_equal(flatten_row(arr[1]), np.array([3, 4]))
def test_transform_2d_array():
arr = np.array([[1, ... | [
{
"docstring": "Flattens a 2D numpy array row into a 1D numpy array.",
"function_declaration": "def flatten_row(row):",
"function_name": "flatten_row",
"parameter_list": "(row)"
},
{
"docstring": "Transforms each row of the 2D numpy array using the flatten_row function.",
"function_decla... | [
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\n\ndef convert_to_1d(array_2d):\n \"\"\"\n Converts a 2D numpy array to a 1D numpy array by flattening each row.\n \"\"\"\n return array_2d.flatten()\n\ndef appl... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012131",
"row_id": 12131,
"seed_ids": "['Llama-3.3-70B-Instruct_31892']"
} | 0.511979 | Filter_12131 | I | [
"flatten_row",
"transform_2d_array"
] | 2 | [
[
"transform_2d_array",
"flatten_row"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 5d7eb9492ddaa53d50c442834d2ccdaac550596d | 5686aa00f17b17f415d3a78169f4e0abb7572e23 | |||
v1.0 | instruct | Filter | Filter_12148_I | Here is the code for a program that checks whether a number is a palindrome or not.
```python
def check_palindrome(num):
num_str = str(num)
if num_str == num_str[::-1]:
return True
else:
return False
def main():
num = int(input("Enter a number: "))
if check_palindrome(num):
... | def check_palindrome(num):
num_str = str(num)
return num_str == num_str[::-1]
def generate_palindromes_in_range(a, b):
"""
Returns a list of all palindromic numbers within the range [a, b] (inclusive).
"""
palindromes = [num for num in range(a, b + 1) if check_palindrome(num)]
return palind... | from solution import check_palindrome, generate_palindromes_in_range
def test_check_palindrome():
assert check_palindrome(121) == True
assert check_palindrome(123) == False
assert check_palindrome(0) == True
assert check_palindrome(1221) == True
assert check_palindrome(12321) == True
assert che... | [
{
"docstring": null,
"function_declaration": "def check_palindrome(num):",
"function_name": "check_palindrome",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all palindromic numbers within the range [a, b] (inclusive).",
"function_declaration": "def generate_palindromes_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def check_palindrome(num):\n \"\"\"\n Checks if a number is a palindrome.\n \n Args:\n num (int): The number to check.\n \n Returns:\n bool: True if num is a palindrome... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012148",
"row_id": 12148,
"seed_ids": "['Llama-3.3-70B-Instruct_31925']"
} | 0.631142 | Filter_12148 | I | [
"check_palindrome",
"generate_palindromes_in_range"
] | 2 | [
[
"generate_palindromes_in_range",
"check_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | adb783ee3f18527be648a0f23c8f12d7c24c77e4 | 90df768a8bae0ba111177b33588ad18732367c78 | |||
v1.0 | instruct | Filter | Filter_12155_I | Here's a code that generates max heap from an array
```python
def heapify(arr, n, i):
# Find largest among root and children
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
# If largest is no... | def min_heapify(arr, n, i):
# Find smallest among root and children
smallest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] > arr[l]:
smallest = l
if r < n and arr[smallest] > arr[r]:
smallest = r
# If smallest is not root
if smallest != i:
arr[i], arr[sma... | from solution import min_heapify, build_min_heap
def test_min_heapify():
arr = [4, 10, 3, 5, 1]
min_heapify(arr, len(arr), 0)
assert arr == [3, 10, 4, 5, 1]
def test_build_min_heap():
arr = [12, 11, 13, 5, 6, 7]
build_min_heap(arr)
assert arr == [5, 6, 7, 11, 12, 13]
arr = [4, 10, 3, 5, 1... | [
{
"docstring": null,
"function_declaration": "def min_heapify(arr, n, i):",
"function_name": "min_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def build_min_heap(arr):",
"function_name": "build_min_heap",
"parameter_list": "(arr)"
}... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_heapify(arr, n, i):\n # Find smallest among root and children\n smallest = i\n l = 2 * i + 1\n r = 2 * i + 2\n\n if l < n and arr[i] > arr[l]:\n smallest = l\n\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012155",
"row_id": 12155,
"seed_ids": "['Llama-3.3-70B-Instruct_31943']"
} | 0.589232 | Filter_12155 | I | [
"min_heapify",
"build_min_heap"
] | 2 | [
[
"build_min_heap",
"min_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 556353ecdacdf9ebfdc57ff1fb82e35673e9b1c0 | 9b509be0aef6e6d22376659c0c565aedf246b079 | |||
v1.0 | instruct | Filter | Filter_12178_I | Here's a family tree of 5 people: Alice, Bob, Carol, Dave, and Emily. Alice is the mother of Bob and Carol. Bob is the father of Dave. Carol is the mother of Emily.
Create a program that uses a dictionary to store the family relationships and then writes out the following to the console:
1. The mother of each person... | family = {
'Alice': {'mother': None, 'father': None, 'children': ['Bob', 'Carol']},
'Bob': {'mother': 'Alice', 'father': None, 'children': ['Dave']},
'Carol': {'mother': 'Alice', 'father': None, 'children': ['Emily']},
'Dave': {'mother': 'Carol', 'father': 'Bob', 'children': []},
'Emily': {'mother':... | def test_find_siblings():
family_tree = {
'Alice': {'mother': None, 'father': None, 'children': ['Bob', 'Carol']},
'Bob': {'mother': 'Alice', 'father': None, 'children': ['Dave']},
'Carol': {'mother': 'Alice', 'father': None, 'children': ['Emily']},
'Dave': {'mother': 'Carol', 'fathe... | [
{
"docstring": null,
"function_declaration": "def find_siblings(person, family_tree):",
"function_name": "find_siblings",
"parameter_list": "(person, family_tree)"
},
{
"docstring": null,
"function_declaration": "def print_family_relationships(family_tree):",
"function_name": "print_... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def print_family_relationships(family):\n for person, info in family.items():\n mother = info['mother'] or 'None'\n father = info['father'] or 'None'\n \n # Prin... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012178",
"row_id": 12178,
"seed_ids": "['Llama-3.3-70B-Instruct_31982']"
} | 0.512928 | Filter_12178 | I | [
"find_siblings",
"print_family_relationships"
] | 2 | [
[
"print_family_relationships",
"find_siblings"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | e62b7c81dc8be2e0b30958f02268d4b6df045b4b | 70ef3f20eab277dc7d5f36c51c5b7a20818a2544 | |||
v1.0 | instruct | Filter | Filter_12193_I | ### Task 3: Towers of Hanoi
The Towers of Hanoi is a classic problem in the field of Computer Science, and it's often used to demonstrate the power of recursion. The problem statement is as follows:
Given three rods (A, B, and C) and a number of disks of different sizes that can slide onto any rod, the objective is to ... | def towers_of_hanoi(n, source, target, auxiliary, moves):
"""
Solves the Towers of Hanoi problem and records each move.
Arguments:
n -- number of disks
source -- the rod where the disks are initially placed
target -- the rod where the disks need to be moved
auxiliary -- the auxiliary rod us... | from solution import solve_towers_of_hanoi
def test_towers_of_hanoi_1_disk():
moves = solve_towers_of_hanoi(1)
expected_moves = [(1, 'A', 'C')]
assert moves == expected_moves
def test_towers_of_hanoi_2_disks():
moves = solve_towers_of_hanoi(2)
expected_moves = [(1, 'A', 'B'), (2, 'A', 'C'), (1, 'B... | [
{
"docstring": "Solves the Towers of Hanoi problem and records each move.\n\nArguments:\nn -- number of disks\nsource -- the rod where the disks are initially placed\ntarget -- the rod where the disks need to be moved\nauxiliary -- the auxiliary rod used in the process\nmoves -- list to record each move as a tu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def towers_of_hanoi(n, source, destination, auxiliary, moves=None):\n \"\"\"\n Solves the Towers of Hanoi problem and returns a list of moves.\n \n Parameters:\n - n (int): The ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012193",
"row_id": 12193,
"seed_ids": "['Llama-3.3-70B-Instruct_32032']"
} | 0.518364 | Filter_12193 | I | [
"towers_of_hanoi",
"solve_towers_of_hanoi"
] | 2 | [
[
"solve_towers_of_hanoi",
"towers_of_hanoi"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 74519bc7a70f1de46d9afc750c771de7ab173db4 | a7e63becb7745e2e1d7728b282a692fb622d7313 | |||
v1.0 | instruct | Filter | Filter_12205_I | Here is the Python code:
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def find_path(root, path, k):
if root is None:
return False
path.append(root.value)
if root.value == k:
return True
if ((root.le... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def find_path(root, path, k):
if root is None:
return False
path.append(root.value)
if root.value == k:
return True
if ((root.left is not None and find_path(root.l... | def test_has_path_true():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
assert has_path(root, 5) == True
def test_has_path_false():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"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 find_path(root, path, k):\n if root is None:\n ret... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012205",
"row_id": 12205,
"seed_ids": "['Llama-3.3-70B-Instruct_32064']"
} | 0.502376 | Filter_12205 | I | [
"find_path",
"has_path",
"print_path"
] | 3 | [
[
"has_path",
"find_path"
],
[
"print_path",
"has_path"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | false | [] | true | c3f46817c21be86b6d6a14e6a8d4878b405a5c5b | c0ab780844318fb1272b7ca4e2d2ca1325401b16 | |||
v1.0 | instruct | Filter | Filter_12206_I | I am trying to implement an algorithm in Python that balances a binary search tree. I have the following code:
```
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def tree_height(node):
if node is None:
return 0
return 1 + max(t... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def tree_height(node):
if node is None:
return 0
return 1 + max(tree_height(node.left), tree_height(node.right))
def is_balanced(node):
if node is None:
return True
... | from solution import Node, tree_height, is_balanced, in_order_traversal, sorted_array_to_bst
# Utility function to create a tree from a list
def create_tree_from_list(values, root=None):
if not values:
return root
mid = len(values) // 2
root = Node(values[mid])
root.left = create_tree_from_list... | [] | [
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\n\ndef tree_height(node):\n if node is None:\n return 0... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012206",
"row_id": 12206,
"seed_ids": "['Llama-3.3-70B-Instruct_32067']"
} | 0.662381 | Filter_12206 | I | [
"tree_height",
"is_balanced",
"in_order_traversal",
"sorted_array_to_bst"
] | 4 | [
[
"is_balanced",
"tree_height"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | fa5431924fcd6ad6ff3b53796e73d0802c92e59a | 3e71fe670caf67f1b511d86c387c71d18e6df928 | |||
v1.0 | instruct | Filter | Filter_12211_I | I have a Python function `f(x)` that takes a numpy array `x` as input and returns a scalar value. I need to maximize this function over a bounded domain defined by `x_lower` and `x_upper`, which are also numpy arrays.
Can you provide a simple example of how to use scipy's minimize function to maximize my function `f(... | import numpy as np
from scipy.optimize import minimize
def f(x):
"""
Example function to be maximized: f(x) = -(x[0]**2 + x[1]**2)
This function achieves its maximum when x = [0, 0].
"""
return -(x[0]**2 + x[1]**2)
def maximize_function():
"""
Function to maximize f(x) using scipy.optimize... | from solution import maximize_function
import numpy as np
def test_maximize_function():
x_opt, max_val = maximize_function()
# Check if the optimal x is close to [0, 0] within some tolerance
assert np.allclose(x_opt, [0, 0], atol=1e-5)
# Check if the maximum value of f(x) is close to 0 within... | [
{
"docstring": "Example function to be maximized: f(x) = -(x[0]**2 + x[1]**2)\nThis function achieves its maximum when x = [0, 0].",
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": "Function to maximize f(x) using scipy.optimize.minimize b... | [
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\nfrom scipy.optimize import minimize\n\ndef f(x):\n \"\"\"\n Example function to maximize.\n Here, we use a simple quadratic function for demonstration.\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012211",
"row_id": 12211,
"seed_ids": "['Llama-3.3-70B-Instruct_32078']"
} | 0.492245 | Filter_12211 | I | [
"f",
"maximize_function"
] | 2 | [
[
"maximize_function",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 55325a730441bf6a3b075d8f4bb065d5eb3db88d | 5c60dac07877c739d54fb9c2716f9b816001fb0b | |||
v1.0 | instruct | Filter | Filter_12223_I | ### Introduction to Web Development
This is the first of a series of problems that will lead you through the process of building a web application. In this problem, you will learn how to handle HTTP requests and send responses using Python and the Flask web framework.
**Task 1:**
Write a Python function `hello_world`... | from flask import Flask, request
app = Flask(__name__)
def hello_world():
"""
Returns the string "Hello, World!".
"""
return "Hello, World!"
def hello_user(name):
"""
Returns the string "Hello, <name>!".
"""
return f"Hello, {name}!"
@app.route('/')
def root():
return hello_world(... | import pytest
from solution import hello_world, hello_user, app
def test_hello_world():
assert hello_world() == "Hello, World!"
def test_hello_user():
assert hello_user("Alice") == "Hello, Alice!"
assert hello_user("Bob") == "Hello, Bob!"
@pytest.fixture
def client():
with app.test_client() as client... | [
{
"docstring": "Returns the string \"Hello, World!\".",
"function_declaration": "def hello_world():",
"function_name": "hello_world",
"parameter_list": "()"
},
{
"docstring": "Returns the string \"Hello, <name>!\".",
"function_declaration": "def hello_user(name):",
"function_name": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request\n\napp = Flask(__name__)\n\ndef hello_world():\n \"\"\"\n Returns the string \"Hello, World!\".\n \"\"\"\n return \"Hello, World!\"\n\ndef hello_us... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012223",
"row_id": 12223,
"seed_ids": "['Llama-3.3-70B-Instruct_32118']"
} | 0.604502 | Filter_12223 | I | [
"hello_world",
"hello_user",
"root",
"user"
] | 4 | [
[
"root",
"hello_world"
],
[
"user",
"hello_user"
]
] | 2 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 14dc7be35298f2f63cbc696483070b84d85a56dc | 503283faa8303e1432e314c872ef8947d984a3e3 | |||
v1.0 | instruct | Filter | Filter_12225_I | I have to find all the symmetric matrices in a list of matrices, and I need a helper function to check if a matrix is symmetric. But I don't know how to get the transpose of a matrix in Python.
How can I use Python with the NumPy library to get the transpose of a matrix? | import numpy as np
def is_symmetric(matrix):
"""
Checks if a given matrix is symmetric.
A matrix is symmetric if it is equal to its transpose.
Parameters:
matrix (np.ndarray): A square numpy matrix to check for symmetry.
Returns:
bool: True if the matrix is symmetric, False otherw... | from solution import is_symmetric, find_symmetric_matrices
import numpy as np
def test_is_symmetric_true():
matrix = np.array([[1, 2, 3],
[2, 5, 6],
[3, 6, 9]])
assert is_symmetric(matrix) == True
def test_is_symmetric_false():
matrix = np.array([[1, 2, 3], ... | [
{
"docstring": "Checks if a given matrix is symmetric.\nA matrix is symmetric if it is equal to its transpose.\n\nParameters:\nmatrix (np.ndarray): A square numpy matrix to check for symmetry.\n\nReturns:\nbool: True if the matrix is symmetric, False otherwise.",
"function_declaration": "def is_symmetric(ma... | [
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 is_symmetric(matrix):\n \"\"\"\n Determines whether a given matrix is symmetric.\n \n Args:\n matrix (np.ndarray): 2D numpy array representing the ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012225",
"row_id": 12225,
"seed_ids": "['Llama-3.3-70B-Instruct_32123']"
} | 0.464495 | Filter_12225 | I | [
"is_symmetric",
"find_symmetric_matrices"
] | 2 | [
[
"find_symmetric_matrices",
"is_symmetric"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | c67089c19e91bfd5e81f20b7496ba68321e86e52 | 07088686f7458d8a603d03b3cecc5d61718ecef3 | |||
v1.0 | instruct | Filter | Filter_12247_I | Here's a quick summary of what I want:
I have a lot of JSON files in a folder.
I want to write a Python app that will allow me to query/filter these JSON files based on certain conditions.
Here's a more detailed breakdown:
- There is a folder named "data" which contains all my JSON files.
- Each JSON file has the s... | import os
import json
def operator_check(value1, operator, value2):
"""
Utility function to apply the comparison operator for filtering.
"""
if operator == "==":
return value1 == value2
elif operator == "!=":
return value1 != value2
elif operator == ">":
return value1 > ... | import os
import json
import pytest
from solution import query_json_files, operator_check
# Mock data directory for testing
@pytest.fixture
def mock_data_directory(tmp_path):
data = [
{"id": "1", "name": "John Doe", "age": 30, "city": "New York", "country": "USA"},
{"id": "2", "name": "Jane Smith",... | [
{
"docstring": "Utility function to apply the comparison operator for filtering.",
"function_declaration": "def operator_check(value1, operator, value2):",
"function_name": "operator_check",
"parameter_list": "(value1, operator, value2)"
},
{
"docstring": "Reads all JSON files in the specifi... | [
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 json\nfrom typing import List, Dict, Any, Callable\n\ndef load_json_files(directory: str) -> List[Dict[str, Any]]:\n \"\"\"\n Loads all JSON files from the specified di... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012247",
"row_id": 12247,
"seed_ids": "['Llama-3.3-70B-Instruct_32165']"
} | 0.673038 | Filter_12247 | I | [
"operator_check",
"load_json_files",
"query_json_files"
] | 3 | [
[
"query_json_files",
"load_json_files"
],
[
"query_json_files",
"operator_check"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7ddd7974b670a9c0a7466282f71717f60a4c2e5c | 95e8aae0801cad8465cc1e7f2e775423f21cc69c | |||
v1.0 | instruct | Filter | Filter_12251_I | Given a binary tree, find the lowest common ancestor (LCA) of two nodes.
### Example Use Cases
* `lca(root, [2, 3])` should return `1`
* `lca(root, [4, 5])` should return `2`
* `lca(root, [4, 1])` should return `1`
### Definition
A binary tree is a tree-like structure in which each node has at most two children (i.e... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def find_path(root, path, k):
"""
Helper function to find the path from the root node to the given node k.
If the node is found, it returns True; otherwise, it returns False.
"""
... | from solution import Node, lca
def test_lca_case1():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
assert lca(root, [2, 3]) == 1
def test_lca_case2():
root = 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 find_path(root, path, k):\n \"\"\"\n Helper function t... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012251",
"row_id": 12251,
"seed_ids": "['Llama-3.3-70B-Instruct_32170']"
} | 0.526737 | Filter_12251 | I | [
"find_path",
"lca"
] | 2 | [
[
"lca",
"find_path"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | c5a06b36e2218e5ca9b9a6649fd052b6fad29127 | 7870f32a2469d3192ca8836bdbb695b8df73aec1 | |||
v1.0 | instruct | Filter | Filter_12290_I | How to create a Python program to find the first 10 prime numbers?
The program should be able to identify prime numbers by checking if a number has any divisors.
The required functionality is to print the first 10 prime numbers. | def is_prime(n):
"""
Returns True if n is a prime number, otherwise returns False.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def first_n_primes(n):
"""
Returns the first n prime numbers as a list.
... | from solution import is_prime, first_n_primes, first_10_primes
def test_is_prime():
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert is_prime(29)
assert not is_prime(30)
def test_first_n_primes():
assert first_n_primes(0) == ... | [
{
"docstring": "Returns True if n is a prime number, otherwise returns False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the first n prime numbers as a list.",
"function_declaration": "def first_n_primes(n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012290",
"row_id": 12290,
"seed_ids": "['Llama-3.3-70B-Instruct_32277']"
} | 0.654509 | Filter_12290 | I | [
"is_prime",
"first_n_primes",
"first_10_primes"
] | 3 | [
[
"first_10_primes",
"first_n_primes"
],
[
"first_n_primes",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 57688746d8e083a3932f26b50968b6e4d55fdac8 | e3103a96af0129494a08376c88858b281de386fd | |||
v1.0 | instruct | Filter | Filter_12304_I | Here is a Python script that encodes and decodes a string using a Caesar cipher:
```python
import string
import random
def encode(text, shift):
result = ""
for char in text:
if char in string.ascii_letters:
ascii_offset = string.ascii_lowercase.index('a') if char.islower() else string.ascii... | import string
import random
import unicodedata
# Define unique code points for each language support
language_code_points = {
'en': [(0x41, 0x5A), (0x61, 0x7A)], # English: A-Z, a-z
'el': [(0x391, 0x3A9), (0x3B1, 0x3C9)], # Greek: Α-Ω, α-ω
'ru': [(0x410, 0x42F), (0x430, 0x44F)], # Cyrillic: А-Я, а-я
}
... | from solution import encode, decode
import random
def test_encode_decode_english():
text = "Hello, World!"
shift = random.randint(1, 25)
encoded_text = encode(text, shift, 'en')
decoded_text = decode(encoded_text, shift, 'en')
assert decoded_text == text
def test_encode_decode_greek():
text = ... | [
{
"docstring": null,
"function_declaration": "def shift_char(char, shift, code_points):",
"function_name": "shift_char",
"parameter_list": "(char, shift, code_points)"
},
{
"docstring": null,
"function_declaration": "def encode(text, shift, lang_code='en'):",
"function_name": "encode... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import string\nimport random\nimport unicodedata\n\n# Define unique code points for each language support\nlanguage_code_points = {\n 'en': [(0x41, 0x5A), (0x61, 0x7A)], # English: A-Z, a-... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012304",
"row_id": 12304,
"seed_ids": "['Llama-3.3-70B-Instruct_32308']"
} | 0.575938 | Filter_12304 | I | [
"shift_char",
"encode",
"decode",
"main"
] | 4 | [
[
"decode",
"encode"
],
[
"encode",
"shift_char"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 296005322a88f15944bf8f3c41718f8e755fad1c | df0dc549e8a6160dcfe40e647806bf2915779439 | |||
v1.0 | instruct | Filter | Filter_12318_I | I would like to know how to write a simple parser for a simple language that can handle the following grammar:
```
S -> A
S -> B
A -> a A
A -> a
B -> b B
B -> b
```
This is a simple language where `S` is the start symbol, `A` and `B` are non-terminals, and `a` and `b` are terminals.
The parser should be recursive des... | def parse_S(input_str):
return parse_A(input_str) or parse_B(input_str)
def parse_A(input_str):
if len(input_str) > 0 and input_str[0] == 'a':
# If 'a' is found, we need to check the rest part of the string
if len(input_str) == 1:
return True
else:
return parse_A... | from solution import parse_S, parse_A, parse_B
def test_empty_string():
assert not parse_S("")
def test_single_a():
assert parse_S("a")
def test_single_b():
assert parse_S("b")
def test_sequence_of_as():
assert parse_S("a" * 10)
def test_sequence_of_bs():
assert parse_S("b" * 10)
def test_mixe... | [
{
"docstring": null,
"function_declaration": "def parse_S(input_str):",
"function_name": "parse_S",
"parameter_list": "(input_str)"
},
{
"docstring": null,
"function_declaration": "def parse_A(input_str):",
"function_name": "parse_A",
"parameter_list": "(input_str)"
},
{
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def parse_S(input_str):\n \"\"\"\n Parses the input string according to the grammar: S -> A | B\n \"\"\"\n return parse_A(input_str) or parse_B(input_str)\n\ndef parse_A(input_str)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012318",
"row_id": 12318,
"seed_ids": "['Llama-3.3-70B-Instruct_32341']"
} | 0.531104 | Filter_12318 | I | [
"parse_S",
"parse_A",
"parse_B"
] | 3 | [
[
"parse_S",
"parse_A"
],
[
"parse_S",
"parse_B"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 850b146a6a892c9827e5174e25d82c7c3dc55133 | a0facb6b732968b4f086c571a81a7cb6548e6f37 | |||
v1.0 | instruct | Filter | Filter_12320_I | I have a webpage that contains several links. I want to write a python script that fetches the webpage, finds all links on the webpage, and then follows each link to see if it is broken or not.
Here's a basic idea of how I think I should approach this
1. Send an HTTP GET request to the webpage.
2. Parse the HTML resp... | import requests
from bs4 import BeautifulSoup
def fetch_webpage_links(url):
"""
Fetches the webpage and returns a list of all links found on the page.
Parameters:
url (str): The URL of the webpage to fetch.
Returns:
list: A list of URLs found on the webpage.
"""
response = request... | from solution import fetch_webpage_links, check_link_status, find_broken_links
from unittest.mock import patch
def test_fetch_webpage_links():
with patch('requests.get') as mock_get:
mock_response = mock_get.return_value
mock_response.text = """
<html>
<body>
<a ... | [
{
"docstring": "Fetches the webpage and returns a list of all links found on the page.\n\nParameters:\nurl (str): The URL of the webpage to fetch.\n\nReturns:\nlist: A list of URLs found on the webpage.",
"function_declaration": "def fetch_webpage_links(url):",
"function_name": "fetch_webpage_links",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom bs4 import BeautifulSoup\n\ndef check_links(url):\n \"\"\"\n Fetches a webpage and checks all the links on that page to see if they are broken.\n \n Parameter... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012320",
"row_id": 12320,
"seed_ids": "['Llama-3.3-70B-Instruct_32343']"
} | 0.67113 | Filter_12320 | I | [
"fetch_webpage_links",
"check_link_status",
"find_broken_links"
] | 3 | [
[
"find_broken_links",
"check_link_status"
],
[
"find_broken_links",
"fetch_webpage_links"
]
] | 2 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | ea829e7bb9675f6c6e9e7a3b9b6fe46d2ab917de | d2afa6f35418613baf04773cc4c9b11b4b1c6c9a | |||
v1.0 | instruct | Filter | Filter_12336_I | ### Question 1: How would you model the chaotic behavior of a double pendulum using Python?
To model the chaotic behavior of a double pendulum using Python, we will use the following steps:
- Define the equations of motion for the double pendulum.
- Use the `scipy.integrate.odeint` function to solve these equations.
-... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def equations(y, t, L1, L2, m1, m2):
g = 9.81
theta1, z1, theta2, z2 = y
cos, sin = np.cos(theta1 - theta2), np.sin(theta1 - theta2)
theta1_dot = z1
z1_dot = (m2 * g * np.sin(theta2) * cos - m2 * sin * (L1 * ... | import numpy as np
from solution import equations, solve_double_pendulum
def test_equations_output_shape():
y = [np.pi / 4, 0, np.pi / 6, 0]
t = 0
result = equations(y, t, 1.0, 1.0, 1.0, 1.0)
assert len(result) == 4
def test_solve_double_pendulum_output_shape():
t, sol = solve_double_pendulum(np.p... | [
{
"docstring": null,
"function_declaration": "def equations(y, t, L1, L2, m1, m2):",
"function_name": "equations",
"parameter_list": "(y, t, L1, L2, m1, m2)"
},
{
"docstring": null,
"function_declaration": "def solve_double_pendulum(theta1, theta2, L1=1.0, L2=1.0, m1=1.0, m2=1.0, t_max=2... | [
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 double_pendulum_derivatives(y, t, L1, L2, m1, m2, g):\n theta1, z1, theta2, z2 = y\n cos_de... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012336",
"row_id": 12336,
"seed_ids": "['Llama-3.3-70B-Instruct_32372']"
} | 0.349592 | Filter_12336 | I | [
"equations",
"solve_double_pendulum",
"plot_double_pendulum_solution"
] | 3 | [
[
"plot_double_pendulum_solution",
"solve_double_pendulum"
],
[
"solve_double_pendulum",
"equations"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 773c4f36f6cda4fcd8d8376b40dc760a2b3d6fa3 | ec8362f53d0b477a76524ff3334420f5a499accc | |||
v1.0 | instruct | Filter | Filter_12356_I | I see that you can use Python to create text-adventure games. Can you show me an example of how you can create a simple text-adventure game using Python? | def start_game():
"""
Starts the text-adventure game.
"""
print("Welcome to the Adventure Game!")
name = input("Enter your name: ")
print(f"Hello, {name}. You find yourself in a dark forest.")
choice = input("Do you go left (1) or right (2)? Please enter 1 or 2: ")
if choice == "1":... | import pytest
from solution import start_game, encounter_bear, find_treasure
def test_encounter_bear_run(monkeypatch):
inputs = iter(["1"])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
encounter_bear("TestPlayer")
assert True # Outputs are printed to console, impossible to capture in ... | [
{
"docstring": "Starts the text-adventure game.",
"function_declaration": "def start_game():",
"function_name": "start_game",
"parameter_list": "()"
},
{
"docstring": "Function for the bear encounter scenario.",
"function_declaration": "def encounter_bear(name):",
"function_name": "e... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_game():\n \"\"\"\n Starts the text-adventure game.\n \"\"\"\n print(\"Welcome to the Adventure Game!\")\n name = input(\"Enter your name: \")\n print(f\"Hello, {nam... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012356",
"row_id": 12356,
"seed_ids": "['Llama-3.3-70B-Instruct_32414']"
} | 0.424873 | Filter_12356 | I | [
"start_game",
"encounter_bear",
"find_treasure"
] | 3 | [
[
"start_game",
"encounter_bear"
],
[
"start_game",
"find_treasure"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8818b0835ee39abc901e7470748f5fc0cc240889 | 48674dd09b3e18b0da86d7ab515369937c512d3c | |||
v1.0 | instruct | Filter | Filter_12361_I | I understand that neither you nor I can access external websites. But I can provide the text and information I want analyzed.
I have a collection of codes that are supposed to be in a specific format, and I would like to create a script to find the codes that are not in the correct format.
The format of the codes a... | def validate_code(code):
"""
Validates a single code based on the given criteria.
"""
if not isinstance(code, str):
return False
if len(code) != 9:
return False
if not code[:2].isalpha():
return False
if not code.isalnum():
return False
return True
def fi... | from solution import validate_code, find_invalid_codes
def test_validate_code_valid():
assert validate_code("AB1234567") == True
assert validate_code("XY9876543") == True
def test_validate_code_invalid_length():
assert validate_code("AB123456") == False
assert validate_code("A123456789") == False
def... | [
{
"docstring": "Validates a single code based on the given criteria.",
"function_declaration": "def validate_code(code):",
"function_name": "validate_code",
"parameter_list": "(code)"
},
{
"docstring": "Identifies all invalid codes from a list of codes.",
"function_declaration": "def fin... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef validate_codes(codes):\n \"\"\"\n Validates a list of codes against specific format rules:\n 1. The code starts with two alphabetic characters.\n 2. The code is ex... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012361",
"row_id": 12361,
"seed_ids": "['Llama-3.3-70B-Instruct_32422']"
} | 0.510121 | Filter_12361 | I | [
"validate_code",
"find_invalid_codes"
] | 2 | [
[
"find_invalid_codes",
"validate_code"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c465cd2207d74fb78f2a18d27d64e07a7dd8903 | dba191f98711c3db2790538b906ec7a5d9d45965 | |||
v1.0 | instruct | Filter | Filter_12367_I | I have a list of items, and each item is either "cat" or "dog". I also have a function that returns the number of cats and dogs in the list. How can I use a list comprehension to create a new list that contains the results of this function for each item in the list? | def count_animals(animal_list):
"""
Returns a tuple with the count of "cat" and "dog" in the animal_list.
"""
cats = sum(1 for animal in animal_list if animal == "cat")
dogs = sum(1 for animal in animal_list if animal == "dog")
return cats, dogs
def animal_counts_in_items(items):
"""
Fo... | from solution import count_animals, animal_counts_in_items
def test_count_animals():
assert count_animals(["cat", "dog", "cat", "dog", "dog"]) == (2, 3)
assert count_animals(["cat", "cat", "cat"]) == (3, 0)
assert count_animals(["dog", "dog", "dog"]) == (0, 3)
assert count_animals(["cat", "dog"]) == (1... | [
{
"docstring": "Returns a tuple with the count of \"cat\" and \"dog\" in the animal_list.",
"function_declaration": "def count_animals(animal_list):",
"function_name": "count_animals",
"parameter_list": "(animal_list)"
},
{
"docstring": "For each item in items, return the count of \"cat\" an... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_cats_and_dogs(items):\n \"\"\"\n Counts the number of 'cat' and 'dog' in the provided list.\n \n Args:\n items (list): A list of strings with either \"cat\" or \"dog\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012367",
"row_id": 12367,
"seed_ids": "['Llama-3.3-70B-Instruct_32434']"
} | 0.500411 | Filter_12367 | I | [
"count_animals",
"animal_counts_in_items"
] | 2 | [
[
"animal_counts_in_items",
"count_animals"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c715ad76066f484665a27d48cb7a811c458d4caa | c441913487d393a594af6245c57e16edf16e952d | |||
v1.0 | instruct | Filter | Filter_12401_I | Your task is to write a program that prints all the prime numbers between 1 and n.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
For example, given the following inputs:
- n = 10, the output will be: [2, 3, 5, 7]
- n = 20, the output will be: [2, 3, 5, 7, 1... | def is_prime(num):
"""
Helper function to determine if a number is prime.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
return True
d... | from solution import is_prime, prime_numbers_up_to
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(11) == True
assert is_prime(25) == False
assert is_prime(29) =... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers up to and including n.",
"function_declaration": "def prime_num... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(number):\n if number <= 1:\n return False\n if number == 2:\n return True\n if number % 2 == 0:\n return False\n for i in range(3, int(number**0.5... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012401",
"row_id": 12401,
"seed_ids": "['Llama-3.3-70B-Instruct_32513']"
} | 0.657115 | Filter_12401 | I | [
"is_prime",
"prime_numbers_up_to"
] | 2 | [
[
"prime_numbers_up_to",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 28318a902bce78364b9d822fdd7904afa92d2258 | 1f69bad9cdc104288620f983427ad85c0daa61e2 | |||
v1.0 | instruct | Filter | Filter_12414_I | I'm a software engineer, and I've been tasked with building a simple web application using Python and the Flask framework. The application needs to have the following endpoints:
1. A GET endpoint for retrieving all users.
2. A POST endpoint for creating a new user.
3. A GET endpoint for retrieving a user by ID.
4. A P... | from flask import Flask, request, jsonify, abort
app = Flask(__name__)
# In-memory storage for users
users = []
# Helper function to find user by ID
def find_user(user_id):
return next((user for user in users if user['id'] == user_id), None)
@app.route('/users', methods=['GET'])
def get_users():
return json... | import pytest
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_get_users(client):
response = client.get('/users')
assert response.status_code == 200
assert response.get_json() == []
def test_create_user(client):
new_user = {'id... | [
{
"docstring": null,
"function_declaration": "def find_user(user_id):",
"function_name": "find_user",
"parameter_list": "(user_id)"
},
{
"docstring": null,
"function_declaration": "def get_users():",
"function_name": "get_users",
"parameter_list": "()"
},
{
"docstring": n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify, abort\n\napp = Flask(__name__)\n\n# In-memory storage for users\nusers = []\n\n# Helper function to find user by ID\ndef find_user(user_id):\n ret... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012414",
"row_id": 12414,
"seed_ids": "['Llama-3.3-70B-Instruct_32539']"
} | 0.478221 | Filter_12414 | I | [
"find_user",
"get_users",
"create_user",
"get_user_by_id",
"update_user",
"delete_user"
] | 6 | [
[
"create_user",
"find_user"
],
[
"delete_user",
"find_user"
],
[
"get_user_by_id",
"find_user"
],
[
"update_user",
"find_user"
]
] | 4 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 877232ba8e022bf53ea6c2b9c67a3feeeebbd8d5 | ac172c01750655c9c58fbfd4380dfd31a7f6b6dd | |||
v1.0 | instruct | Filter | Filter_12460_I | I've got 2 massive XML files that I want to compare. Each file has the same structure and contains the same elements, but with potentially different values. I'm looking to identify the differences between the two files. I'm thinking of using Python and the `xml.etree.ElementTree` module. Can you provide me with a code ... | import xml.etree.ElementTree as ET
def compare_xml_elements(elem1, elem2, path=""):
"""
Compares two XML elements and returns the differences.
:param elem1: First XML element.
:param elem2: Second XML element.
:param path: The path of the current element in the XML.
:return: List of differ... | import xml.etree.ElementTree as ET
from solution import compare_xml_files
def test_compare_xml_files_identical():
xml_content1 = """<root>
<child attribute="value">Text</child>
</root>"""
xml_content2 = """<root>
<child attribute="value">Te... | [
{
"docstring": "Compares two XML elements and returns the differences.\n\n:param elem1: First XML element.\n:param elem2: Second XML element.\n:param path: The path of the current element in the XML.\n:return: List of differences.",
"function_declaration": "def compare_xml_elements(elem1, elem2, path=''):",... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\n\ndef compare_xml_elements(element1, element2):\n \"\"\"\n Recursively compares two XML elements and returns the differences.\n \"\"\"\n differe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012460",
"row_id": 12460,
"seed_ids": "['Llama-3.3-70B-Instruct_32637']"
} | 0.513815 | Filter_12460 | I | [
"compare_xml_elements",
"compare_xml_files"
] | 2 | [
[
"compare_xml_files",
"compare_xml_elements"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50e8f97ec4cc972c5437813a63aa1a46141d0249 | af6a63c61b86c8e5542f37e1d4b87f929beb703e | |||
v1.0 | instruct | Filter | Filter_12478_I | I've made a program to detect DDoS attacks from an Apache access log file. I want to detect if the number of requests from any IP is exceeding a certain limit within a time frame.
Here's my Python code:
```python
import re
from collections import defaultdict
from datetime import datetime
import sys
# Initialize a di... | import re
from collections import defaultdict, deque
from datetime import datetime
# Initialize variables
log_path = 'access.log'
time_frame = 60 # 1 minute in seconds
threshold = 100 # 100 requests
# Compile the regular expression to match IP addresses and log timestamp
log_pattern = re.compile(r'(\d{1,3}\.\d{1,3}... | import pytest
from solution import parse_log
def test_no_ddos_detected(tmp_path):
log_file = tmp_path / "access.log"
log_file.write_text("192.168.1.1 - - [06/Sep/2022:00:00:00 +0000] \"GET / HTTP/1.1\" 200 1234\n" * 50)
assert parse_log(log_file, 60, 100) == set()
def test_ddos_detected(tmp_path):
... | [
{
"docstring": null,
"function_declaration": "def parse_log(log_path, time_frame, threshold):",
"function_name": "parse_log",
"parameter_list": "(log_path, time_frame, threshold)"
},
{
"docstring": null,
"function_declaration": "def detect_ddos(log_path, time_frame, threshold):",
"fu... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import defaultdict, deque\nfrom datetime import datetime, timedelta\nimport sys\n\n# Initialize a dict to keep track of IP addresses and their timestamps\nip_reques... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012478",
"row_id": 12478,
"seed_ids": "['Llama-3.3-70B-Instruct_32671']"
} | 0.600359 | Filter_12478 | I | [
"parse_log",
"detect_ddos",
"main"
] | 3 | [
[
"detect_ddos",
"parse_log"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8812aab51f261074c3854e12591ef7c7e6bedf3 | a243dd7bc4d4b6f43b8bc1703c760daad69274b7 | |||
v1.0 | instruct | Filter | Filter_12485_I | I would like to create a program that filters through email addresses and removes duplicates. I would like to send each email address to a specific function based on the domain. What is the best way to accomplish this? | def filter_emails(email_list):
"""
Filters through email addresses and removes duplicates.
"""
return list(set(email_list))
def send_email_to_function_based_on_domain(email_list, domain_function_mapping):
"""
Sends each email address to a specific function based on the domain.
:param e... | from solution import filter_emails, send_email_to_function_based_on_domain
def test_filter_emails():
emails = ["test@example.com", "user@test.com", "test@example.com"]
assert set(filter_emails(emails)) == set(["test@example.com", "user@test.com"])
def mock_function(email):
mock_function.call_count += 1
mo... | [
{
"docstring": "Filters through email addresses and removes duplicates.",
"function_declaration": "def filter_emails(email_list):",
"function_name": "filter_emails",
"parameter_list": "(email_list)"
},
{
"docstring": "Sends each email address to a specific function based on the domain.\n\n:p... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def filter_emails(email_list):\n \"\"\"\n Filters through email addresses, removes duplicates, and routes each email to a specific function based on the domain.\n \n :param email_l... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012485",
"row_id": 12485,
"seed_ids": "['Llama-3.3-70B-Instruct_32688']"
} | 0.442393 | Filter_12485 | I | [
"filter_emails",
"send_email_to_function_based_on_domain"
] | 2 | [
[
"send_email_to_function_based_on_domain",
"filter_emails"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ed48f5a26ce30e1507ef8ab98cf44dc2020a665 | 49ca81f750355a02825a150cfd5ea2034e85c128 | |||
v1.0 | instruct | Filter | Filter_12506_I | I need a program that will simulate a coin flip and return the results in a chart that shows the number of heads and tails after a certain number of flips.
Here is a sample of what the output should look like:
```
Flip Results:
+----------+--------+--------+
| Flips | Heads | Tails |
+----------+--------+-------... | import random
def coin_flip(flips):
heads = 0
tails = 0
for _ in range(flips):
if random.choice([0, 1]) == 0:
heads += 1
else:
tails += 1
return heads, tails
def simulate_trials(num_trials, flips):
total_heads = 0
total_tails = 0
for _ in range(num_t... | from solution import coin_flip, simulate_trials
def test_coin_flip():
heads, tails = coin_flip(100)
assert heads + tails == 100
def test_simulate_trials():
avg_heads, avg_tails = simulate_trials(1000, 100)
assert abs(avg_heads + avg_tails - 100) < 1
def test_simulate_trials_large():
avg_heads, av... | [
{
"docstring": null,
"function_declaration": "def coin_flip(flips):",
"function_name": "coin_flip",
"parameter_list": "(flips)"
},
{
"docstring": null,
"function_declaration": "def simulate_trials(num_trials, flips):",
"function_name": "simulate_trials",
"parameter_list": "(num_t... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef coin_flip(flips):\n heads = 0\n tails = 0\n for _ in range(flips):\n if random.choice([0, 1]) == 0:\n heads += 1\n else:\n tai... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012506",
"row_id": 12506,
"seed_ids": "['Llama-3.3-70B-Instruct_32732']"
} | 0.617389 | Filter_12506 | I | [
"coin_flip",
"simulate_trials",
"print_results_table"
] | 3 | [
[
"print_results_table",
"simulate_trials"
],
[
"simulate_trials",
"coin_flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6f3ea404c319cd102c0b17f01ecfa3b2d203ffbf | 4ce8836a3dbe3a8e28da7aca961b7ad2b6454638 | |||
v1.0 | instruct | Filter | Filter_12510_I | Here is a code snippet:
```python
def get_inputs():
"""Get user input for name, email, and phone number."""
name = input("Enter your name: ")
email = input("Enter your email: ")
phone_number = input("Enter your phone number: ")
return name, email, phone_number
def process_data(name, email, phone_nu... | import re
def get_inputs():
"""Get user input for name, email, and phone number."""
name = input("Enter your name: ")
email = input("Enter your email: ")
phone_number = input("Enter your phone number: ")
return name, email, phone_number
def validate_email(email):
"""Validate the email format u... | import pytest
from solution import process_data, validate_email, validate_phone
def test_validate_email():
assert validate_email("test@example.com")
assert not validate_email("test@")
assert not validate_email("test@example")
assert not validate_email("test.example.com")
assert validate_email("user... | [
{
"docstring": "Get user input for name, email, and phone number.",
"function_declaration": "def get_inputs():",
"function_name": "get_inputs",
"parameter_list": "()"
},
{
"docstring": "Validate the email format using a regular expression.",
"function_declaration": "def validate_email(em... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef get_inputs():\n \"\"\"Get user input for name, email, and phone number.\"\"\"\n name = input(\"Enter your name: \")\n email = input(\"Enter your email: \")\n phone... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012510",
"row_id": 12510,
"seed_ids": "['Llama-3.3-70B-Instruct_32739']"
} | 0.472532 | Filter_12510 | I | [
"get_inputs",
"validate_email",
"validate_phone",
"process_data"
] | 4 | [
[
"process_data",
"validate_email"
],
[
"process_data",
"validate_phone"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 46714e147db207e0ecf91ff04f95d9b2d0284cf7 | abf4733c71df6dd9a20e8ce18010333d587774a0 | |||
v1.0 | instruct | Filter | Filter_12544_I | I have a text file that contains a list of strings, and I want to write a Python script that will find the longest common prefix among all the strings in the file.
Here are the details:
1. The file is named `strings.txt`.
2. The file contains only one string per line.
3. All the strings in the file are lowercase Engl... | def longest_common_prefix(strings):
"""
Find the longest common prefix among a list of strings.
"""
if not strings:
return ""
prefix = strings[0]
for s in strings[1:]:
while s[:len(prefix)] != prefix and prefix:
prefix = prefix[:len(prefix)-1]
return pr... | from solution import longest_common_prefix, read_file_and_find_prefix
import tempfile
def test_longest_common_prefix():
assert longest_common_prefix(["banana", "bandana", "bangladesh", "banger"]) == "ban"
assert longest_common_prefix(["apple", "ape", "apricot"]) == "ap"
assert longest_common_prefix(["flowe... | [
{
"docstring": "Find the longest common prefix among a list of strings.",
"function_declaration": "def longest_common_prefix(strings):",
"function_name": "longest_common_prefix",
"parameter_list": "(strings)"
},
{
"docstring": null,
"function_declaration": "def read_file_and_find_prefix(... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_common_prefix(strs):\n \"\"\"\n Returns the longest common prefix in a list of strings.\n \"\"\"\n if not strs:\n return \"\"\n \n # The prefix starts as t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012544",
"row_id": 12544,
"seed_ids": "['Llama-3.3-70B-Instruct_32817']"
} | 0.704588 | Filter_12544 | I | [
"longest_common_prefix",
"read_file_and_find_prefix"
] | 2 | [
[
"read_file_and_find_prefix",
"longest_common_prefix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd7c1f30078f496cb072333faf4259edf5b2a62d | e0bb7814476e5e4b40fe4d7081ed0abc9dd814f6 | |||
v1.0 | instruct | Filter | Filter_12563_I | Here is a code that converts an integer to binary, octal, and hexadecimal string representations:
```python
def convert_to_base(number, base):
convertString = "0123456789ABCDEF"
if number < base:
return convertString[number]
else:
return convert_to_base(number // base, base) + convertString... | def convert_to_base(number, base):
convertString = "0123456789ABCDEF"
if number < base:
return convertString[number]
else:
return convert_to_base(number // base, base) + convertString[number % base]
def int_to_base(number):
return convert_to_base(number, 2), convert_to_base(number, 8), ... | from solution import int_to_base
def test_int_to_base_10():
assert int_to_base(10) == ('1010', '12', 'A')
def test_int_to_base_255():
assert int_to_base(255) == ('11111111', '377', 'FF')
def test_int_to_base_0():
assert int_to_base(0) == ('0', '0', '0')
def test_int_to_base_1():
assert int_to_base(1... | [
{
"docstring": null,
"function_declaration": "def convert_to_base(number, base):",
"function_name": "convert_to_base",
"parameter_list": "(number, base)"
},
{
"docstring": null,
"function_declaration": "def int_to_base(number):",
"function_name": "int_to_base",
"parameter_list": ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "[Solution Code in Python]",
"test_code": "[Unit Test Code in Python]",
"test_coverage": null,
"test_result": "Fail"
},
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012563",
"row_id": 12563,
"seed_ids": "['Llama-3.3-70B-Instruct_32858']"
} | 0.681434 | Filter_12563 | I | [
"convert_to_base",
"int_to_base"
] | 2 | [
[
"int_to_base",
"convert_to_base"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b9d7b9d408d5611235369fa77952a95447d08b0 | d3c82a361b718fd507b22100e8e86b1675846f95 | |||
v1.0 | instruct | Filter | Filter_12573_I | I have a Python script that is used to monitor the temperature of a server. I need to help to add a feature that sends an email to the system administrator when the temperature exceeds a certain threshold. | import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to):
"""
Sends an email with the given subject and body to the specified recipient.
"""
from_email = "your_email@example.com"
from_password = "your_password"
msg = MIMEText(body)
msg['Subject'] = subject
... | import pytest
from unittest.mock import patch
from solution import monitor_temperature, send_email
def test_monitor_temperature_above_threshold():
temp = 85
threshold = 80
email = "admin@example.com"
with patch('solution.send_email') as mock_send_email:
monitor_temperature(temp, threshold,... | [
{
"docstring": "Sends an email with the given subject and body to the specified recipient.",
"function_declaration": "def send_email(subject, body, to):",
"function_name": "send_email",
"parameter_list": "(subject, body, to)"
},
{
"docstring": "Monitors the temperature and sends an email if ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.text import MIMEText\n\ndef send_email(subject, body, to_email):\n \"\"\"\n Sends an email with the given subject and body to the specified email address.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012573",
"row_id": 12573,
"seed_ids": "['Llama-3.3-70B-Instruct_32879']"
} | 0.424702 | Filter_12573 | I | [
"send_email",
"monitor_temperature"
] | 2 | [
[
"monitor_temperature",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e00a9064cb4201372819ef404affcde386bae35a | 571fe6700b247b9ac062e8a1efe784439a294128 | |||
v1.0 | instruct | Filter | Filter_12591_I | How can I use a programming language to simulate the behavior of a chaotic system, such as the Lorenz attractor, using the Lorenz equations? | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def lorenz(X, t, sigma, rho, beta):
"""
The Lorenz equations.
Parameters:
X : list or array
The current state of the system [x, y, z].
t : float
The current time step.
sigma, rho, beta : f... | from solution import lorenz, simulate_lorenz
import numpy as np
def test_lorenz():
X = [1.0, 1.0, 1.0]
t = 0
sigma = 10
rho = 28
beta = 8/3
dxdt, dydt, dzdt = lorenz(X, t, sigma, rho, beta)
assert isinstance(dxdt, float)
assert isinstance(dydt, float)
assert isinstance(dzdt, float)
... | [
{
"docstring": "The Lorenz equations.\n\nParameters:\nX : list or array\n The current state of the system [x, y, z].\nt : float\n The current time step.\nsigma, rho, beta : float\n The parameters of the Lorenz system.\n \nReturns:\nlist or array\n The derivatives [dx/dt, dy/dt, dz/dt].",
"fun... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\n\ndef lorenz_attractor(state, t, sigma, rho, beta):\n \"\"\"\n Computes the derivatives for the L... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012591",
"row_id": 12591,
"seed_ids": "['Llama-3.3-70B-Instruct_32905']"
} | 0.256615 | Filter_12591 | I | [
"lorenz",
"simulate_lorenz"
] | 2 | [
[
"simulate_lorenz",
"lorenz"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 95b90d11a98eca99e308cafff89f5270045d72c3 | 24cca7b0347f76f67c0428f0823727b16842c020 | |||
v1.0 | instruct | Filter | Filter_12593_I | The User will provide a list of Websites to be crawled ( crawl list ) . The program will crawl the websites , download HTML , and save it to the file system . What is the best way to implement a program to download and save the HTML of websites on the crawl list using Python? | import os
import requests
def download_and_save_html(url, save_path):
"""
Downloads the HTML content from the specified URL and saves it to the given path.
:param url: The URL of the website to be crawled.
:param save_path: The file system path where the HTML content should be saved.
"""
t... | from solution import download_and_save_html, crawl_list
import os
def test_download_and_save_html():
# We use a known, small page for the sake of this test.
test_url = 'http://example.com'
test_path = 'example_com.html'
result = download_and_save_html(test_url, test_path)
assert result == True... | [
{
"docstring": "Downloads the HTML content from the specified URL and saves it to the given path.\n\n:param url: The URL of the website to be crawled.\n:param save_path: The file system path where the HTML content should be saved.",
"function_declaration": "def download_and_save_html(url, save_path):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\nfrom urllib.parse import urlparse\n\ndef crawl_websites(crawl_list, save_dir=\"html_files\"):\n \"\"\"\n Crawls websites in the crawl list, downloads their HT... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012593",
"row_id": 12593,
"seed_ids": "['Llama-3.3-70B-Instruct_32907']"
} | 0.623364 | Filter_12593 | I | [
"download_and_save_html",
"crawl_list"
] | 2 | [
[
"crawl_list",
"download_and_save_html"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | b5561f22ddd2ea6e27156a559b6f98aa081e7508 | 79668c7eb299a8fa0d5715ccf23ddad0f284a712 | |||
v1.0 | instruct | Filter | Filter_12596_I | Here is the code for a simple banking system in Python. How can I modify it to include a user's account balance and display it on the menu?
```python
# Define the menu options
menu = {
"1": "Create Account",
"2": "Login",
"3": "Exit"
}
# Define the users dictionary
users = {}
def create_account():
us... | # Define the menu options
main_menu = {
"1": "Create Account",
"2": "Login",
"3": "Exit"
}
login_menu = {
"1": "Deposit",
"2": "Withdraw",
"3": "Check Balance",
"4": "Logout"
}
# Define the users dictionary with balance
users = {}
def create_account():
username = input("Enter your use... | import pytest
from unittest.mock import patch
from solution import create_account, login, deposit, withdraw, check_balance, users
def test_create_account():
with patch('builtins.input', side_effect=['user1', 'pass1']):
create_account()
assert 'user1' in users
assert users['user1']['password'] == '... | [
{
"docstring": null,
"function_declaration": "def create_account():",
"function_name": "create_account",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def login():",
"function_name": "login",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Define the menu options\nmain_menu = {\n \"1\": \"Create Account\",\n \"2\": \"Login\",\n \"3\": \"Exit\"\n}\n\nlogin_menu = {\n \"1\": \"Deposit\",\n \"2\": \"Withdraw\",\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012596",
"row_id": 12596,
"seed_ids": "['Llama-3.3-70B-Instruct_32914']"
} | 0.475271 | Filter_12596 | I | [
"create_account",
"login",
"deposit",
"withdraw",
"check_balance",
"user_menu",
"main"
] | 7 | [
[
"login",
"user_menu"
],
[
"user_menu",
"check_balance"
],
[
"user_menu",
"deposit"
],
[
"user_menu",
"withdraw"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | f0e6fc4d53513231a472dda996d447bdcf2d3879 | c5bc9923f59584c88cc7623b0814768a02c2b033 | |||
v1.0 | instruct | Filter | Filter_12628_I | ### Example Use Cases
The following example use cases illustrate how to validate a user's input data, create an account, and generate a unique identifier for the account.
**Use Case 1: Validate User Input Data**
* **Preconditions**: The user has entered their name, email address, and password.
* **Triggers**: Th... | import uuid
import re
def validate_input_data(name, email, password):
"""
Validate user input data.
Args:
name (str): The user's name.
email (str): The user's email address.
password (str): The user's password.
Returns:
bool: True if the input data is valid, False othe... | from solution import validate_input_data, create_account, generate_unique_identifier
def test_validate_input_data():
assert validate_input_data("Alice", "alice@example.com", "Password123") == True
assert validate_input_data("", "alice@example.com", "Password123") == False
assert validate_input_data("Alice"... | [
{
"docstring": "Validate user input data.\n\nArgs:\n name (str): The user's name.\n email (str): The user's email address.\n password (str): The user's password.\n\nReturns:\n bool: True if the input data is valid, False otherwise.",
"function_declaration": "def validate_input_data(name, email, ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import uuid\nimport re\n\ndef validate_input_data(name, email, password):\n \"\"\"\n Validate user input data.\n\n Args:\n name (str): The user's name.\n email (str): Th... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012628",
"row_id": 12628,
"seed_ids": "['Llama-3.3-70B-Instruct_32978']"
} | 0.315864 | Filter_12628 | I | [
"validate_input_data",
"create_account",
"generate_unique_identifier"
] | 3 | [
[
"create_account",
"generate_unique_identifier"
],
[
"create_account",
"validate_input_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | eed398386c772975d1975e73d73046b1a008ecaa | 53b395921330b80c0ec25eead56f32e11fcee5b0 | |||
v1.0 | instruct | Filter | Filter_12631_I | I have a list of strings and I want to find the shortest possible way to concatenate all the strings together such that the overlap between any two adjacent strings is maximized.
For instance, if I have a list of strings ["abc", "bcc", "ccf"], the shortest possible way to concatenate these strings would be "abccf" be... | from itertools import permutations
def find_overlap(a, b):
"""
Find the maximum overlap between the end of string `a` and the start of string `b`.
"""
max_overlap = 0
for i in range(1, min(len(a), len(b)) + 1):
if a[-i:] == b[:i]:
max_overlap = i
return max_overlap
def merg... | from solution import shortest_concatenation
def test_shortest_concatenation_example():
assert shortest_concatenation(["abc", "bcc", "ccf"]) == "abccf"
def test_shortest_concatenation_no_overlap():
assert shortest_concatenation(["cat", "dog", "fish"]) == "catdogfish"
def test_shortest_concatenation_full_overl... | [
{
"docstring": "Find the maximum overlap between the end of string `a` and the start of string `b`.",
"function_declaration": "def find_overlap(a, b):",
"function_name": "find_overlap",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the merged string of `a` and `b` with the given over... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef find_overlap(a, b):\n \"\"\"\n Returns the maximum overlap length between the end of string a and the start of string b.\n \"\"\"\n max_ov... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012631",
"row_id": 12631,
"seed_ids": "['Llama-3.3-70B-Instruct_32987']"
} | 0.572077 | Filter_12631 | I | [
"find_overlap",
"merge_strings",
"shortest_concatenation"
] | 3 | [
[
"shortest_concatenation",
"find_overlap"
],
[
"shortest_concatenation",
"merge_strings"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2e2b2d1625e9d7a6375bad0bd607a4c3a0932c53 | 61393ba6f6a6559e0bbd3d7acf3d03d6eddb7cab | |||
v1.0 | instruct | Filter | Filter_12637_I | Create a command-line interface (CLI) calculator in Python that can perform addition, subtraction, multiplication, and division. | import sys
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 oper... | from solution import add, subtract, multiply, divide, calculator
import pytest
def test_add():
assert add(2, 3) == 5
assert add(-1, -1) == -2
assert add(0, 0) == 0
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(-1, -1) == 0
assert subtract(0, 0) == 0
def test_multiply():
... | [
{
"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": "import sys\n\ndef 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(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012637",
"row_id": 12637,
"seed_ids": "['Llama-3.3-70B-Instruct_32998']"
} | 0.539845 | Filter_12637 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | e9d783a82495133d851cbbbb1f4bdff5629e45b2 | 07c0af2da0f1e27f2c917af50a0d1efbf8dd47ce | |||
v1.0 | instruct | Filter | Filter_12654_I | I have a task to write a simple Python program that calculates and prints the number of days in each month of a given year. The program should take into account whether the year is a leap year or not. What's the best way to do it using Python? | def is_leap_year(year):
"""
Returns True if the given year is a leap year, False otherwise.
"""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
return False
def days_in_month(year, month):
"""
Returns the number of days in a given month of a given year.
... | from solution import is_leap_year, days_in_month, print_days_in_each_month
def test_is_leap_year():
assert is_leap_year(2000) == True
assert is_leap_year(1900) == False
assert is_leap_year(2004) == True
assert is_leap_year(2003) == False
def test_days_in_month():
# Non-leap year
assert days_in... | [
{
"docstring": "Returns True if the given year is a leap year, False otherwise.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"docstring": "Returns the number of days in a given month of a given year.\nTakes into account... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_leap_year(year):\n \"\"\"\n Returns True if the given year is a leap year, False otherwise.\n \"\"\"\n if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012654",
"row_id": 12654,
"seed_ids": "['Llama-3.3-70B-Instruct_33038']"
} | 0.656528 | Filter_12654 | I | [
"is_leap_year",
"days_in_month",
"print_days_in_each_month"
] | 3 | [
[
"days_in_month",
"is_leap_year"
],
[
"print_days_in_each_month",
"days_in_month"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e2fd7536cb983f0a5014e6add774df15e41667c6 | 133bdce4ddd4b1b08500b288821bc713042f4515 | |||
v1.0 | instruct | Filter | Filter_12746_I | I have a series of 5 or 6 digit numbers and I want to find the most frequent digit in each number. However, my numbers are stored in a text file, and I need to read the file and then calculate the frequency of each digit in each number. How can I do this using Python? | def most_frequent_digit(number):
"""
Returns the most frequent digit in a given number string.
If there are ties, it returns the smallest digit.
"""
from collections import Counter
digit_count = Counter(number)
# Find the maximum frequency
max_freq = max(digit_count.values())
... | def test_most_frequent_digit_single():
assert most_frequent_digit("12345") == "1"
assert most_frequent_digit("123456") == "1"
def test_most_frequent_digit_multiple():
assert most_frequent_digit("111225") == "1"
assert most_frequent_digit("112233") == "1"
assert most_frequent_digit("444455") == "4"
... | [
{
"docstring": "Returns the most frequent digit in a given number string.\nIf there are ties, it returns the smallest digit.",
"function_declaration": "def most_frequent_digit(number):",
"function_name": "most_frequent_digit",
"parameter_list": "(number)"
},
{
"docstring": "Reads a file of 5... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_numbers_from_file(file_path):\n \"\"\"\n Reads lines from the given file and returns them as a list of strings.\n \"\"\"\n with open(file_path, 'r') as file:\n line... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012746",
"row_id": 12746,
"seed_ids": "['Llama-3.3-70B-Instruct_33246']"
} | 0.611879 | Filter_12746 | I | [
"most_frequent_digit",
"process_numbers_from_file"
] | 2 | [
[
"process_numbers_from_file",
"most_frequent_digit"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 59bf59499589d194a369f6bdd4ee9825eb536a44 | d8b2d4bc6268b8727e85bf4928809d60a40893f3 | |||
v1.0 | instruct | Filter | Filter_12757_I | You've been tasked with writing code to simulate a simple game where players take turns picking numbers from a pool of numbers. The pool of numbers is shuffled at the start of each round. The game continues until one player has picked a total of 50 points or more. The players take turns picking a number from the pool, ... | import random
def shuffle_pool(pool):
"""
Shuffle the list of numbers representing the pool.
"""
random.shuffle(pool)
return pool
def pick_number(pool, picked_numbers):
"""
Simulate picking a number from the shuffled pool.
Removes the picked number from the pool and adds it to the play... | from solution import shuffle_pool, pick_number, simulate_game
def test_shuffle_pool_maintains_all_elements():
pool = [1, 2, 3, 4, 5]
shuffled_pool = shuffle_pool(pool.copy())
assert sorted(pool) == sorted(shuffled_pool)
assert len(pool) == len(shuffled_pool)
def test_pick_number_reduces_pool():
po... | [
{
"docstring": "Shuffle the list of numbers representing the pool.",
"function_declaration": "def shuffle_pool(pool):",
"function_name": "shuffle_pool",
"parameter_list": "(pool)"
},
{
"docstring": "Simulate picking a number from the shuffled pool.\nRemoves the picked number from the pool an... | [
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 shuffle_pool(pool):\n \"\"\"\n Shuffle the list of numbers representing the pool.\n \"\"\"\n random.shuffle(pool)\n return pool\n\ndef pick_number(pool, pic... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012757",
"row_id": 12757,
"seed_ids": "['Llama-3.3-70B-Instruct_33275']"
} | 0.641789 | Filter_12757 | I | [
"shuffle_pool",
"pick_number",
"simulate_game"
] | 3 | [
[
"simulate_game",
"pick_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09e3655066ec09da7248ceda64fb5adbee8773e9 | 00f1ff6b0ff91e31c3b40b879c97b92adca5f523 | |||
v1.0 | instruct | Filter | Filter_12762_I | I am looking for a way to automate the process of closing idle user sessions to free up system resources, and I need a solution that can be implemented in a Python script. | import os
import time
# Define the idle time in seconds after which user sessions should be terminated
IDLE_TIME_LIMIT = 300 # 5 minutes
def get_idle_time(user_id):
"""
Get the idle time for the specified user ID in seconds.
"""
try:
# Using the `who` command pipelined with `awk` to simulate ... | import pytest
from unittest.mock import patch, MagicMock
from solution import get_idle_time, close_idle_sessions
def test_get_idle_time_no_user():
with patch('os.popen') as mocked_popen:
mocked_popen.return_value.read.return_value = ""
assert get_idle_time('no_user') == 0
def test_get_idle_time_wi... | [
{
"docstring": "Get the idle time for the specified user ID in seconds.",
"function_declaration": "def get_idle_time(user_id):",
"function_name": "get_idle_time",
"parameter_list": "(user_id)"
},
{
"docstring": "Closes user sessions that have been idle for longer than the IDLE_TIME_LIMIT.",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import subprocess\nimport time\nimport os\n\n\ndef get_idle_users(idle_time_threshold):\n \"\"\"\n Returns a list of users who have been idle for more than idle_time_threshold seconds.\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012762",
"row_id": 12762,
"seed_ids": "['Llama-3.3-70B-Instruct_33289']"
} | 0.363781 | Filter_12762 | I | [
"get_idle_time",
"close_idle_sessions"
] | 2 | [
[
"close_idle_sessions",
"get_idle_time"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f2bc39fb8237e4a406801fa7826df68187798a40 | a2b7fc3610ca864cd734386ab0a9fd3cb48d5fd3 | |||
v1.0 | instruct | Filter | Filter_12792_I | Please provide the steps to create a ChatBot with Python.
Please provide the code to create a simple chatbot that can understand and respond to basic queries.
Here's a detailed specification:
* The chatbot should be able to have a basic conversation with the user.
* The chatbot should be able to understand basic qu... | def chatbot_response(user_input):
"""
This function responds to basic user queries.
"""
responses = {
"hi": "Hello! How can I assist you today?",
"hello": "Hi there! How can I help?",
"what is your name?": "I am a ChatBot created to assist you with basic queries.",
"how a... | from solution import chatbot_response
def test_chatbot_response_greetings():
assert chatbot_response("hi") == "Hello! How can I assist you today?"
assert chatbot_response("hello") == "Hi there! How can I help?"
def test_chatbot_response_name():
assert chatbot_response("What is your name?") == "I am a Chat... | [
{
"docstring": "This function responds to basic user queries.",
"function_declaration": "def chatbot_response(user_input):",
"function_name": "chatbot_response",
"parameter_list": "(user_input)"
},
{
"docstring": "This function starts a simple chatbot conversation.",
"function_declaratio... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def chatbot_response(user_input):\n \"\"\"\n This function responds to basic user queries.\n \"\"\"\n responses = {\n \"hi\": \"Hello! How can I assist you today?\",\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012792",
"row_id": 12792,
"seed_ids": "['Llama-3.3-70B-Instruct_33347']"
} | 0.434957 | Filter_12792 | I | [
"chatbot_response",
"chatbot"
] | 2 | [
[
"chatbot",
"chatbot_response"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4b693c95af1caedbd7ecb008a296fa326b9c1f31 | 5ff45eac0a6446775f6b6842ea38088d7ddd74b7 | |||
v1.0 | instruct | Filter | Filter_12807_I | I'm trying to create a simple, 2-player game. The goal is for each player to get the highest score. The score is calculated by multiplying the number of cards in the player's hand by a modifier that depends on the type of card.
Each player starts with a hand of 5 cards, each card is randomly assigned a type (A, B, C,... | def calculate_score(hand):
"""
Calculate the score based on the card types in the hand.
"""
card_modifiers = {
'A': 1.5,
'B': 2,
'C': 3,
'D': 4,
'E': 5
}
return sum(card_modifiers[card] for card in hand)
def determine_winner(players):
"""
Determin... | from solution import determine_winner
def test_determine_winner_player1():
players = [
{"player": "Player 1", "hand": ["A", "B", "C", "D", "E"]},
{"player": "Player 2", "hand": ["A", "B", "C", "D", "A"]}
]
assert determine_winner(players) == "Player 1"
def test_determine_winner_player2():
... | [
{
"docstring": "Calculate the score based on the card types in the hand.",
"function_declaration": "def calculate_score(hand):",
"function_name": "calculate_score",
"parameter_list": "(hand)"
},
{
"docstring": "Determine the winner based on the scores of the players' hands.\nIf scores are ti... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_score(hand):\n card_modifiers = {\n 'A': 1.5,\n 'B': 2,\n 'C': 3,\n 'D': 4,\n 'E': 5\n }\n score = sum(card_modifiers[card] for card i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012807",
"row_id": 12807,
"seed_ids": "['Llama-3.3-70B-Instruct_33370']"
} | 0.589543 | Filter_12807 | I | [
"calculate_score",
"determine_winner"
] | 2 | [
[
"determine_winner",
"calculate_score"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 12b059094f86a56b30f85a06a08f42aaac76636f | 34660e3cef3cc65da76254d66d776b4d1c47c438 | |||
v1.0 | instruct | Filter | Filter_12814_I | A number is said to be prime if it is greater than 1 and has no divisors other than 1 and itself. The objective of the problem is to write a Python program to find the n largest prime numbers. | def is_prime(num):
"""
Check if a number is prime.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num ** 0.5) + 1, 2):
if num % i == 0:
return False
return True
def n_largest_primes(n... | from solution import is_prime, n_largest_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(1) == False
assert is_prime(-5) == False
def test_n_largest_primes... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Return the n largest prime numbers.",
"function_declaration": "def n_largest_primes(n):",
"function_name": "n_largest_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012814",
"row_id": 12814,
"seed_ids": "['Llama-3.3-70B-Instruct_33385']"
} | 0.745077 | Filter_12814 | I | [
"is_prime",
"n_largest_primes"
] | 2 | [
[
"n_largest_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c82cb3ab75ea4fd224619aefc48ba35a0fb9e09b | 614a83798d4508c03bea857b54a6d3a2dbfc7c88 | |||
v1.0 | instruct | Filter | Filter_12822_I | I need to convert a large number of financial data files from their current format to a new format required by a new accounting system. The files are in CSV format and contain financial transaction data, including dates, amounts, and descriptions. I have been tasked with writing a Python script to automate this convers... | import csv
from datetime import datetime
def convert_date_format(date_str):
"""
Converts date from MM/DD/YYYY to YYYY-MM-DD format.
Parameters:
date_str (str): Date in MM/DD/YYYY format.
Returns:
str: Date in YYYY-MM-DD format.
"""
return datetime.strptime(date_str, "%m/%d/%Y"... | import pytest
import os
import csv
from solution import convert_file, convert_date_format
def test_convert_date_format():
assert convert_date_format("12/31/2021") == "2021-12-31"
assert convert_date_format("01/01/2022") == "2022-01-01"
def test_convert_file(tmp_path):
input_file = tmp_path / "input.csv"
... | [
{
"docstring": "Converts date from MM/DD/YYYY to YYYY-MM-DD format.\n\nParameters:\ndate_str (str): Date in MM/DD/YYYY format.\n\nReturns:\nstr: Date in YYYY-MM-DD format.",
"function_declaration": "def convert_date_format(date_str):",
"function_name": "convert_date_format",
"parameter_list": "(date... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nfrom datetime import datetime\n\ndef convert_csv_format(input_file, output_file):\n \"\"\"\n Converts CSV file from old format to new format required by the accounting system... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012822",
"row_id": 12822,
"seed_ids": "['Llama-3.3-70B-Instruct_33408']"
} | 0.587947 | Filter_12822 | I | [
"convert_date_format",
"convert_file"
] | 2 | [
[
"convert_file",
"convert_date_format"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 932058fbea553a0677d4930973868fed01f26060 | 9bb4a5631bbfaf2d151c7191474e2398eef5dabd | |||
v1.0 | instruct | Filter | Filter_12823_I | Here is the prompt:
Using Python, write a functional program that calculates and prints:
1. The square of a number
2. The cube of a number
3. The factorial of a number
4. The sum of the first n positive integers
5. The sum of the squares of the first n positive integers
6. The sum of the cubes of the first n positive... | def square(n):
"""
Returns the square of n.
"""
return n * n
def cube(n):
"""
Returns the cube of n.
"""
return n * n * n
def factorial(n):
"""
Returns the factorial of n.
"""
if n == 0:
return 1
result = 1
for i in range(1, n + 1):
result *= i
... | import pytest
from solution import square, cube, factorial, sum_of_first_n_positive_integers, sum_of_squares_of_first_n_positive_integers, sum_of_cubes_of_first_n_positive_integers
def test_square():
assert square(5) == 25
assert square(0) == 0
assert square(-3) == 9
def test_cube():
assert cube(5) ==... | [
{
"docstring": "Returns the square of n.",
"function_declaration": "def square(n):",
"function_name": "square",
"parameter_list": "(n)"
},
{
"docstring": "Returns the cube of n.",
"function_declaration": "def cube(n):",
"function_name": "cube",
"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 square(n):\n \"\"\"Returns the square of n.\"\"\"\n return n * n\n\ndef cube(n):\n \"\"\"Returns the cube of n.\"\"\"\n return n * n * n\n\ndef factorial(n):\n \"\"\"Returns... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012823",
"row_id": 12823,
"seed_ids": "['Llama-3.3-70B-Instruct_33409']"
} | 0.645068 | Filter_12823 | I | [
"square",
"cube",
"factorial",
"sum_of_first_n_positive_integers",
"sum_of_squares_of_first_n_positive_integers",
"sum_of_cubes_of_first_n_positive_integers"
] | 6 | [
[
"sum_of_cubes_of_first_n_positive_integers",
"sum_of_first_n_positive_integers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 00091b7a1056966f2847af8bffe4e3868d8f1deb | f874c2d96eb20b3f0933feddee0c50621c0aaa60 | |||
v1.0 | instruct | Filter | Filter_12857_I | I have a commodity trading firm and I am looking to use a new trading strategy that involves creating a portfolio of commodity futures contracts. I've identified a set of commodity futures contracts that I am interested in, but I want to optimize the portfolio by choosing the optimal weights for each contract.
To do t... | import pandas as pd
import numpy as np
from scipy.optimize import minimize
# Define the historical prices of the commodity futures contracts
historical_prices = pd.DataFrame({
'Contract1': [100, 105, 110, 115, 120],
'Contract2': [50, 55, 60, 65, 70],
'Contract3': [200, 210, 220, 230, 240]
})
# Calculate t... | from solution import get_optimal_portfolio, expected_returns, cov_matrix
def test_optimal_weights_sum_to_one():
weights = get_optimal_portfolio()
assert np.isclose(np.sum(weights), 1), "The sum of the weights should be 1"
def test_optimal_weights_non_negative():
weights = get_optimal_portfolio()
asser... | [
{
"docstring": null,
"function_declaration": "def optimize_portfolio(weights):",
"function_name": "optimize_portfolio",
"parameter_list": "(weights)"
},
{
"docstring": null,
"function_declaration": "def get_optimal_portfolio():",
"function_name": "get_optimal_portfolio",
"paramet... | [
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 numpy as np\nfrom scipy.optimize import minimize\n\n# Define the historical prices of the commodity futures contracts\nhistorical_prices = pd.DataFrame({\n 'Cont... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012857",
"row_id": 12857,
"seed_ids": "['Llama-3.3-70B-Instruct_33490']"
} | 0.450909 | Filter_12857 | I | [
"optimize_portfolio",
"get_optimal_portfolio"
] | 2 | [
[
"get_optimal_portfolio",
"optimize_portfolio"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"scipy"
] | false | 486e952d82fd70b1f71040e3f1bc516ed7997ffb | 8a7f949e51dff00d58057b5f215d4a6418d7f610 | |||
v1.0 | instruct | Filter | Filter_12934_I | I have a list of nodes (n1, n2, n3, n4, n5, n6) and a list of edges between them (n1->n2, n1->n3, n2->n5, n3->n4, n4->n5, n5->n6). I want to find all possible paths between n1 and n6.
I can use depth first search to find the paths. Here is my code in python:
```python
def dfs(graph, start, end, path=[]):
path = ... | def dfs(graph, start, end, path=[]):
"""
Depth First Search to find all paths from start node to end node in graph.
"""
path = path + [start]
if start == end:
return [path]
if start not in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
... | from solution import dfs, all_paths
def test_dfs():
graph = {
'n1': ['n2', 'n3'],
'n2': ['n5'],
'n3': ['n4'],
'n4': ['n5'],
'n5': ['n6'],
'n6': []
}
assert dfs(graph, 'n1', 'n6') == [['n1', 'n2', 'n5', 'n6'], ['n1', 'n3', 'n4', 'n5', 'n6']]
assert dfs(gra... | [
{
"docstring": "Depth First Search to find all paths from start node to end node in graph.",
"function_declaration": "def dfs(graph, start, end, path=[]):",
"function_name": "dfs",
"parameter_list": "(graph, start, end, path=[])"
},
{
"docstring": "Finds all paths between all pairs of nodes ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def dfs(graph, start, end, path=[]):\n \"\"\"\n Depth First Search to find all possible paths between start and end nodes in a graph.\n \n :param graph: Dictionary representing the... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012934",
"row_id": 12934,
"seed_ids": "['Llama-3.3-70B-Instruct_33653']"
} | 0.508226 | Filter_12934 | I | [
"dfs",
"all_paths"
] | 2 | [
[
"all_paths",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c372938f82b58af3b293f8d50d613d53f57969c4 | be6eae65f3f2c6b2a782e575953c6adb15dc3034 | |||
v1.0 | instruct | Filter | Filter_12957_I | I am working on a program to build a game and am having trouble with a particular function that is designed to check if a move is valid. My function is supposed to check if a move is within the bounds of a grid and if there are no obstacles in the way.
I could really use an example of how to implement this function i... | def is_valid_move(grid, obstacles, current_position, move):
"""
Determines if a move is valid in the given grid.
Args:
grid (list of list of int): The game grid.
obstacles (list of tuple of int): List of coordinates with obstacles.
current_position (tuple of int): The starting position in the g... | def test_is_valid_move():
grid = [[0 for _ in range(10)] for _ in range(10)]
obstacles = [(3, 3), (3, 4), (3, 5), (6, 6), (6, 7), (6, 8)]
# Valid move
assert is_valid_move(grid, obstacles, (0, 0), (2, 2)) == True
# Out of bounds move
assert is_valid_move(grid, obstacles, (0, 0), (10, 10)) == F... | [
{
"docstring": "Determines if a move is valid in the given grid.\n\nArgs:\ngrid (list of list of int): The game grid.\nobstacles (list of tuple of int): List of coordinates with obstacles.\ncurrent_position (tuple of int): The starting position in the grid.\nmove (tuple of int): The desired move destination.\n\... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid_move(grid, obstacles, current_position, move):\n def bresenham_line(x0, y0, x1, y1):\n \"\"\"Generate points on a line from (x0, y0) to (x1, y1) using Bresenham's algori... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00012957",
"row_id": 12957,
"seed_ids": "['Llama-3.3-70B-Instruct_33702']"
} | 0.586023 | Filter_12957 | I | [
"is_valid_move",
"get_path"
] | 2 | [
[
"is_valid_move",
"get_path"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bc8ed303c501a8c0611420608c25a961b461fb56 | 0d44c54c8b10bf2f1617346e35776eb7d7efe791 | |||
v1.0 | instruct | Filter | Filter_12961_I | Can you write an example of a 2 player game using only Python's built-in data types and control structures? | def print_board(board):
"""
Prints 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.
"""
# Check rows
for row in board:
if all(s == player for s in row)... | from solution import print_board, check_winner, is_full
def test_print_board(capsys):
board = [['X', 'O', ' '], [' ', 'X', 'O'], ['O', ' ', 'X']]
print_board(board)
captured = capsys.readouterr()
assert captured.out == "X | O | \n-----\n | X | O\n-----\nO | | X\n-----\n"
def test_check_winner():
... | [
{
"docstring": "Prints 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.",
"function_declaration": "def check_winner(board, player):",
"functio... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"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\n\ndef check_winner(boar... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012961",
"row_id": 12961,
"seed_ids": "['Llama-3.3-70B-Instruct_33711']"
} | 0.451616 | Filter_12961 | I | [
"print_board",
"check_winner",
"is_full",
"tic_tac_toe"
] | 4 | [
[
"tic_tac_toe",
"check_winner"
],
[
"tic_tac_toe",
"is_full"
],
[
"tic_tac_toe",
"print_board"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | dee5951c87ac6ce5a7355e86b471d11d8a6269d6 | 86b0507e8dcb011994cd797e2ef20ec5117477b3 | |||
v1.0 | instruct | Filter | Filter_12975_I | I have a Python script that I'm trying to modify to handle an arbitrary number of input files. The current script processes a single file, and I want to modify it to handle multiple files. I'm looking for advice on the best way to do this. | def process_file(file_path):
"""
Placeholder function to process a single file.
Replace this with actual file processing logic.
"""
print(f"Processing {file_path}")
# file processing logic here
return True
def process_files(file_paths):
"""
Process an arbitrary number of input files... | from solution import process_files
def test_process_files():
# Simulating the file processing with dummy paths
file_paths = ["/path/to/file1.txt", "/path/to/file2.txt", "/path/to/file3.txt"]
results = process_files(file_paths)
assert results["/path/to/file1.txt"] == True
assert results["/path/... | [
{
"docstring": "Placeholder function to process a single file.\nReplace this with actual file processing logic.",
"function_declaration": "def process_file(file_path):",
"function_name": "process_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Process an arbitrary number of input f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_files(file_list):\n \"\"\"\n Processes a list of files and returns a list of results for each file.\n \n :param file_list: list of file paths to be processed\n :retu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012975",
"row_id": 12975,
"seed_ids": "['Llama-3.3-70B-Instruct_33743']"
} | 0.527254 | Filter_12975 | I | [
"process_file",
"process_files"
] | 2 | [
[
"process_files",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c8853aa301b7766d6256a9d57473412e9395cabd | 85ead90c618762b037a8fcdd1ad22834d7759a2e | |||
v1.0 | instruct | Filter | Filter_12985_I | Okay so im trying to build a python script that will auto restart a service on my server when its down and also when it gets back online so that it is always running.
The script will check every 5 seconds if the service is running, and if its not, it will restart it.
Here is the script i have so far:
```python
impor... | import os
import time
import subprocess
import logging
# Set up logging
logging.basicConfig(filename='service_restart.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def is_service_running(service_name):
"""
Check if the service is active.
Returns True if the service is activ... | from unittest.mock import patch, call
import logging
import pytest
import subprocess
from solution import is_service_running, restart_service, check_and_restart
def test_is_service_running_active():
with patch('subprocess.check_output') as mock_check_output:
assert is_service_running('my_service') == True
... | [
{
"docstring": "Check if the service is active.\nReturns True if the service is active, False otherwise.",
"function_declaration": "def is_service_running(service_name):",
"function_name": "is_service_running",
"parameter_list": "(service_name)"
},
{
"docstring": "Restart the specified servi... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport time\nimport subprocess\nimport logging\n\n# Set up logging\nlogging.basicConfig(filename='service_restart.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(m... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00012985",
"row_id": 12985,
"seed_ids": "['Llama-3.3-70B-Instruct_33757']"
} | 0.60628 | Filter_12985 | I | [
"is_service_running",
"restart_service",
"check_and_restart",
"main"
] | 4 | [
[
"check_and_restart",
"is_service_running"
],
[
"check_and_restart",
"restart_service"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 53396b71f5088374cfe8ae0f58e88d04529a4395 | 1dd93401c8460dfcc78f6eb3f1ce6bab8b8a3d5f | |||
v1.0 | instruct | Filter | Filter_12999_I | I want to know how to build a simple chatbot that can understand and respond to user queries. Can you provide a step-by-step guide on how to build a chatbot using Python and the Natural Language Processing (NLP) library? | import random
import re
def preprocess_text(text):
"""
Clean and preprocess the text input.
"""
text = text.lower()
text = re.sub(r'\W', ' ', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
def get_response(user_input):
"""
Generate a response based on the user's input.
... | from solution import preprocess_text, get_response
def test_preprocess_text():
assert preprocess_text("Hello!!") == "hello"
assert preprocess_text("I'm good, thank you.") == "i m good thank you"
assert preprocess_text(" Extra spaces ") == "extra spaces"
def test_get_response_greeting():
assert get_... | [
{
"docstring": "Clean and preprocess the text input.",
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": "Generate a response based on the user's input.",
"function_declaration": "def get_response(user_i... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport nltk\nfrom nltk.chat.util import Chat, reflections\n\n# Download NLTK data files (only need to run once)\nnltk.download('punkt')\n\ndef build_simple_chatbot():\n \"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00012999",
"row_id": 12999,
"seed_ids": "['Llama-3.3-70B-Instruct_33791']"
} | 0.323422 | Filter_12999 | I | [
"preprocess_text",
"get_response"
] | 2 | [
[
"get_response",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b31ac791468088bc94a8d5c1ea01946911315aa | fcb022883dfd93d3857289160548b48c2d2e195d | |||
v1.0 | instruct | Filter | Filter_13000_I | I've been tasked with creating a program that can play a game of Tic-Tac-Toe against a human opponent. Here's the rough outline of what I need to do:
1. Create a 3x3 grid and display it to the user.
2. Ask the user to input their move (the number of the space where they'd like to place their piece, 1-9).
3. Validate t... | def print_grid(grid):
for i in range(3):
print(' | '.join(grid[i*3:(i+1)*3]))
if i < 2:
print('---------')
def get_user_move():
while True:
user_move = input("Enter your move (1-9): ")
if user_move.isdigit() and 1 <= int(user_move) <= 9:
return int(user_m... | import pytest
from solution import print_grid, check_win, get_computer_move
def test_print_grid(capsys):
grid = ['X', 'O', ' ', ' ', 'X', ' ', 'O', ' ', 'X']
print_grid(grid)
captured = capsys.readouterr()
expected_output = "X | O | \n---------\n | X | \n---------\nO | | X\n"
assert captured.o... | [
{
"docstring": null,
"function_declaration": "def print_grid(grid):",
"function_name": "print_grid",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def get_user_move():",
"function_name": "get_user_move",
"parameter_list": "()"
},
{
"docstring... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def print_grid(grid):\n for i in range(3):\n print(' | '.join(grid[i*3:(i+1)*3]))\n if i < 2:\n print('---------')\n\ndef get_user_move():\n while True:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013000",
"row_id": 13000,
"seed_ids": "['Llama-3.3-70B-Instruct_33795']"
} | 0.569296 | Filter_13000 | I | [
"print_grid",
"get_user_move",
"check_win",
"get_computer_move",
"play_game"
] | 5 | [
[
"play_game",
"check_win"
],
[
"play_game",
"get_computer_move"
],
[
"play_game",
"get_user_move"
],
[
"play_game",
"print_grid"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 19463b61c1f1adb4d812d28cea8199e1342cfdcb | 57af74977d7ceb80c84fc0406a77d30c1cac703d | |||
v1.0 | instruct | Filter | Filter_13006_I | I would like to create a simple game where the user can play against the computer. The game should be a simple text-based version of the classic game "Rock, Paper, Scissors". Here is a simple version of the game, but I'd like to add some additional features to make it more interesting.
```python
import random
def gam... | import random
def get_computer_choice():
return random.choice(["rock", "paper", "scissors"])
def determine_winner(user_choice, computer_choice):
game_rules = {
"rock": {"scissors": "Rock smashes scissors! You win!", "paper": "Paper covers rock! You lose."},
"paper": {"rock": "Paper covers rock... | from solution import get_computer_choice, determine_winner, validate_user_choice
def test_get_computer_choice():
choices = ["rock", "paper", "scissors"]
assert get_computer_choice() in choices
def test_determine_winner_tie():
assert determine_winner("rock", "rock") == "Both players selected rock. It's a t... | [
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def determine_winner(user_choice, computer_choice):",
"function_name": "determine_winner",
"p... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef determine_winner(user_choice, computer_choice):\n \"\"\"\n Determines the winner between user and computer given their choices.\n \"\"\"\n if user_choice == co... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013006",
"row_id": 13006,
"seed_ids": "['Llama-3.3-70B-Instruct_33805']"
} | 0.54132 | Filter_13006 | I | [
"get_computer_choice",
"determine_winner",
"validate_user_choice",
"game"
] | 4 | [
[
"game",
"determine_winner"
],
[
"game",
"get_computer_choice"
],
[
"game",
"validate_user_choice"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1dd80901d8ec46ce11d31a6f4fb42c9b4ce43bba | b3cde7f4f51d46f6c4f9091a048658aed4ba3c87 | |||
v1.0 | instruct | Filter | Filter_13013_I | Here is my attempt at creating a recursive algorithm for mergesort:
```python
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
result.extend(left)
resu... | def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]: # Use <= to maintain stability
result.append(left.pop(0))
else:
result.append(right.pop(0))
result.extend(left)
result.extend(right)
return result
def mergeso... | from solution import mergesort
def test_mergesort_empty():
assert mergesort([]) == []
def test_mergesort_single_element():
assert mergesort([1]) == [1]
def test_mergesort_two_elements():
assert mergesort([2, 1]) == [1, 2]
def test_mergesort_multiple_elements():
assert mergesort([64, 34, 25, 12, 22, ... | [
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docstring": null,
"function_declaration": "def mergesort(arr):",
"function_name": "mergesort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge(left, right):\n \"\"\"\n Merges two sorted lists into a single sorted list.\n \n :param left: First sorted list.\n :param right: Second sorted list.\n :return: Merg... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013013",
"row_id": 13013,
"seed_ids": "['Llama-3.3-70B-Instruct_33816']"
} | 0.557822 | Filter_13013 | I | [
"merge",
"mergesort"
] | 2 | [
[
"mergesort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4213bb6885599728bf156e7c40332a94c08c84b3 | 1e275a17cbf59a0c36e7d47b08a280996c0b1ac7 | |||
v1.0 | instruct | Filter | Filter_13023_I | You can create a simple calculator in Python that performs basic arithmetic operations such as addition, subtraction, multiplication, and division. The calculator will be based on a simple text-based menu. | 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(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(-10, -5) == -5
assert subtract(0, 0) == 0
def test_multiply():
assert multip... | [
{
"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... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"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_1 | {
"original_instruction": "",
"prompt_id": "00013023",
"row_id": 13023,
"seed_ids": "['Llama-3.3-70B-Instruct_33836']"
} | 0.59028 | Filter_13023 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | e60031c73f79fb5a12ffa5bebd0b50a02e4412a4 | 2752a4debac2421e270912a2e659bc782a34acc9 | |||
v1.0 | instruct | Filter | Filter_13030_I | You have been tasked with creating a program that can automatically set reminder notifications for a user based on their schedule. The user's schedule is represented as a list of strings, where each string represents a time in the format "HH:MM" and is associated with a reminder message. The list is sorted in ascending... | import time
from datetime import datetime, timedelta
def parse_schedule(schedule):
"""
Parses a list of strings representing times and associated reminders.
Args:
schedule: list of strings, where each string is in the format "HH:MM: Reminder message"
Returns:
list of tuples, where eac... | import pytest
from datetime import datetime
from solution import parse_schedule, notify_user
def test_parse_schedule():
schedule = ["15:30: Take a break", "16:00: Meeting with team"]
parsed = parse_schedule(schedule)
# Assuming current date for the test
now = datetime.now()
assert len(pa... | [
{
"docstring": "Parses a list of strings representing times and associated reminders.\n\nArgs:\nschedule: list of strings, where each string is in the format \"HH:MM: Reminder message\"\n\nReturns:\nlist of tuples, where each tuple contains a datetime object and the reminder message.",
"function_declaration... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom datetime import datetime, timedelta\n\ndef parse_schedule(schedule):\n \"\"\"\n Parses a list of strings representing times and associated reminders.\n \n Args:\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013030",
"row_id": 13030,
"seed_ids": "['Llama-3.3-70B-Instruct_33855']"
} | 0.438456 | Filter_13030 | I | [
"parse_schedule",
"set_reminders",
"notify_user",
"process_schedule"
] | 4 | [
[
"process_schedule",
"parse_schedule"
],
[
"process_schedule",
"set_reminders"
],
[
"set_reminders",
"notify_user"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 93bdd0eea24310070e4d5a98befbfed846c98e5f | 67aa892e516fb4ca9e23ea9afae1ef84022ecdf8 | |||
v1.0 | instruct | Filter | Filter_13045_I | Here's a basic implementation of a binary search tree in Python. How would I implement the functionality to delete a node from the tree? | class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert_node(root, key):
if root is None:
return TreeNode(key)
else:
if root.key < key:
root.right = insert_node(root.right, key)
else:
root.... | import pytest
from solution import insert_node, delete_node, inorder_traversal, TreeNode
def test_insert_and_delete():
root = None
keys_to_insert = [50, 30, 20, 40, 70, 60, 80]
for key in keys_to_insert:
root = insert_node(root, key)
assert inorder_traversal(root) == [20, 30, 40, 50, 60, 7... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n\ndef insert_node(root, key):\n if root is None:\n return ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013045",
"row_id": 13045,
"seed_ids": "['Llama-3.3-70B-Instruct_33885']"
} | 0.387445 | Filter_13045 | I | [
"insert_node",
"min_value_node",
"delete_node",
"inorder_traversal"
] | 4 | [
[
"delete_node",
"min_value_node"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 87baf397c348b7a40b92fe16d7d4b40046d42a4b | d99063d98e75be441e8f92364acd50c5e780658f | |||
v1.0 | instruct | Filter | Filter_13055_I | ### Define a function `is_prime(n)` that checks whether a given number `n` is prime or not. Then, use this function to filter out prime numbers from a list of numbers.
```python
# Example list of numbers
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
### To solve this problem, follow these steps:
1. Define the `i... | def is_prime(n):
"""
Check if a given number n is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def filter_primes(numbers)... | from solution import is_prime, filter_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(-3) == Fal... | [
{
"docstring": "Check if a given number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filter prime numbers from a given list of numbers.",
"function_declaration": "def filter_primes(numbers):",
"funct... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks whether a number is prime.\n \n Args:\n - n (int): The number to be checked.\n \n Returns:\n - bool: True if the number is prime, Fal... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013055",
"row_id": 13055,
"seed_ids": "['Llama-3.3-70B-Instruct_33915']"
} | 0.78281 | Filter_13055 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b09ccf82cdff9912e1c346dbf69ae71acde982e9 | 52b4fa4c68f19d480a037557271015aa43043c5b | |||
v1.0 | instruct | Filter | Filter_13065_I | I have been tasked with creating a chatbot to help users find restaurants and make reservations. I have the following user stories and acceptance criteria:
**User Story 1**
As a user, I want to be able to search for restaurants by name, so that I can easily find a specific restaurant.
Acceptance Criteria:
- The chatbo... | import pandas as pd
from datetime import datetime
import random
# Sample restaurant data
restaurants = [
{"name": "Italian Place", "cuisine": "Italian", "available": True},
{"name": "Taco Tuesday", "cuisine": "Mexican", "available": True},
{"name": "Sushi Spot", "cuisine": "Japanese", "available": True},
... | from solution import search_restaurants_by_name, filter_restaurants_by_cuisine, make_reservation, search_and_reserve
def test_search_restaurants_by_name_found():
result = search_restaurants_by_name("Italian")
assert isinstance(result, list)
assert len(result) > 0
def test_search_restaurants_by_name_not_fo... | [
{
"docstring": null,
"function_declaration": "def search_restaurants_by_name(name):",
"function_name": "search_restaurants_by_name",
"parameter_list": "(name)"
},
{
"docstring": null,
"function_declaration": "def filter_restaurants_by_cuisine(cuisine):",
"function_name": "filter_rest... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom datetime import datetime\nimport random\n\n# Sample restaurant data\nrestaurants = [\n {\"name\": \"Italian Place\", \"cuisine\": \"Italian\", \"available\": True}... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013065",
"row_id": 13065,
"seed_ids": "['Llama-3.3-70B-Instruct_33943']"
} | 0.53735 | Filter_13065 | I | [
"search_restaurants_by_name",
"filter_restaurants_by_cuisine",
"make_reservation",
"search_and_reserve"
] | 4 | [
[
"search_and_reserve",
"make_reservation"
],
[
"search_and_reserve",
"search_restaurants_by_name"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | ae85b00a64bcdc8040b4777250e8b70ed7e6f35f | e52442e26ae5f37ecd525e2387a7ff5e09b1bed9 | |||
v1.0 | instruct | Filter | Filter_13074_I | I have 3 lists of integers and I want to find the longest increasing subsequence in the combined list of integers. The 3 lists are:
```
list1 = [1, 2, 3, 4, 6, 7, 8, 10, 11]
list2 = [2, 4, 5, 6, 7, 10, 12]
list3 = [3, 6, 8, 10, 11, 12, 13, 14, 15]
```
I want to write a Python program that can find the longest increasi... | def longest_increasing_subsequence(nums):
if len(nums) == 0:
return []
dp = [[num] for num in nums]
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j] and len(dp[i]) < len(dp[j]) + 1:
dp[i] = dp[j] + [nums[i]]
max_length_idx = max(range(len(... | from solution import find_lis_from_multiple_lists
def test_combined_lists():
list1 = [1, 2, 3, 4, 6, 7, 8, 10, 11]
list2 = [2, 4, 5, 6, 7, 10, 12]
list3 = [3, 6, 8, 10, 11, 12, 13, 14, 15]
assert find_lis_from_multiple_lists(list1, list2, list3) == [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15]
def ... | [
{
"docstring": null,
"function_declaration": "def longest_increasing_subsequence(nums):",
"function_name": "longest_increasing_subsequence",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def find_lis_from_multiple_lists(*lists):",
"function_name": "find_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_increasing_subsequence(nums):\n if len(nums) == 0:\n return []\n\n dp = [[num] for num in nums]\n\n for i in range(len(nums)):\n for j in range(i):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013074",
"row_id": 13074,
"seed_ids": "['Llama-3.3-70B-Instruct_33962']"
} | 0.646772 | Filter_13074 | I | [
"longest_increasing_subsequence",
"find_lis_from_multiple_lists"
] | 2 | [
[
"find_lis_from_multiple_lists",
"longest_increasing_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 873d6b87b291c97647c8943d54a8176228c4c4ee | bf534672e6214fa0bcf2ddf4d73c614909ba4dbf | |||
v1.0 | instruct | Filter | Filter_13084_I | Here's a question from a previous exam:
"Write a program that prints the following output when the input is a valid English word:
hello
*hello*
hello
if the input is not a valid English word, print
invalid word "
Here is an example of what I mean:
Input: hello
Output:
hello
*hello*
hello
Input: apple
... | import re
def is_valid_word(word):
"""
Checks if the input string is a valid English word with only alphabetic characters.
"""
return bool(re.match("^[a-zA-Z]+$", word))
def print_word_pattern(word):
"""
Prints the word pattern if the word is valid, otherwise prints 'invalid word'.
"""
... | from io import StringIO
import sys
from solution import is_valid_word, print_word_pattern
def test_is_valid_word():
assert is_valid_word("hello") == True
assert is_valid_word("apple") == True
assert is_valid_word("apple123") == False
assert is_valid_word("apple!") == False
assert is_valid_word("hel... | [
{
"docstring": "Checks if the input string is a valid English word with only alphabetic characters.",
"function_declaration": "def is_valid_word(word):",
"function_name": "is_valid_word",
"parameter_list": "(word)"
},
{
"docstring": "Prints the word pattern if the word is valid, otherwise pr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef check_word(word):\n \"\"\"\n Prints the specified output format if the input is a valid English word.\n Otherwise, prints \"invalid word\".\n \n A valid English... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013084",
"row_id": 13084,
"seed_ids": "['Llama-3.3-70B-Instruct_33980']"
} | 0.697356 | Filter_13084 | I | [
"is_valid_word",
"print_word_pattern"
] | 2 | [
[
"print_word_pattern",
"is_valid_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ce624a5daaea43951df87c4178d082cc26964835 | a4ffc957f9eaaaa06c317cbc329de56cd7b1d16b | |||
v1.0 | instruct | Filter | Filter_13103_I | I have a large list of URLs, and I want to extract only the domain name from each URL. I want to write a Python script to accomplish this.
Here is a sample list of URLs:
```
http://www.google.com
http://www.example.com
http://www.stackoverflow.com
http://www.github.com
http://www.python.org
```
I want my output to lo... | from urllib.parse import urlparse
def extract_domain(url):
"""
Extracts and returns the domain name from a given URL.
"""
parsed_url = urlparse(url)
domain = parsed_url.netloc
if domain.startswith('www.'):
domain = domain[4:]
return domain
def extract_domains(urls):
... | from solution import extract_domain, extract_domains
def test_extract_domain():
assert extract_domain('http://www.google.com') == 'google.com'
assert extract_domain('http://www.example.com') == 'example.com'
assert extract_domain('http://www.stackoverflow.com') == 'stackoverflow.com'
assert extract_dom... | [
{
"docstring": "Extracts and returns the domain name from a given URL.",
"function_declaration": "def extract_domain(url):",
"function_name": "extract_domain",
"parameter_list": "(url)"
},
{
"docstring": "Given a list of URLs, this function extracts and returns a list of domain names.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from urllib.parse import urlparse\n\ndef extract_domain(url):\n \"\"\"\n Extracts and returns the domain name from a URL.\n \"\"\"\n parsed_url = urlparse(url)\n domain = parsed... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013103",
"row_id": 13103,
"seed_ids": "['Llama-3.3-70B-Instruct_34030']"
} | 0.700982 | Filter_13103 | I | [
"extract_domain",
"extract_domains"
] | 2 | [
[
"extract_domains",
"extract_domain"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2bd63fdd6e1f87e93ef13710c3810f90a777554c | 5be57bc6cea3de0770931ba09a0ffef6000c5809 | |||
v1.0 | instruct | Filter | Filter_13104_I | ### Overview
The goal of this project is to create a game called "Monster Hunter." The game is a simplified version of the popular game "Monster Hunter" by Capcom, where players hunt and kill monsters in a fantasy setting.
### Game Description
In "Monster Hunter," players take on the role of a hunter tasked with killi... | import random
class Monster:
def __init__(self, name, health, attack_power, speed):
self.name = name
self.health = health
self.attack_power = attack_power
self.speed = speed
class Player:
def __init__(self, name, health, attack_power, speed, gold=0, experience=0):
self.... | from solution import Monster, Player, combat, reward_player
def test_player_win():
player = Player("Hero", 100, 50, 20)
monster = Monster("Goblin", 50, 10, 5)
result = combat(player, monster)
assert result == "Hero wins!"
def test_monster_win():
player = Player("Hero", 10, 5, 20)
monster = Mon... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass Monster:\n def __init__(self, name, health, attack_power, speed):\n self.name = name\n self.health = health\n self.attack_power = attack_power\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013104",
"row_id": 13104,
"seed_ids": "['Llama-3.3-70B-Instruct_34036']"
} | 0.46626 | Filter_13104 | I | [
"combat",
"reward_player",
"game_loop"
] | 3 | [
[
"combat",
"reward_player"
],
[
"game_loop",
"combat"
]
] | 2 | [] | false | [
"Monster",
"Player"
] | true | pytest | true | [] | true | b2096e04fc01a7f270ff59275cd7d6659302f5d8 | a92773af12f8a0b08f6edf463834d324ab45c588 | |||
v1.0 | instruct | Filter | Filter_13124_I | I have some outputs that I want to compare. I have two sets of data, let's call them A and B. Set A consists of 10 files and set B consists of 10 files. Each file in set A has a corresponding file in set B.
What I want to do is for each pair of corresponding files in set A and set B, I want to compute the difference ... | import os
def file_difference(fileA_path, fileB_path, output_path):
"""
Computes the difference between fileA and fileB line by line and writes
the result to the output file.
:param fileA_path: Path to the first input file (from Set A)
:param fileB_path: Path to the second input file (from Se... | import os
import tempfile
from solution import file_difference, process_file_sets
def test_file_difference():
fileA_content = "line1\nline2\nline3"
fileB_content = "line1\nLINE2\nline3"
with tempfile.TemporaryDirectory() as tmpdir:
fileA_path = os.path.join(tmpdir, 'fileA.txt')
fileB_path ... | [
{
"docstring": "Computes the difference between fileA and fileB line by line and writes \nthe result to the output file.\n\n:param fileA_path: Path to the first input file (from Set A)\n:param fileB_path: Path to the second input file (from Set B)\n:param output_path: Path to the output file where differences a... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef compute_file_differences(set_A, set_B, output_dir):\n \"\"\"\n Computes the differences between corresponding files in set_A and set_B,\n and writes the differences t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013124",
"row_id": 13124,
"seed_ids": "['Llama-3.3-70B-Instruct_34086']"
} | 0.71026 | Filter_13124 | I | [
"file_difference",
"process_file_sets"
] | 2 | [
[
"process_file_sets",
"file_difference"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 98afba5821a008bf1f0ebb564c755ca6f760a531 | 8b0bab46f2cf215c10b86c1503d56da065e79c02 | |||
v1.0 | instruct | Filter | Filter_13125_I | # Function to check if number is a prime number
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = int(n**0.5) + 1
for d in range(3, max_divisor, 2):
if n % d == 0:
return False
return True
# Func... | def is_prime(n):
"""
Checks if a number `n` is a prime number.
Args:
n (int): The number to check.
Returns:
bool: True if `n` is prime, False otherwise.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = int(... | from solution import is_prime, get_next_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(97) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5) == Fal... | [
{
"docstring": "Checks if a number `n` is a prime number.\n\nArgs:\nn (int): The number to check.\n\nReturns:\nbool: True if `n` is prime, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds the next pri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number `n` is a prime number.\n\n Args:\n n (int): The number to check.\n\n Returns:\n bool: True if `n` is prime, False otherwise.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013125",
"row_id": 13125,
"seed_ids": "['Llama-3.3-70B-Instruct_34088']"
} | 0.783616 | Filter_13125 | I | [
"is_prime",
"get_next_prime",
"main"
] | 3 | [
[
"get_next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 381af27d45349df3b9dededb9931b8cb48511a75 | c0f09681248aeeb67a3720f927df79a7d831ded3 | |||
v1.0 | instruct | Filter | Filter_13146_I | I have a function that adds two numbers together. The function takes in two parameters, num1 and num2, and returns their sum. Here is the code:
```python
def add(num1, num2):
return num1 + num2
```
I want to create a new function that adds three numbers together. Instead of writing a new function that takes in th... | def add(num1, num2):
return num1 + num2
def add_three_numbers(num1, num2, num3):
"""
Returns the sum of num1, num2, and num3 using the existing add function.
"""
return add(add(num1, num2), num3) | from solution import add_three_numbers
def test_add_three_positive_numbers():
assert add_three_numbers(1, 2, 3) == 6
def test_add_three_numbers_with_zero():
assert add_three_numbers(0, 1, 2) == 3
assert add_three_numbers(1, 0, 2) == 3
assert add_three_numbers(1, 2, 0) == 3
def test_add_three_negative... | [
{
"docstring": null,
"function_declaration": "def add(num1, num2):",
"function_name": "add",
"parameter_list": "(num1, num2)"
},
{
"docstring": "Returns the sum of num1, num2, and num3 using the existing add function.",
"function_declaration": "def add_three_numbers(num1, num2, num3):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_three_numbers(num1, num2, num3):\n \"\"\"\n Returns the sum of num1, num2, and num3 using the existing add function.\n \"\"\"\n return add(add(num1, num2), num3)\n\ndef add... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013146",
"row_id": 13146,
"seed_ids": "['Llama-3.3-70B-Instruct_34132']"
} | 0.651661 | Filter_13146 | I | [
"add",
"add_three_numbers"
] | 2 | [
[
"add_three_numbers",
"add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 795e21b503b133c2a6f3740da3cfbec686d7a79d | 7174fbf3f607cbf870ebf0da5c9ff108d74571a8 | |||
v1.0 | instruct | Filter | Filter_13151_I | I've been tasked with writing a simple web scraper using Python and BeautifulSoup. The goal is to scrape data from a website that has multiple pages of articles, and output the results to a CSV file.
I've written the code to scrape a single page, and it works as expected. Now, I'd like to modify it to scrape multiple ... | import csv
import requests
from bs4 import BeautifulSoup
def scrape_page(url):
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.find_all('article')
data = []
for article in articles:
... | import requests
from unittest.mock import patch, Mock
import pytest
from solution import scrape_page, scrape_all_pages, save_to_csv
# Sample HTML structure for testing
html_content = '''
<html>
<body>
<article>
<h2>Article 1</h2>
<a href="http://example.com/article1">Read more</a>
... | [
{
"docstring": null,
"function_declaration": "def scrape_page(url):",
"function_name": "scrape_page",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def scrape_all_pages(base_url, num_pages):",
"function_name": "scrape_all_pages",
"parameter_list": "(b... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef scrape_page(url):\n try:\n response = requests.get(url)\n response.raise_for_status()\n soup = Beautif... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00013151",
"row_id": 13151,
"seed_ids": "['Llama-3.3-70B-Instruct_34140']"
} | 0.700258 | Filter_13151 | I | [
"scrape_page",
"scrape_all_pages",
"save_to_csv"
] | 3 | [
[
"scrape_all_pages",
"scrape_page"
]
] | 1 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | 2256c0010519748487543f0b20816893d3fc0656 | e761168f1817c10f1b99c57941545ac5a25a8fca | |||
v1.0 | instruct | Filter | Filter_13156_I | Here is the code
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def f(energy):
# Gaussian function
return np.exp(-energy)
# Function to perform the analysis
def analysis(df):
# Create an array for the energy
energy = np.linspace(-10, 10, 100)
# Create an array for the ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def f(energy):
# Gaussian function
return np.exp(-energy)
# Function to perform the analysis
def analysis(df, file_name=None):
# Create an array for the energy
energy = np.linspace(-10, 10, 100)
# Create an array for the Gauss... | import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from solution import analysis, f
def test_f():
energy = np.array([0, 1, 2])
expected = np.exp(-energy)
assert np.allclose(f(energy), expected)
def test_analysis_show(monkeypatch):
import builtins
import matplotlib.pyp... | [
{
"docstring": null,
"function_declaration": "def f(energy):",
"function_name": "f",
"parameter_list": "(energy)"
},
{
"docstring": null,
"function_declaration": "def analysis(df, file_name=None):",
"function_name": "analysis",
"parameter_list": "(df, file_name=None)"
},
{
... | [
0,
1,
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 numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(energy):\n # Gaussian function\n return np.exp(-energy)\n\n# Function to perform the analysis\ndef analy... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013156",
"row_id": 13156,
"seed_ids": "['Llama-3.3-70B-Instruct_34153']"
} | 0.612764 | Filter_13156 | I | [
"f",
"analysis",
"main"
] | 3 | [
[
"analysis",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas"
] | false | aacd9cc6d5a27b47c7756b75956680b70ec0df9b | f39091f90a807a83a9c5834911cf44a3a4997b1f | |||
v1.0 | instruct | Filter | Filter_13164_I | Here is a simple Python function that converts a list of JSON objects into a single JSON object:
```python
import json
def convert_to_single_json(lst):
"""
Convert a list of JSON objects into a single JSON object.
Args:
lst (list): A list of JSON objects
Returns:
dict: A single JSON object
... | import json
def merge_dicts(dict1, dict2):
"""
Recursively merges dict2 into dict1.
Args:
dict1 (dict): The dictionary to merge into
dict2 (dict): The dictionary to merge from
Returns:
dict: The merged dictionary
"""
for key in dict2:
if key in dict1 and isinstance(dict1[k... | from solution import convert_to_single_json
def test_convert_to_single_json_simple():
lst = [{"a": 1}, {"b": 2}, {"c": 3}]
expected = {"a": 1, "b": 2, "c": 3}
assert convert_to_single_json(lst) == expected
def test_convert_to_single_json_nested():
lst = [{"a": {"x": 10}}, {"a": {"y": 20}}, {"b": {"z":... | [
{
"docstring": "Recursively merges dict2 into dict1.\n\nArgs:\ndict1 (dict): The dictionary to merge into\ndict2 (dict): The dictionary to merge from\n\nReturns:\ndict: The merged dictionary",
"function_declaration": "def merge_dicts(dict1, dict2):",
"function_name": "merge_dicts",
"parameter_list":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef merge_dicts(dict1, dict2):\n \"\"\"\n Recursively merges dict2 into dict1.\n \"\"\"\n for key, value in dict2.items():\n if key in dict1 and isinstance(di... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013164",
"row_id": 13164,
"seed_ids": "['Llama-3.3-70B-Instruct_34167']"
} | 0.589877 | Filter_13164 | I | [
"merge_dicts",
"convert_to_single_json"
] | 2 | [
[
"convert_to_single_json",
"merge_dicts"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 12ece638813534749cc4dc933e6794a80b7b5bf6 | 8adddcd5e608738dc7603c89bdbfda506cbe2fc1 | |||
v1.0 | instruct | Filter | Filter_13179_I | I have a script that contains multiple functions. How can I call one function from within another function in Python? | def greet(name):
"""
Returns a greeting message for the given name.
"""
return f"Hello, {name}!"
def welcome_user(name, age):
"""
Calls the greet function and combines its result with an additional welcome message.
"""
greeting_message = greet(name)
welcome_message = f"{greeting_mes... | from solution import greet, welcome_user
def test_greet():
assert greet("Alice") == "Hello, Alice!"
assert greet("Bob") == "Hello, Bob!"
assert greet("") == "Hello, !"
def test_welcome_user():
assert welcome_user("Alice", 30) == "Hello, Alice! You are 30 years old."
assert welcome_user("Bob", 25) ... | [
{
"docstring": "Returns a greeting message for the given name.",
"function_declaration": "def greet(name):",
"function_name": "greet",
"parameter_list": "(name)"
},
{
"docstring": "Calls the greet function and combines its result with an additional welcome message.",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greet(name):\n \"\"\"\n Returns a greeting message for the given name.\n \"\"\"\n return f\"Hello, {name}!\"\n\ndef welcome_message(name):\n \"\"\"\n Returns a welcome me... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013179",
"row_id": 13179,
"seed_ids": "['Llama-3.3-70B-Instruct_34197']"
} | 0.439504 | Filter_13179 | I | [
"greet",
"welcome_user"
] | 2 | [
[
"welcome_user",
"greet"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f5929ccd08ac02f05314e31f801fe7ba16fbc49 | 64b24acc1a43ac4d8dd6a91ee687dce555d88614 | |||
v1.0 | instruct | Filter | Filter_13185_I | Here is a Python code that prints out the first 10 prime numbers:
```python
def is_prime(num):
"""Return True if a number is prime."""
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def get_n_primes(n):
"""Return the first n pr... | def is_prime(num):
"""Return True 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 get_n_primes(n):
"""Return the first n prime numbers."""
primes = []
num = 2
while len(prim... | from solution import is_prime, get_n_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(9) == False
assert is_prime(11) == True
def test_get_n_primes():
assert get_n_primes(0) == []
as... | [
{
"docstring": "Return True if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Return the first n prime numbers.",
"function_declaration": "def get_n_primes(n):",
"function_name": "get_n_prim... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"Return True if a number is prime.\"\"\"\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013185",
"row_id": 13185,
"seed_ids": "['Llama-3.3-70B-Instruct_34215']"
} | 0.714637 | Filter_13185 | I | [
"is_prime",
"get_n_primes"
] | 2 | [
[
"get_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ebc2e5f8be650fa2ad1353b1e101c53723e8869 | ec815ff7fd71cd7af9a7b47c76d87072bbd20752 | |||
v1.0 | instruct | Filter | Filter_13207_I | I've been trying to create a simple game for my kids and I've got a bit stuck.
I have a grid of 10x10 squares that the player can move around in. The movement can only be horizontal or vertical (no diagonal movement).
The player starts at a random position on the grid, and should move towards the goal location at the... | import random
import time
# Initialize grid size
grid_size = 10
# Function to generate a random starting position
def get_random_start():
return (random.randint(0, grid_size-1), random.randint(0, grid_size-1))
# Function to generate the goal location
def get_goal_location(start):
# Ensure goal location is at... | from solution import get_random_start, get_goal_location, get_next_move
def test_get_random_start():
start = get_random_start()
assert 0 <= start[0] < 10
assert 0 <= start[1] < 10
def test_get_goal_location():
goal = get_goal_location((0, 0))
assert goal == (9, 9)
goal = get_goal_location((9, ... | [
{
"docstring": null,
"function_declaration": "def get_random_start():",
"function_name": "get_random_start",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_goal_location(start):",
"function_name": "get_goal_location",
"parameter_list": "(start)"
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Initialize grid size\ngrid_size = 10\n\n# Function to generate a random starting position\ndef get_random_start():\n return (random.randint(0, grid_size - 1), random.rand... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013207",
"row_id": 13207,
"seed_ids": "['Llama-3.3-70B-Instruct_34261']"
} | 0.63358 | Filter_13207 | I | [
"get_random_start",
"get_goal_location",
"get_next_move",
"game_loop"
] | 4 | [
[
"game_loop",
"get_goal_location"
],
[
"game_loop",
"get_next_move"
],
[
"game_loop",
"get_random_start"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 79c949faf8f3623222124d40e39cd14b813f23e1 | 72920355a79f74f590f18067e843155d0a35d56c | |||
v1.0 | instruct | Filter | Filter_13208_I | I'm trying to implement a code that could generate a random number between 1 and 100. Then take the result of that random number and find the closest prime number to it. The problem is, I haven't been able to find the closest prime in the range.
Here's the code that I'm working with so now:
```python
import random
d... | import random
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = int(n**0.5) + 1
for d in range(3, max_divisor, 2):
if n % d == 0:
return False
return True
d... | from solution import is_prime, find_closest_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(15) == False
def test_find_closest_prime():
assert find_closest_prime(14) == 13
assert find_c... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the closest prime number to n.",
"function_declaration": "def find_closest_prime(n):",
"function_name": "find_closest... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return Fa... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00013208",
"row_id": 13208,
"seed_ids": "['Llama-3.3-70B-Instruct_34263']"
} | 0.588485 | Filter_13208 | I | [
"is_prime",
"find_closest_prime",
"main"
] | 3 | [
[
"find_closest_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 91b3be13893491bfcd2bcae6e008aa6af9a281dd | 03077a970b025f3b02fb09e01755a67dc57bca42 | |||
v1.0 | instruct | Filter | Filter_13211_I | ### Introduction to Algorithms and Data Structures
#### 4.4 Dividing and Conquering
In divide-and-conquer algorithms, the problem is divided into smaller subproblems that are more easily solvable, and then the solutions to the sub-problems are combined to solve the original problem. The basic steps of a divide-and-conq... | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
return merge(left_half, right_half)
def merge(left, right):
result = []
i, j = 0, 0
... | # Unit tests for merge_sort
from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_rever... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Implements the merge sort algorithm using the divide-and-conquer approach.\n It sorts an input list of numbers in ascending order.\n \n Args:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013211",
"row_id": 13211,
"seed_ids": "['Llama-3.3-70B-Instruct_34268']"
} | 0.541719 | Filter_13211 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ddf1df22f0d65c5fb9960d7caff912866657b8cf | b451165b6916982344a60258eb2c709165fb542e | |||
v1.0 | instruct | Filter | Filter_13219_I | ### Introduction to Algorithms
# Mergesort
Mergesort is a comparison-based sorting algorithm that uses the divide-and-conquer technique. It works by splitting the input list into two halves, recursively sorting each half, and then merging the two sorted halves.
## Step-by-step analysis of the problem:
1. **Divide the... | def mergesort(arr):
"""
Sorts an array using the mergesort algorithm.
Args:
arr (list): The input list to be sorted.
Returns:
list: The sorted list.
"""
# Base case: If the list has one or zero elements, it's already sorted
if len(arr) <= 1:
return arr
# Find t... | from solution import mergesort
def test_mergesort_empty():
assert mergesort([]) == []
def test_mergesort_single_element():
assert mergesort([1]) == [1]
def test_mergesort_sorted_list():
assert mergesort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_mergesort_reverse_sorted_list():
assert mergesor... | [
{
"docstring": "Sorts an array using the mergesort algorithm.\n\nArgs:\n arr (list): The input list to be sorted.\n\nReturns:\n list: The sorted list.",
"function_declaration": "def mergesort(arr):",
"function_name": "mergesort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def mergesort(arr):\n \"\"\"\n Sorts an array using the mergesort algorithm.\n\n Args:\n arr (list): The input list to be sorted.\n\n Returns:\n list: The sorted list... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00013219",
"row_id": 13219,
"seed_ids": "['Llama-3.3-70B-Instruct_34286']"
} | 0.590217 | Filter_13219 | I | [
"mergesort",
"merge"
] | 2 | [
[
"mergesort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3fd6f401de080a769aeda00dbadd1088e7e79068 | 74b11f4f2d16a6a2c8f3f9b38d18a729022a24cf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.