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_69913_I | Write a Python function that takes an integer `n` and returns a list containing the first `n` prime numbers. For example, if `n = 5`, the function should return `[2, 3, 5, 7, 11]`. | def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
p = 3
while p * p <= num:
if num % p == 0:
return False
p += 2
return True
def first_n_primes(... | from solution import first_n_primes
def test_first_5_primes():
assert first_n_primes(5) == [2, 3, 5, 7, 11]
def test_first_1_prime():
assert first_n_primes(1) == [2]
def test_first_10_primes():
assert first_n_primes(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_zero_primes():
assert first_n_p... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list containing the first n prime numbers.",
"function_declaration": "def first_n_primes(n):",
"function_na... | [
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 Checks 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 retur... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00069913",
"row_id": 69913,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141658']"
} | 0.734363 | Filter_69913 | I | [
"is_prime",
"first_n_primes"
] | 2 | [
[
"first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ebb644a3eaba49348ae45412a9e7992a57e3f00a | fd7bd36192e7eccec0b4f348716a04e40c78b983 | |||
v1.0 | instruct | Filter | Filter_69918_I | Create a Python code snippet that simulates a simple neural network for regression using only numpy. No external libraries like TensorFlow or PyTorch are allowed. | import numpy as np
def initialize_weights(input_size, hidden_size, output_size):
np.random.seed(42) # For reproducibility
W1 = np.random.rand(hidden_size, input_size)
b1 = np.zeros((hidden_size, 1))
W2 = np.random.rand(output_size, hidden_size)
b2 = np.zeros((output_size, 1))
return W1, b1, W2... | import numpy as np
from solution import train_neural_network, predict, initialize_weights, forward_propagation
def test_initialize_weights():
W1, b1, W2, b2 = initialize_weights(2, 3, 1)
assert W1.shape == (3, 2)
assert b1.shape == (3, 1)
assert W2.shape == (1, 3)
assert b2.shape == (1, 1)
def tes... | [
{
"docstring": null,
"function_declaration": "def initialize_weights(input_size, hidden_size, output_size):",
"function_name": "initialize_weights",
"parameter_list": "(input_size, hidden_size, output_size)"
},
{
"docstring": null,
"function_declaration": "def sigmoid(x):",
"function... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_parameters(input_dim, hidden_dim, output_dim):\n np.random.seed(1)\n W1 = np.random.randn(hidden_dim, input_dim) * 0.01\n b1 = np.zeros((hidden_di... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00069918",
"row_id": 69918,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141671']"
} | 0.434576 | Filter_69918 | I | [
"initialize_weights",
"sigmoid",
"sigmoid_derivative",
"mean_squared_error",
"forward_propagation",
"back_propagation",
"train_neural_network",
"predict"
] | 8 | [
[
"back_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"predict",
"forward_propagation"
],
[
"train_neural_network",
"back_propagation"
],
[
"train_neural_network",
"forward_propagation"
],
[
"train_neural_network",
"... | 7 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 7e88a053adfc6d6da014e86047710b443f121e58 | 9ec88e0c5d7bf2fb7b8036c1be0b0d20aac21bd1 | |||
v1.0 | instruct | Filter | Filter_69925_I | Can you explain the concept of merge sort and provide a Python implementation? | def merge_sort(arr):
"""
Sorts the array in ascending order using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
"""
Merges two ... | from solution import merge_sort, merge
def test_merge_sort_empty():
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():
as... | [
{
"docstring": "Sorts the array in ascending order using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into one sorted array.",
"function_declaration": "def ... | [
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 Performs merge sort on a list of elements.\n\n :param arr: List of elements to be sorted.\n :return: Sorted list of elements.\n \"\"\"\n if le... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069925",
"row_id": 69925,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141682']"
} | 0.604037 | Filter_69925 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5cd07fdf1119e74800d546d37a7cb75a9eaf68b7 | d8baa3bbf51b68d9c96372c0660958a9171ab7c2 | |||
v1.0 | instruct | Filter | Filter_69938_I | Can you provide a Python function to calculate the balance factors of a given AVL tree? The balance factor of a node in an AVL tree is the difference between the heights of its left and right subtrees. | class TreeNode:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
self.height = 1
def update_height(node):
if node is None:
return 0
node.height = max(update_height(node.left), update_height(node.right)) + 1
return... | from solution import TreeNode, calculate_balance_factors
def test_single_node_tree():
tree = TreeNode(1)
assert calculate_balance_factors(tree) == {1: 0}
def test_balanced_tree():
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.right = TreeNode(3)
assert calculate_balance_factors(tree) == {1: ... | [] | [
0,
1,
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, key):\n self.left = None\n self.right = None\n self.val = key\n self.height = 1 # AVL tree nodes store height\n\ndef height... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069938",
"row_id": 69938,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141710']"
} | 0.58035 | Filter_69938 | I | [
"update_height",
"get_height",
"calculate_balance_factors"
] | 3 | [
[
"calculate_balance_factors",
"get_height"
],
[
"calculate_balance_factors",
"update_height"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | ca5b47f3c711b2dde0d9ccc3e6fb508dad1cfaa5 | 1d67edfff92a67422a6e5f268dc2137fc8698e27 | |||
v1.0 | instruct | Filter | Filter_69951_I | Given a list of integers, write a Python function that identifies all prime numbers within that list and returns them in a sorted list. The function should be optimized to handle large lists efficiently. | def is_prime(n):
"""
Check if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | from solution import find_primes
def test_find_primes_no_primes():
assert find_primes([1, 4, 6, 8, 10]) == []
def test_find_primes_all_primes():
assert find_primes([2, 3, 5, 7, 11]) == [2, 3, 5, 7, 11]
def test_find_primes_mixed():
assert find_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7]
def ... | [
{
"docstring": "Check if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Identify all prime numbers within a list of integers and return them in a sorted list.",
"function_declaration": "def find_p... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069951",
"row_id": 69951,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141730']"
} | 0.665499 | Filter_69951 | I | [
"is_prime",
"find_primes"
] | 2 | [
[
"find_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c804fb4a180f533a5106ac4130b0c5e980c341ba | c2ce27b903b1100ad2a2fd2f21d45723571145d5 | |||
v1.0 | instruct | Filter | Filter_69970_I | Hello! I need to create a simple text-based adventure game using Python. The game should have a main menu where the user can choose between starting the game or exiting. If the user chooses to start the game, they should be prompted to choose a path. Each path should lead to a different story outcome. How can I structu... | def main_menu():
"""
Display the main menu and handle user input to start the game or exit.
"""
print("Welcome to the Adventure Game!")
print("1: Start Game")
print("2: Exit")
choice = input("Enter your choice: ")
if choice == '1':
choose_path()
elif choice == '2':
... | # It is challenging to test interactive console-based input with pytest directly.
# Instead, we can simulate input/output using the 'unittest.mock' module.
from unittest.mock import patch
import pytest
from solution import main_menu, choose_path
def test_main_menu_start_game():
with patch('builtins.input', side_e... | [
{
"docstring": "Display the main menu and handle user input to start the game or exit.",
"function_declaration": "def main_menu():",
"function_name": "main_menu",
"parameter_list": "()"
},
{
"docstring": "Prompt the user to choose a path and display the story outcome.",
"function_declara... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def main_menu():\n while True:\n print(\"\\nWelcome to the Adventure Game!\")\n print(\"1. Start Game\")\n print(\"2. Exit\")\n choice = input(\"Enter your choic... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00069970",
"row_id": 69970,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141773']"
} | 0.40275 | Filter_69970 | I | [
"main_menu",
"choose_path"
] | 2 | [
[
"main_menu",
"choose_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1f65d5bf1513b985d039053fc879e8fcf74c5958 | 26d650cc6abb5b06f96732bfc9311e9409486eab | |||
v1.0 | instruct | Filter | Filter_70029_I | Write a Python script that takes a folder path as input and lists all the files in that folder. The script should also print the file sizes in a human-readable format (e.g., KB, MB, GB). | import os
def human_readable_size(size, decimal_places=2):
"""
Convert a file size to a human-readable format (e.g., KB, MB, GB).
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.{decimal_places}f} {unit}"
size /= 1024
def list_files_with_sizes... | import os
import pytest
from solution import human_readable_size, list_files_with_sizes
def test_human_readable_size():
assert human_readable_size(1023) == "1023.00 B"
assert human_readable_size(1024) == "1.00 KB"
assert human_readable_size(1048576) == "1.00 MB"
assert human_readable_size(1073741824) =... | [
{
"docstring": "Convert a file size to a human-readable format (e.g., KB, MB, GB).",
"function_declaration": "def human_readable_size(size, decimal_places=2):",
"function_name": "human_readable_size",
"parameter_list": "(size, decimal_places=2)"
},
{
"docstring": "List all files in the given... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef human_readable_size(size, decimal_places=2):\n \"\"\"\n Converts a file size in bytes to a human-readable string.\n \"\"\"\n for unit in ['B', 'KB', 'MB', 'GB', 'T... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070029",
"row_id": 70029,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141914']"
} | 0.630252 | Filter_70029 | I | [
"human_readable_size",
"list_files_with_sizes"
] | 2 | [
[
"list_files_with_sizes",
"human_readable_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d8adfe022fe85477b5f7bf767e1c2c95fc366782 | 9688d2b05f1789465264b7af5a1963e631d2b319 | |||
v1.0 | instruct | Filter | Filter_70034_I | How can I create a Python script to monitor the temperature of a server in real-time? | import psutil
import time
def get_cpu_temperature():
"""
Returns the current CPU temperature.
"""
temps = psutil.sensors_temperatures()
if not temps:
raise RuntimeError("Unable to retrieve temperature data")
for name, entries in temps.items():
for entry in entries:
i... | from solution import get_cpu_temperature
def test_get_cpu_temperature():
try:
temp = get_cpu_temperature()
# Assuming reasonable range for CPU temperature in degrees Celsius
assert 10 <= temp <= 100
except RuntimeError as e:
assert str(e) in ["Unable to retrieve temperature dat... | [
{
"docstring": "Returns the current CPU temperature.",
"function_declaration": "def get_cpu_temperature():",
"function_name": "get_cpu_temperature",
"parameter_list": "()"
},
{
"docstring": "Monitors and prints the CPU temperature at the specified interval.",
"function_declaration": "def... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport time\n\ndef get_cpu_temperature():\n \"\"\"\n Returns the current CPU temperature.\n \"\"\"\n temps = psutil.sensors_temperatures()\n if not temps:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00070034",
"row_id": 70034,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_141922']"
} | 0.487017 | Filter_70034 | I | [
"get_cpu_temperature",
"monitor_temperature"
] | 2 | [
[
"monitor_temperature",
"get_cpu_temperature"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | ec1c26c6064d7acc2b89a530a7959b087af67a10 | 15c4bac33a9ed18a13be1f8966abe3224ce80333 | |||
v1.0 | instruct | Filter | Filter_70125_I | I need to create a script that compares two JSON files, finds the differences, and outputs them in a structured format. The script should handle potential errors gracefully. How can I achieve this in Python? | import json
import os
def load_json(file_path):
"""
Load JSON data from a file.
"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
try:
with open(file_path, 'r') as file:
data = json.load(file)
except json.JSONDecod... | import pytest
from solution import load_json, find_differences, compare_json_files
import json
def test_load_json_valid(tmpdir):
file_path = tmpdir.join("valid.json")
file_path.write(json.dumps({"key": "value"}))
assert load_json(str(file_path)) == {"key": "value"}
def test_load_json_invalid(tmpdir):
... | [
{
"docstring": "Load JSON data from a file.",
"function_declaration": "def load_json(file_path):",
"function_name": "load_json",
"parameter_list": "(file_path)"
},
{
"docstring": "Recursively find differences between two JSON objects.",
"function_declaration": "def find_differences(json1... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nfrom deepdiff import DeepDiff\n\ndef load_json(file_path):\n \"\"\"\n Load JSON data from a file.\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070125",
"row_id": 70125,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142106']"
} | 0.642986 | Filter_70125 | I | [
"load_json",
"find_differences",
"compare_json_files"
] | 3 | [
[
"compare_json_files",
"find_differences"
],
[
"compare_json_files",
"load_json"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 988cd26539c0bee11b9af07ddd9ec160b7826353 | 78f2850249099b4e72ffd0f42f5dd0979e135df5 | |||
v1.0 | instruct | Filter | Filter_70169_I | Can you create a Python function that simulates the placement of ships in a standard 10x10 Battleship game grid? The ships must not overlap and must be placed either horizontally or vertically. The ships are of the following sizes: one battleship (4 cells), two cruisers (3 cells each), three destroyers (2 cells each), ... | import random
def is_within_bounds(x, y, length, direction, grid_size=10):
if direction == 'H':
return x + length <= grid_size
elif direction == 'V':
return y + length <= grid_size
def is_overlap(x, y, length, direction, grid):
if direction == 'H':
for i in range(length):
... | from solution import generate_battleship_grid
def test_grid_size():
grid = generate_battleship_grid()
assert len(grid) == 10
assert all(len(row) == 10 for row in grid)
def test_correct_ship_counts():
grid = generate_battleship_grid()
ship_counts = {
1: 4,
2: 3,
3: 3,
... | [
{
"docstring": null,
"function_declaration": "def is_within_bounds(x, y, length, direction, grid_size=10):",
"function_name": "is_within_bounds",
"parameter_list": "(x, y, length, direction, grid_size=10)"
},
{
"docstring": null,
"function_declaration": "def is_overlap(x, y, length, dire... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef place_ships():\n \"\"\"\n Simulates the placement of ships on a 10x10 Battleship game grid.\n The ships must not overlap and must be placed either horizontally or... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070169",
"row_id": 70169,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142193']"
} | 0.4029 | Filter_70169 | I | [
"is_within_bounds",
"is_overlap",
"place_ship",
"generate_battleship_grid"
] | 4 | [
[
"generate_battleship_grid",
"is_overlap"
],
[
"generate_battleship_grid",
"is_within_bounds"
],
[
"generate_battleship_grid",
"place_ship"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ebf62b1e0f7d7133693649c17aee283896ed8759 | f83b8c17f6b8baece11aa6ad65a41356b09ca3e8 | |||
v1.0 | instruct | Filter | Filter_70211_I | Hey Qwen, I'm trying to write a program that identifies duplicate files in a directory. How can I achieve this in Python? | import os
import hashlib
def get_file_hash(file_path):
"""
Returns the SHA-256 hash of the file.
"""
hasher = hashlib.sha256()
with open(file_path, 'rb') as f:
for byte_block in iter(lambda: f.read(4096), b""):
hasher.update(byte_block)
return hasher.hexdigest()
def find_du... | import os
import shutil
import pytest
from solution import get_file_hash, find_duplicate_files
@pytest.fixture
def setup_test_files(tmp_path):
# Create a temporary directory with duplicate files
dir_path = tmp_path / "test_dir"
dir_path.mkdir()
file1 = dir_path / "file1.txt"
file2 = dir_path / "fi... | [
{
"docstring": "Returns the SHA-256 hash of the file.",
"function_declaration": "def get_file_hash(file_path):",
"function_name": "get_file_hash",
"parameter_list": "(file_path)"
},
{
"docstring": "Identifies duplicate files in the directory.",
"function_declaration": "def find_duplicate... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\n\ndef get_file_hash(file_path):\n \"\"\"Returns the MD5 hash of the file specified by file_path.\"\"\"\n hasher = hashlib.md5()\n with open(file_path, 'rb')... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070211",
"row_id": 70211,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142275']"
} | 0.603673 | Filter_70211 | I | [
"get_file_hash",
"find_duplicate_files"
] | 2 | [
[
"find_duplicate_files",
"get_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aa17e0639721e8091204c0ed0b27c252fabd3115 | ee610498283020750a7f6fbf7d86df998e7dfdaa | |||
v1.0 | instruct | Filter | Filter_70218_I | I'm interested in creating a Python script that can detect and list all the prime numbers within a given range. I want the script to prompt the user to input the range limits. How can I do this? | def is_prime(n):
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i... | from solution import is_prime, list_primes_in_range
def test_is_prime():
# Test edge cases
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
# Test some prime numbers
assert is_prime(5)
assert is_prime(11)
assert is_prime(... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers in the specified range [start, end].",
"function_declaration": "def l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00070218",
"row_id": 70218,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142285']"
} | 0.521371 | Filter_70218 | I | [
"is_prime",
"list_primes_in_range"
] | 2 | [
[
"list_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 828399ac9925af50253671b77d1a06f888ff840b | c644952da3cb03a48d05d6cd10eafca51a0b03d0 | |||
v1.0 | instruct | Filter | Filter_70241_I | Create a Python function that reads a file containing numerical values and calculates the mean, median, and mode of the numbers. The function should handle potential errors such as file not found, invalid data, and divide by zero. The file should contain one number per line. Assume numbers are integers. | import statistics
def read_numbers_from_file(file_path):
"""
Reads a file containing numerical values, one per line, and returns a list of integers.
Handles potential errors such as file not found and invalid data.
"""
try:
with open(file_path, 'r') as file:
numbers = [int(line.... | import os
import pytest
from solution import read_numbers_from_file, calculate_statistics
def test_read_numbers_from_file(tmp_path):
# Create a temporary file
d = tmp_path / "sub"
d.mkdir()
file = d / "numbers.txt"
# Write numbers to the file
numbers = "1\n2\n3\n4\n5\n"
file.write_text(num... | [
{
"docstring": "Reads a file containing numerical values, one per line, and returns a list of integers.\nHandles potential errors such as file not found and invalid data.",
"function_declaration": "def read_numbers_from_file(file_path):",
"function_name": "read_numbers_from_file",
"parameter_list": ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import statistics\n\ndef calculate_statistics(file_path):\n \"\"\"\n Reads a file containing numerical values and calculates the mean, median, and mode of the numbers.\n Handles error... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070241",
"row_id": 70241,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142323']"
} | 0.714478 | Filter_70241 | I | [
"read_numbers_from_file",
"calculate_statistics"
] | 2 | [
[
"calculate_statistics",
"read_numbers_from_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b808cbeb7e0c2332bb71340c2e6db34b02a4fe28 | 4f38c28483719ddf8be7664fed5a17a97f2e2972 | |||
v1.0 | instruct | Filter | Filter_70257_I | Can you explain how to create a process in Python that simulates a simple dice rolling game? | import random
def roll_die():
"""
Rolls a single 6-sided die and returns the result (an integer between 1 and 6).
"""
return random.randint(1, 6)
def roll_dice(num_dice):
"""
Rolls `num_dice` 6-sided dice and returns a list of results.
Args:
num_dice (int): The number of dice ... | from solution import roll_die, roll_dice, determine_winner
import random
def test_roll_die():
# Test rolling a single die
result = roll_die()
assert 1 <= result <= 6
def test_roll_dice():
# Test rolling multiple dice
num_dice = 5
results = roll_dice(num_dice)
assert len(results) == num_dic... | [
{
"docstring": "Rolls a single 6-sided die and returns the result (an integer between 1 and 6).",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Rolls `num_dice` 6-sided dice and returns a list of results.\n\nArgs:\n num_d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a dice and returns a random number between 1 and 6.\n \"\"\"\n return random.randint(1, 6)",
"test_code": "from s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070257",
"row_id": 70257,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142357']"
} | 0.569908 | Filter_70257 | I | [
"roll_die",
"roll_dice",
"determine_winner"
] | 3 | [
[
"roll_dice",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 464c402d6ba638ec110aad9e5f237868b45a6720 | 284228961f28f6646c5c5217f77bd69d7d237852 | |||
v1.0 | instruct | Filter | Filter_70316_I | Can you provide the code for a simple dice game in Python where two players roll a six-sided die and the player with the higher number wins? | import random
def roll_die():
"""
Simulates rolling a six-sided die and returns the result (an integer between 1 and 6).
"""
return random.randint(1, 6)
def play_dice_game():
"""
Simulates a simple dice game where two players roll a die.
The player with the higher number wins.
If both ... | from solution import roll_die, play_dice_game
def test_roll_die():
for _ in range(100): # Test 100 times to ensure randomness covers all cases
result = roll_die()
assert 1 <= result <= 6, f"Roll die returned an out-of-bounds number: {result}"
def test_play_dice_game_tie(monkeypatch):
"""
... | [
{
"docstring": "Simulates rolling a six-sided die and returns the result (an integer between 1 and 6).",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a simple dice game where two players roll a die.\nThe player wi... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided dice and returns the result.\n \"\"\"\n return random.randint(1, 6)\n\ndef dice_game():\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070316",
"row_id": 70316,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142491']"
} | 0.500849 | Filter_70316 | I | [
"roll_die",
"play_dice_game"
] | 2 | [
[
"play_dice_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1de5544ca129ee0e4b99df27478b066c5de9b7b2 | 7166142eb2cfa995288ad09ef2b537df6f73ddfa | |||
v1.0 | instruct | Filter | Filter_70322_I | Can you provide an example of how to create a simple command-line utility in Python that encrypts and decrypts a message using a simple Caesar cipher? | def caesar_cipher_encrypt(message, shift):
"""
Encrypts a message using a Caesar cipher with a given shift.
"""
encrypted_message = ""
for char in message:
if char.isalpha():
shift_amount = 65 if char.isupper() else 97
encrypted_char = chr((ord(char) - shift_amount + ... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt_basic():
assert caesar_cipher_encrypt("HELLO", 3) == "KHOOR"
def test_caesar_cipher_encrypt_lower():
assert caesar_cipher_encrypt("hello", 3) == "khoor"
def test_caesar_cipher_encrypt_with_spaces():
assert c... | [
{
"docstring": "Encrypts a message using a Caesar cipher with a given shift.",
"function_declaration": "def caesar_cipher_encrypt(message, shift):",
"function_name": "caesar_cipher_encrypt",
"parameter_list": "(message, shift)"
},
{
"docstring": "Decrypts a message using a Caesar cipher with... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encrypt(message, shift):\n \"\"\"\n Encrypts a message using the Caesar cipher technique.\n \n :param message: str - The message to encrypt.\n :param shift: in... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070322",
"row_id": 70322,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142504']"
} | 0.542712 | Filter_70322 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 59bbf0ef8e255847b14a217f849a8035fe48a896 | f4ff27a5046a6a8ca6429d850003bf64f6ce48ec | |||
v1.0 | instruct | Filter | Filter_70325_I | Can you show me how to create a Python script that reads data from a file and processes it to find the average of numbers listed in a file? | def read_numbers_from_file(file_path):
"""
Reads a list of numbers from a file and returns them as a list of floats.
Each number should be on a separate line in the file.
"""
with open(file_path, 'r') as file:
numbers = [float(line.strip()) for line in file if line.strip()]
return number... | import tempfile
import os
from solution import read_numbers_from_file, calculate_average, average_from_file
def test_read_numbers_from_file():
test_data = "1.0\n2.0\n3.0\n"
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(test_data.encode())
temp_file_path = temp_fil... | [
{
"docstring": "Reads a list of numbers from a file and returns them as a list of floats.\nEach number should be on a separate line in the file.",
"function_declaration": "def read_numbers_from_file(file_path):",
"function_name": "read_numbers_from_file",
"parameter_list": "(file_path)"
},
{
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_average(file_path):\n \"\"\"\n Reads numbers from a file and calculates the average.\n \n Parameters:\n file_path (str): The path to the file containing number... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070325",
"row_id": 70325,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142508']"
} | 0.655746 | Filter_70325 | I | [
"read_numbers_from_file",
"calculate_average",
"average_from_file"
] | 3 | [
[
"average_from_file",
"calculate_average"
],
[
"average_from_file",
"read_numbers_from_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ff8c9f4dcfe595b73c0e81d806078268be3769ce | 1b7c680a7c9f5a27f17486dc778a2e1cd3ab3aaa | |||
v1.0 | instruct | Filter | Filter_70333_I | Can you provide a Python script that simulates a simple game of rock, paper, scissors? The game should allow a user to play against the computer, which randomly selects its move. The game should continue until the user decides to stop. | import random
def get_computer_choice():
"""
Randomly selects the computer's choice of rock, paper, or scissors.
"""
choices = ["rock", "paper", "scissors"]
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
"""
Determines the winner of a rock, paper, scissor... | from solution import get_computer_choice, determine_winner, play_round
def test_get_computer_choice():
choices = set(get_computer_choice() for _ in range(100))
assert choices.issubset({"rock", "paper", "scissors"})
def test_determine_winner():
assert determine_winner("rock", "scissors") == "user"
asse... | [
{
"docstring": "Randomly selects the computer's choice of rock, paper, or scissors.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of a rock, paper, scissors game.",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly selects the computer's move.\n \"\"\"\n return random.choice(['rock', 'paper', 'scissors'])\n\ndef determine_winner(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070333",
"row_id": 70333,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142527']"
} | 0.375397 | Filter_70333 | I | [
"get_computer_choice",
"determine_winner",
"play_round",
"play_game"
] | 4 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"play_round"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f2fd45c3dc2e180014e1b126556bab4780efe5c6 | 0c3c7ef716ffe65567b3961c2a8b2285ab19a8de | |||
v1.0 | instruct | Filter | Filter_70335_I | I am learning Python and I want to write a program that can print the first 100 prime numbers. Can you guide me on how to do this? | def is_prime(n):
"""
Check if a number is a prime number.
"""
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import is_prime, first_n_primes
def test_is_prime():
assert not is_prime(-1)
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert is_prime(13)
assert not is_prime(15)
def test_first_n_prim... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the first n prime numbers.",
"function_declaration": "def first_n_primes(n):",
"function_name": "first_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 Checks whether a number is a 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_1 | {
"original_instruction": "",
"prompt_id": "00070335",
"row_id": 70335,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142531']"
} | 0.586224 | Filter_70335 | I | [
"is_prime",
"first_n_primes"
] | 2 | [
[
"first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a6f3f1b4e73145f488a69d7a95847fbe4b6100ba | 59c01c73206e5ba5063c1932adc476ef29b108a5 | |||
v1.0 | instruct | Filter | Filter_70364_I | How can I write a Python script that reads a large text file, processes it, and writes the output to another file? How can I handle memory constraints when dealing with large files? | def process_line(line):
"""
Placeholder function to process a single line of text.
Modify this function according to the required processing.
"""
# Example processing: convert line to uppercase
return line.upper()
def process_large_file(input_file_path, output_file_path, buffer_size=1024*1024):... | import os
from solution import process_large_file, process_line
def test_process_line():
assert process_line("hello\n") == "HELLO\n"
assert process_line("world") == "WORLD"
def test_process_large_file(tmpdir):
input_file_path = os.path.join(tmpdir, 'input.txt')
output_file_path = os.path.join(tmpdir, ... | [
{
"docstring": "Placeholder function to process a single line of text.\nModify this function according to the required processing.",
"function_declaration": "def process_line(line):",
"function_name": "process_line",
"parameter_list": "(line)"
},
{
"docstring": "Reads a large text file, proc... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_line(line):\n \"\"\"\n Process a single line of text and return the processed line.\n This is a placeholder function and should be implemented with actual processing logic... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070364",
"row_id": 70364,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142589']"
} | 0.419958 | Filter_70364 | I | [
"process_line",
"process_large_file"
] | 2 | [
[
"process_large_file",
"process_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3719654def868da8e2fb24cfb724d31249237635 | 236fed2d5df38cd0a2fe29a1eb051155d2c5e4d0 | |||
v1.0 | instruct | Filter | Filter_70371_I | Can you generate a Python code that calculates the total cost of items in a shopping cart, given their individual prices, quantities, and a discount rate? The code should include functions for calculating the subtotal, applying the discount, and calculating the final total cost. | def calculate_subtotal(prices, quantities):
"""
Calculates the subtotal cost for the items in the cart.
:param prices: List of item prices.
:param quantities: List of item quantities.
:return: Subtotal cost.
"""
return sum(price * quantity for price, quantity in zip(prices, quantities))... | from solution import calculate_subtotal, apply_discount, calculate_total_cost
def test_calculate_subtotal():
prices = [10, 20, 30]
quantities = [1, 2, 3]
assert calculate_subtotal(prices, quantities) == 140
def test_apply_discount():
subtotal = 200
discount_rate = 10
assert apply_discount(subt... | [
{
"docstring": "Calculates the subtotal cost for the items in the cart.\n\n:param prices: List of item prices.\n:param quantities: List of item quantities.\n:return: Subtotal cost.",
"function_declaration": "def calculate_subtotal(prices, quantities):",
"function_name": "calculate_subtotal",
"parame... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_subtotal(prices, quantities):\n \"\"\"\n Calculates the subtotal cost for the items in the cart.\n \n :param prices: List of item prices.\n :param quantities: List... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00070371",
"row_id": 70371,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142599']"
} | 0.440593 | Filter_70371 | I | [
"calculate_subtotal",
"apply_discount",
"calculate_total_cost"
] | 3 | [
[
"calculate_total_cost",
"apply_discount"
],
[
"calculate_total_cost",
"calculate_subtotal"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6909986aefd43a5540a27f63c5109478f4c3a447 | 5ea4339170401feffb9ad0a130d61b6ceaeb0083 | |||
v1.0 | instruct | Filter | Filter_70373_I | Can you help me with developing a Python program that simulates a simple game of rock-paper-scissors? The game should allow a user to play against the computer, and the computer's choice should be randomly generated. The program should also keep track of the score and allow the user to play multiple rounds until they d... | import random
def get_computer_choice():
"""
Randomly selects a choice for the computer from Rock, Paper, and Scissors.
"""
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of a rock-paper-scissors round between... | from solution import get_computer_choice, determine_winner, play_round
import pytest
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
for _ in range(100):
choice = get_computer_choice()
assert choice in choices
def test_determine_winner():
assert determine_winner('ro... | [
{
"docstring": "Randomly selects a choice for the computer from Rock, Paper, and Scissors.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of a rock-paper-scissors round between pl... | [
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_computer_choice():\n choices = [\"rock\", \"paper\", \"scissors\"]\n return random.choice(choices)\n\ndef get_winner(user_choice, computer_choice):\n if user_... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070373",
"row_id": 70373,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142609']"
} | 0.395933 | Filter_70373 | I | [
"get_computer_choice",
"determine_winner",
"play_round",
"play_game"
] | 4 | [
[
"play_game",
"get_computer_choice"
],
[
"play_game",
"play_round"
],
[
"play_round",
"determine_winner"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b220d9436540841e1977e917e46683e2f703f105 | 101995a4b923721669c6d83c20cbccee5ecc9765 | |||
v1.0 | instruct | Filter | Filter_70381_I | What are the steps to create a Python function that generates a list of prime numbers within a given range? | def is_prime(n):
"""
Check if a number n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import is_prime, generate_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(30) == False
def test_generate_primes():
assert generate_primes(10, 2... | [
{
"docstring": "Check if a number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of primes within the given range [start, end].",
"function_declaration": "def generate_primes(start... | [
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 if n == 2:\n return True\n if n % 2 == 0:\n return False\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070381",
"row_id": 70381,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142624']"
} | 0.667428 | Filter_70381 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71bc4ae43f6f8eaca82481689b70407f9dbe930c | e2ae9647733c975b06d02fce566038691655a045 | |||
v1.0 | instruct | Filter | Filter_70409_I | I need to create a Python script that can handle a JSON file with user data, such as name, age, and email. The script should be able to read the JSON file, modify a user's age, and then save the changes back to the JSON file. How can I achieve this? | import json
def read_json_file(file_path):
"""
Reads a JSON file and returns its content as a dictionary.
"""
with open(file_path, 'r') as file:
data = json.load(file)
return data
def write_json_file(file_path, data):
"""
Writes a dictionary to a JSON file.
"""
with open(fi... | import json
import os
import pytest
from solution import modify_user_age, read_json_file, write_json_file
# Define sample test data
sample_data = {
"John Doe": {
"age": 30,
"email": "john.doe@example.com"
},
"Jane Doe": {
"age": 25,
"email": "jane.doe@example.com"
}
}
#... | [
{
"docstring": "Reads a JSON file and returns its content as a dictionary.",
"function_declaration": "def read_json_file(file_path):",
"function_name": "read_json_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes a dictionary to a JSON file.",
"function_declaration": "def ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef read_json(file_path):\n \"\"\"\n Reads a JSON file and returns the data.\n \n Parameters:\n file_path (str): The path to the JSON file.\n \n Ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070409",
"row_id": 70409,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142676']"
} | 0.58374 | Filter_70409 | I | [
"read_json_file",
"write_json_file",
"modify_user_age"
] | 3 | [
[
"modify_user_age",
"read_json_file"
],
[
"modify_user_age",
"write_json_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5527256bb3dc609b8e31d48c46f08d738b9857a7 | 189a3b0d50c79e8635f4ed74a0e97114c2a31d05 | |||
v1.0 | instruct | Filter | Filter_70416_I | How can I create a Python function that calculates the sum of all prime numbers up to a given number `n`? Can you provide a Python code snippet that implements this functionality? | def is_prime(num):
"""
Check if a number is prime.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def sum_of_primes(n):
"""
Calculate the sum of all prime numbers up to a given number n (inclusive... | from solution import is_prime, sum_of_primes
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert not is_prime(0)
assert not is_prime(-1)
def test_sum_of_primes():
assert sum_of_primes(10) == 17 # 2 + 3 + 5 +... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Calculate the sum of all prime numbers up to a given number n (inclusive).",
"function_declaration": "def sum_of_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(num):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070416",
"row_id": 70416,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142692']"
} | 0.675754 | Filter_70416 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 698ad8cee5a1bddf562350c60823b0c0ea7f0330 | 4185ec6ec5507cb1e09782887594220e26955890 | |||
v1.0 | instruct | Filter | Filter_70423_I | How can I implement a JSON-to-XML converter in Python? | import json
from xml.etree.ElementTree import Element, tostring
def json_to_xml(json_obj, line_padding=""):
"""
Converts a JSON object to an XML string.
:param json_obj: A JSON object (either a dictionary, list, or value)
:param line_padding: A string to prefix each line in the output XML
:ret... | from solution import convert_json_to_xml_string
def test_simple_dict():
json_str = '{"a": "1", "b": "2"}'
expected_xml = '<a>\n\t1\n</a>\n<b>\n\t2\n</b>'
assert convert_json_to_xml_string(json_str) == expected_xml
def test_nested_dict():
json_str = '{"a": {"b": "2"}}'
expected_xml = '<a>\n\t<b>\n\... | [
{
"docstring": "Converts a JSON object to an XML string.\n\n:param json_obj: A JSON object (either a dictionary, list, or value)\n:param line_padding: A string to prefix each line in the output XML\n:return: A string containing the XML",
"function_declaration": "def json_to_xml(json_obj, line_padding=''):",... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport xml.etree.ElementTree as ET\n\ndef json_to_xml(json_obj, line_padding=\"\"):\n \"\"\"\n Convert a JSON object to an XML string.\n \n :param json_obj: The JSON o... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070423",
"row_id": 70423,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142707']"
} | 0.718261 | Filter_70423 | I | [
"json_to_xml",
"convert_json_to_xml_string"
] | 2 | [
[
"convert_json_to_xml_string",
"json_to_xml"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a5be7ebe2c13a4dda3e3dd7c1971cd175950306 | 5b495e687ef60dca86d395d28b1f95d0b22775cd | |||
v1.0 | instruct | Filter | Filter_70454_I | How can I create a Python program that can parse and analyze a given data structure to find all the prime numbers within it? | def is_prime(n):
"""
Check if a number n is prime.
Parameters:
n (int): The number to check for primality.
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
... | from solution import is_prime, find_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(11) == True
assert is_prime(1) == False
assert is_prime(-7) == False
def test_find_primes_list():
... | [
{
"docstring": "Check if a number n is prime.\n\nParameters:\nn (int): The number to check for primality.\n\nReturns:\nbool: True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Fin... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070454",
"row_id": 70454,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142763']"
} | 0.552312 | Filter_70454 | I | [
"is_prime",
"find_primes"
] | 2 | [
[
"find_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8aac8bf1d0de8af2e526c698c81cfb998b357d18 | cd4c19a4369006fee600e1dbe17bb1c3a3770905 | |||
v1.0 | instruct | Filter | Filter_70467_I | I need help with an algorithm to detect cycles in a directed graph. Can you explain how the algorithm works and provide a Python implementation? | def is_cyclic_util(v, visited, recStack, graph):
"""
Helper function for detecting cycle using DFS.
"""
visited[v] = True
recStack[v] = True
for neighbor in graph[v]:
if not visited[neighbor]:
if is_cyclic_util(neighbor, visited, recStack, graph):
return True... | from solution import is_cyclic
def test_no_cycle():
graph = [
[1, 2],
[2],
[]
]
assert not is_cyclic(graph)
def test_cycle_self_loop():
graph = [
[1],
[2],
[0, 3],
[3]
]
assert is_cyclic(graph)
def test_cycle_simple():
graph = [
... | [
{
"docstring": "Helper function for detecting cycle using DFS.",
"function_declaration": "def is_cyclic_util(v, visited, recStack, graph):",
"function_name": "is_cyclic_util",
"parameter_list": "(v, visited, recStack, graph)"
},
{
"docstring": "Function to detect cycle in a directed graph.\n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def detect_cycle(graph):\n def dfs(node):\n if state[node] == \"processing\":\n return True\n if state[node] == \"visited\":\n return False\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070467",
"row_id": 70467,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142785']"
} | 0.540468 | Filter_70467 | I | [
"is_cyclic_util",
"is_cyclic"
] | 2 | [
[
"is_cyclic",
"is_cyclic_util"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b84c59e7950fe82040cec1931aba9fc0f5867544 | dca54868f9f00770d137df14db4e4346482bdbb2 | |||
v1.0 | instruct | Filter | Filter_70489_I | Can you provide a Python function that takes a list of words and returns a new list containing only the words that are palindromes? A palindrome is a word that reads the same backward as forward, ignoring case and spaces. | def is_palindrome(word):
"""
Checks if a given word is a palindrome.
"""
cleaned_word = ''.join(word.split()).lower()
return cleaned_word == cleaned_word[::-1]
def filter_palindromes(words):
"""
Returns a list of words that are palindromes from the given list.
"""
return [word for w... | from solution import is_palindrome, filter_palindromes
def test_is_palindrome_simple_cases():
assert is_palindrome("level") == True
assert is_palindrome("world") == False
def test_is_palindrome_mixed_cases():
assert is_palindrome("Deleveled") == True
assert is_palindrome("Kayak") == True
assert is... | [
{
"docstring": "Checks if a given word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Returns a list of words that are palindromes from the given list.",
"function_declaration": "def f... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(word):\n \"\"\"\n Checks if a given word is a palindrome, ignoring case and spaces.\n \n Parameters:\n word (str): The word to check.\n \n Returns:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070489",
"row_id": 70489,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142825']"
} | 0.730809 | Filter_70489 | I | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca6d93b17256d2fc2a08d06138bdd46d2bed90ac | 48e943edb12038aa4ea9d39da997a38a3efeb7c5 | |||
v1.0 | instruct | Filter | Filter_70531_I | Write a Python function that finds and prints the sum of all prime numbers within a given range (inclusive). Your function should be named `sum_of_primes_in_range(start, end)`, where `start` and `end` are integers representing the start and end of the range, respectively. | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def sum_of_primes_in_range(start, end):
... | from solution import sum_of_primes_in_range
def test_sum_of_primes_in_range_positive_numbers():
assert sum_of_primes_in_range(10, 20) == 60 # primes: 11, 13, 17, 19
def test_sum_of_primes_in_range_including_0_and_1():
assert sum_of_primes_in_range(0, 10) == 17 # primes: 2, 3, 5, 7
def test_sum_of_primes_in... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds and returns the sum of all prime numbers within the range [start, end].",
"function_declaration": "def sum_of_primes_in_range(start, end):",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is a prime number.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070531",
"row_id": 70531,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_142901']"
} | 0.659838 | Filter_70531 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c72524cf6376f5d773adc74e32a3ee7f982be40c | 2fbd05d5fedef80c5b72dc4cd0bf94f7a4474ff5 | |||
v1.0 | instruct | Filter | Filter_70599_I | How can I create a Python program that allows users to input their favorite color and stores it in a list? This list should be preserved even after the program is closed and reopened. How can I achieve this using Python? | import json
import os
FILENAME = "favorite_colors.json"
def load_colors():
"""
Loads the list of favorite colors from the JSON file.
"""
if os.path.exists(FILENAME):
with open(FILENAME, "r") as file:
return json.load(file)
return []
def save_colors(colors):
"""
Saves t... | import os
import json
import pytest
from solution import add_favorite_color, get_favorite_colors, FILENAME
@pytest.fixture
def setup_and_teardown():
# Setup: Ensure the file doesn't exist before the test
if os.path.exists(FILENAME):
os.remove(FILENAME)
yield
# Teardown: Clean up the file after ... | [
{
"docstring": "Loads the list of favorite colors from the JSON file.",
"function_declaration": "def load_colors():",
"function_name": "load_colors",
"parameter_list": "()"
},
{
"docstring": "Saves the list of favorite colors to the JSON file.",
"function_declaration": "def save_colors(c... | [
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\n\nFILENAME = 'favorite_colors.json'\n\ndef load_colors():\n if os.path.exists(FILENAME):\n with open(FILENAME, 'r') as file:\n return json.load(fil... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070599",
"row_id": 70599,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143035']"
} | 0.469861 | Filter_70599 | I | [
"load_colors",
"save_colors",
"add_favorite_color",
"get_favorite_colors"
] | 4 | [
[
"add_favorite_color",
"load_colors"
],
[
"add_favorite_color",
"save_colors"
],
[
"get_favorite_colors",
"load_colors"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 72da9ed58041c9bf372aea8fcfc8fac579d4eb2a | 10535d17f05cd897d27836948c6be93b3af2b1e4 | |||
v1.0 | instruct | Filter | Filter_70623_I | Create a Python script that simulates a simple game where the user rolls a six-sided die. The game allows the user to roll the die as many times as they wish until they decide to stop. The script should keep track of the total sum of all rolls and display it after each roll. The user should be prompted to enter 'y' to ... | import random
def roll_dice():
"""
Simulates the rolling of a six-sided die.
Returns an integer between 1 and 6 inclusive.
"""
return random.randint(1, 6)
def play_game():
"""
Simulates a game where the user rolls a six-sided die,
with the option to roll multiple times and the total su... | from solution import roll_dice
def test_roll_dice_range():
for _ in range(100):
roll = roll_dice()
assert 1 <= roll <= 6
# The play_game function involves user interaction,
# which is not straightforward to test with simple unit tests.
# We would need to use a mock input to fully test play_game,
... | [
{
"docstring": "Simulates the rolling of a six-sided die.\nReturns an integer between 1 and 6 inclusive.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a game where the user rolls a six-sided die,\nwith the opti... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates the rolling of a six-sided die.\n Returns an integer between 1 and 6 inclusive.\n \"\"\"\n return random.randint(1, 6)\n\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00070623",
"row_id": 70623,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143084']"
} | 0.597021 | Filter_70623 | I | [
"roll_dice",
"play_game"
] | 2 | [
[
"play_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c03ade49b9f18dfb421a6a91481dcdfe5cdf5e32 | 1e0e158f8178f04e19911d306e426f86b4e330fa | |||
v1.0 | instruct | Filter | Filter_70662_I | Sure, let's talk about how to implement a simple blockchain using Python. Could you provide a basic example? | import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def calculate_hash(index, previous_hash, timestamp, da... | import time
from solution import Block, calculate_hash, create_genesis_block, create_new_block
def test_calculate_hash():
hash_result = calculate_hash(0, "0", 1234567890, "Genesis Block")
assert len(hash_result) == 64
def test_create_genesis_block():
genesis_block = create_genesis_block()
assert genes... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport time\n\nclass Block:\n def __init__(self, index, previous_hash, timestamp, data, hash):\n self.index = index\n self.previous_hash = previous_hash\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00070662",
"row_id": 70662,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143169']"
} | 0.345271 | Filter_70662 | I | [
"calculate_hash",
"create_genesis_block",
"create_new_block"
] | 3 | [
[
"create_genesis_block",
"calculate_hash"
],
[
"create_new_block",
"calculate_hash"
]
] | 2 | [] | false | [
"Block"
] | true | pytest | true | [] | true | 072ba9e3636e4c2c62621201c278739251afde01 | 94b3f5f4b051e76cc36efe96c13b7d4823acf10a | |||
v1.0 | instruct | Filter | Filter_70689_I | I want to create a Python Flask web application that calculates the Fibonacci sequence up to a given number. How can I design the application to be simple and user-friendly? | from flask import Flask, request, jsonify
app = Flask(__name__)
def fibonacci_sequence(n):
"""
Returns the Fibonacci sequence up to the n-th term.
"""
if n <= 0:
return []
sequence = [0, 1]
while len(sequence) < n:
sequence.append(sequence[-1] + sequence[-2])
return sequenc... | import pytest
from flask import Flask
from solution import app, fibonacci_sequence
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_fibonacci_sequence():
assert fibonacci_sequence(0) == []
assert fibonacci_sequence(1) == [0]
... | [
{
"docstring": "Returns the Fibonacci sequence up to the n-th term.",
"function_declaration": "def fibonacci_sequence(n):",
"function_name": "fibonacci_sequence",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def fibonacci():",
"function_name": "fibonacci",... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\ndef fibonacci(n):\n \"\"\"\n Returns a list containing the Fibonacci sequence up to the n-th element.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070689",
"row_id": 70689,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143219']"
} | 0.575637 | Filter_70689 | I | [
"fibonacci_sequence",
"fibonacci"
] | 2 | [
[
"fibonacci",
"fibonacci_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | b29a9cd68789172e9f0dc4c0096cbcaa4a780051 | 97dd555546aae2c808af985bef5055f8266bd1bf | |||
v1.0 | instruct | Filter | Filter_70696_I | I need a Python code to simulate a simple text-based adventure game. The game should allow the player to navigate through different rooms connected by doors. Each room can contain objects or enemies. How can I implement this? | class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
self.objects = []
self.enemies = []
def add_path(self, direction, room):
self.paths[direction] = room
def add_object(self, object):
sel... | from solution import Room, describe_room, game
def test_room_initialization():
room = Room("Test Room", "This is a test room.")
assert room.name == "Test Room"
assert room.description == "This is a test room."
assert room.paths == {}
assert room.objects == []
assert room.enemies == []
def test... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Room:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.paths = {}\n self.objects = []\n self.enem... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00070696",
"row_id": 70696,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143235']"
} | 0.362326 | Filter_70696 | I | [
"describe_room",
"game"
] | 2 | [
[
"game",
"describe_room"
]
] | 1 | [] | false | [
"Room"
] | true | pytest | true | [] | true | 2cf6c39263c1b58ac1162ba69276b428a899e166 | b4459d488f5f5a2f61224d28f8887e5f108f0ad7 | |||
v1.0 | instruct | Filter | Filter_70726_I | I want to create a simple chatbot using Python for a specific application in a restaurant. The chatbot should be able to greet the customer, ask for their order, and take the order details such as the name of the items they want to order, quantities, and any special requests. After taking the order, the chatbot should ... | def greet_customer():
return "Hello! Welcome to our restaurant. How can I assist you today?"
def ask_for_order():
return "What would you like to order today? Please provide the item names, quantities, and any special requests."
def take_order(order_details):
# Simulate storing order details and return a c... | import pytest
from solution import chatbot_interface
def test_greeting():
response = chatbot_interface("hello")
assert response == "Hello! Welcome to our restaurant. How can I assist you today?"
def test_ask_for_order():
response = chatbot_interface("I want to place an order")
assert response == "What... | [
{
"docstring": null,
"function_declaration": "def greet_customer():",
"function_name": "greet_customer",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def ask_for_order():",
"function_name": "ask_for_order",
"parameter_list": "()"
},
{
"docstring... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class RestaurantChatbot:\n def __init__(self, menu_items):\n self.menu_items = menu_items\n self.order = {}\n\n def greet(self):\n return \"Hello! Welcome to our res... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070726",
"row_id": 70726,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143298']"
} | 0.358125 | Filter_70726 | I | [
"greet_customer",
"ask_for_order",
"take_order",
"confirm_order",
"modify_order",
"chatbot_interface"
] | 6 | [
[
"chatbot_interface",
"ask_for_order"
],
[
"chatbot_interface",
"confirm_order"
],
[
"chatbot_interface",
"greet_customer"
],
[
"chatbot_interface",
"modify_order"
],
[
"chatbot_interface",
"take_order"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 66ec14f8efee2a7681f9f947f7bbd463645d84a3 | 90e8b0a7afc5a84a00b7d8b081b89fe23e5610b1 | |||
v1.0 | instruct | Filter | Filter_70736_I | Can you help me understand the concept of "aspect-oriented programming" (AOP) and provide an example in Python? | import wrapt
def log_arguments(wrapped, instance, args, kwargs):
print(f"Called function {wrapped.__name__} with args: {args} and kwargs: {kwargs}")
return wrapped(*args, **kwargs)
@wrapt.decorator
def log_decorator(wrapped, instance, args, kwargs):
return log_arguments(wrapped, instance, args, kwargs)
@... | from solution import add, subtract
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 | [
{
"docstring": null,
"function_declaration": "def log_arguments(wrapped, instance, args, kwargs):",
"function_name": "log_arguments",
"parameter_list": "(wrapped, instance, args, kwargs)"
},
{
"docstring": null,
"function_declaration": "def log_decorator(wrapped, instance, args, kwargs):... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\ndef log_decorator(func):\n \"\"\"\n A decorator that logs the execution of a function.\n \"\"\"\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070736",
"row_id": 70736,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143314']"
} | 0.354221 | Filter_70736 | I | [
"log_arguments",
"log_decorator",
"add",
"subtract"
] | 4 | [
[
"log_decorator",
"log_arguments"
]
] | 1 | [] | false | [] | false | pytest | true | [
"wrapt"
] | false | ccceb9f95a7abd8de6d707fec7df2a47d963ec6c | 444cd5dae01beac13c0c6f6b020df294c51442f2 | |||
v1.0 | instruct | Filter | Filter_70743_I | Can you explain how to implement a URL shortener in a Python web application? | from flask import Flask, request, redirect, jsonify
import string
import random
app = Flask(__name__)
# Dictionary to store long URLs with their corresponding short codes
url_store = {}
short_code_chars = string.ascii_letters + string.digits
def generate_short_code(length=6):
"""Generate a random short code"""
... | import pytest
from flask import Flask
from solution import app, url_store, generate_short_code
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_generate_short_code():
short_code = generate_short_code()
assert len(short_code) == ... | [
{
"docstring": "Generate a random short code",
"function_declaration": "def generate_short_code(length=6):",
"function_name": "generate_short_code",
"parameter_list": "(length=6)"
},
{
"docstring": null,
"function_declaration": "def shorten_url():",
"function_name": "shorten_url",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nimport string\nimport random\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070743",
"row_id": 70743,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143327']"
} | 0.492048 | Filter_70743 | I | [
"generate_short_code",
"shorten_url",
"redirect_url"
] | 3 | [
[
"shorten_url",
"generate_short_code"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 47f1c8a8eb7407a6a4f38a94d93f0290b12fd4ba | de7e9df196f767fab77992604293b869665840cf | |||
v1.0 | instruct | Filter | Filter_70757_I | Can you provide a Python code snippet that demonstrates how to use AWS Lambda to trigger a specific function when a file is uploaded to a particular Amazon S3 bucket? | import json
import boto3
s3_client = boto3.client('s3')
def lambda_handler(event, context):
"""
Lambda function to be triggered when a file is uploaded to an S3 bucket.
"""
# Extract bucket name and object key from the event
bucket_name = event['Records'][0]['s3']['bucket']['name']
object_key ... | from solution import lambda_handler, process_uploaded_file
def test_lambda_handler():
# Example S3 event
event = {
"Records": [
{
"s3": {
"bucket": {
"name": "example-bucket"
},
"object": {
... | [
{
"docstring": "Lambda function to be triggered when a file is uploaded to an S3 bucket.",
"function_declaration": "def lambda_handler(event, context):",
"function_name": "lambda_handler",
"parameter_list": "(event, context)"
},
{
"docstring": "Function to process the uploaded file.",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport boto3\n\ndef lambda_handler(event, context):\n \"\"\"\n AWS Lambda handler function to trigger when a file is uploaded to a specific S3 bucket.\n \"\"\"\n s3 = ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070757",
"row_id": 70757,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143355']"
} | 0.466022 | Filter_70757 | I | [
"lambda_handler",
"process_uploaded_file"
] | 2 | [
[
"lambda_handler",
"process_uploaded_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"boto3"
] | false | ac16df41d883fd2f04e4203fdf13683465aabf06 | 7f93a7ccefb3e0cdc9c2ee7384091b8709aa7d66 | |||
v1.0 | instruct | Filter | Filter_70778_I | Can you provide a Python script to simulate a simple dice game where two players roll a six-sided die and the player with the higher number wins? | import random
def roll_die():
"""
Simulates rolling a six-sided die.
Returns a random number between 1 and 6 inclusive.
"""
return random.randint(1, 6)
def dice_game():
"""
Simulates a simple dice game where two players roll a six-sided die.
The player with the higher number wins.
... | from solution import roll_die, dice_game
def test_roll_die():
for _ in range(100):
roll = roll_die()
assert 1 <= roll <= 6
def test_dice_game():
for _ in range(100):
player1_roll, player2_roll, winner = dice_game()
assert 1 <= player1_roll <= 6
assert 1 <= play... | [
{
"docstring": "Simulates rolling a six-sided die.\nReturns a random number between 1 and 6 inclusive.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a simple dice game where two players roll a six-sided die.\nThe... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"\n Simulates rolling a six-sided die and returns the result.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_dice_game():\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070778",
"row_id": 70778,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143409']"
} | 0.520743 | Filter_70778 | I | [
"roll_die",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 89d3325f779c71b93113a58cd08dd3c837e9bbf1 | 866709394889b09cea2f54225428e952c78ab725 | |||
v1.0 | instruct | Filter | Filter_70797_I | You are a robot coder and your main job is to write code. One day, a client asks you to create a simple calculator in Python that can perform basic arithmetic operations. The calculator should be able to add, subtract, multiply, and divide. The user should be able to choose the operation and input two numbers for the c... | 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 simple_calculator(operation, num1, num2):
if operation == 'add':
return add(num1, num2)
el... | import pytest
from solution import add, subtract, multiply, divide, simple_calculator
def test_add():
assert add(3, 4) == 7
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(0, 5) == -5
assert subtract(5, 0) == 5
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... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b.\n \"\"\"\n return a + b\n\ndef subtract(a, b):\n \"\"\"\n Returns the difference of a and b.\n \"\"\"\n return a -... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070797",
"row_id": 70797,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143455']"
} | 0.53458 | Filter_70797 | I | [
"add",
"subtract",
"multiply",
"divide",
"simple_calculator"
] | 5 | [
[
"simple_calculator",
"add"
],
[
"simple_calculator",
"divide"
],
[
"simple_calculator",
"multiply"
],
[
"simple_calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 4b891140c6da6b1c6d7400e95b4ddd56f0cda5af | f044e522d7e3a9723791a2070ef1ebf8c0498acf | |||
v1.0 | instruct | Filter | Filter_70827_I | Given a list of integers, how can I find the maximum sum of a contiguous subarray using the divide and conquer approach in Python? | def max_crossing_sum(arr, left, mid, right):
"""
Find the maximum possible sum of a subarray crossing the midpoint.
"""
sm = 0
left_sum = float('-inf')
# Include elements on left of mid.
for i in range(mid, left-1, -1):
sm += arr[i]
if sm > left_sum:
left_sum = s... | from solution import find_max_subarray
def test_single_element():
assert find_max_subarray([1]) == 1
assert find_max_subarray([-1]) == -1
def test_all_positive_elements():
assert find_max_subarray([1, 2, 3, 4, 5]) == 15
assert find_max_subarray([3, 1, 2, 1, 4]) == 11
def test_all_negative_elements():... | [
{
"docstring": "Find the maximum possible sum of a subarray crossing the midpoint.",
"function_declaration": "def max_crossing_sum(arr, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(arr, left, mid, right)"
},
{
"docstring": "Returns the maximum sum of a contig... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(arr, low, mid, high):\n \"\"\"\n Find the maximum possible sum in arr[] such that the subarray crosses the midpoint.\n \"\"\"\n sm = 0\n left_sum = float('-... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070827",
"row_id": 70827,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143521']"
} | 0.703899 | Filter_70827 | I | [
"max_crossing_sum",
"max_subarray_sum",
"find_max_subarray"
] | 3 | [
[
"find_max_subarray",
"max_subarray_sum"
],
[
"max_subarray_sum",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d643841977ae47d3ab37c2bcd79c7d4845a6e2b1 | 3c1b6331f4704a1f9a1d1b57a90f90f94f175f42 | |||
v1.0 | instruct | Filter | Filter_70865_I | Can you show me how to simulate a hardware system using a software model in Python? Simulating a hardware system in Python involves creating a software representation of the hardware components and their interactions. This can be useful for testing, development, and education purposes. However, I am particularly intere... | def AND(a, b):
"""
Simulates an AND gate.
"""
return a & b
def OR(a, b):
"""
Simulates an OR gate.
"""
return a | b
def NOT(a):
"""
Simulates a NOT gate.
"""
return ~a & 1 # Ensure the output is either 0 or 1
def XOR(a, b):
"""
Simulates an XOR gate.
"""
... | from solution import AND, OR, NOT, XOR, NAND, NOR, ALU
def test_AND_gate():
assert AND(0, 0) == 0
assert AND(0, 1) == 0
assert AND(1, 0) == 0
assert AND(1, 1) == 1
def test_OR_gate():
assert OR(0, 0) == 0
assert OR(0, 1) == 1
assert OR(1, 0) == 1
assert OR(1, 1) == 1
def test_NOT_gate... | [
{
"docstring": "Simulates an AND gate.",
"function_declaration": "def AND(a, b):",
"function_name": "AND",
"parameter_list": "(a, b)"
},
{
"docstring": "Simulates an OR gate.",
"function_declaration": "def OR(a, b):",
"function_name": "OR",
"parameter_list": "(a, b)"
},
{
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def AND(a, b):\n return a & b\n\ndef OR(a, b):\n return a | b\n\ndef NOT(a):\n return ~a & 1\n\ndef XOR(a, b):\n return a ^ b",
"test_code": "from solution import AND, OR, NOT,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070865",
"row_id": 70865,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143592']"
} | 0.319154 | Filter_70865 | I | [
"AND",
"OR",
"NOT",
"XOR",
"NAND",
"NOR",
"ALU"
] | 7 | [
[
"ALU",
"AND"
],
[
"ALU",
"NOT"
],
[
"ALU",
"OR"
],
[
"ALU",
"XOR"
],
[
"NAND",
"AND"
],
[
"NAND",
"NOT"
],
[
"NOR",
"NOT"
],
[
"NOR",
"OR"
]
] | 8 | [] | false | [] | false | pytest | true | [] | true | 759fee70b9c8effc048a9832ab87b085e32611c0 | aaa1503ed911d30662d55dd05a57cd7e9de101f0 | |||
v1.0 | instruct | Filter | Filter_70917_I | Hello, I'm trying to design a compact and efficient system for mapping different types of files to their respective processing pipelines based on file extensions. How can I implement this in Python? | def process_text(file):
return f"Processing text file: {file}"
def process_image(file):
return f"Processing image file: {file}"
def process_audio(file):
return f"Processing audio file: {file}"
def process_video(file):
return f"Processing video file: {file}"
def process_unknown(file):
return f"Un... | from solution import process_file, process_text, process_image, process_audio, process_video, process_unknown
def test_process_text_file():
assert process_file('document.txt') == "Processing text file: document.txt"
def test_process_image_file():
assert process_file('picture.jpg') == "Processing image file: p... | [
{
"docstring": null,
"function_declaration": "def process_text(file):",
"function_name": "process_text",
"parameter_list": "(file)"
},
{
"docstring": null,
"function_declaration": "def process_image(file):",
"function_name": "process_image",
"parameter_list": "(file)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_text_file(file_path):\n \"\"\"\n Process a text file located at file_path.\n \"\"\"\n print(f\"Processing text file: {file_path}\")\n # Implement actual text file pr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070917",
"row_id": 70917,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143694']"
} | 0.601122 | Filter_70917 | I | [
"process_text",
"process_image",
"process_audio",
"process_video",
"process_unknown",
"get_processing_function",
"process_file"
] | 7 | [
[
"get_processing_function",
"process_unknown"
],
[
"process_file",
"get_processing_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 02b43e53f6598490e764547b7cae2f8a7642e704 | 3a5616f53920fde807007f06e4572b48cce56c8f | |||
v1.0 | instruct | Filter | Filter_70946_I | I have a Python script that checks for duplicate files in a directory and deletes them, keeping only one copy of each file. How can I modify it to work recursively for all subdirectories within a given directory? | import os
import hashlib
def hash_file(file_path):
"""
Generate the hash for a file.
"""
hasher = hashlib.md5()
with open(file_path, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
return hasher.hexdigest()
def find_duplicate_files(directory):
"""
Find and delete ... | import os
import tempfile
import shutil
from solution import hash_file, find_duplicate_files
def test_hash_file():
# Create a temporary file and check its hash
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b"test content")
temp_file_name = temp_file.name
... | [
{
"docstring": "Generate the hash for a file.",
"function_declaration": "def hash_file(file_path):",
"function_name": "hash_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Find and delete duplicate files recursively in the given directory.",
"function_declaration": "def find_du... | [
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 hashlib\n\ndef hash_file(filepath):\n \"\"\"Generate SHA-256 hash for the given file.\"\"\"\n hasher = hashlib.sha256()\n with open(filepath, 'rb') as file:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070946",
"row_id": 70946,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143761']"
} | 0.535902 | Filter_70946 | I | [
"hash_file",
"find_duplicate_files",
"main"
] | 3 | [
[
"find_duplicate_files",
"hash_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 572af90258a5d04fb04b1e9c8db15edb02784b10 | 5744e2829c39c966a3612ffd42c81b3b9b234085 | |||
v1.0 | instruct | Filter | Filter_70975_I | Can you provide an example of how to implement a simple chat application using WebSocket in Python? | import asyncio
import websockets
clients = set()
async def register(websocket):
clients.add(websocket)
await websocket.send("You are connected to the chat server.")
await notify_users()
async def unregister(websocket):
clients.remove(websocket)
await notify_users()
async def notify_users():
... | import pytest
import asyncio
import websockets
from solution import handle_messages, register, unregister, notify_users, notify_message
# Helper function to start WebSocket client
async def connect_and_send(uri, message):
async with websockets.connect(uri) as websocket:
await websocket.send(message)
... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport websockets\nimport json\n\n# Create a set to hold the clients connected to the WebSocket server\nclients = set()\n\nasync def register(websocket):\n # Add the client ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00070975",
"row_id": 70975,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143829']"
} | 0.50831 | Filter_70975 | I | [
"register",
"unregister",
"notify_users",
"handle_messages",
"notify_message"
] | 5 | [
[
"handle_messages",
"notify_message"
],
[
"handle_messages",
"register"
],
[
"handle_messages",
"unregister"
],
[
"register",
"notify_users"
],
[
"unregister",
"notify_users"
]
] | 5 | [] | false | [] | false | pytest | true | [
"websockets"
] | false | f1f47727aa6591897700b7e8c70a599e2521d2e4 | 1d40ddf86eaa24e96d43bea787ebcdc0bd01502b | |||
v1.0 | instruct | Filter | Filter_70977_I | Hello Qwen, I'm asking for help with a coding challenge. The challenge is to find the smallest number that has exactly k divisors. I need to write a function that takes an integer k as input and returns the smallest number with exactly k divisors. How can I approach this problem? | import math
def count_divisors(n):
"""
Returns the number of divisors of n.
"""
count = 0
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
if i == n // i:
count += 1
else:
count += 2
return count
def smallest_number_with_k... | from solution import smallest_number_with_k_divisors
def test_smallest_number_with_1_divisor():
assert smallest_number_with_k_divisors(1) == 1 # only 1 has 1 divisor
def test_smallest_number_with_2_divisors():
assert smallest_number_with_k_divisors(2) == 2 # only prime numbers have 2 divisors, smallest is 2... | [
{
"docstring": "Returns the number of divisors of n.",
"function_declaration": "def count_divisors(n):",
"function_name": "count_divisors",
"parameter_list": "(n)"
},
{
"docstring": "Returns the smallest number with exactly k divisors.",
"function_declaration": "def smallest_number_with_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import isqrt\n\ndef prime_factors(n):\n \"\"\"\n Helper function to compute the prime factorization of n.\n Returns a dictionary where keys are primes and values are the exp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00070977",
"row_id": 70977,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143834']"
} | 0.660507 | Filter_70977 | I | [
"count_divisors",
"smallest_number_with_k_divisors"
] | 2 | [
[
"smallest_number_with_k_divisors",
"count_divisors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 19e36ad31cc711344a9d6c31532f67ab5e15c702 | 3ed0e5bbf2f7c370b6f1e3b33b2c0aa538ebfe24 | |||
v1.0 | instruct | Filter | Filter_71014_I | Write a Python function that finds the largest prime palindrome less than a given number `n`. A prime palindrome is a prime number that is also a palindrome. For example, 131 is both a prime number and a palindrome. The function should return the largest prime palindrome less than `n`. If there is no such number, it sh... | def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def is_palindrome(num):
"""
Checks if a number is a palindrome.
"""
return str(num) == st... | from solution import largest_prime_palindrome
def test_no_prime_palindrome():
assert largest_prime_palindrome(2) == -1
assert largest_prime_palindrome(10) == 7
def test_prime_palindrome_below_50():
assert largest_prime_palindrome(50) == 11
def test_prime_palindrome_below_200():
assert largest_prime_p... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Checks if a number is a palindrome.",
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindr... | [
0,
1,
0
] | 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 Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071014",
"row_id": 71014,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143914']"
} | 0.695524 | Filter_71014 | I | [
"is_prime",
"is_palindrome",
"largest_prime_palindrome"
] | 3 | [
[
"largest_prime_palindrome",
"is_palindrome"
],
[
"largest_prime_palindrome",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 048a98858ac06771db3cfb6213753ffff12fedd3 | 9f9ebc93d8e52a6b4efa34c8fd97bc01ccd800a6 | |||
v1.0 | instruct | Filter | Filter_71018_I | Write a Python program to implement a simple arithmetic calculator using functions. The program should be able to handle addition, subtraction, multiplication, and division. It should take two numbers as input and the operation to perform. The program should continue to prompt the user for input until they choose to ex... | 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 == 's... | import pytest
from solution import add, subtract, multiply, divide, calculator
def test_addition():
assert add(3, 2) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtraction():
assert subtract(3, 2) == 1
assert subtract(-1, 1) == -2
assert subtract(0, 0) == 0
def test_multiplica... | [
{
"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,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071018",
"row_id": 71018,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143925']"
} | 0.623595 | Filter_71018 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | fa81150fe6941f167ca2f0c554832417229dfa4d | ecc5836c8d9fd0a38a9d1585d9f0dde82a08d9ed | |||
v1.0 | instruct | Filter | Filter_71030_I | I want to create a simple chatbot using Python and OpenAI's GPT-3. How can I set up and deploy it on a local server? | from flask import Flask, request, jsonify
import openai
app = Flask(__name__)
# Replace 'your-api-key' with your actual OpenAI API key
openai.api_key = 'your-api-key'
def query_gpt3(prompt):
response = openai.Completion.create(
engine="davinci-codex", # Or any other engine you are using
prompt=pr... | import pytest
from flask import Flask, json
from solution import app, query_gpt3
def test_query_gpt3(monkeypatch):
def mock_create(engine, prompt, max_tokens):
class MockResponse:
def __init__(self):
self.choices = [MockChoice()]
class MockChoice:
def __init... | [
{
"docstring": null,
"function_declaration": "def query_gpt3(prompt):",
"function_name": "query_gpt3",
"parameter_list": "(prompt)"
},
{
"docstring": null,
"function_declaration": "def chat():",
"function_name": "chat",
"parameter_list": "()"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nimport openai\n\n# Replace YOUR_API_KEY with your actual OpenAI API key\nopenai.api_key = 'YOUR_API_KEY'\n\napp = Flask(__name__)\n\n@app.route('/cha... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071030",
"row_id": 71030,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143949']"
} | 0.300602 | Filter_71030 | I | [
"query_gpt3",
"chat"
] | 2 | [
[
"chat",
"query_gpt3"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"openai"
] | false | fce303ca7a45b292cc529b7988190aed1a24c3b6 | 1e49a1d55d3e59bd17b0067c023da1a7f2b41a0e | |||
v1.0 | instruct | Filter | Filter_71045_I | Can you help me with a Python script to analyze the complexity of sorting algorithms? Specifically, I want to measure how the time taken by different sorting algorithms changes with the size of the input list. I'm interested in comparing bubble sort, quicksort, and mergesort. How can I achieve this? | import time
import random
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
... | from solution import bubble_sort, quicksort, mergesort, measure_time
def test_bubble_sort():
assert bubble_sort([3, 2, 1]) == [1, 2, 3]
assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]
assert bubble_sort([]) == []
def test_quicksort():
assert quicksort([3, 2, 1]) == [1, 2, 3]
assert quicksor... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport random\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071045",
"row_id": 71045,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143983']"
} | 0.478014 | Filter_71045 | I | [
"bubble_sort",
"quicksort",
"mergesort",
"merge",
"measure_time",
"analyze_sorting_algorithms"
] | 6 | [
[
"analyze_sorting_algorithms",
"measure_time"
],
[
"mergesort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c28ac8cf9ebe3e7ca434264c92fb73f81c67d6f6 | dc86882be5d5abdef2bdf7fd7954a96028b134ca | |||
v1.0 | instruct | Filter | Filter_71051_I | Can you provide a Python code to simulate a simple game of dice where a player rolls two dice and the game ends when the sum of the two dice is 7 or 11? The game should also keep track of the number of rolls it took to end the game. | import random
def roll_dice():
"""
Simulates rolling two dice and returns their sum.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def play_dice_game():
"""
Simulates a simple game of dice where a player rolls two dice until the sum is 7 or 11.
Retu... | from solution import roll_dice, play_dice_game
def test_roll_dice():
for _ in range(100):
sum_of_dice = roll_dice()
assert 2 <= sum_of_dice <= 12, "Sum of dice should be between 2 and 12 inclusive"
def test_play_dice_game():
for _ in range(100):
roll_count = play_dice_game()
as... | [
{
"docstring": "Simulates rolling two dice and returns their sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a simple game of dice where a player rolls two dice until the sum is 7 or 11.\nReturns the number ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling two six-sided dice.\n \n Returns:\n A tuple containing the results of the two dice rolls.\n \"\"\"\n die... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071051",
"row_id": 71051,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_143991']"
} | 0.520094 | Filter_71051 | I | [
"roll_dice",
"play_dice_game"
] | 2 | [
[
"play_dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50365beb2c59d01d8feae81b4e4913bc504af73d | 892958e94d128b107963ba4518b120d4fe5005ba | |||
v1.0 | instruct | Filter | Filter_71087_I | How can I write a code to simulate a simple dice game where two players take turns rolling a six-sided die? The game continues until one player reaches a score of 20 points. How can I implement this in Python? | import random
def roll_die():
"""
Simulates rolling a six-sided die and returns the result.
"""
return random.randint(1, 6)
def play_dice_game():
"""
Simulates a two-player dice game where the first player to reach 20 points wins.
"""
player1_score = 0
player2_score = 0
turn = ... | from solution import roll_die, play_dice_game
def test_roll_die():
for _ in range(100):
roll = roll_die()
assert 1 <= roll <= 6
def test_play_dice_game():
result = play_dice_game()
assert "Player 1 wins" in result or "Player 2 wins" in result
def test_dice_game_not_tie():
result = pla... | [
{
"docstring": "Simulates rolling a six-sided die and returns the result.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a two-player dice game where the first player to reach 20 points wins.",
"function_decla... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling a six-sided dice and returns the result.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_game(target_score=20):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071087",
"row_id": 71087,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144064']"
} | 0.485781 | Filter_71087 | I | [
"roll_die",
"play_dice_game"
] | 2 | [
[
"play_dice_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 72b3aca9be1993690e62a08ef188bd2bb0223833 | fcb405adc9996f58743a36117ca613fe7e184378 | |||
v1.0 | instruct | Filter | Filter_71097_I | I need a function in Python that can find the nearest prime number less than a given number. If no such prime number exists, the function should return `None`. How can I implement this? | import math
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def nearest_prime_less_than(n):
... | from solution import nearest_prime_less_than
def test_nearest_prime_less_than():
assert nearest_prime_less_than(10) == 7
assert nearest_prime_less_than(20) == 19
assert nearest_prime_less_than(2) == None
assert nearest_prime_less_than(3) == 2
assert nearest_prime_less_than(1) == None
assert nea... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds the nearest prime number less than the given number n.\nReturns None if no such prime number exists.",
"function_declaration": "def nearest_prime... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071097",
"row_id": 71097,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144092']"
} | 0.61316 | Filter_71097 | I | [
"is_prime",
"nearest_prime_less_than"
] | 2 | [
[
"nearest_prime_less_than",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f2fb85fcf6097c171fcaa5adccf6fedd132e769 | 54a747f1e1aaff6560d31772e48ce7eb454439eb | |||
v1.0 | instruct | Filter | Filter_71121_I | Can you provide a detailed explanation of how to set up a WebSocket server in Python using the `websockets` library? | import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)
def start_server():
server = websockets.serve(echo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever() | import asyncio
import websockets
import pytest
@pytest.fixture
async def websocket_client():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
yield websocket
@pytest.mark.asyncio
async def test_echo(websocket_client):
message = "Hello, WebSocket!"
await websocket_cl... | [
{
"docstring": null,
"function_declaration": "def start_server():",
"function_name": "start_server",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport websockets\n\nasync def echo(websocket, path):\n \"\"\"\n This handler is called whenever a new client connects to the WebSocket server.\n It listens for messag... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071121",
"row_id": 71121,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144146']"
} | 0.476633 | Filter_71121 | I | [
"echo",
"start_server"
] | 2 | [
[
"start_server",
"echo"
]
] | 1 | [] | false | [] | false | pytest | false | [
"websockets"
] | false | df7fafbe137fb10633ecc9e80b242367c804f423 | 1668f79f2eb975d011feaaf2971fc281b7431a79 | |||
v1.0 | instruct | Filter | Filter_71184_I | Can you provide a simple Python script to find the sum of the first n prime numbers? The script should take an integer n as input and output the sum of the first n prime numbers. | def is_prime(num):
"""
Check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6... | from solution import sum_of_first_n_primes
def test_sum_of_first_n_primes_0():
assert sum_of_first_n_primes(0) == 0
def test_sum_of_first_n_primes_1():
assert sum_of_first_n_primes(1) == 2
def test_sum_of_first_n_primes_2():
assert sum_of_first_n_primes(2) == 5 # 2 + 3
def test_sum_of_first_n_primes_5(... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Return the sum of the first n prime numbers.",
"function_declaration": "def sum_of_first_n_primes(n):",
"function_name... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071184",
"row_id": 71184,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144291']"
} | 0.579555 | Filter_71184 | I | [
"is_prime",
"sum_of_first_n_primes"
] | 2 | [
[
"sum_of_first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 088ef928fd42ac1bbd9cbe9ec6933540f8018f5f | 61c243da92fc81030c0ade5e56134068ac44ea51 | |||
v1.0 | instruct | Filter | Filter_71185_I | Write a Python function that checks if a number is a prime number. If it is, the function should return the number itself; if not, it should return the next closest prime number greater than the given number. This function should handle edge cases, such as numbers less than 2. | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +... | from solution import next_prime
def test_next_prime_prime_number():
assert next_prime(7) == 7
assert next_prime(2) == 2
assert next_prime(13) == 13
def test_next_prime_not_prime_number():
assert next_prime(8) == 11
assert next_prime(14) == 17
assert next_prime(20) == 23
def test_next_prime_ed... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Function to return the number if it is prime, \nor the next closest prime number greater than the given number ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 ==... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071185",
"row_id": 71185,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144292']"
} | 0.783987 | Filter_71185 | I | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a668116d11608027a245a99854e4178f5aa51f69 | c82e99bc20b292f5ac7b886b03a0fe8bcbf7d40d | |||
v1.0 | instruct | Filter | Filter_71210_I | Write a program in Python to find the chemical formula of a compound given its empirical formula and the molecular weight. The program should take two inputs: the empirical formula and the molecular weight. The formula should be given as a string, for example, "CH2O", and the molecular weight should be given as a float... | def get_element_masses():
"""
Returns a dictionary of atomic masses for common elements.
"""
return {
'H': 1.008,
'He': 4.0026,
'Li': 6.94,
'Be': 9.0122,
'B': 10.81,
'C': 12.011,
'N': 14.007,
'O': 15.999,
'F': 18.998,
'Ne': ... | from solution import molecular_formula
def test_empirical_formula_ch2o_molecular_wt_180_16():
assert molecular_formula("CH2O", 180.16) == "C6H12O6"
def test_empirical_formula_nh2_molecular_wt_32_05():
assert molecular_formula("NH2", 32.05) == "N2H4"
def test_empirical_formula_co2_molecular_wt_88_02():
as... | [
{
"docstring": "Returns a dictionary of atomic masses for common elements.",
"function_declaration": "def get_element_masses():",
"function_name": "get_element_masses",
"parameter_list": "()"
},
{
"docstring": "Parses an empirical formula and returns a dictionary with the count of each eleme... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nimport re\n\n# Atomic weights of elements for common elements (for simplicity)\nATOMIC_WEIGHTS = {\n 'H': 1.008, \n 'C': 12.01, \n 'N': 14.007, \n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071210",
"row_id": 71210,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144335']"
} | 0.399653 | Filter_71210 | I | [
"get_element_masses",
"parse_formula",
"molecular_formula"
] | 3 | [
[
"molecular_formula",
"get_element_masses"
],
[
"molecular_formula",
"parse_formula"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6513f1b651610e773beb08db1f4f296285a194fe | 02ba3d0611b26aa7675d13809aa7ba485a040997 | |||
v1.0 | instruct | Filter | Filter_71286_I | Develop a Python script that checks for palindrome numbers within a given range. A palindrome number is a number that reads the same backward as forward, like 121 or 1331. | def is_palindrome(number):
"""
Checks if a given number is a palindrome.
"""
str_num = str(number)
return str_num == str_num[::-1]
def find_palindromes_in_range(start, end):
"""
Finds all palindrome numbers within a given range [start, end].
"""
palindromes = []
for num in range... | from solution import is_palindrome, find_palindromes_in_range
def test_is_palindrome_true():
assert is_palindrome(121) is True
assert is_palindrome(1221) is True
assert is_palindrome(0) is True
assert is_palindrome(1) is True
assert is_palindrome(1331) is True
def test_is_palindrome_false():
a... | [
{
"docstring": "Checks if a given number is a palindrome.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Finds all palindrome numbers within a given range [start, end].",
"function_declaration": "d... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(num):\n \"\"\"\n Checks if a given number is a palindrome.\n \"\"\"\n num_str = str(num)\n return num_str == num_str[::-1]\n\ndef find_palindromes_in_range(sta... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071286",
"row_id": 71286,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144496']"
} | 0.663053 | Filter_71286 | I | [
"is_palindrome",
"find_palindromes_in_range"
] | 2 | [
[
"find_palindromes_in_range",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6cbdb036fabf1b49f458d1dbfb31fd9600fc6dba | 7fc12c10319454918341544c66d5a40515bc5891 | |||
v1.0 | instruct | Filter | Filter_71288_I | Write a Python function that converts a list of integers into a binary search tree (BST) and then performs an in-order traversal of the BST to return the elements in sorted order. | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
roo... | from solution import sorted_bst_from_list
def test_sorted_bst_from_list_empty():
assert sorted_bst_from_list([]) == []
def test_sorted_bst_from_list_single_element():
assert sorted_bst_from_list([1]) == [1]
def test_sorted_bst_from_list_sorted_input():
assert sorted_bst_from_list([1, 2, 3]) == [1, 2, 3]
... | [] | [
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, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef insert_bst(root, value):\n if root is None:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071288",
"row_id": 71288,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144499']"
} | 0.52676 | Filter_71288 | I | [
"insert_into_bst",
"list_to_bst",
"in_order_traversal",
"sorted_bst_from_list"
] | 4 | [
[
"list_to_bst",
"insert_into_bst"
],
[
"sorted_bst_from_list",
"in_order_traversal"
],
[
"sorted_bst_from_list",
"list_to_bst"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | d1834a17a94d64a5b34ff8e2c6815e7b00f7ff51 | 718fd833ce34e1e6c0ade673b89d66ff1aa509aa | |||
v1.0 | instruct | Filter | Filter_71298_I | How can I implement a web navigation system using Dijkstra's algorithm in a Python web application? | from flask import Flask, request, jsonify
import heapq
app = Flask(__name__)
# Representation of the graph (adjacency list)
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}
}
def dijkstra(graph, start_node, end_node):
"""
Ret... | from solution import dijkstra
def test_dijkstra_same_node():
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 = dijkstra(graph, 'A', 'A')
assert distance == 0
assert path == ['A']
d... | [
{
"docstring": "Returns the shortest path and its distance from start_node to end_node using Dijkstra's algorithm.",
"function_declaration": "def dijkstra(graph, start_node, end_node):",
"function_name": "dijkstra",
"parameter_list": "(graph, start_node, end_node)"
},
{
"docstring": null,
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(graph, start):\n \"\"\"\n Implements Dijkstra's algorithm.\n \n :param graph: Dictionary representing the graph where keys are node names and\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071298",
"row_id": 71298,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144526']"
} | 0.366833 | Filter_71298 | I | [
"dijkstra",
"shortest_path"
] | 2 | [
[
"shortest_path",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | b59ac956093f2f938c87de52602d955cb84cbf4e | 896243fe8a2e2286cddd1612516d72cf03848d8d | |||
v1.0 | instruct | Filter | Filter_71356_I | Can I use a Python function to read a text file and process it to create a structured data format like JSON or CSV? Yes, you can! To demonstrate, let's create a Python script that reads a text file, processes the data, and writes it to both CSV and JSON files. Here's a step-by-step example. | import csv
import json
def read_text_file(file_path):
"""
Reads a text file and returns its content as a list of lines.
"""
with open(file_path, 'r') as file:
lines = file.readlines()
return [line.strip() for line in lines]
def process_data(lines):
"""
Processes the list of lines f... | import os
import json
import csv
from solution import read_text_file, process_data, write_to_csv, write_to_json, process_file_to_csv_and_json
def test_read_text_file():
file_path = 'test.txt'
with open(file_path, 'w') as file:
file.write("key1:value1\nkey2:value2\n")
lines = read_text_file(fil... | [
{
"docstring": "Reads a text file and returns its content as a list of lines.",
"function_declaration": "def read_text_file(file_path):",
"function_name": "read_text_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Processes the list of lines from the text file into a structured for... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport csv\n\ndef read_text_file(file_path):\n \"\"\"\n Reads a text file and returns the contents as a list of lines.\n \"\"\"\n with open(file_path, 'r') as file:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071356",
"row_id": 71356,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144639']"
} | 0.594745 | Filter_71356 | I | [
"read_text_file",
"process_data",
"write_to_csv",
"write_to_json",
"process_file_to_csv_and_json"
] | 5 | [
[
"process_file_to_csv_and_json",
"process_data"
],
[
"process_file_to_csv_and_json",
"read_text_file"
],
[
"process_file_to_csv_and_json",
"write_to_csv"
],
[
"process_file_to_csv_and_json",
"write_to_json"
]
] | 4 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 2301a60e5658ce3543fa06f1595ec7bf157a2c2b | 482e05cdf4c0ba75ec3ec3113c761af313238100 | |||
v1.0 | instruct | Filter | Filter_71359_I | How can I create a Python script that monitors a website for updates every hour and sends an email if there are any changes? | import requests
import hashlib
import smtplib
import time
# Configurations
URL = 'http://example.com'
EMAIL_ADDRESS = 'your_email@example.com'
EMAIL_PASSWORD = 'your_password'
TO_EMAIL = 'recipient@example.com'
HASH_FILE = 'hash.txt'
def get_website_content(url):
response = requests.get(url)
response.raise_fo... | import pytest
import requests
import hashlib
from unittest.mock import patch, mock_open
from solution import get_website_content, compute_hash, read_stored_hash, write_hash, send_email, check_website_for_updates
def test_get_website_content():
with patch('requests.get') as mock_get:
mock_get.return_value.s... | [
{
"docstring": null,
"function_declaration": "def get_website_content(url):",
"function_name": "get_website_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def compute_hash(content):",
"function_name": "compute_hash",
"parameter_list": "(conte... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport hashlib\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom time import sleep\n\ndef get_website_content(url):\n \"\"\"\n Returns the content of the websi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071359",
"row_id": 71359,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144644']"
} | 0.436781 | Filter_71359 | I | [
"get_website_content",
"compute_hash",
"read_stored_hash",
"write_hash",
"send_email",
"check_website_for_updates"
] | 6 | [
[
"check_website_for_updates",
"compute_hash"
],
[
"check_website_for_updates",
"get_website_content"
],
[
"check_website_for_updates",
"read_stored_hash"
],
[
"check_website_for_updates",
"send_email"
],
[
"check_website_for_updates",
"write_hash"
]
] | 5 | [] | false | [] | false | pytest | true | [
"requests"
] | false | fef46d4f53e2102cb2a98b1e08e2c6a0a1e6085b | 124f7c19de6b2862d539fadca09570fae3f20c3b | |||
v1.0 | instruct | Filter | Filter_71413_I | How can I efficiently identify and count the number of unique email addresses in a given text using Python? | import re
def extract_unique_emails(text):
"""
Extracts and counts unique email addresses from the provided text.
:param text: A string containing the text to search for email addresses.
:return: A set containing unique email addresses.
"""
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[... | from solution import extract_unique_emails, count_unique_emails
def test_extract_unique_emails_with_duplicates():
text = "test.email+alex@leetcode.com, test.email.leet+alex@code.com, test.email+alex@leetcode.com"
expected_emails = {"test.email+alex@leetcode.com", "test.email.leet+alex@code.com"}
assert ext... | [
{
"docstring": "Extracts and counts unique email addresses from the provided text.\n\n:param text: A string containing the text to search for email addresses.\n:return: A set containing unique email addresses.",
"function_declaration": "def extract_unique_emails(text):",
"function_name": "extract_unique... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef count_unique_emails(text):\n \"\"\"\n Identifies and counts the number of unique email addresses in the given text.\n \n :param text: String containing the input t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071413",
"row_id": 71413,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144747']"
} | 0.608726 | Filter_71413 | I | [
"extract_unique_emails",
"count_unique_emails"
] | 2 | [
[
"count_unique_emails",
"extract_unique_emails"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58c66eec17b5aa810d854997c0760af609589ded | 6ace06cb68ab53bf0c3ad6443e296695c12782ac | |||
v1.0 | instruct | Filter | Filter_71414_I | Write a script in Python to automate the monitoring of a specific website for new content. This script should check for changes in the HTML content of the website every hour and send an email notification if any changes are detected. You can assume the website's content is in HTML format and that you have access to an ... | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from bs4 import BeautifulSoup
import requests
import time
import hashlib
# Configuration Variables
URL = "http://example.com" # replace with the actual URL
CHECK_INTERVAL = 3600 # 1 hour in seconds
SMTP_SERVER = "smtp.ex... | import pytest
from unittest.mock import patch, MagicMock
from solution import get_website_content, get_hash, send_email
def test_get_website_content():
with patch('requests.get') as mock_get:
mock_response = MagicMock()
mock_response.text = "<html>Test Content</html>"
mock_get.return_value ... | [
{
"docstring": null,
"function_declaration": "def send_email(subject, body):",
"function_name": "send_email",
"parameter_list": "(subject, body)"
},
{
"docstring": null,
"function_declaration": "def get_website_content(url):",
"function_name": "get_website_content",
"parameter_li... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport smtplib\nimport requests\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom bs4 import BeautifulSoup\nfrom email.mime.base import M... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071414",
"row_id": 71414,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144748']"
} | 0.416921 | Filter_71414 | I | [
"send_email",
"get_website_content",
"get_hash",
"monitor_website"
] | 4 | [
[
"monitor_website",
"get_hash"
],
[
"monitor_website",
"get_website_content"
],
[
"monitor_website",
"send_email"
]
] | 3 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | 19c8891da72cb9eb7ba9c9643e8a01dfbe91bec1 | 9901a4a206f291058b2f423e1d10857897b5fe50 | |||
v1.0 | instruct | Filter | Filter_71462_I | Could you provide a Python code snippet to calculate the sum of all the prime numbers within a given range, say from 1 to 100? | 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
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def sum_of_primes_in_range(start, en... | from solution import is_prime, sum_of_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(-1) == False
assert is_prime(0) == False
assert is_prime(1) == False
def test_sum_of_prime... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of all prime numbers in the given range [start, end].",
"function_declaration": "def sum_of_primes_in_range(... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071462",
"row_id": 71462,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144838']"
} | 0.650836 | Filter_71462 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a78a028bafec355034205ee9a195904825e18d4 | 404cf94d741ecbb8a94a9e23122a9795046dd31f | |||
v1.0 | instruct | Filter | Filter_71467_I | How can I create a simple text-based command-line interface (CLI) program in Python that allows users to perform basic operations like creating, reading, updating, and deleting items in a list? | def display_menu():
print("Choose an action:")
print("1. Create an item")
print("2. Read all items")
print("3. Update an item")
print("4. Delete an item")
print("5. Exit")
def create_item(items):
item = input("Enter the new item: ")
items.append(item)
print(f"'{item}' has been added... | import pytest
from io import StringIO
from unittest.mock import patch
from solution import create_item, read_items, update_item, delete_item
def test_create_item():
items = []
with patch('builtins.input', return_value='Test item'):
create_item(items)
assert items == ['Test item']
def test_read_ite... | [
{
"docstring": null,
"function_declaration": "def display_menu():",
"function_name": "display_menu",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def create_item(items):",
"function_name": "create_item",
"parameter_list": "(items)"
},
{
"docstri... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def display_menu():\n print(\"Choose an action:\")\n print(\"1. Create an item\")\n print(\"2. Read all items\")\n print(\"3. Update an item\")\n print(\"4. Delete an item\")\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071467",
"row_id": 71467,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144846']"
} | 0.40786 | Filter_71467 | I | [
"display_menu",
"create_item",
"read_items",
"update_item",
"delete_item",
"main"
] | 6 | [
[
"delete_item",
"read_items"
],
[
"update_item",
"read_items"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c4b11a7e7b4d4280cf04e01480c36cb648b18627 | 383025f3bcf28fd9a504327b4d84a68b572e88ed | |||
v1.0 | instruct | Filter | Filter_71497_I | {Create Answer} Generate a detailed response to the user's question about creating a batch watermarking script in Python. The user wants to understand how to add a watermark to multiple images in a directory using Python. The user is also interested in learning about handling errors and optimizing performance for large... | import os
from PIL import Image
def apply_watermark(input_dir, output_dir, watermark_path, position=(0, 0), concurrency=False):
"""
Adds a watermark to all images in the input directory and saves them in the output directory.
If concurrency is enabled, processes images concurrently for better performance.... | import os
import shutil
from PIL import Image, ImageDraw
import pytest
from solution import apply_watermark
@pytest.fixture(scope="module")
def setup_test_environment():
"""
Sets up a test environment before running tests.
"""
os.makedirs('test_input', exist_ok=True)
os.makedirs('test_output', exis... | [
{
"docstring": "Adds a watermark to all images in the input directory and saves them in the output directory.\nIf concurrency is enabled, processes images concurrently for better performance.\n\n:param input_dir: Directory containing the input images.\n:param output_dir: Directory where watermarked images will ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image, ImageDraw, ImageFont\nimport os\n\ndef add_watermark(input_dir, output_dir, watermark_text, font_path, font_size):\n \"\"\"\n Adds a watermark to all images in the... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071497",
"row_id": 71497,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144918']"
} | 0.377564 | Filter_71497 | I | [
"apply_watermark",
"process_image"
] | 2 | [
[
"apply_watermark",
"process_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 8ca80289e330557107c0f090a0479f532f07cf97 | 7c2675cd5085b017ab28b16c528f88889eb1d101 | |||
v1.0 | instruct | Filter | Filter_71504_I | Create a Python script that calculates the sum of all prime numbers within a given range [a, b], where a and b are provided by the user. The script should include a function to check if a number is prime and another function to calculate the sum of primes in the specified range. The script should also handle edge cases... | def is_prime(n):
"""
Determines if a number n is prime.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
def sum_of_primes(a, b):
"""
Returns the sum of all prime numbers within the range [a, b].
"""
... | from solution import is_prime, sum_of_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(13) == True
assert is_prime(1) == False
assert is_prime(0) == False... | [
{
"docstring": "Determines if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within the range [a, b].",
"function_declaration": "def sum_of_primes(a, b):",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071504",
"row_id": 71504,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_144935']"
} | 0.606526 | Filter_71504 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 675d6e048df14747fb4b7822f2a666371535b2c6 | 0f9ce0b58a4bbe0af876a2a7cf8a0b9aa000a3da | |||
v1.0 | instruct | Filter | Filter_71557_I | I need help with a Python script that can sort a list of numbers using the merge sort algorithm. Can you provide a simple implementation of merge sort in Python? | def merge_sort(arr):
"""
Sorts an array of numbers using merge sort algorithm.
"""
if len(arr) <= 1:
return arr
# Split the array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
# Merge the two halves and retu... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert... | [
{
"docstring": "Sorts an array of numbers using merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into a single sorted array.",
"function_declaration": "def merge(le... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts a list of numbers using the merge sort algorithm.\n \"\"\"\n if len(arr) > 1:\n # Finding the mid of the array\n mid = len(arr) ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071557",
"row_id": 71557,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145039']"
} | 0.591807 | Filter_71557 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40f9b633f4ad9b458d9e83753202f7780baae4bc | 666eb5edc0d085d6b6fb88743e0b840038b11851 | |||
v1.0 | instruct | Filter | Filter_71577_I | I want to create a Python program that can process and display the results of a simple arithmetic test. The program should prompt the user to input the number of questions they want in the test, generate random arithmetic questions (addition, subtraction, multiplication, and division), and then display the results at t... | import random
import operator
def generate_random_question():
"""
Generates a random arithmetic question and returns the question as a string and the correct answer.
"""
operations = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
... | from solution import generate_random_question, arithmetic_test, display_results
def test_generate_random_question():
question, answer = generate_random_question()
assert isinstance(question, str)
assert isinstance(answer, (int, float))
def test_arithmetic_test(monkeypatch):
inputs = iter(['1', '10.0']... | [
{
"docstring": "Generates a random arithmetic question and returns the question as a string and the correct answer.",
"function_declaration": "def generate_random_question():",
"function_name": "generate_random_question",
"parameter_list": "()"
},
{
"docstring": "Runs an arithmetic test with... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport operator\n\ndef generate_random_question():\n \"\"\"\n Generates a random arithmetic question and returns the question as a string and the correct answer.\n \"\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071577",
"row_id": 71577,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145074']"
} | 0.48051 | Filter_71577 | I | [
"generate_random_question",
"arithmetic_test",
"display_results"
] | 3 | [
[
"arithmetic_test",
"generate_random_question"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0784336138e947112bfc8d832722f600fc91464 | 4b14e54068dcfa8f889f582d5e3cfb4016cdad2e | |||
v1.0 | instruct | Filter | Filter_71589_I | Given a string s, find the longest palindromic substring in s. A palindromic string reads the same backward as forward. | def longest_palindromic_substring(s):
"""
Returns the longest palindromic substring in the given string s.
"""
if not s:
return ""
n = len(s)
result = ""
for i in range(n):
# Check for the longest odd length palindrome with center at i
temp = expand_around_center(s,... | from solution import longest_palindromic_substring
def test_basic_palindromes():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
assert longest_palindromic_substring("cbbd") == "bb"
def test_full_string_palindromes():
assert longest_palindromic_substring("a") == "a"
assert longest_pali... | [
{
"docstring": "Returns the longest palindromic substring in the given string s.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_list": "(s)"
},
{
"docstring": "Expands around the center and returns the longest p... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s):\n \"\"\"\n Returns the longest palindromic substring in the given string s.\n \"\"\"\n if not s:\n return \"\"\n\n n = len(s)\n r... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071589",
"row_id": 71589,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145104']"
} | 0.809559 | Filter_71589 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d761299d95923c4cbc7df2d72ccd7239bdc23422 | 7436906bbf068989e71a7cdde1792fb58731dc0c | |||
v1.0 | instruct | Filter | Filter_71625_I | How can I create a Python script that emulates a simple calculator with basic operations and handles user input errors effectively? | 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():
try:
a = float(input("Enter the first number: "))
b = float(input("Ente... | from solution import add, subtract, multiply, divide
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(-1, -1) == -2
assert add(0, 0) == 0
def test_subtract():
assert subtract(3, 2) == 1
assert subtract(-1, 1) == -2
assert subtract(-1, -1) == 0
assert subtract(0, ... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n return \"Error: Division by zer... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071625",
"row_id": 71625,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145185']"
} | 0.408018 | Filter_71625 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 0173a89d23fb084c36499f15906bacd9de4ab61f | 1f356dc1cab8a65d19b39aadd16b469d3196c98b | |||
v1.0 | instruct | Filter | Filter_71632_I | Can you write a Python function that checks if the sum of the ASCII values of all characters in a given string is a prime number? | def is_prime(n):
"""
Returns True if n is a prime number, otherwise 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 is_ascii_sum_prime(s):
"""
Returns True if the sum of ASCII values of all ch... | from solution import is_ascii_sum_prime
def test_is_ascii_sum_prime_with_prime_sum():
# "AB" -> ASCII values: 65 + 66 = 131 (which is prime)
assert is_ascii_sum_prime("AB") == True
def test_is_ascii_sum_prime_with_non_prime_sum():
# "ABC" -> ASCII values: 65 + 66 + 67 = 198 (which is not prime)
assert... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns True if the sum of ASCII values of all characters in the string s\nis a prime number, otherwise ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071632",
"row_id": 71632,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145203']"
} | 0.685525 | Filter_71632 | I | [
"is_prime",
"is_ascii_sum_prime"
] | 2 | [
[
"is_ascii_sum_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2d340f520ae96c9c1b66f708d77e8c8d8f08dd05 | b49fefe5aaee18acdd92e7b68b4c97c213c3d352 | |||
v1.0 | instruct | Filter | Filter_71649_I | Can you provide a detailed explanation of how to create a custom command-line interface (CLI) in Python using the `argparse` module? Building a simple CLI tool for managing tasks, such as adding, listing, and removing tasks, would be great. | import argparse
import json
import os
TASKS_FILE = 'tasks.json'
def load_tasks():
if os.path.isfile(TASKS_FILE):
with open(TASKS_FILE, 'r') as f:
tasks = json.load(f)
else:
tasks = []
return tasks
def save_tasks(tasks):
with open(TASKS_FILE, 'w') as f:
json.dump(ta... | import os
import json
from solution import add_task, list_tasks, remove_task, load_tasks, save_tasks, TASKS_FILE
def setup_function():
if os.path.isfile(TASKS_FILE):
os.remove(TASKS_FILE)
def teardown_function():
if os.path.isfile(TASKS_FILE):
os.remove(TASKS_FILE)
def test_add_task():
se... | [
{
"docstring": null,
"function_declaration": "def load_tasks():",
"function_name": "load_tasks",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def save_tasks(tasks):",
"function_name": "save_tasks",
"parameter_list": "(tasks)"
},
{
"docstring": n... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport json\nimport os\n\nTASKS_FILE = 'tasks.json'\n\ndef load_tasks():\n if os.path.isfile(TASKS_FILE):\n with open(TASKS_FILE, 'r') as f:\n tasks = jso... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071649",
"row_id": 71649,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145241']"
} | 0.428519 | Filter_71649 | I | [
"load_tasks",
"save_tasks",
"add_task",
"list_tasks",
"remove_task",
"main"
] | 6 | [
[
"add_task",
"load_tasks"
],
[
"add_task",
"save_tasks"
],
[
"list_tasks",
"load_tasks"
],
[
"remove_task",
"load_tasks"
],
[
"remove_task",
"save_tasks"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 8184f35efd2a4fa7889f2ff6cc68329c9277f363 | d40de7a7f616cec0f8e466ffe0d8d647dd69c3b2 | |||
v1.0 | instruct | Filter | Filter_71665_I | Hey, I'm working on a project where I need to simulate a simple neural network for image classification. I'm using NumPy for my implementation. Can you guide me through the basic steps to create a neural network from scratch without using any deep learning frameworks? | import numpy as np
def sigmoid(x):
"""
Sigmoid activation function.
"""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
"""
Derivative of the sigmoid function.
"""
return x * (1 - x)
def initialize_weights(input_size, hidden_size, output_size):
"""
Initialize weights an... | import numpy as np
from solution import sigmoid, sigmoid_derivative, initialize_weights, forward_propagation, backward_propagation, train
def test_sigmoid():
assert np.isclose(sigmoid(0), 0.5)
assert np.isclose(sigmoid(1), 0.7310585786300049)
def test_sigmoid_derivative():
assert np.isclose(sigmoid_deriva... | [
{
"docstring": "Sigmoid activation function.",
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": "Derivative of the sigmoid function.",
"function_declaration": "def sigmoid_derivative(x):",
"function_name": "sigmoid_deriv... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Sigmoid activation function.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n \"\"\"\n Derivative of th... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071665",
"row_id": 71665,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145281']"
} | 0.275731 | Filter_71665 | I | [
"sigmoid",
"sigmoid_derivative",
"initialize_weights",
"forward_propagation",
"backward_propagation",
"train"
] | 6 | [
[
"backward_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"train",
"backward_propagation"
],
[
"train",
"forward_propagation"
],
[
"train",
"initialize_weights"
]
] | 5 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | eaa2cbdda1f4aafbd954993cfc0f6ec700ff39b8 | 56d48070bcbffa128b5038f101e6288e3018cbf2 | |||
v1.0 | instruct | Filter | Filter_71671_I | Write a Python function that takes a list of integers as input and returns a list containing the prime numbers from the input list. The function should be efficient and use a helper function to check for prime numbers. | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def filter_primes... | from solution import filter_primes
def test_filter_primes_with_mixed_numbers():
assert filter_primes([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7]
def test_filter_primes_with_prime_only():
assert filter_primes([2, 3, 5, 7, 11, 13]) == [2, 3, 5, 7, 11, 13]
def test_filter_primes_with_non_prime_only():
ass... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers from the input list of integers.",
"function_declaration": "def filter_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(n):\n \"\"\"\n Helper function to check if a number is prime.\n Returns True if the number is prime, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071671",
"row_id": 71671,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145289']"
} | 0.724034 | Filter_71671 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fac7ad348e30ca3589e0aa7e02e0938e5f49d52d | 85d0d1707e54a40becf9293a872eb870e82c0bb9 | |||
v1.0 | instruct | Filter | Filter_71686_I | Can you provide a Python code snippet that demonstrates how to calculate the average temperature for a week and then compare it with the average temperature of the previous week? Assuming I have a list of temperatures for each day of the week for both current and previous weeks. | def calculate_average_temperature(temperatures):
"""
Returns the average temperature from a list of temperatures.
"""
return sum(temperatures) / len(temperatures)
def compare_weekly_average(current_week, previous_week):
"""
Compares the average temperature of the current week with the previous ... | from solution import calculate_average_temperature, compare_weekly_average
def test_calculate_average_temperature():
assert calculate_average_temperature([70, 72, 68, 65, 74, 75, 73]) == 71.0
assert calculate_average_temperature([90, 85, 88, 87, 92, 91, 89]) == 88.85714285714286
def test_compare_weekly_averag... | [
{
"docstring": "Returns the average temperature from a list of temperatures.",
"function_declaration": "def calculate_average_temperature(temperatures):",
"function_name": "calculate_average_temperature",
"parameter_list": "(temperatures)"
},
{
"docstring": "Compares the average temperature ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_average_temperature(temperatures):\n \"\"\"\n Returns the average temperature from a list of daily temperatures.\n \"\"\"\n if not temperatures:\n raise ValueE... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071686",
"row_id": 71686,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145328']"
} | 0.490971 | Filter_71686 | I | [
"calculate_average_temperature",
"compare_weekly_average"
] | 2 | [
[
"compare_weekly_average",
"calculate_average_temperature"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f724d6690d3683fb754e40c47f73b7d1bb537c6 | 77e4f7be5d1698b0237ca93a994acf19fe5945db | |||
v1.0 | instruct | Filter | Filter_71726_I | I need help with a Python code snippet that can generate a list of prime numbers in a given range. Can you provide a simple and efficient way to do this? | def is_prime(n):
"""
Check if a number is a prime number.
"""
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 prime_numbers_in_rang... | from solution import prime_numbers_in_range, is_prime
def test_is_prime():
assert is_prime(7) == True
assert is_prime(10) == False
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(17) == True
def test_prime_numbers_in_range_basic():
assert prime_numbers_in_range(10, 20) =... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of prime numbers in the given range [start, end].",
"function_declaration": "def prime_numbers_in_ran... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_primes(start, end):\n \"\"\"\n Generates a list of prime numbers in the given range [start, end].\n \"\"\"\n if start > end:\n return []\n\n def is_prime(n):... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071726",
"row_id": 71726,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145400']"
} | 0.585455 | Filter_71726 | I | [
"is_prime",
"prime_numbers_in_range"
] | 2 | [
[
"prime_numbers_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec2187ba115ef98d0702ae830c4ec6d089759cde | a79c08e0d1a2447d393a0e8a2059606a7be19d07 | |||
v1.0 | instruct | Filter | Filter_71763_I | I want to write a Python script that can ping a list of IP addresses and determine if they are reachable. How can I achieve this? | import subprocess
def ping_ip(ip):
"""
Pings a given IP address to check if it is reachable.
Args:
ip (str): The IP address to ping.
Returns:
bool: True if the IP address is reachable, False otherwise.
"""
try:
output = subprocess.check_output(['ping', '-c', '1', ip], stderr=s... | from solution import ping_ip, ping_ips
def test_ping_ip():
# Note: In practice, these tests can only be evaluated in a live network environment.
assert ping_ip("127.0.0.1") == True # localhost should always be reachable
assert ping_ip("8.8.8.8") # Google's public DNS; usually reachable if internet is up
... | [
{
"docstring": "Pings a given IP address to check if it is reachable.\n\nArgs:\nip (str): The IP address to ping.\n\nReturns:\nbool: True if the IP address is reachable, False otherwise.",
"function_declaration": "def ping_ip(ip):",
"function_name": "ping_ip",
"parameter_list": "(ip)"
},
{
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import subprocess\n\ndef ping_ip(ip_address):\n \"\"\"\n Pings an IP address to check if it is reachable.\n \n Args:\n ip_address (str): The IP address to ping.\n \n Retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071763",
"row_id": 71763,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145477']"
} | 0.755249 | Filter_71763 | I | [
"ping_ip",
"ping_ips"
] | 2 | [
[
"ping_ips",
"ping_ip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f7c18fb54353c6f32e52c6fc9a44503fcc98f22 | 7202076f503fdf68f76efbdeecd8ff287f288bcc | |||
v1.0 | instruct | Filter | Filter_71786_I | Hey, I'm learning Python and I want to practice by creating a simple program that simulates a basic calculator. This calculator should be able to perform addition, subtraction, multiplication, and division. It should also handle basic input validation to ensure the user enters valid numbers and operations. Can you guid... | def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def subtract(a, b):
"""
Returns the difference of a and b.
"""
return a - b
def multiply(a, b):
"""
Returns the product of a and b.
"""
return a * b
def divide(a, b):
"""
Returns the quotient of a ... | import pytest
from solution import add, subtract, multiply, divide, run_calculator
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(-2, -3) == -5
def test_subtract():
assert subtract(3, 2) == 1
assert subtract(1, -1) == 2
assert subtract(-3, -2) == -1
def test_multiply(... | [
{
"docstring": "Returns the sum of a and b.",
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the difference of a and b.",
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"paramete... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b.\n \"\"\"\n return a + b\n\ndef subtract(a, b):\n \"\"\"\n Returns the difference of a and b.\n \"\"\"\n return a -... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071786",
"row_id": 71786,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145515']"
} | 0.516249 | Filter_71786 | I | [
"add",
"subtract",
"multiply",
"divide",
"run_calculator"
] | 5 | [
[
"run_calculator",
"add"
],
[
"run_calculator",
"divide"
],
[
"run_calculator",
"multiply"
],
[
"run_calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 47713af1bec2cf6446940c4efbec9ff488d2f041 | 1b29726695dc7d0fadad5204c4f91b98b9e860a8 | |||
v1.0 | instruct | Filter | Filter_71812_I | If I want to create a chatbot using Python that can base its responses on data from a CSV file, how can I do it? | import csv
def read_csv(file_path):
"""
Reads a CSV file and returns a dictionary with the first column as keys and the second as values.
"""
responses = {}
with open(file_path, mode='r') as file:
reader = csv.reader(file)
for row in reader:
if len(row) >= 2:
... | from solution import read_csv, find_response
def test_read_csv(tmp_path):
test_file = tmp_path / "test_responses.csv"
test_file.write_text("hello,Hi there!\nbye,Goodbye!\n")
responses = read_csv(test_file)
assert responses == {"hello": "Hi there!", "bye": "Goodbye!"}
def test_find_response():
... | [
{
"docstring": "Reads a CSV file and returns a dictionary with the first column as keys and the second as values.",
"function_declaration": "def read_csv(file_path):",
"function_name": "read_csv",
"parameter_list": "(file_path)"
},
{
"docstring": "Finds the response corresponding to the user... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef load_data(file_path):\n \"\"\"\n Load data from a CSV file.\n\n :param file_path: Path to the CSV file\n :return: List of dictionaries representing rows in the CS... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071812",
"row_id": 71812,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145576']"
} | 0.45175 | Filter_71812 | I | [
"read_csv",
"find_response",
"chatbot"
] | 3 | [
[
"chatbot",
"find_response"
],
[
"chatbot",
"read_csv"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a2db830324682814010e9251f539ece8e95a92ee | 1fe916f9125554af55cced2f254522857925a52f | |||
v1.0 | instruct | Filter | Filter_71832_I | Can you provide a simple Python function to convert a list of numbers into their corresponding ordinal representations? For example, converting `1` to `'1st'`, `2` to `'2nd'`, `3` to `'3rd'`, and so on? | def number_to_ordinal(n):
"""
Converts a number n into its ordinal representation as a string.
"""
if 10 <= n % 100 <= 20:
suffix = "th"
elif n % 10 == 1:
suffix = "st"
elif n % 10 == 2:
suffix = "nd"
elif n % 10 == 3:
suffix = "rd"
else:
suffix = ... | from solution import convert_list_to_ordinals
from solution import number_to_ordinal
def test_number_to_ordinal():
assert number_to_ordinal(1) == "1st"
assert number_to_ordinal(2) == "2nd"
assert number_to_ordinal(3) == "3rd"
assert number_to_ordinal(4) == "4th"
assert number_to_ordinal(11) == "11t... | [
{
"docstring": "Converts a number n into its ordinal representation as a string.",
"function_declaration": "def number_to_ordinal(n):",
"function_name": "number_to_ordinal",
"parameter_list": "(n)"
},
{
"docstring": "Converts a list of numbers into their corresponding ordinal representations... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def number_to_ordinal(n):\n \"\"\"\n Convert a number into its ordinal representation.\n \"\"\"\n if 10 <= n % 100 <= 20:\n suffix = 'th'\n else:\n suffix = {1: 's... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071832",
"row_id": 71832,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145613']"
} | 0.477097 | Filter_71832 | I | [
"number_to_ordinal",
"convert_list_to_ordinals"
] | 2 | [
[
"convert_list_to_ordinals",
"number_to_ordinal"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8aa2c9bd891ab32d4624c2074a75ac42a9b8820c | 990c1d179bea5f263b6a02d4ffaaeb65ab3e137d | |||
v1.0 | instruct | Filter | Filter_71838_I | Can you provide a Python script that can verify the integrity of a list of files using their hash sums? You can use SHA-256 for this task. | import hashlib
import os
def calculate_sha256(file_path):
"""
Calculates and returns the SHA-256 hash of the specified file.
:param file_path: Path to the file.
:return: SHA-256 hash of the file content.
"""
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
# Read and... | import os
import hashlib
from solution import calculate_sha256, verify_files
def create_test_file(file_path, content):
with open(file_path, 'w') as f:
f.write(content)
def test_calculate_sha256():
test_file = 'test_file.txt'
content = 'This is a test file.'
expected_hash = hashlib.sha256(conte... | [
{
"docstring": "Calculates and returns the SHA-256 hash of the specified file.\n\n:param file_path: Path to the file.\n:return: SHA-256 hash of the file content.",
"function_declaration": "def calculate_sha256(file_path):",
"function_name": "calculate_sha256",
"parameter_list": "(file_path)"
},
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport os\n\ndef calculate_sha256(file_path):\n \"\"\"\n Calculates and returns the SHA-256 hash of the specified file.\n\n :param file_path: Path to the file.\n :r... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071838",
"row_id": 71838,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145628']"
} | 0.632268 | Filter_71838 | I | [
"calculate_sha256",
"verify_files"
] | 2 | [
[
"verify_files",
"calculate_sha256"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8058fc5ef2cce6bef1c89dac2c5c30658d8952b4 | 625e2dfd6e76e529b0668d9b9045ee9beed6d29d | |||
v1.0 | instruct | Filter | Filter_71845_I | I need to create a Python script that generates a list of prime numbers within a given range. The script should take two arguments, `start` and `end`, which represent the range of numbers to check for primality. The prime numbers found within this range should be returned as a list. How can I write this script? | def is_prime(n):
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i... | from solution import generate_primes
def test_generate_primes_within_single_digit_range():
assert generate_primes(1, 10) == [2, 3, 5, 7]
def test_generate_primes_within_double_digit_range():
assert generate_primes(10, 20) == [11, 13, 17, 19]
def test_generate_primes_no_primes_in_range():
assert generate_... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers between start and end (inclusive).",
"function_declaration": "def generat... | [
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 if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071845",
"row_id": 71845,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145639']"
} | 0.549493 | Filter_71845 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3053b6e8cafb8c8217744736c454577bb2e886d | 8cb68613f1d2146fcf4e67dd0ebe5b6c24e764a4 | |||
v1.0 | instruct | Filter | Filter_71859_I | A student is practicing her drawing skills by sketching a Sierpinski triangle using Python. She wants the triangle to point upwards. The Sierpinski triangle is a fractal pattern that includes multiple smaller triangles within a larger one. How can she implement this in Python using recursion? | import matplotlib.pyplot as plt
import numpy as np
def draw_sierpinski(ax, p1, p2, p3, depth):
"""
Draws a Sierpinski triangle on a given set of Axes object using matplotlib.
Parameters:
ax (matplotlib axes): The axes on which to draw the triangle.
p1, p2, p3 (tuple): The vertices of the main tria... | from solution import midpoint, create_sierpinski_triangle
def test_midpoint():
assert midpoint((0, 0), (2, 2)) == (1, 1)
assert midpoint((0, 0), (4, 0)) == (2, 0)
assert midpoint((1, 1), (3, 3)) == (2, 2)
def test_create_sierpinski_triangle():
create_sierpinski_triangle(0)
create_sierpinski_triang... | [
{
"docstring": "Draws a Sierpinski triangle on a given set of Axes object using matplotlib.\n\nParameters:\nax (matplotlib axes): The axes on which to draw the triangle.\np1, p2, p3 (tuple): The vertices of the main triangle.\ndepth (int): The depth of recursion to determine levels of detail.",
"function_de... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sierpinski_triangle(order, size):\n \"\"\"\n Draws a Sierpinski triangle of the given order and size pointing upwards.\n \"\"\"\n import turtle\n \n def draw_triangle(ver... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071859",
"row_id": 71859,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145672']"
} | 0.506315 | Filter_71859 | I | [
"draw_sierpinski",
"midpoint",
"create_sierpinski_triangle"
] | 3 | [
[
"create_sierpinski_triangle",
"draw_sierpinski"
],
[
"draw_sierpinski",
"midpoint"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 1fb3cad3a664468352799548bedd77f1ba49a118 | fbab6e4fa9f54936ee3ae7242a4f7462caa84f2a | |||
v1.0 | instruct | Filter | Filter_71862_I | Can you help me with a programming task? I need to modify a function so that it returns a list of all prime numbers within a given range, say from `m` to `n` (inclusive). The function should be efficient and handle large ranges. | def is_prime(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:... | from solution import find_primes
def test_prime_range():
assert find_primes(1, 10) == [2, 3, 5, 7]
assert find_primes(10, 20) == [11, 13, 17, 19]
assert find_primes(50, 60) == [53, 59]
assert find_primes(90, 100) == [97]
def test_prime_empty_range():
assert find_primes(14, 16) == []
assert fin... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers in the range from m to n (inclusive).",
"function_declarat... | [
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 Determines if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071862",
"row_id": 71862,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145677']"
} | 0.628366 | Filter_71862 | I | [
"is_prime",
"find_primes"
] | 2 | [
[
"find_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ffc85617b59a49f3f9c6a54a94fe2a0f22797273 | d028c5a06ac12c894bf6508e0c9558e337e684f2 | |||
v1.0 | instruct | Filter | Filter_71869_I | Write a Python function that takes a list of tuples, where each tuple contains two strings representing two words, and returns a list of tuples containing the longest common subsequence (LCS) of each pair of words. | def lcs(X, Y):
"""
Returns the longest common subsequence (LCS) of the strings X and Y.
"""
m = len(X)
n = len(Y)
# Create a 2D array to store lengths of longest common subsequence
L = [[0] * (n + 1) for i in range(m + 1)]
# Building the matrix in bottom-up way
for i in ran... | from solution import find_lcs_pairs
def test_find_lcs_pairs():
pairs = [
("abcde", "ace"),
("abc", "abc"),
("abc", "def"),
("axyz", "baz"),
("human", "chimpanzee")
]
expected = [
("abcde", "ace", "ace"),
("abc", "abc", "abc"),
("abc", "de... | [
{
"docstring": "Returns the longest common subsequence (LCS) of the strings X and Y.",
"function_declaration": "def lcs(X, Y):",
"function_name": "lcs",
"parameter_list": "(X, Y)"
},
{
"docstring": "Takes a list of tuples where each tuple contains two words and returns\na list of tuples cont... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def lcs(X, Y):\n \"\"\"\n Returns the longest common subsequence of two strings X and Y.\n \"\"\"\n m = len(X)\n n = len(Y)\n \n # Create a table to store lengths of longe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071869",
"row_id": 71869,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145688']"
} | 0.677197 | Filter_71869 | I | [
"lcs",
"find_lcs_pairs"
] | 2 | [
[
"find_lcs_pairs",
"lcs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0cc2bc3cb33dbaa1ee58239ab53bfeb5c830f46f | 8705510c5fdd136cc97ff99473da5c78596cd9a3 | |||
v1.0 | instruct | Filter | Filter_71871_I | Please provide a Python implementation of the k-means clustering algorithm without using any external libraries like NumPy or SciPy. | from random import sample
import math
def euclidean_distance(point1, point2):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def initialize_centroids(data, k):
return sample(data, k)
def assign_clusters(data, centroids):
clusters = [[] for _ in centroids]
for point in data:
... | from solution import euclidean_distance, kmeans
def test_euclidean_distance():
assert math.isclose(euclidean_distance([1, 2], [4, 6]), 5.0, rel_tol=1e-5)
assert math.isclose(euclidean_distance([1, 2, 3], [4, 5, 6]), 5.196152, rel_tol=1e-5)
def test_kmeans():
data = [
[1, 2], [2, 3], [3, 4], [8, 9]... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def initialize_centroids(data, k):",
"function_name": "initialize_centr... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from random import sample\nimport math\n\ndef euclidean_distance(point1, point2):\n return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))\n\ndef initialize_centroids(data, k):... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00071871",
"row_id": 71871,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145691']"
} | 0.589032 | Filter_71871 | I | [
"euclidean_distance",
"initialize_centroids",
"assign_clusters",
"calculate_new_centroids",
"kmeans"
] | 5 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"kmeans",
"assign_clusters"
],
[
"kmeans",
"calculate_new_centroids"
],
[
"kmeans",
"initialize_centroids"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 6012173f8706ba955af37ba7721449439977e91e | 9b31bd700013e0a59d91b2b10533e26e981c8c55 | |||
v1.0 | instruct | Filter | Filter_71872_I | Can you explain how to implement a custom compare function for sorting in Python? | from functools import cmp_to_key
def custom_compare(x, y):
"""
Comparison function that sorts in descending order.
Returns negative if x > y, zero if x == y, positive if x < y.
"""
if x > y:
return -1
elif x < y:
return 1
else:
return 0
def sort_with_custom_compare(... | from solution import custom_compare, sort_with_custom_compare
def test_custom_compare():
assert custom_compare(5, 3) == -1
assert custom_compare(2, 4) == 1
assert custom_compare(7, 7) == 0
def test_sort_with_custom_compare():
assert sort_with_custom_compare([5, 2, 9, 1, 5, 6]) == [9, 6, 5, 5, 2, 1]
... | [
{
"docstring": "Comparison function that sorts in descending order.\nReturns negative if x > y, zero if x == y, positive if x < y.",
"function_declaration": "def custom_compare(x, y):",
"function_name": "custom_compare",
"parameter_list": "(x, y)"
},
{
"docstring": "Sorts the array using the... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_sort(strings):\n \"\"\"\n Sorts a list of strings based on their lengths and, in case of ties, alphabetically.\n \"\"\"\n return sorted(strings, key=lambda x: (len(x), x... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071872",
"row_id": 71872,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145696']"
} | 0.664613 | Filter_71872 | I | [
"custom_compare",
"sort_with_custom_compare"
] | 2 | [
[
"sort_with_custom_compare",
"custom_compare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a72a821fdfec19310f2993bf3d778520da34b1d8 | 509de9a1b4b27e8f08f9858c0fd16aa78b1ea553 | |||
v1.0 | instruct | Filter | Filter_71874_I | You recently got an assignment to write a Python function that finds all the prime numbers in a given range. Can you explain how you would approach this problem in Python? | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tru... | from solution import is_prime, find_primes_in_range
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(11)
assert not is_prime(15)
assert is_prime(13)
def test_find_prime... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find all prime numbers in a given range [start, end].",
"function_declaration": "def find_primes_in_range(start, end):",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number n is a prime number.\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": "00071874",
"row_id": 71874,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145698']"
} | 0.682177 | Filter_71874 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 244a0c2afc933ce1e948cb5cc4130a76ca6b309d | c124e7a66595d239ac078b2d697b54a2fd54dd5d | |||
v1.0 | instruct | Filter | Filter_71913_I | Design a system that sorts a list of integers using the heap sort algorithm. Implement the system in Python. | def heapify(arr, n, i):
"""
Function to heapify the subtree rooted at index i.
n is size of heap.
"""
largest = i # Initialize largest as root
left = 2 * i + 1 # left = 2*i + 1
right = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is greater than root
if... | from solution import heap_sort
def test_heap_sort_empty():
assert heap_sort([]) == []
def test_heap_sort_single_element():
assert heap_sort([1]) == [1]
def test_heap_sort_multiple_elements():
assert heap_sort([4, 10, 3, 5, 1]) == [1, 3, 4, 5, 10]
def test_heap_sort_sorted_list():
assert heap_sort([1... | [
{
"docstring": "Function to heapify the subtree rooted at index i.\nn is size of heap.",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Function to perform heap sort on the given list.",
"function_declarat... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i):\n \"\"\"\n Helper function to maintain the heap property.\n \"\"\"\n largest = i # Initialize largest as root\n left = 2 * i + 1 # left = 2*i + 1\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00071913",
"row_id": 71913,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145786']"
} | 0.74233 | Filter_71913 | I | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7654864ff516ad5584e0a8714a630c1f1ff9c61f | 2d3a280106492768df77f445f331b475784aec8d | |||
v1.0 | instruct | Filter | Filter_71923_I | Write a Python code to generate a list of the first 1000 Fibonacci numbers and then calculate the sum of all these Fibonacci numbers. | def generate_fibonacci(n):
"""
Generate a list of the first n Fibonacci numbers.
"""
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
fib_list = [0, 1]
for i in range(2, n):
fib_list.append(fib_list[-1] + fib_list[-2])
return fi... | from solution import generate_fibonacci, sum_fibonacci
def test_generate_fibonacci_first_10():
expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
assert generate_fibonacci(10) == expected
def test_generate_fibonacci_first_1():
expected = [0]
assert generate_fibonacci(1) == expected
def test_generate_fibona... | [
{
"docstring": "Generate a list of the first n Fibonacci numbers.",
"function_declaration": "def generate_fibonacci(n):",
"function_name": "generate_fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of the first n Fibonacci numbers and return the sum of all these numbers... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_fibonacci(n):\n \"\"\"\n Generates a list of the first n Fibonacci numbers.\n \"\"\"\n if n <= 0:\n return []\n \n fib_list = [0, 1]\n \n while len(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071923",
"row_id": 71923,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145811']"
} | 0.691505 | Filter_71923 | I | [
"generate_fibonacci",
"sum_fibonacci"
] | 2 | [
[
"sum_fibonacci",
"generate_fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e332412e5589bbdc75a0780d2114466937fa9f04 | 9d50a5b9bcd97fc058f11fb780b89c58566b987e | |||
v1.0 | instruct | Filter | Filter_71961_I | Write a Python script that takes a string as input and counts the occurrences of each character in the string. The script should then print the count of each character in the order they first appear in the string. | def count_character_occurrences(s):
"""
Takes a string as input and returns a dictionary with the count of each character in the order
they first appear in the string.
"""
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
c... | from solution import count_character_occurrences, print_character_occurrences
from io import StringIO
import sys
def test_count_character_occurrences():
assert count_character_occurrences("hello") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}
assert count_character_occurrences("aabbcc") == {'a': 2, 'b': 2, 'c': 2}
a... | [
{
"docstring": "Takes a string as input and returns a dictionary with the count of each character in the order \nthey first appear in the string.",
"function_declaration": "def count_character_occurrences(s):",
"function_name": "count_character_occurrences",
"parameter_list": "(s)"
},
{
"doc... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_characters(s):\n \"\"\"\n Takes a string as input and counts the occurrences of each character in the string.\n Returns a dictionary with the count of each character in the ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00071961",
"row_id": 71961,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145885']"
} | 0.76379 | Filter_71961 | I | [
"count_character_occurrences",
"print_character_occurrences"
] | 2 | [
[
"print_character_occurrences",
"count_character_occurrences"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0ebfcf8d59d27f0553c69bb79935a276afd1373 | f770bcfb44c4b013eca7768f1029e803305f52c3 | |||
v1.0 | instruct | Filter | Filter_72000_I | Can you provide a Python code to animate a random walk process on a 2D grid? | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def random_walk_2d(n_steps):
x = np.zeros(n_steps)
y = np.zeros(n_steps)
for i in range(1, n_steps):
direction = np.random.choice(['up', 'down', 'left', 'right'])
if direction == 'up':
... | from solution import random_walk_2d
def test_random_walk_2d_initial_position():
x, y = random_walk_2d(10)
assert x[0] == 0
assert y[0] == 0
def test_random_walk_2d_length():
n_steps = 50
x, y = random_walk_2d(n_steps)
assert len(x) == n_steps
assert len(y) == n_steps
def test_random_walk_... | [
{
"docstring": null,
"function_declaration": "def random_walk_2d(n_steps):",
"function_name": "random_walk_2d",
"parameter_list": "(n_steps)"
},
{
"docstring": null,
"function_declaration": "def animate_random_walk(n_steps):",
"function_name": "animate_random_walk",
"parameter_li... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\ndef random_walk_2d(n_steps):\n x = np.zeros(n_steps)\n y = np.zeros(n_steps)\n \... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072000",
"row_id": 72000,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145974']"
} | 0.658493 | Filter_72000 | I | [
"random_walk_2d",
"animate_random_walk"
] | 2 | [
[
"animate_random_walk",
"random_walk_2d"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | f934390a91c76983d67ab991efbee067bc32fc65 | 6e2b5f43edae5fb65ba8a7068a8d0ee718bb21fe | |||
v1.0 | instruct | Filter | Filter_72005_I | How can I implement a simple reversi game in Python? | EMPTY = 0
BLACK = 1
WHITE = 2
def create_board():
"""
Creates an 8x8 board initialized with the starting position for Reversi
"""
board = [[EMPTY for _ in range(8)] for _ in range(8)]
board[3][3] = WHITE
board[3][4] = BLACK
board[4][3] = BLACK
board[4][4] = WHITE
return board
def i... | from solution import create_board, is_valid_move, make_move, BLACK, WHITE, EMPTY
def test_create_board():
board = create_board()
assert board[3][3] == WHITE
assert board[3][4] == BLACK
assert board[4][3] == BLACK
assert board[4][4] == WHITE
assert all(board[row][col] == EMPTY for row in range(8... | [
{
"docstring": "Creates an 8x8 board initialized with the starting position for Reversi",
"function_declaration": "def create_board():",
"function_name": "create_board",
"parameter_list": "()"
},
{
"docstring": "Returns True if the move is valid for the given player, else False",
"functi... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "EMPTY, BLACK, WHITE = '.', 'B', 'W'\n\ndef initialize_board():\n \"\"\"\n Initialize the board with initial four pieces placed in the center.\n \"\"\"\n board = [[EMPTY]*8 for _ in... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072005",
"row_id": 72005,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145982']"
} | 0.49633 | Filter_72005 | I | [
"create_board",
"is_valid_move",
"make_move"
] | 3 | [
[
"make_move",
"is_valid_move"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc98ad204f64e9cfc4c8782e64153b239f8fb859 | 432e7a4071ad683675447089e0ace98a9f54d080 | |||
v1.0 | instruct | Filter | Filter_72008_I | Could you provide a Python code snippet for a simple game of Rock, Paper, Scissors? | import random
def get_computer_choice():
"""
Randomly returns 'rock', 'paper', or 'scissors' as the computer's choice.
"""
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of a Rock, Paper, Scissors game.
... | from solution import determine_winner, play_rock_paper_scissors
def test_determine_winner():
assert determine_winner('rock', 'scissors') == 'player'
assert determine_winner('rock', 'paper') == 'computer'
assert determine_winner('rock', 'rock') == 'tie'
assert determine_winner('paper', 'rock') == 'playe... | [
{
"docstring": "Randomly returns 'rock', 'paper', or 'scissors' as the computer's choice.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of a Rock, Paper, Scissors game.\n\nParame... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly returns 'rock', 'paper', or 'scissors' as the computer's choice.\n \"\"\"\n return random.choice(['rock', 'paper', '... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072008",
"row_id": 72008,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_145991']"
} | 0.443984 | Filter_72008 | I | [
"get_computer_choice",
"determine_winner",
"play_rock_paper_scissors"
] | 3 | [
[
"play_rock_paper_scissors",
"determine_winner"
],
[
"play_rock_paper_scissors",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 10e304f5f539f12260ec25170e82e53312357a50 | b291417bc546a055b169659b3f7f426391b11344 | |||
v1.0 | instruct | Filter | Filter_72033_I | Can you provide a Python function that calculates the sum of all prime numbers within a given range, say from 1 to 100? We can define a helper function to check if a number is prime. | def is_prime(num):
"""
Helper function to 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 s... | from solution import is_prime, sum_of_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(1) == False
assert is_prime(0) == False
assert is_prime(-3) == False
def test_sum_of_primes():
... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the sum of all prime numbers in the range from start to end (inclusive).",
"function_declaratio... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072033",
"row_id": 72033,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146032']"
} | 0.648984 | Filter_72033 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d20ed51f09afaea28254cbcb3043bfffbb9f4d5b | fa3e29d8c4d693357adbe9fcc4e19abe62121b05 | |||
v1.0 | instruct | Filter | Filter_72065_I | Can you provide a Python code snippet to calculate the dot product of two vectors and the cosine similarity between them? | import math
def dot_product(vector1, vector2):
"""
Calculates the dot product of two vectors.
"""
return sum(a * b for a, b in zip(vector1, vector2))
def cosine_similarity(vector1, vector2):
"""
Calculates the cosine similarity between two vectors.
"""
dot_prod = dot_product(vector1, v... | from solution import dot_product, cosine_similarity
def test_dot_product_basic():
assert dot_product([1, 2, 3], [4, 5, 6]) == 32
def test_dot_product_orthogonal_vectors():
assert dot_product([1, 0, 0], [0, 1, 0]) == 0
def test_dot_product_negative_values():
assert dot_product([-1, -2, -3], [4, 5, 6]) == ... | [
{
"docstring": "Calculates the dot product of two vectors.",
"function_declaration": "def dot_product(vector1, vector2):",
"function_name": "dot_product",
"parameter_list": "(vector1, vector2)"
},
{
"docstring": "Calculates the cosine similarity between two vectors.",
"function_declarati... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef dot_product(vector1, vector2):\n \"\"\"\n Calculates the dot product of two vectors.\n \"\"\"\n return sum(a * b for a, b in zip(vector1, vector2))\n\ndef cosine... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072065",
"row_id": 72065,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146081']"
} | 0.479843 | Filter_72065 | I | [
"dot_product",
"cosine_similarity"
] | 2 | [
[
"cosine_similarity",
"dot_product"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 476833ceefed6f295999268eb083f066a732bc76 | 30aaad28279d3a15ae8b47326a79d54590a957eb | |||
v1.0 | instruct | Filter | Filter_72071_I | Write a Python program that reads a text file and counts the frequency of each word in the file. The program should ignore common stop words such as "the", "and", "is", etc. You can use a predefined list of stop words for this task. Additionally, the program should handle punctuation and be case-insensitive. | import string
from collections import defaultdict
STOP_WORDS = {"the", "and", "is", "in", "it", "to", "of", "that", "a", "with", "as", "for", "its", "was"}
def read_file(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
def process_text(text):
text = text.lower()
... | import tempfile
import pytest
from solution import word_frequency
def create_test_file(content):
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(content.encode('utf-8'))
temp_file.close()
return temp_file.name
def test_word_frequency_single_word():
content = "Hello"
file_... | [
{
"docstring": null,
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def process_text(text):",
"function_name": "process_text",
"parameter_list": "(text)"
},
{
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import string\nfrom collections import defaultdict\n\nSTOP_WORDS = {\"the\", \"and\", \"is\", \"in\", \"it\", \"to\", \"of\", \"that\", \"a\", \"with\", \"as\", \"for\", \"its\", \"was\"}\n\nd... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072071",
"row_id": 72071,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146092']"
} | 0.78334 | Filter_72071 | I | [
"read_file",
"process_text",
"word_frequency"
] | 3 | [
[
"word_frequency",
"process_text"
],
[
"word_frequency",
"read_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9ce9a93ddeeaddba3095868fbeba19af2930829a | f6cd9d3b011d50765c9c7845082b67cffc76012f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.