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_72078_I | Write a Python function that receives a dictionary and changes its values from Celsius to Fahrenheit. The function should return the dictionary with updated values. | def celsius_to_fahrenheit(celsius):
"""
Convert Celsius to Fahrenheit.
"""
return (celsius * 9/5) + 32
def convert_dict_values_to_fahrenheit(data):
"""
Convert all dictionary values from Celsius to Fahrenheit.
Parameters:
data (dict): A dictionary with values in Celsius.
... | from solution import convert_dict_values_to_fahrenheit, celsius_to_fahrenheit
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenheit(-40) == -40 # edge case where Celsius and Fahrenheit are the same
def test_convert_di... | [
{
"docstring": "Convert Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(celsius)"
},
{
"docstring": "Convert all dictionary values from Celsius to Fahrenheit.\n\nParameters:\n data (dict)... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius_dict):\n \"\"\"\n Converts the values of the given dictionary from Celsius to Fahrenheit.\n \n Parameters:\n celsius_dict (dict): A dictionary ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072078",
"row_id": 72078,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146106']"
} | 0.503188 | Filter_72078 | I | [
"celsius_to_fahrenheit",
"convert_dict_values_to_fahrenheit"
] | 2 | [
[
"convert_dict_values_to_fahrenheit",
"celsius_to_fahrenheit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 978602bd5db2d97038440e926934ea6a2a82e593 | da1b2596b993d4d8c2d5a8a477d92001d091276c | |||
v1.0 | instruct | Filter | Filter_72081_I | In a coding challenge, you are tasked with finding the first pair of palindromic numbers in a list that add up to a target sum. A palindromic number reads the same backward as forward. For example, 121 and 131 are palindromic numbers. You are given a list of integers and a target sum. Your job is to write a function th... | def is_palindromic(number):
"""
Check if a number is a palindrome.
"""
return str(number) == str(number)[::-1]
def find_palindromic_pair(numbers, target_sum):
"""
Finds the first pair of palindromic numbers in a list that add up to the target sum.
If no such pair exists, return an empty lis... | from solution import find_palindromic_pair
def test_find_palindromic_pair_exists():
assert find_palindromic_pair([121, 131, 22, 44, 55], 165) == [121, 44]
assert find_palindromic_pair([121, 131, 33, 44, 55], 154) == [121, 33]
def test_no_palindromic_pair():
assert find_palindromic_pair([121, 131, 22, 44, ... | [
{
"docstring": "Check if a number is a palindrome.",
"function_declaration": "def is_palindromic(number):",
"function_name": "is_palindromic",
"parameter_list": "(number)"
},
{
"docstring": "Finds the first pair of palindromic numbers in a list that add up to the target sum.\nIf no such pair... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindromic(number):\n \"\"\"\n Check if a number is a palindrome.\n \"\"\"\n return str(number) == str(number)[::-1]\n\ndef find_palindromic_pair(numbers, target_sum):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072081",
"row_id": 72081,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146110']"
} | 0.633475 | Filter_72081 | I | [
"is_palindromic",
"find_palindromic_pair"
] | 2 | [
[
"find_palindromic_pair",
"is_palindromic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 736ab25c2e6df11e21f8792e6d78848d9e0a3970 | 5ee168ac56eba3a0e55cad216e141413ac6539cf | |||
v1.0 | instruct | Filter | Filter_72152_I | I want to create a Python script that converts a JSON object to a CSV file. The JSON object contains nested data structures. How can I handle these nested structures when converting to CSV? | import csv
import json
from collections.abc import Iterable
def flatten_json(y):
"""
Flatten a nested json object.
"""
out = {}
def flatten(x, name=''):
if isinstance(x, dict):
for a in x:
flatten(x[a], name + a + '_')
elif isinstance(x, list):
... | from solution import json_to_csv
import os
def compare_csv(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
return f1.readlines() == f2.readlines()
def test_json_to_csv_simple():
input_json = '[{"a": 1, "b": 2}, {"a": 3, "b": 4}]'
expected_csv = 'expected_simple.csv'
wi... | [
{
"docstring": "Flatten a nested json object.",
"function_declaration": "def flatten_json(y):",
"function_name": "flatten_json",
"parameter_list": "(y)"
},
{
"docstring": "Convert JSON to CSV.\n\nParameters:\n- json_data: The JSON data to convert (either a dict or a list of dicts).\n- csv_fi... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport json\nfrom collections.abc import Iterable\n\ndef flatten_json(y):\n \"\"\"\n Flatten a nested json object.\n \"\"\"\n out = {}\n\n def flatten(x, name=''):\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072152",
"row_id": 72152,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146238']"
} | 0.634333 | Filter_72152 | I | [
"flatten_json",
"json_to_csv"
] | 2 | [
[
"json_to_csv",
"flatten_json"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f982c0c131285494e179e66566f112915415c91 | 891874f6e8eddb6d770fe35d42e23224d8511f45 | |||
v1.0 | instruct | Filter | Filter_72190_I | Compose a Python script that reads data from four different text files, processes the data by removing any lines that are empty or contain only whitespace, and then writes the processed data to four new files, appending a timestamp to each filename. The script should also log the number of lines read and written for ea... | import os
from datetime import datetime
def process_file(input_filepath, output_filepath):
with open(input_filepath, 'r') as infile:
lines = infile.readlines()
processed_lines = [line for line in lines if line.strip()]
with open(output_filepath, 'w') as outfile:
outfile.writelines(process... | import os
import pytest
from datetime import datetime
def create_test_file(filename, contents):
with open(filename, 'w') as f:
f.writelines(contents)
def read_file(filename):
with open(filename, 'r') as f:
return f.readlines()
def test_process_file():
test_input = "test_input.txt"
tes... | [
{
"docstring": null,
"function_declaration": "def process_file(input_filepath, output_filepath):",
"function_name": "process_file",
"parameter_list": "(input_filepath, output_filepath)"
},
{
"docstring": null,
"function_declaration": "def log_data(filename, lines_read, lines_written):",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport datetime\n\ndef process_file(input_file_path, output_file_path):\n lines_read = 0\n lines_written = 0\n\n with open(input_file_path, 'r') as input_file:\n lin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072190",
"row_id": 72190,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146332']"
} | 0.483214 | Filter_72190 | I | [
"process_file",
"log_data",
"main"
] | 3 | [
[
"process_file",
"log_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee7510c236b0b0a9c47b3fa1158f5f28c2a9e6ca | 369bce311cd7f7e485989457f31d3f8b715093ae | |||
v1.0 | instruct | Filter | Filter_72212_I | I need to create a Python function that calculates the sum of all the prime numbers in a given list. How can I achieve this? | def is_prime(n):
"""
Returns True if n is a prime number, otherwise 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
... | from solution import sum_of_primes, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(15) == False
assert is_prime(29) == True
def test_sum_of_primes():
assert sum_of_primes([1, 2, 3, ... | [
{
"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 the sum of all prime numbers in the given list.",
"function_declaration": "def sum_of_primes... | [
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, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072212",
"row_id": 72212,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146385']"
} | 0.626563 | Filter_72212 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 380d6d82d0e7f40f44c9b5793f14b51864937f88 | afc945569821a773b466ad9bc1c31d0402baabba | |||
v1.0 | instruct | Filter | Filter_72243_I | Can you provide a Python code that simulates a simple genetic algorithm to evolve a population of binary strings towards a specific target binary string? | import random
def initialize_population(size, string_length):
"""
Initialize a population of binary strings.
"""
return [''.join(random.choice('01') for _ in range(string_length)) for _ in range(size)]
def fitness_function(individual, target):
"""
Calculate fitness as the number of bits matchi... | from solution import initialize_population, fitness_function, selection, crossover, mutation, genetic_algorithm
def test_initialize_population():
population = initialize_population(10, 5)
assert len(population) == 10
assert all(len(individual) == 5 for individual in population)
def test_fitness_function()... | [
{
"docstring": "Initialize a population of binary strings.",
"function_declaration": "def initialize_population(size, string_length):",
"function_name": "initialize_population",
"parameter_list": "(size, string_length)"
},
{
"docstring": "Calculate fitness as the number of bits matching the ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nTARGET = \"111100001111\"\nPOP_SIZE = 100 # Population size\nGENERATIONS = 5000\nMUTATION_RATE = 0.01\n\ndef generate_individual(length):\n \"\"\"Generate a random indivi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072243",
"row_id": 72243,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146439']"
} | 0.448114 | Filter_72243 | I | [
"initialize_population",
"fitness_function",
"selection",
"crossover",
"mutation",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutation"
],
[
"genetic_algorithm",
"selection"
],
[
"selection",
"fitness_function"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 26f967ddcff2a42b824219eee5c2f7e1dfeaafe1 | 6ad6f4f7132a94612f404923bda78e7775176b96 | |||
v1.0 | instruct | Filter | Filter_72264_I | What are the steps to reproduce the Brusselator model in Python using the `scipy` library for solving the system of Ordinary Differential Equations (ODEs)? | from scipy.integrate import solve_ivp
import numpy as np
import matplotlib.pyplot as plt
def brusselator(t, y, a, b):
"""
Defines the Brusselsator system of ODEs.
Parameters:
- t: time
- y: a list or array with the state variables [x, y]
- a: parameter 'a'
- b: parameter 'b'
R... | from solution import brusselator, solve_brusselator
import numpy as np
def test_brusselator():
a = 1.0
b = 3.0
t = 0.0
y = [1.0, 1.0]
dydt = brusselator(t, y, a, b)
assert np.isclose(dydt[0], -2.0, atol=1e-5)
assert np.isclose(dydt[1], 2.0, atol=1e-5)
def test_solve_brusselator_initial():
... | [
{
"docstring": "Defines the Brusselsator system of ODEs.\n\nParameters:\n- t: time\n- y: a list or array with the state variables [x, y]\n- a: parameter 'a'\n- b: parameter 'b'\n\nReturns:\n- dydt: derivatives",
"function_declaration": "def brusselator(t, y, a, b):",
"function_name": "brusselator",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from scipy.integrate import solve_ivp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef brusselator(t, y, a, b):\n \"\"\"\n Defines the Brusselsator system of ODEs.\n \n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072264",
"row_id": 72264,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146483']"
} | 0.255814 | Filter_72264 | I | [
"brusselator",
"solve_brusselator"
] | 2 | [
[
"solve_brusselator",
"brusselator"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | fffa659b0fa2a53b45dd6a79d33d935c34256268 | 676b500e57bbbbf8359e5e2afb24e8f78a1556a3 | |||
v1.0 | instruct | Filter | Filter_72344_I | Write a Python function that calculates the sum of the first 1000 prime numbers. The function should be efficient and use a helper function to check for prime numbers. | def is_prime(n):
"""
Helper function to determine if n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import is_prime, sum_of_first_1000_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(1) == False
assert is_prime(0) == False
assert is_prime(-... | [
{
"docstring": "Helper function to determine if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Function to calculate the sum of the first 1000 prime numbers.",
"function_declaration": "def sum_of_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n 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": "00072344",
"row_id": 72344,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146640']"
} | 0.623945 | Filter_72344 | I | [
"is_prime",
"sum_of_first_1000_primes"
] | 2 | [
[
"sum_of_first_1000_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4a30db1924fbaa4ebfb1aab8ca728f8a767fe31 | 25c86684d274ff72391df3553c457ab787d565ad | |||
v1.0 | instruct | Filter | Filter_72348_I | I'm working on a game project and need help with some programming. Specifically, I'm trying to implement a pathfinding algorithm that finds the shortest path between two nodes in a grid-based map. Could you guide me on how to do this? | from heapq import heappop, heappush
def heuristic(a, b):
"""
Calculates the Manhattan distance from a to b.
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def astar(grid, start, goal):
"""
Finds the shortest path from start to goal in a grid using A* algorithm.
:param grid: 2D list re... | from solution import astar
def test_astar_basic():
grid = [
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
start = (0, 0)
goal = (3, 3)
assert astar(grid, start, goal) == [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (3, 2), (3, 3)] or [(0, 0), (0, 1), (0, 2), (... | [
{
"docstring": "Calculates the Manhattan distance from a to b.",
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": "Finds the shortest path from start to goal in a grid using A* algorithm.\n\n:param grid: 2D list repres... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from heapq import heappop, heappush\n\ndef heuristic(a, b):\n \"\"\"Helper function to calculate the heuristic distance between two points\"\"\"\n return abs(a[0] - b[0]) + abs(a[1] - b[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072348",
"row_id": 72348,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146650']"
} | 0.568937 | Filter_72348 | I | [
"heuristic",
"astar"
] | 2 | [
[
"astar",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 37bcace79b5576713282ca20a623741ec07e1014 | c2f500f0280bdf9fa2c486e3128c48cd3a6be84c | |||
v1.0 | instruct | Filter | Filter_72380_I | Can you provide a Python code snippet to simulate a simple dice game where a player rolls two dice and tries to get a sum of seven? The game should allow the player to roll the dice up to five times, and if the player gets a sum of seven on any of the rolls, they win. If they don't get a seven in all five rolls, they l... | import random
def roll_dice():
"""
Simulates rolling two dice and returns their sum.
"""
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
return dice1 + dice2
def play_dice_game():
"""
Simulates a dice game where the player tries to roll a sum of seven with two dice.
The p... | from solution import roll_dice, play_dice_game
def test_roll_dice():
for _ in range(1000): # roll dice 1000 times to ensure robustness of the test
result = roll_dice()
assert 2 <= result <= 12
assert isinstance(result, int)
def test_play_dice_game_win(monkeypatch):
# Mocking roll_dice... | [
{
"docstring": "Simulates rolling two dice and returns their sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a dice game where the player tries to roll a sum of seven with two dice.\nThe player has up to fiv... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulates rolling two dice and returns their sum.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n return d... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072380",
"row_id": 72380,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146719']"
} | 0.544576 | Filter_72380 | I | [
"roll_dice",
"play_dice_game"
] | 2 | [
[
"play_dice_game",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7d31f4fad4d8b402db5493902b09f29f6052f2d0 | 3d0de268545c80551da9bd22282a03674c4f011e | |||
v1.0 | instruct | Filter | Filter_72402_I | Implement a Depth First Search (DFS) algorithm for finding connected components in an undirected graph. The graph is represented as a list of edges, and the goal is to identify all the connected components within the graph. | def dfs(graph, node, visited, component):
"""
Helper function to perform DFS and find all nodes in the current connected component.
"""
stack = [node]
while stack:
n = stack.pop()
if n not in visited:
visited.add(n)
component.append(n)
stack.extend... | from solution import find_connected_components
def test_single_component():
edges = [(1, 2), (2, 3), (3, 4)]
result = find_connected_components(edges)
assert result == [[1, 2, 3, 4]] or result == [[4, 3, 2, 1]]
def test_two_components():
edges = [(1, 2), (2, 3), (4, 5)]
result = find_connected_com... | [
{
"docstring": "Helper function to perform DFS and find all nodes in the current connected component.",
"function_declaration": "def dfs(graph, node, visited, component):",
"function_name": "dfs",
"parameter_list": "(graph, node, visited, component)"
},
{
"docstring": "Returns a list of conn... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def dfs(graph, node, visited, component):\n \"\"\"\n Helper function to perform DFS and find all nodes in the current connected component.\n \"\"\"\n stack = [node]\n while stac... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072402",
"row_id": 72402,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146752']"
} | 0.493783 | Filter_72402 | I | [
"dfs",
"find_connected_components"
] | 2 | [
[
"find_connected_components",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 89fcbd1981d9c0c0c065f17eaa0debf05d34ee57 | 051dbcef48a7d0e47f03acb1a3a3b0d84ed6daa9 | |||
v1.0 | instruct | Filter | Filter_72440_I | Write a Python function to find all Armstrong numbers in a given range and return them as a list. An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. | def is_armstrong_number(num):
"""
Check if a number is an Armstrong number.
"""
digits = list(map(int, str(num)))
num_digits = len(digits)
return num == sum([digit ** num_digits for digit in digits])
def find_armstrong_numbers(start, end):
"""
Find all Armstrong numbers within the given... | from solution import is_armstrong_number, find_armstrong_numbers
def test_is_armstrong_number():
assert is_armstrong_number(153) == True
assert is_armstrong_number(370) == True
assert is_armstrong_number(371) == True
assert is_armstrong_number(9474) == True
assert is_armstrong_number(9475) == False... | [
{
"docstring": "Check if a number is an Armstrong number.",
"function_declaration": "def is_armstrong_number(num):",
"function_name": "is_armstrong_number",
"parameter_list": "(num)"
},
{
"docstring": "Find all Armstrong numbers within the given range [start, end].",
"function_declaratio... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_armstrong_number(num):\n \"\"\"\n Checks if a number is an Armstrong number.\n \"\"\"\n digits = [int(d) for d in str(num)]\n num_digits = len(digits)\n return num == ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072440",
"row_id": 72440,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146834']"
} | 0.396406 | Filter_72440 | I | [
"is_armstrong_number",
"find_armstrong_numbers"
] | 2 | [
[
"find_armstrong_numbers",
"is_armstrong_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 529cf532ee0dc55ec44a14abe9cfe1c525f72e61 | cf7d10636d46987979ec4c05c09bc5d91537a388 | |||
v1.0 | instruct | Filter | Filter_72468_I | Can you provide the source code for a simple text-based calculator in Python? | 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 calculate(operation, a, b):
if operation == 'add':
return add(a, b)
elif operation == 'sub... | from solution import add, subtract, multiply, divide, calculate
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(2, 1) == 1
assert subtract(-1, 1) == -2
assert subtract(0, 0) == 0
def test_multiply():
assert multiply(2... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculator(operation, a, b):\n \"\"\"\n Perform a simple calculation based on the provided operation.\n\n Parameters:\n operation (str): The operation to perform: 'add', 'subtr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072468",
"row_id": 72468,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146887']"
} | 0.445468 | Filter_72468 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculate"
] | 5 | [
[
"calculate",
"add"
],
[
"calculate",
"divide"
],
[
"calculate",
"multiply"
],
[
"calculate",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b3d3edb11602e27370ee05a90b27fbf2cb9d6e90 | c30cf1e8fb862dd9c59ee537fe34fd6e539b240f | |||
v1.0 | instruct | Filter | Filter_72494_I | How can I calculate the first 20 prime numbers and store them in a list in Python? | def is_prime(n):
"""
Check if a number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
re... | from solution import is_prime, first_n_primes, first_20_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(11) == True
def test_first_n_primes():
assert first_... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of the first n prime numbers.",
"function_declaration": "def first_n_primes(n):",
"function_name":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if the number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072494",
"row_id": 72494,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146939']"
} | 0.585332 | Filter_72494 | I | [
"is_prime",
"first_n_primes",
"first_20_primes"
] | 3 | [
[
"first_20_primes",
"first_n_primes"
],
[
"first_n_primes",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7c4b851179521d472bad659542958fbf0c5002f0 | 13f0da500e70d7ca3cef138da026a7e3e9a2be20 | |||
v1.0 | instruct | Filter | Filter_72495_I | How can I modify the given Python script to handle multiple input files and process each one individually? | def process_file(file_path):
"""
Processes a single file and returns the result.
The specific processing logic should be defined inside this function.
"""
with open(file_path, 'r') as file:
# Implement your specific file processing logic here
data = file.read()
# Example: jus... | import os
# Note: You need to create some sample files for these tests to run properly
# Let's simulate creating 2 files with temporary content for testing purposes
def setup_temp_files():
file_paths = ["test_file_1.txt", "test_file_2.txt"]
content = ["Hello, this is test file 1", "Hello, this is test file 2"]... | [
{
"docstring": "Processes a single file and returns the result.\nThe specific processing logic should be defined inside this function.",
"function_declaration": "def process_file(file_path):",
"function_name": "process_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Processes multi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import glob\n\ndef process_file(file_path):\n \"\"\"\n Placeholder function to process a single file.\n Returns the file name reversed as a simple processing example.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072495",
"row_id": 72495,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_146942']"
} | 0.531221 | Filter_72495 | I | [
"process_file",
"process_multiple_files"
] | 2 | [
[
"process_multiple_files",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bdda29521b5f8597432ccfb0ad621f486783f05a | db47d0ac870f87269a99bd3b26b9b16cb29294d4 | |||
v1.0 | instruct | Filter | Filter_72571_I | I want to make a simple game where players can guess a random number generated by the computer. Can you provide a basic outline of how to create this game in Python? | import random
def generate_random_number(start, end):
"""
Generates a random number between start and end inclusive.
"""
return random.randint(start, end)
def guess_number(target, guess):
"""
Compares the guess to the target number and provides feedback.
"""
if guess < target:
... | from solution import generate_random_number, guess_number
def test_generate_random_number_range():
start, end = 1, 100
random_number = generate_random_number(start, end)
assert start <= random_number <= end
def test_guess_number_correct():
target = 50
guess = 50
assert guess_number(target, gue... | [
{
"docstring": "Generates a random number between start and end inclusive.",
"function_declaration": "def generate_random_number(start, end):",
"function_name": "generate_random_number",
"parameter_list": "(start, end)"
},
{
"docstring": "Compares the guess to the target number and provides ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_number(start, end):\n \"\"\"\n Generates a random number between start and end, inclusive.\n \"\"\"\n return random.randint(start, end)\n\ndef ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072571",
"row_id": 72571,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147091']"
} | 0.494167 | Filter_72571 | I | [
"generate_random_number",
"guess_number",
"play_game"
] | 3 | [
[
"play_game",
"generate_random_number"
],
[
"play_game",
"guess_number"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d0c3fc5122cace22d3cddac0ec4c0a3025f16175 | 02133790a39972329e4216fae4bb98992ae42d4a | |||
v1.0 | instruct | Filter | Filter_72576_I | Can you provide a Python script to monitor a local directory for changes and send alerts via email when changes are detected? | import os
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, body, to_email, from_email, from_password):
"""
Send an email with a specified subject and body.
"""
message = MIMEMultipart()
message['From'] = from_emai... | import os
import tempfile
import time
import subprocess
from unittest.mock import patch
from solution import monitor_directory, send_email
def test_send_email():
# This function would normally send an email, but here we'll mock it for testing
with patch('smtplib.SMTP') as mock_smtp:
send_email("Test Su... | [
{
"docstring": "Send an email with a specified subject and body.",
"function_declaration": "def send_email(subject, body, to_email, from_email, from_password):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, from_email, from_password)"
},
{
"docstring": "Monitor... | [
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 time\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nclass DirectoryMoni... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072576",
"row_id": 72576,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147104']"
} | 0.451819 | Filter_72576 | I | [
"send_email",
"monitor_directory"
] | 2 | [
[
"monitor_directory",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 07243f59c4753f51ad1df09216bcdc3743eb84f1 | b8dba6b0074f51540cfcfd49500dff4ae19cf537 | |||
v1.0 | instruct | Filter | Filter_72585_I | Can you generate a Python code to simulate a simple rock-paper-scissors game where a user plays against the computer? | import random
def get_computer_choice():
"""
Randomly returns 'rock', 'paper', or 'scissors'.
"""
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
"""
Determines the winner of the game based on the choices.
Return... | from solution import get_computer_choice, determine_winner, play_rock_paper_scissors
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
assert get_computer_choice() in choices
def test_determine_winner():
assert determine_winner('rock', 'scissors') == 'user'
assert determine_winne... | [
{
"docstring": "Randomly returns 'rock', 'paper', or 'scissors'.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of the game based on the choices.\nReturns 'user', 'computer', or '... | [
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 choices = ['rock', 'paper', 'scissors']\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072585",
"row_id": 72585,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147135']"
} | 0.447022 | Filter_72585 | 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 | 1752448ce3cfddde9da60127c26591929e2641e2 | e78539838a921eeeeb8a1bccf9025a828d83731e | |||
v1.0 | instruct | Filter | Filter_72614_I | Please provide a Python code snippet that checks if a number is a prime number and then prints whether the number is prime or not. | def is_prime(n):
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def check_prime(n):
"""
Prints whether the number is prime or not.
"""
if i... | from solution import is_prime, check_prime
import pytest
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(16) == False
assert is_prime(17) == True
assert is_prime(1) == False
assert is_prime... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Prints whether the number is prime or not.",
"function_declaration": "def check_prime(n):",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072614",
"row_id": 72614,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147187']"
} | 0.791376 | Filter_72614 | I | [
"is_prime",
"check_prime"
] | 2 | [
[
"check_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ac461ad42dbbf498b18662fc67afd1561aed5a8 | 163d837593952fb71448c3f0d5d057b67ef1b4ed | |||
v1.0 | instruct | Filter | Filter_72620_I | How can I write a Python function to check if a string is a valid email address? How can I modify the function to use a dictionary to manage and validate multiple email addresses? | import re
def is_valid_email(email):
"""
This function checks if the given string is a valid email address.
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def validate_emails(emails_dict):
"""
This function takes a dictionary o... | from solution import is_valid_email, validate_emails
def test_is_valid_email():
assert is_valid_email("example@example.com")
assert is_valid_email("user.name+tag+sorting@example.com")
assert not is_valid_email("plainaddress")
assert not is_valid_email("example.com")
assert not is_valid_email("user@... | [
{
"docstring": "This function checks if the given string is a valid email address.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "This function takes a dictionary of emails and checks their validity.\n... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_email(email):\n \"\"\"\n Checks if the provided email is valid or not.\n\n Parameters:\n email (str): The email address to validate.\n\n Returns:\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072620",
"row_id": 72620,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147206']"
} | 0.571895 | Filter_72620 | I | [
"is_valid_email",
"validate_emails"
] | 2 | [
[
"validate_emails",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86951a0db3a78c04b21f9a86edaefc477a3fe75d | 21159e3ba7a426202c7acd4ebf629b57c5218dbc | |||
v1.0 | instruct | Filter | Filter_72649_I | Hey Qwen, could you provide a Python code snippet to simulate a simple coin flip game where the user wins if the coin lands on heads? How can I modify this game to include a betting system where the user can place a bet and win or lose double their bet based on the result of the coin flip? | import random
def coin_flip():
"""
Simulates a coin flip. Returns 'Heads' or 'Tails'.
"""
return 'Heads' if random.choice([True, False]) else 'Tails'
def coin_flip_game_with_bet(bet_amount):
"""
Simulates a coin flip game with a betting system.
If the coin lands on heads, the user wins dou... | from solution import coin_flip, coin_flip_game_with_bet
def test_coin_flip():
results = [coin_flip() for _ in range(1000)]
heads_count = results.count('Heads')
tails_count = results.count('Tails')
assert heads_count > 0, "No 'Heads' were flipped"
assert tails_count > 0, "No 'Tails' were flipped"
... | [
{
"docstring": "Simulates a coin flip. Returns 'Heads' or 'Tails'.",
"function_declaration": "def coin_flip():",
"function_name": "coin_flip",
"parameter_list": "()"
},
{
"docstring": "Simulates a coin flip game with a betting system.\nIf the coin lands on heads, the user wins double their b... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef coin_flip():\n \"\"\"\n Simulates a coin flip. Returns 'Heads' or 'Tails'.\n \"\"\"\n return 'Heads' if random.choice([True, False]) else 'Tails'\n\ndef coin_f... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072649",
"row_id": 72649,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147253']"
} | 0.459767 | Filter_72649 | I | [
"coin_flip",
"coin_flip_game_with_bet"
] | 2 | [
[
"coin_flip_game_with_bet",
"coin_flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1f9772307e24bd7f7c97879f36f50624c8c29223 | 06e01720aa634e2aa075fa7f5391ba70bd358c72 | |||
v1.0 | instruct | Filter | Filter_72698_I | Write a recursive function to print the Fibonacci sequence up to a given number of terms. The function should also calculate and print the sum of the Fibonacci sequence up to the given number of terms. | def fibonacci(n, sequence=None):
if sequence is None:
sequence = []
if n <= 0:
return sequence
elif len(sequence) == 0:
sequence.append(0)
elif len(sequence) == 1:
sequence.append(1)
else:
sequence.append(sequence[-1] + sequence[-2])
return fibonacci... | from solution import fibonacci_sum
def test_fibonacci_empty():
sequence, fib_sum = fibonacci_sum(0)
assert sequence == []
assert fib_sum == 0
def test_fibonacci_one_term():
sequence, fib_sum = fibonacci_sum(1)
assert sequence == [0]
assert fib_sum == 0
def test_fibonacci_two_terms():
sequ... | [
{
"docstring": null,
"function_declaration": "def fibonacci(n, sequence=None):",
"function_name": "fibonacci",
"parameter_list": "(n, sequence=None)"
},
{
"docstring": null,
"function_declaration": "def fibonacci_sum(n):",
"function_name": "fibonacci_sum",
"parameter_list": "(n)"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_sequence(n, a=0, b=1, sequence=None):\n \"\"\"\n Prints the Fibonacci sequence up to n terms and returns the sum \n of the Fibonacci sequence.\n \"\"\"\n if sequen... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072698",
"row_id": 72698,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147348']"
} | 0.689456 | Filter_72698 | I | [
"fibonacci",
"fibonacci_sum"
] | 2 | [
[
"fibonacci_sum",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 22d594d3c92e832a38b2a230f00ae585e78a0a85 | 8aebc8adf5f445b4436e4be9c9a8b3f65513ff9f | |||
v1.0 | instruct | Filter | Filter_72764_I | As an AI language model, I want to understand how to implement the n-gram model in Python. Can you guide me through the process with a simple example? | import collections
import itertools
def generate_ngrams(text, n):
"""
Generates n-grams from the input text.
Parameters:
text (str): The input text.
n (int): The number of words in each n-gram.
Returns:
List[Tuple[str]]: A list of n-grams as tuples of words.
"""
words = text.split... | from solution import generate_ngrams, ngram_counts
def test_generate_ngrams_unigram():
text = "I am learning NLP"
expected = [('I',), ('am',), ('learning',), ('NLP',)]
assert generate_ngrams(text, 1) == expected
def test_generate_ngrams_bigram():
text = "I am learning NLP"
expected = [('I', 'am'),... | [
{
"docstring": "Generates n-grams from the input text.\n\nParameters:\ntext (str): The input text.\nn (int): The number of words in each n-gram.\n\nReturns:\nList[Tuple[str]]: A list of n-grams as tuples of words.",
"function_declaration": "def generate_ngrams(text, n):",
"function_name": "generate_ngra... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nfrom typing import List, Dict, Tuple\n\ndef create_n_grams(text: str, n: int) -> List[Tuple[str, ...]]:\n \"\"\"\n Generates n-grams from the given t... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072764",
"row_id": 72764,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147499']"
} | 0.476987 | Filter_72764 | I | [
"generate_ngrams",
"ngram_counts"
] | 2 | [
[
"ngram_counts",
"generate_ngrams"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 37551dc2220520fd6612b8898ccf467b757dffd2 | eaea592d45dcbe2f2538454ad094251b71fd5d70 | |||
v1.0 | instruct | Filter | Filter_72768_I | Can you explain how to run a simple simulation of a particle movement in a box using Python and the Lennard-Jones potential for inter-particle interactions? | import numpy as np
def initialize_particles(num_particles, box_length):
"""
Initialize particles with random positions and velocities.
"""
positions = np.random.rand(num_particles, 3) * box_length
velocities = np.random.randn(num_particles, 3)
return positions, velocities
def lennard_jones_for... | from solution import (
initialize_particles,
lennard_jones_force,
compute_forces,
update_positions,
update_velocities,
run_simulation
)
import numpy as np
def test_initialize_particles():
num_particles = 10
box_length = 5.0
positions, velocities = initialize_particles(num_particles,... | [
{
"docstring": "Initialize particles with random positions and velocities.",
"function_declaration": "def initialize_particles(num_particles, box_length):",
"function_name": "initialize_particles",
"parameter_list": "(num_particles, box_length)"
},
{
"docstring": "Calculate Lennard-Jones for... | [
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 initialize_particles(num_particles, box_length):\n \"\"\"\n Initialize particles with random positions and velocities.\n \"\"\"\n positions = np.random.ra... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072768",
"row_id": 72768,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147503']"
} | 0.303822 | Filter_72768 | I | [
"initialize_particles",
"lennard_jones_force",
"compute_forces",
"update_positions",
"update_velocities",
"run_simulation"
] | 6 | [
[
"compute_forces",
"lennard_jones_force"
],
[
"run_simulation",
"compute_forces"
],
[
"run_simulation",
"initialize_particles"
],
[
"run_simulation",
"update_positions"
],
[
"run_simulation",
"update_velocities"
]
] | 5 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | ec1bb69f1fd27c815cc359b90c5a357a846410c4 | 5957ca95033463171889f4576ff0bd2bf605ad94 | |||
v1.0 | instruct | Filter | Filter_72793_I | How can I handle JSON data for abstract syntax trees (ASTs) in Python? | import ast
import json
def ast_to_dict(node):
if isinstance(node, ast.AST):
fields = {k: ast_to_dict(v) for k, v in ast.iter_fields(node)}
return {'_type': node.__class__.__name__, **fields}
elif isinstance(node, list):
return [ast_to_dict(n) for n in node]
else:
return node... | import ast
from solution import ast_to_json, json_to_ast
def test_ast_to_json():
code = "a = 1"
tree = ast.parse(code)
json_data = ast_to_json(tree)
assert isinstance(json_data, str)
def test_json_to_ast():
code = "a = 1"
tree = ast.parse(code)
json_data = ast_to_json(tree)
new_tree = ... | [
{
"docstring": null,
"function_declaration": "def ast_to_dict(node):",
"function_name": "ast_to_dict",
"parameter_list": "(node)"
},
{
"docstring": null,
"function_declaration": "def dict_to_ast(d):",
"function_name": "dict_to_ast",
"parameter_list": "(d)"
},
{
"docstring... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ast\nimport json\n\ndef parse_code_to_ast(code):\n \"\"\"\n Parses Python source code into its AST representation.\n \n :param code: str, Python source code\n :return: as... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072793",
"row_id": 72793,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147560']"
} | 0.542876 | Filter_72793 | I | [
"ast_to_dict",
"dict_to_ast",
"ast_to_json",
"json_to_ast"
] | 4 | [
[
"ast_to_json",
"ast_to_dict"
],
[
"json_to_ast",
"dict_to_ast"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 201a3a94d21b0f9785a820ae62b35a2ac291627b | dc976627ace20ee7e72ab2f0565e2b573fe4699e | |||
v1.0 | instruct | Filter | Filter_72795_I | Can you assist with generating a set of steganography techniques for hiding data within digital images using Python? Certainly! Below is a simple example of how to hide text inside an image using Python. This technique is known as Least Significant Bit (LSB) steganography. | from PIL import Image
def bit_set(value, bit_index, bit_value):
"""
Sets the `bit_index`-th bit of `value` to `bit_value`.
"""
mask = 1 << bit_index
value &= ~mask
if bit_value:
value |= mask
return value
def hide_text_in_image(image_path, text, output_image_path):
"""
Hide... | from solution import hide_text_in_image, extract_text_from_image
import os
def test_hide_and_extract_text():
# Create a dummy image
input_image_path = "dummy_image.png"
output_image_path = "output_image.png"
image = Image.new("RGB", (10, 10), color = 'white')
image.save(input_image_path)
... | [
{
"docstring": "Sets the `bit_index`-th bit of `value` to `bit_value`.",
"function_declaration": "def bit_set(value, bit_index, bit_value):",
"function_name": "bit_set",
"parameter_list": "(value, bit_index, bit_value)"
},
{
"docstring": "Hides text inside an image using Least Significant Bi... | [
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\n\ndef _char_to_bits(char):\n \"\"\"\n Convert character to binary bits.\n \"\"\"\n return bin(ord(char))[2:].zfill(8)\n\ndef _bits_to_char(bits):\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072795",
"row_id": 72795,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147562']"
} | 0.315633 | Filter_72795 | I | [
"bit_set",
"hide_text_in_image",
"extract_text_from_image"
] | 3 | [
[
"hide_text_in_image",
"bit_set"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | bef9a6682f0c106856f1af493b885e246d776a06 | aa8be5d72ce503531e7b32b2ad96b6c67aaf7188 | |||
v1.0 | instruct | Filter | Filter_72828_I | Can you provide a Python function that generates a list of all prime numbers within a given range, say from 1 to 100? | def is_prime(n):
"""Helper function to determine if 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 generate_primes
def test_generate_primes_within_range():
assert generate_primes(1, 10) == [2, 3, 5, 7]
def test_generate_primes_large_range():
assert generate_primes(1, 100) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def test_gener... | [
{
"docstring": "Helper function to determine if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers within the given range from start to end (inclusive).",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072828",
"row_id": 72828,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147626']"
} | 0.659996 | Filter_72828 | I | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 927c0cee98e996dd83799fe2ecb1f85b1759880a | c8e4cf87a03fedda2a086931aac183a00ef121e1 | |||
v1.0 | instruct | Filter | Filter_72837_I | Write a Python program that takes a user's name and prints a greeting message along with the current date and time. The program should also include a function to fetch the current date and time using Python's `datetime` module. Make sure to format the date and time in a友好的 human-readable format, such as "Month Day, Yea... | from datetime import datetime
def get_current_datetime():
"""
Returns the current date and time as a formatted string.
"""
now = datetime.now()
return now.strftime("%B %d, %Y, %H:%M")
def greet_user(name):
"""
Prints a greeting message to the user along with the current date and time.
... | from solution import get_current_datetime, greet_user
import re
from datetime import datetime
def test_get_current_datetime():
current_datetime = get_current_datetime()
# Check if the format matches the expected pattern
pattern = r"^[A-Za-z]+\s\d{1,2},\s\d{4},\s\d{2}:\d{2}$"
assert re.match(pattern, cu... | [
{
"docstring": "Returns the current date and time as a formatted string.",
"function_declaration": "def get_current_datetime():",
"function_name": "get_current_datetime",
"parameter_list": "()"
},
{
"docstring": "Prints a greeting message to the user along with the current date and time.",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef get_current_datetime():\n \"\"\"\n Returns the current date and time in a human-readable format.\n \"\"\"\n now = datetime.now()\n formatted... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072837",
"row_id": 72837,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147638']"
} | 0.393526 | Filter_72837 | I | [
"get_current_datetime",
"greet_user"
] | 2 | [
[
"greet_user",
"get_current_datetime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db61e738e616b4afe6a79778b6c42a3d4dbab86f | 79ecb0240a59344790db41ed3ee2cb540ea357da | |||
v1.0 | instruct | Filter | Filter_72851_I | Could you provide a detailed explanation of how to implement a meta-learner in PyTorch for a few-shot learning task, using the Model-Agnostic Meta-Learning (MAML) algorithm? A step-by-step guide would be very helpful. | import torch
import torch.nn as nn
import torch.optim as optim
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.layer1 = nn.Linear(10, 40)
self.layer2 = nn.Linear(40, 20)
self.layer3 = nn.Linear(20, 1)
def forward(self, x):
... | import torch
from solution import SimpleModel, compute_loss, maml_update
def test_simple_model_forward():
model = SimpleModel()
x = torch.randn(32, 10)
output = model(x)
assert output.shape == (32, 1), f"Expected shape (32, 1), but got {output.shape}"
def test_compute_loss():
model = SimpleModel()... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n super(SimpleModel, self).__init__()\n self.layer1 = n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00072851",
"row_id": 72851,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147671']"
} | 0.196181 | Filter_72851 | I | [
"compute_loss",
"maml_update",
"main"
] | 3 | [
[
"maml_update",
"compute_loss"
]
] | 1 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 1c9cda03c3ae703c976ba60f024df04e1bb898ae | cde4952aba96831cbb420c01b4e71f18bea4782a | |||
v1.0 | instruct | Filter | Filter_72856_I | Design a Python function that takes two positive integers, A and B, and returns their greatest common divisor (GCD) using the method of prime factorization. The function should also output the prime factors of both A and B as part of its return value. | import math
from collections import Counter
def prime_factors(n):
"""Returns the list of prime factors of a given number n."""
factors = []
while n % 2 == 0:
factors.append(2)
n //= 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
factors.append(i)
... | from solution import gcd_prime_factors, prime_factors
def test_prime_factors():
assert prime_factors(10) == [2, 5]
assert prime_factors(15) == [3, 5]
assert prime_factors(21) == [3, 7]
def test_gcd_prime_factors():
assert gcd_prime_factors(10, 15) == (5, [2, 5], [3, 5])
assert gcd_prime_factors(21... | [
{
"docstring": "Returns the list of prime factors of a given number n.",
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": "Returns the greatest common divisor (GCD) of A and B using their prime factors,\nalong with t... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nfrom math import gcd\n\ndef prime_factors(n):\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072856",
"row_id": 72856,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147681']"
} | 0.794323 | Filter_72856 | I | [
"prime_factors",
"gcd_prime_factors"
] | 2 | [
[
"gcd_prime_factors",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 619d4631d1c865f1905b1fdf4815001aceb16d8f | ff7522ec716e7cf7a2101a13c51e737e4f4252b4 | |||
v1.0 | instruct | Filter | Filter_72920_I | Can you explain how to use the `reduce` function from the `functools` module in Python, and provide an example? | from functools import reduce
def multiply(x, y):
"""
Returns the product of x and y.
"""
return x * y
def reduce_example(numbers):
"""
Reduces the list of numbers by multiplying them together using reduce.
"""
return reduce(multiply, numbers) | from solution import multiply, reduce_example
def test_multiply():
assert multiply(2, 3) == 6
assert multiply(-1, 5) == -5
assert multiply(0, 10) == 0
def test_reduce_example():
assert reduce_example([1, 2, 3, 4, 5]) == 120
assert reduce_example([5, 10]) == 50
assert reduce_example([6]) == 6
... | [
{
"docstring": "Returns the product of x and y.",
"function_declaration": "def multiply(x, y):",
"function_name": "multiply",
"parameter_list": "(x, y)"
},
{
"docstring": "Reduces the list of numbers by multiplying them together using reduce.",
"function_declaration": "def reduce_example... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import reduce\n\ndef multiply(x, y):\n \"\"\"\n Returns the product of x and y.\n \"\"\"\n return x * y\n\ndef product_of_list(lst):\n \"\"\"\n Returns the pro... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072920",
"row_id": 72920,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147811']"
} | 0.503366 | Filter_72920 | I | [
"multiply",
"reduce_example"
] | 2 | [
[
"reduce_example",
"multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 392074008e70ba07422ec77a6988413e91dff5c4 | da20999242e2c050f169890d541edae89c15c10f | |||
v1.0 | instruct | Filter | Filter_72937_I | Write a Python function to find the smallest prime number greater than a given integer `n`. The function should return the next prime number after `n`. | def is_prime(num):
"""
Helper function to 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 next_prime(n):
"""
Returns the smallest prime number greater than the given... | from solution import next_prime
def test_next_prime_after_10():
assert next_prime(10) == 11
def test_next_prime_after_14():
assert next_prime(14) == 17
def test_next_prime_after_17():
assert next_prime(17) == 19
def test_next_prime_after_20():
assert next_prime(20) == 23
def test_next_prime_after_l... | [
{
"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 smallest prime number greater than the given integer n.",
"function_declaration": "def next... | [
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": "00072937",
"row_id": 72937,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147845']"
} | 0.669212 | Filter_72937 | I | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f64414661366cabdfe4ffc6965565252c361f967 | abc4172244aa84a9400f7eb771d9dee5a350a142 | |||
v1.0 | instruct | Filter | Filter_72943_I | In Python, how can I create a sequence that generates the first 10 prime numbers? | def is_prime(n):
"""
Returns True if n is a prime number, otherwise 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
... | from solution import is_prime, first_n_primes
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert is_prime(7)
assert not is_prime(9)
assert is_prime(11)
assert not is_prime(0)
assert not is_prime(1)
assert not is_prime(-5)
... | [
{
"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 a list of the first `n` prime numbers.",
"function_declaration": "def first_n_primes(n):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_primes(n=10):\n \"\"\"\n Generates the first n prime numbers.\n :param n: The number of prime numbers to generate.\n :return: A list of the first n prime numbers.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00072943",
"row_id": 72943,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147860']"
} | 0.557417 | Filter_72943 | I | [
"is_prime",
"first_n_primes"
] | 2 | [
[
"first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 20b61bc95bfbea90f9c7705e4f8f7098df70485e | 019db8f424f41e329df9c84c9e8d6675959f95e3 | |||
v1.0 | instruct | Filter | Filter_72970_I | Write a Python program that simulates a simple dice game. In this game, two players take turns rolling a six-sided die. The game continues until the total score for either player reaches 30 or more points. The player with the higher score wins. If both players have the same score when one reaches 30 points, the game is... | import random
def roll_die():
"""
Simulate rolling a six-sided die.
"""
return random.randint(1, 6)
def dice_game():
"""
Simulates a dice game where two players take turns rolling a six-sided die until one player's
score reaches 30 or more. The player with the higher score wins; if both ha... | from solution import dice_game
def test_dice_game():
# Since the dices are random, we can't assert to exact values, but we can
# check that the function behaves as expected in general
player1_score, player2_score, winner = dice_game()
# One player must have reached at least 30 points
asse... | [
{
"docstring": "Simulate rolling a six-sided die.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Simulates a dice game where two players take turns rolling a six-sided die until one player's\nscore reaches 30 or more. The p... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"\n Simulates rolling a six-sided die.\n Returns a random integer between 1 and 6.\n \"\"\"\n return random.randint(1, 6)\n\ndef play_gam... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072970",
"row_id": 72970,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147913']"
} | 0.56554 | Filter_72970 | I | [
"roll_die",
"dice_game"
] | 2 | [
[
"dice_game",
"roll_die"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9736e2d9299802aa107d89018a2ea5eec0bc3d0c | 0224e432643a642190c580dd1619ff98704c4556 | |||
v1.0 | instruct | Filter | Filter_72985_I | How can I implement a Sudoku solver in Python using backtracking? | def is_valid(board, row, col, num):
"""
Checks if placing num in the given row, column is valid according to Sudoku rules.
"""
# Check the row
if num in board[row]:
return False
# Check the column
if num in (board[r][col] for r in range(9)):
return False
# Check the... | from solution import solve_sudoku, is_valid
def test_is_valid():
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, ... | [
{
"docstring": "Checks if placing num in the given row, column is valid according to Sudoku rules.",
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": "Solves the Sudoku puzzle using backtr... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if placing num in the given row and column is valid according to Sudoku rules.\n \"\"\"\n # Check the row\n for i in range(9... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00072985",
"row_id": 72985,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_147943']"
} | 0.438551 | Filter_72985 | I | [
"is_valid",
"solve_sudoku"
] | 2 | [
[
"solve_sudoku",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b0b51056f5fa60799cbda8deb3848a6b90eb29f6 | 5ca6ab6c8f6361feca080f9300ef46776196bf4a | |||
v1.0 | instruct | Filter | Filter_73033_I | How can I implement a basic character-level text data processing pipeline in PyTorch? | import torch
import torch.nn as nn
import torch.optim as optim
# Character-level Text Data Processing Pipeline in PyTorch
def create_char_dict(text):
"""
Creates a dictionary that maps characters to indices.
"""
unique_chars = sorted(set(text))
char_to_index = {char: i for i, char in enumerate(uniq... | import torch
from solution import create_char_dict, text_to_tensor, tensor_to_text, process_text
def test_create_char_dict():
text = "hello"
char_to_index, index_to_char = create_char_dict(text)
assert char_to_index == {'e': 0, 'h': 1, 'l': 2, 'o': 3}
assert index_to_char == {0: 'e', 1: 'h', 2: 'l', 3:... | [
{
"docstring": "Creates a dictionary that maps characters to indices.",
"function_declaration": "def create_char_dict(text):",
"function_name": "create_char_dict",
"parameter_list": "(text)"
},
{
"docstring": "Converts text to a tensor of character indices.",
"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 torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Character-level Text Data Processing Pipeline in PyTorch\ndef create_char_dict(text):\n \"\"\"\n Creates a dictionar... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073033",
"row_id": 73033,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148050']"
} | 0.418095 | Filter_73033 | I | [
"create_char_dict",
"text_to_tensor",
"tensor_to_text",
"process_text"
] | 4 | [
[
"process_text",
"create_char_dict"
],
[
"process_text",
"tensor_to_text"
],
[
"process_text",
"text_to_tensor"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | a9d733115cb130a2e2082979e1ed447cbb5bcfa4 | fd0c17c77748f91224c6f2ce9d0ff2f1775cf8f9 | |||
v1.0 | instruct | Filter | Filter_73055_I | Can you explain how to create a simple AWS Lambda function that processes a JSON payload and logs the output to CloudWatch? | import json
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def lambda_handler(event, context):
"""
AWS Lambda function that processes a JSON payload and logs the output to CloudWatch.
"""
# Log the incoming event
logger.info("Received event: %s", json.dumps(eve... | from solution import lambda_handler, process_event
def test_lambda_handler_success():
event = {'key1': 'value1', 'key2': 'value2'}
context = None # For simplicity, we don't provide a context object in this test
response = lambda_handler(event, context)
assert response['statusCode'] == 200
... | [
{
"docstring": "AWS Lambda function that processes a JSON payload and logs the output to CloudWatch.",
"function_declaration": "def lambda_handler(event, context):",
"function_name": "lambda_handler",
"parameter_list": "(event, context)"
},
{
"docstring": "Dummy processing function that just... | [
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 logging\n\n# Configure logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef lambda_handler(event, context):\n \"\"\"\n AWS Lambda function to p... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073055",
"row_id": 73055,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148105']"
} | 0.453192 | Filter_73055 | I | [
"lambda_handler",
"process_event"
] | 2 | [
[
"lambda_handler",
"process_event"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6934b7be623aabdccad5fc4f2abf57bc35e19e12 | 061201bf6e3101df1f2cf1277e2162baa28e71aa | |||
v1.0 | instruct | Filter | Filter_73076_I | How can we apply the `filter` function in Python to extract elements from a list that meet a certain condition? For example, how can we filter out all even numbers from a list? | def is_even(number):
"""
Returns True if the number is even, False otherwise.
"""
return number % 2 == 0
def filter_even_numbers(numbers):
"""
Filters out all even numbers from the given list.
Returns a list of even numbers.
"""
return list(filter(is_even, numbers)) | from solution import is_even, filter_even_numbers
def test_is_even():
assert is_even(2) == True
assert is_even(3) == False
assert is_even(0) == True
assert is_even(-4) == True
assert is_even(-3) == False
def test_filter_even_numbers():
assert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6... | [
{
"docstring": "Returns True if the number is even, False otherwise.",
"function_declaration": "def is_even(number):",
"function_name": "is_even",
"parameter_list": "(number)"
},
{
"docstring": "Filters out all even numbers from the given list.\nReturns a list of even numbers.",
"functio... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def filter_even_numbers(numbers):\n \"\"\"\n Returns a list of all even numbers from the input list.\n \n :param numbers: List of integers.\n :return: List of even integers.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073076",
"row_id": 73076,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148133']"
} | 0.6767 | Filter_73076 | I | [
"is_even",
"filter_even_numbers"
] | 2 | [
[
"filter_even_numbers",
"is_even"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31c4301ac565f516337a7b3b5dd271e00072fd3d | dea95da47ceca9b66cf30dfbfe6aec11f46b1648 | |||
v1.0 | instruct | Filter | Filter_73116_I | Can you provide a detailed explanation of how to implement the Genetic Algorithm (GA) from scratch in Python? Implementing GA from scratch means not using any pre-built GA libraries. | import random
def initialize_population(pop_size, gene_length):
"""
Initializes a population with given population size and gene length.
Each individual in the population is represented by a binary string.
"""
population = []
for _ in range(pop_size):
individual = ''.join(random.choice(... | from solution import initialize_population, fitness_function, select_parents, crossover, mutate, genetic_algorithm
def test_initialize_population():
population = initialize_population(5, 10)
assert len(population) == 5
assert all(len(ind) == 10 for ind in population)
def test_fitness_function():
asser... | [
{
"docstring": "Initializes a population with given population size and gene length.\nEach individual in the population is represented by a binary string.",
"function_declaration": "def initialize_population(pop_size, gene_length):",
"function_name": "initialize_population",
"parameter_list": "(pop_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef initialize_population(pop_size, gene_length):\n \"\"\"\n Initializes a population with given population size and gene length.\n Each individual in the population ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073116",
"row_id": 73116,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148213']"
} | 0.332987 | Filter_73116 | I | [
"initialize_population",
"fitness_function",
"select_parents",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness_function"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select_parents"
],
[
"select_parents",
"fitness_function... | 6 | [] | false | [] | false | pytest | true | [] | true | fe6dd7e10e63741c0744bab1eb4e995e095ec854 | 49c91832ece998ebf4db6b74cf6251b7a0cacfdf | |||
v1.0 | instruct | Filter | Filter_73131_I | Write a Python function `simple_interest_calculator` that calculates the simple interest given the principal amount, the rate of interest per annum, and the time period in years. Use the formula: Simple Interest = (Principal * Rate * Time) / 100. Include a docstring that explains the function and its parameters. Then, ... | def simple_interest_calculator(principal, rate, time):
"""
Calculates the simple interest.
Parameters:
principal (float): The principal amount.
rate (float): The rate of interest per annum.
time (float): The time period in years.
Returns:
float: The simple interest.
"""
return ... | from solution import simple_interest_calculator, check_interest
def test_simple_interest_calculator_basic():
assert simple_interest_calculator(1000, 5, 2) == 100.0
def test_simple_interest_calculator_zero_principal():
assert simple_interest_calculator(0, 5, 2) == 0.0
def test_simple_interest_calculator_zero_... | [
{
"docstring": "Calculates the simple interest.\n\nParameters:\nprincipal (float): The principal amount.\nrate (float): The rate of interest per annum.\ntime (float): The time period in years.\n\nReturns:\nfloat: The simple interest.",
"function_declaration": "def simple_interest_calculator(principal, rate,... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def simple_interest_calculator(principal, rate, time):\n \"\"\"\n Calculates the simple interest.\n \n Parameters:\n principal (float): The principal amount.\n rate (float): ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073131",
"row_id": 73131,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148235']"
} | 0.376049 | Filter_73131 | I | [
"simple_interest_calculator",
"check_interest"
] | 2 | [
[
"check_interest",
"simple_interest_calculator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 521905ce63aacb5a5cf7ba340c7183a107a9ed50 | 4f5d76ca8f9a29a7e7977869f16d2d9f0c3d9c16 | |||
v1.0 | instruct | Filter | Filter_73165_I | What are the steps to implement disease spread simulations using Python, and what libraries should I consider using? | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def SIR_model(y, t, beta, gamma):
"""
Function to compute the derivatives for the SIR model.
"""
S, I, R = y
dS_dt = -beta * S * I
dI_dt = beta * S * I - gamma * I
dR_dt = gamma * I
return dS_dt, dI_dt... | import numpy as np
from solution import SIR_model, simulate_disease_spread
def test_SIR_model():
beta = 0.3
gamma = 0.1
S0 = 0.99
I0 = 0.01
R0 = 0
t = np.linspace(0, 160, 160)
y0 = [S0, I0, R0]
# Check if the model returns appropriate shape
dy_dt = SIR_model(y0, t, beta, gamma)... | [
{
"docstring": "Function to compute the derivatives for the SIR model.",
"function_declaration": "def SIR_model(y, t, beta, gamma):",
"function_name": "SIR_model",
"parameter_list": "(y, t, beta, gamma)"
},
{
"docstring": "Simulate disease spread using SIR model and return results.",
"fu... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def simulate_disease_spread(initial_population, infection_rate, days):\n \"\"\"\n Simulates the spread of a disease over a number of days.\n \n Parameters:\n initial_population ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073165",
"row_id": 73165,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148301']"
} | 0.345649 | Filter_73165 | I | [
"SIR_model",
"simulate_disease_spread"
] | 2 | [
[
"simulate_disease_spread",
"SIR_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 2b36294d17cc768ee74d5011e34e40d70e56c6e2 | 0b0d1c9db7637d5b44eebaedb0ffea6f82276de7 | |||
v1.0 | instruct | Filter | Filter_73167_I | Can you walk me through the process of creating a neural network model using PyTorch, starting from data preparation to model evaluation? | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
def create_dataset(n_samples=1000, n_features=20, ... | def test_create_dataset():
X, y = create_dataset(n_samples=100, n_features=10, n_classes=2)
assert X.shape == (100, 10)
assert y.shape == (100,)
assert len(set(y)) == 2
def test_prepare_data():
X, y = create_dataset(n_samples=100, n_features=10, n_classes=2)
train_loader, val_loader = prepare_d... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, Dataset, random_split\nfrom torchvision import datasets, transforms\n\n# Define a sim... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073167",
"row_id": 73167,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148303']"
} | 0.365228 | Filter_73167 | I | [
"create_dataset",
"prepare_data",
"train_model",
"evaluate_model",
"run_pipeline"
] | 5 | [
[
"run_pipeline",
"create_dataset"
],
[
"run_pipeline",
"evaluate_model"
],
[
"run_pipeline",
"prepare_data"
],
[
"run_pipeline",
"train_model"
]
] | 4 | [] | false | [
"SimpleNN"
] | true | pytest | false | [
"sklearn",
"torch"
] | false | 00a188785494262c207ba3a69b67778fca6c64d2 | 9155906d36a3e49869354cc4a94826996c29a197 | |||
v1.0 | instruct | Filter | Filter_73184_I | Can you explain how to implement a quantum encryption algorithm like the Quantum Key Distribution (QKD) protocol, specifically BB84, in Python? Implementing a full-scale quantum computer is not feasible at this time, but how can I simulate the BB84 protocol? | import numpy as np
import random
def prepare_state(bit, basis):
"""
Prepare the quantum state for the given bit and basis.
Bases: 'rectilinear' -> 0, 'diagonal' -> 1
"""
if basis == 0: # Rectilinear basis
return np.array([1, 0]) if bit == 0 else np.array([0, 1])
if basis == 1: # Diago... | from solution import prepare_state, measure_state, bb84_protocol
import numpy as np
def test_prepare_state():
np.testing.assert_array_equal(prepare_state(0, 0), np.array([1, 0]))
np.testing.assert_array_equal(prepare_state(1, 0), np.array([0, 1]))
np.testing.assert_array_almost_equal(prepare_state(0, 1), (... | [
{
"docstring": "Prepare the quantum state for the given bit and basis.\nBases: 'rectilinear' -> 0, 'diagonal' -> 1",
"function_declaration": "def prepare_state(bit, basis):",
"function_name": "prepare_state",
"parameter_list": "(bit, basis)"
},
{
"docstring": "Measure the state in the given ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport random\n\ndef prepare_state(bit, basis):\n \"\"\"\n Prepare the quantum state for the given bit and basis.\n Bases: 'rectilinear' -> 0, 'diagonal' -> 1\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073184",
"row_id": 73184,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148338']"
} | 0.372822 | Filter_73184 | I | [
"prepare_state",
"measure_state",
"bb84_protocol"
] | 3 | [
[
"bb84_protocol",
"measure_state"
],
[
"bb84_protocol",
"prepare_state"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | e564aa5c54ddf6c238be1e4f0db1f6482553f7ad | f1a83f852d1acb3261fc0b26951c7c5eacfe42c7 | |||
v1.0 | instruct | Filter | Filter_73187_I | Write a Python program to find all prime pairs within a given range [L, R] where the difference between the two primes in a pair is 2. These pairs are also known as twin primes. | def is_prime(n):
"""
Checks if a number n is a prime number.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import find_twin_primes
def test_find_twin_primes_basic_cases():
assert find_twin_primes(1, 10) == [(3, 5), (5, 7)]
assert find_twin_primes(10, 20) == [(11, 13), (17, 19)]
assert find_twin_primes(20, 30) == []
def test_find_twin_primes_edge_cases():
assert find_twin_primes(3, 5) == [(3, ... | [
{
"docstring": "Checks if a number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds and returns all twin prime pairs within the range [L, R].\nA twin prime pair is a pair of primes (p1, p2) such t... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a 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": "00073187",
"row_id": 73187,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148345']"
} | 0.664652 | Filter_73187 | I | [
"is_prime",
"find_twin_primes"
] | 2 | [
[
"find_twin_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 17f293d26ccf9adb605530e9e17abfd1c5c748ff | de490b626792a17ca3123b5f145eba89f9116528 | |||
v1.0 | instruct | Filter | Filter_73199_I | Can you help me with a Python script that handles a file containing a list of email addresses? The script should read the file, check if the email addresses are valid, and then write the valid ones to a new file. How can I achieve this? | import re
def is_valid_email(email):
"""
Validates the given email address using a regular expression.
A valid email must have the following format: localpart@domain.
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def process_email... | import os
from solution import is_valid_email, process_emails
def test_is_valid_email():
assert is_valid_email("test@example.com")
assert not is_valid_email("invalid-email")
assert not is_valid_email("test@.com")
assert not is_valid_email("test@com.")
assert is_valid_email("user.name+tag+sorting@ex... | [
{
"docstring": "Validates the given email address using a regular expression.\nA valid email must have the following format: localpart@domain.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "Reads email... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_email(email):\n \"\"\"\n Returns True if the email is valid, False otherwise.\n \"\"\"\n regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073199",
"row_id": 73199,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148367']"
} | 0.510829 | Filter_73199 | I | [
"is_valid_email",
"process_emails"
] | 2 | [
[
"process_emails",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae6e8d5be6fdc7b3121d37d689fc52c14a6fb3dc | aedc535ffeb2f9285c3f618c7a4722e7fd5fcacb | |||
v1.0 | instruct | Filter | Filter_73229_I | Write a Python function to find the largest palindrome in a given string. A palindrome is a sequence of characters that reads the same forward and backward. If the string contains no palindromes, return an empty string. The function should be efficient and handle edge cases. | def is_palindrome(s):
"""
Checks if the given string s is a palindrome.
"""
return s == s[::-1]
def largest_palindrome(s):
"""
Finds the largest palindrome in the given string s.
If no palindrome is found, returns an empty string.
"""
max_palindrome = ""
n = len(s)
for ... | from solution import largest_palindrome
def test_largest_palindrome_single_character():
assert largest_palindrome("a") == "a"
def test_largest_palindrome_two_characters():
assert largest_palindrome("aa") == "aa"
assert largest_palindrome("ab") == "a"
def test_largest_palindrome_no_palindrome():
asser... | [
{
"docstring": "Checks if the given string s is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Finds the largest palindrome in the given string s.\nIf no palindrome is found, returns an empty strin... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def largest_palindrome(s):\n \"\"\"\n Returns the largest palindrome in the given string.\n If the string contains no palindromes, return an empty string.\n \"\"\"\n if not s:\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073229",
"row_id": 73229,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148431']"
} | 0.749978 | Filter_73229 | I | [
"is_palindrome",
"largest_palindrome"
] | 2 | [
[
"largest_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 010855661120ea5d89c39e7ffa953c7bb73d8078 | e06031da53f429b04a6ccf30ea7b2982a204c49a | |||
v1.0 | instruct | Filter | Filter_73232_I | I want to create a Python script that simulates a simple text-based game. The game should include a main menu with options to start a new game, load a game, or quit. If the player chooses to start a new game, they should be asked to enter their name and then presented with a series of text-based challenges or puzzles. ... | import os
import json
def main_menu():
"""
Display the main menu and return the player's choice.
"""
print("Welcome to the Text-Based Game")
print("1. Start a New Game")
print("2. Load Game")
print("3. Quit")
choice = input("Enter your choice: ")
return choice
def start_new_game():... | import pytest
import os
import json
from solution import start_new_game, load_game, save_game, quit_game, challenge_1, challenge_2
def test_start_new_game(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: 'TestPlayer')
player_name, current_challenge = start_new_game()
assert player_name == 'Te... | [
{
"docstring": "Display the main menu and return the player's choice.",
"function_declaration": "def main_menu():",
"function_name": "main_menu",
"parameter_list": "()"
},
{
"docstring": "Start a new game by asking the player for their name.",
"function_declaration": "def start_new_game(... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport os\n\ndef main_menu():\n \"\"\"\n Main menu for the game.\n \"\"\"\n print(\"1. Start a New Game\")\n print(\"2. Load Game\")\n print(\"3. Quit\")\n ch... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073232",
"row_id": 73232,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148438']"
} | 0.414419 | Filter_73232 | I | [
"main_menu",
"start_new_game",
"load_game",
"save_game",
"quit_game",
"challenge_1",
"challenge_2",
"play_game",
"main"
] | 9 | [
[
"quit_game",
"save_game"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8760db5de3cac95bc4f4460ba3ab7e466e510a36 | 8c5e6469a1bf20dcef9732a44269a32ca5eed8b1 | |||
v1.0 | instruct | Filter | Filter_73236_I | How can I create a Python script to monitor the memory usage of a system and send an alert if it exceeds a certain threshold? | import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def check_memory(threshold):
"""
Check system memory usage and return True if it exceeds the threshold.
Args:
threshold (int): The memory usage percentage threshold.
Return... | from solution import check_memory, send_alert_email, monitor_memory
def test_check_memory_high_usage(monkeypatch):
class MockVirtualMemory:
percent = 85
monkeypatch.setattr('psutil.virtual_memory', MockVirtualMemory)
assert check_memory(80) == True
def test_check_memory_low_usage(monkeypatch):
... | [
{
"docstring": "Check system memory usage and return True if it exceeds the threshold.\n\nArgs:\n threshold (int): The memory usage percentage threshold.\n\nReturns:\n bool: True if memory usage exceeds threshold, False otherwise.",
"function_declaration": "def check_memory(threshold):",
"function... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef send_email_alert(subject, body, to_email):\n \"\"\"\n Send an email alert with the given subject and body to th... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073236",
"row_id": 73236,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148450']"
} | 0.631252 | Filter_73236 | I | [
"check_memory",
"send_alert_email",
"monitor_memory"
] | 3 | [
[
"monitor_memory",
"check_memory"
],
[
"monitor_memory",
"send_alert_email"
]
] | 2 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | c667725e84f8a6aa1dc77a47e36f5d5780c2cf4a | e1b5c4995f634df40da9eec929e199babda83f96 | |||
v1.0 | instruct | Filter | Filter_73243_I | Can you provide a Python code to simulate a simple dice roll game where a user can roll a six-sided dice and guess the outcome? The user should be able to play as many rounds as they want, and the program should keep track of the number of correct guesses. | import random
def roll_dice():
return random.randint(1, 6)
def play_round():
print("Rolling the dice...")
result = roll_dice()
guess = int(input("Guess the outcome (1-6): "))
return guess == result, result
def play_game():
correct_guesses = 0
rounds_played = 0
play_again = 'y'
wh... | from solution import roll_dice, play_round
def test_roll_dice():
for _ in range(100):
result = roll_dice()
assert 1 <= result <= 6
def test_play_round(monkeypatch):
inputs = ['3']
input_generator = (i for i in inputs)
monkeypatch.setattr('builtins.input', lambda _: next(input_generator... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def play_round():",
"function_name": "play_round",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
1,
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 return random.randint(1, 6)\n\ndef play_round():\n print(\"Rolling the dice...\")\n result = roll_dice()\n guess = int(input(\"Guess the outcome... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073243",
"row_id": 73243,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148471']"
} | 0.527161 | Filter_73243 | I | [
"roll_dice",
"play_round",
"play_game"
] | 3 | [
[
"play_game",
"play_round"
],
[
"play_round",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 55b0dcaba560f4d5f7ae1b9c111c836909da00a3 | 478a65469f01f17ba60085512b53f78e67972c29 | |||
v1.0 | instruct | Filter | Filter_73248_I | Can you create a Python script that generates a CSV file with random data, including names, ages, and cities? The age should be between 18 and 60, and the city should be selected from a predefined list of cities. The script should also allow the user to specify the number of records to generate. | import csv
import random
import string
def generate_random_name():
"""
Generates a random name with a capitalized first letter and remaining lowercase.
"""
first_letter = random.choice(string.ascii_uppercase)
name_length = random.randint(4, 8)
remaining_letters = ''.join(random.choices(string.a... | from solution import generate_random_name, generate_random_age, generate_random_city, generate_csv
import os
import csv
def test_generate_random_name():
name = generate_random_name()
assert name[0].isupper()
assert name[1:].islower()
assert 4 <= len(name) <= 8
def test_generate_random_age():
age =... | [
{
"docstring": "Generates a random name with a capitalized first letter and remaining lowercase.",
"function_declaration": "def generate_random_name():",
"function_name": "generate_random_name",
"parameter_list": "()"
},
{
"docstring": "Generates a random age between 18 and 60.",
"functi... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport random\nfrom faker import Faker\n\ndef generate_random_data(num_records, output_file=\"random_data.csv\"):\n \"\"\"\n Generate a CSV file with random data including na... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073248",
"row_id": 73248,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148479']"
} | 0.689275 | Filter_73248 | I | [
"generate_random_name",
"generate_random_age",
"generate_random_city",
"generate_csv"
] | 4 | [
[
"generate_csv",
"generate_random_age"
],
[
"generate_csv",
"generate_random_city"
],
[
"generate_csv",
"generate_random_name"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c4c9c4a108422f6d1cc03fcf4877dca23bde2f5e | dd473841e29296ee7ab88b178c6fb4f956f65908 | |||
v1.0 | instruct | Filter | Filter_73294_I | How can I create a Python program that checks if a given username exists in an existing username list and ensures it meets certain criteria before adding it to the list? | def is_username_valid(username, min_length=5, max_length=20):
"""
Check if the given username meets the criteria:
- It should be within the length limits.
- It should only contain alphanumeric characters and underscores.
"""
if not (min_length <= len(username) <= max_length):
return Fals... | from solution import is_username_valid, is_username_existing, add_username
def test_is_username_valid():
assert is_username_valid("user1")
assert is_username_valid("user_name")
assert not is_username_valid("u")
assert not is_username_valid("thisisaverylongusernamethatisinvalid")
assert not is_usern... | [
{
"docstring": "Check if the given username meets the criteria:\n- It should be within the length limits.\n- It should only contain alphanumeric characters and underscores.",
"function_declaration": "def is_username_valid(username, min_length=5, max_length=20):",
"function_name": "is_username_valid",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_username(existing_usernames, new_username):\n \"\"\"\n Check if the new username exists in the existing_usernames list and\n ensure it meets certain criteria before adding it ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073294",
"row_id": 73294,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148567']"
} | 0.533636 | Filter_73294 | I | [
"is_username_valid",
"is_username_existing",
"add_username"
] | 3 | [
[
"add_username",
"is_username_existing"
],
[
"add_username",
"is_username_valid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6683c3edde84f390b3c2ff8e153cebbae27f615f | 429da8af4c614ff2fc051c2f75bd2ca4e9dc7e56 | |||
v1.0 | instruct | Filter | Filter_73318_I | Please write a Python script to generate a list of random passwords for a specified number of users. Each password should be a mix of uppercase letters, lowercase letters, digits, and special characters. The length of each password should also be customizable. Additionally, the script should allow the user to specify t... | import random
import string
def generate_password(length):
"""
Generate a random password of the specified length.
The password contains a mix of uppercase letters,
lowercase letters, digits, and special characters.
"""
all_chars = string.ascii_letters + string.digits + string.punctuation
... | from solution import generate_password, generate_passwords
def test_generate_password_length():
password = generate_password(10)
assert len(password) == 10
def test_generate_password_contains_characters():
password = generate_password(10)
has_upper = any(c.isupper() for c in password)
has_lower = ... | [
{
"docstring": "Generate a random password of the specified length.\nThe password contains a mix of uppercase letters, \nlowercase letters, digits, and special characters.",
"function_declaration": "def generate_password(length):",
"function_name": "generate_password",
"parameter_list": "(length)"
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_password(length):\n \"\"\"\n Generates a random password of specified length which includes \n uppercase letters, lowercase letters, digit... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073318",
"row_id": 73318,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148633']"
} | 0.729609 | Filter_73318 | I | [
"generate_password",
"generate_passwords"
] | 2 | [
[
"generate_passwords",
"generate_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b6ca5b9f7ecbb3e53d0402d86a2fb5fb44638e20 | d274d29239dbd0c55b99e886513621c42464a9a8 | |||
v1.0 | instruct | Filter | Filter_73400_I | Given a string `s` and a list of strings `d`, find the longest string in `d` that is a subsequence of `s`. If there are multiple longest subsequences, choose the lexicographically smallest one. If there is no common subsequence, return an empty string. How can this problem be solved efficiently? | def is_subsequence(x, y):
"""
Check if string x is a subsequence of string y.
"""
it = iter(y)
return all(c in it for c in x)
def find_longest_subsequence(s, d):
"""
Find the longest string in d that is a subsequence of s.
If there are multiple longest subsequences, return the lexicogra... | from solution import find_longest_subsequence
def test_single_word_subsequence():
assert find_longest_subsequence("abpcplea", ["ale", "apple", "monkey", "plea"]) == "apple"
def test_multiple_possible_subsequences():
assert find_longest_subsequence("abpcplea", ["a", "b", "c", "d"]) == "a"
def test_lexicog... | [
{
"docstring": "Check if string x is a subsequence of string y.",
"function_declaration": "def is_subsequence(x, y):",
"function_name": "is_subsequence",
"parameter_list": "(x, y)"
},
{
"docstring": "Find the longest string in d that is a subsequence of s.\nIf there are multiple longest subs... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_subsequence(x, y):\n it = iter(y)\n return all(c in it for c in x)\n\ndef find_longest_subsequence(s, d):\n longest_subsequence = \"\"\n for word in sorted(d):\n if i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073400",
"row_id": 73400,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148834']"
} | 0.668344 | Filter_73400 | I | [
"is_subsequence",
"find_longest_subsequence"
] | 2 | [
[
"find_longest_subsequence",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fed8eac160d35ae845e1a14ad2d4ec089a1188f5 | 1eaf1b840e1e9148f3a8ab52ecaac25d8bcaab90 | |||
v1.0 | instruct | Filter | Filter_73411_I | Write a Python program to read and write files in binary mode. This program should include features to read a binary file, modify its content, and then write the modified content back to a new binary file. For demonstration, let's assume the binary file contains a sequence of integers. The program should increase each ... | def read_binary_file(file_path):
"""
Reads the content of a binary file and returns a list of integers.
"""
with open(file_path, 'rb') as file:
content = file.read()
# Convert bytes to list of integers
return list(content)
def write_binary_file(file_path, data):
"""
Writes a lis... | import os
import pytest
from solution import read_binary_file, write_binary_file, modify_binary_file
def test_read_binary_file(tmp_path):
file_path = os.path.join(tmp_path, "test.bin")
with open(file_path, 'wb') as file:
file.write(bytearray([1, 2, 3, 4]))
result = read_binary_file(file_path)
... | [
{
"docstring": "Reads the content of a binary file and returns a list of integers.",
"function_declaration": "def read_binary_file(file_path):",
"function_name": "read_binary_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes a list of integers to a binary file.",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import struct\n\ndef read_binary_file(file_path):\n \"\"\"\n Reads a binary file containing integers and returns them as a list of integers.\n \"\"\"\n with open(file_path, 'rb') a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073411",
"row_id": 73411,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148849']"
} | 0.589448 | Filter_73411 | I | [
"read_binary_file",
"write_binary_file",
"modify_binary_file"
] | 3 | [
[
"modify_binary_file",
"read_binary_file"
],
[
"modify_binary_file",
"write_binary_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e61025afa54be1b828201f0b239a8c199a7d8c48 | 8c83d1a727500709606335d276c4e35beb11f839 | |||
v1.0 | instruct | Filter | Filter_73413_I | Can you provide a Python script to read a CSV file and check if a specific column contains only numeric values? How can I handle cases where the values are stored as strings but are still numeric? | import csv
def is_column_numeric(file_path, column_name):
"""
Reads a CSV file and checks if a specific column contains only numeric values.
Args:
file_path (str): The path to the CSV file.
column_name (str): The name of the column to check.
Returns:
bool: True if the column c... | from solution import is_column_numeric, is_numeric
import csv
import tempfile
def test_is_column_numeric_all_numeric():
with tempfile.NamedTemporaryFile(mode='w+', newline='', delete=False) as temp_file:
writer = csv.writer(temp_file)
writer.writerow(["id", "value"])
writer.writerow(["1", "... | [
{
"docstring": "Reads a CSV file and checks if a specific column contains only numeric values.\n\nArgs:\n file_path (str): The path to the CSV file.\n column_name (str): The name of the column to check.\n\nReturns:\n bool: True if the column contains only numeric values, False otherwise.",
"functio... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef is_numeric_column(file_path, column_name):\n \"\"\"\n Checks if the specified column in the given CSV file contains only numeric values.\n \n Parameters:... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073413",
"row_id": 73413,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148852']"
} | 0.534782 | Filter_73413 | I | [
"is_column_numeric",
"is_numeric"
] | 2 | [
[
"is_column_numeric",
"is_numeric"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c5e0d7d6e98b4bc399f4867a3a6a510851997299 | 9c8902a1edca96015872a8336e09d49f97b6af97 | |||
v1.0 | instruct | Filter | Filter_73429_I | Can you provide a detailed explanation of how to implement a client-server architecture for a simple chat application using Python's socket library? This should include setting up the server and client, handling multiple clients, and basic message passing. | import socket
import threading
# Server Code
def handle_client(client_socket):
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
if message:
print(f"Received: {message}")
broadcast(message, client_socket)
else:
... | from threading import Thread
from solution import server_program, client_program
def test_chat_server_client_interaction():
server_thread = Thread(target=server_program)
server_thread.daemon = True
server_thread.start()
client_thread_1 = Thread(target=client_program)
client_thread_1.daemon = True
... | [
{
"docstring": null,
"function_declaration": "def handle_client(client_socket):",
"function_name": "handle_client",
"parameter_list": "(client_socket)"
},
{
"docstring": null,
"function_declaration": "def broadcast(message, client_socket):",
"function_name": "broadcast",
"paramet... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport threading\n\n# Server Code\ndef handle_client(client_socket):\n while True:\n try:\n message = client_socket.recv(1024).decode('utf-8')\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073429",
"row_id": 73429,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148897']"
} | 0.575477 | Filter_73429 | I | [
"handle_client",
"broadcast",
"remove",
"server_program",
"client_program",
"receive_message"
] | 6 | [
[
"broadcast",
"remove"
],
[
"handle_client",
"broadcast"
],
[
"handle_client",
"remove"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d0375d72bdfc3703527a7442c1e14724b40fb87a | 2b0e690b4b4e222586281cc9f6e574798dec774c | |||
v1.0 | instruct | Filter | Filter_73451_I | Please provide a Python code snippet to find the nearest palindrome to a given number. A nearest palindrome is a number that is closest to the given number and is also a palindrome. If two numbers are equally close, the smaller number should be chosen. | def is_palindrome(num):
return str(num) == str(num)[::-1]
def nearest_palindrome(num):
if num < 0:
return None # Negative numbers are not considered for palindromes
# Initially check the closest number itself
if is_palindrome(num):
return num
lower = num - 1
upper... | from solution import nearest_palindrome
def test_nearest_palindrome_with_same_number():
assert nearest_palindrome(121) == 121
def test_nearest_palindrome_less_than_ten():
assert nearest_palindrome(7) == 7
assert nearest_palindrome(3) == 3
def test_nearest_palindrome_standard_case():
assert nearest_pa... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def nearest_palindrome(num):",
"function_name": "nearest_palindrome",
"parameter_list": "(num)"
}... | [
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(n):\n \"\"\"\n Check if the number is a palindrome.\n \"\"\"\n return str(n) == str(n)[::-1]\n\ndef nearest_palindrome(n):\n \"\"\"\n Find the nearest palin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073451",
"row_id": 73451,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_148947']"
} | 0.727368 | Filter_73451 | I | [
"is_palindrome",
"nearest_palindrome"
] | 2 | [
[
"nearest_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c893ca5c6e476bb837d3b17675ec5e91cab3fbdc | 8a10f911b78e44b70b89ed6a58c4e84a6d8e4c7a | |||
v1.0 | instruct | Filter | Filter_73499_I | I want to create a Python program that generates and plays audio based on a musical scale. For example, C major scale. Do you have any suggestions on how to achieve this? | from pydub import AudioSegment
from pydub.playback import play
import numpy as np
def generate_tone(frequency, duration_ms, volume=0.5, sample_rate=44100):
"""
Generates a tone at a given frequency (Hz) for a given duration (ms).
"""
t = np.linspace(0, duration_ms / 1000, int(sample_rate * duration_ms ... | import numpy as np
from pydub import AudioSegment
from solution import generate_tone, generate_scale
def test_generate_tone_length():
tone = generate_tone(440, 1000) # Generate A4 note (440 Hz) for 1 second
assert len(tone) == 1000 # The tone should be 1000 ms long
def test_generate_tone_frequency():
to... | [
{
"docstring": "Generates a tone at a given frequency (Hz) for a given duration (ms).",
"function_declaration": "def generate_tone(frequency, duration_ms, volume=0.5, sample_rate=44100):",
"function_name": "generate_tone",
"parameter_list": "(frequency, duration_ms, volume=0.5, sample_rate=44100)"
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport sounddevice as sd\n\n# Define constants for the audio sampling\nSAMPLE_RATE = 44100\n\n# Define the frequencies for the C major scale\nC_MAJOR_SCALE_FREQS = [261.63,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073499",
"row_id": 73499,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149049']"
} | 0.512477 | Filter_73499 | I | [
"generate_tone",
"generate_scale",
"play_scale"
] | 3 | [
[
"generate_scale",
"generate_tone"
],
[
"play_scale",
"generate_scale"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pydub"
] | false | 74a96a58516638e768fd8f20aecbb56fb0361752 | d4bfe8eb5b03f73fcac5aa072fb9c3c477b81a47 | |||
v1.0 | instruct | Filter | Filter_73500_I | Write a Python program that takes a negative integer as input from the user, converts it to its absolute value, and then checks if the converted number is a palindrome. A palindrome number is a number that reads the same backward as forward. | def is_palindrome(number):
"""
Returns True if the given number is a palindrome; False otherwise.
"""
str_num = str(number)
return str_num == str_num[::-1]
def convert_and_check_palindrome(negative_number):
"""
Converts a negative integer to its absolute value and checks if it is a palindro... | from solution import convert_and_check_palindrome, is_palindrome
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(12321) == True
assert is_palindrome(123) == False
assert is_palindrome(10) == False
assert is_palindrome(0) == True
def test_convert_and_check_palindrom... | [
{
"docstring": "Returns True if the given number is a palindrome; False otherwise.",
"function_declaration": "def is_palindrome(number):",
"function_name": "is_palindrome",
"parameter_list": "(number)"
},
{
"docstring": "Converts a negative integer to its absolute value and checks if it is a... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(n):\n \"\"\"\n Checks if a number n is a palindrome.\n \"\"\"\n return str(n) == str(n)[::-1]\n\ndef check_negative_palindrome(number):\n \"\"\"\n Converts ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073500",
"row_id": 73500,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149050']"
} | 0.660572 | Filter_73500 | I | [
"is_palindrome",
"convert_and_check_palindrome"
] | 2 | [
[
"convert_and_check_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae5321897c248604b1579e867410496c6a742c88 | d7bd5b75f2a125493f29277f55813b6afb1c981f | |||
v1.0 | instruct | Filter | Filter_73553_I | How can I create a function in Python that prints the current date and time, and another function that runs every minute using threading? | import threading
import time
from datetime import datetime
def print_current_date_time():
"""
Prints the current date and time.
"""
now = datetime.now()
print("Current date and time:", now)
def run_every_minute():
"""
Runs the print_current_date_time function every minute.
"""
def ... | import threading
import time
from datetime import datetime, timedelta
def test_print_current_date_time(capfd):
# Capture the printed output
print_current_date_time()
out, err = capfd.readouterr()
now = datetime.now()
assert now.strftime("Current date and time: %Y-%m-%d %H:%M") in out
def test_run_... | [
{
"docstring": "Prints the current date and time.",
"function_declaration": "def print_current_date_time():",
"function_name": "print_current_date_time",
"parameter_list": "()"
},
{
"docstring": "Runs the print_current_date_time function every minute.",
"function_declaration": "def run_e... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import threading\nimport time\nfrom datetime import datetime\n\ndef print_current_date_time():\n \"\"\"\n Prints the current date and time.\n \"\"\"\n now = datetime.now()\n pri... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073553",
"row_id": 73553,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149162']"
} | 0.519363 | Filter_73553 | I | [
"print_current_date_time",
"run_every_minute"
] | 2 | [
[
"run_every_minute",
"print_current_date_time"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | fe17fac2d187e9f52bda2f3e2a4269f0557394c8 | 2589f40cc123a544c9722e8bb54c6ff0711fb29c | |||
v1.0 | instruct | Filter | Filter_73584_I | How can I create a custom data generator for a blockchain simulation in Python? | import random
import string
import time
from hashlib import sha256
def generate_transaction():
"""
Generates a mock transaction with random data.
"""
sender = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
receiver = ''.join(random.choices(string.ascii_uppercase + string.digi... | import time
from solution import generate_transaction, generate_block
def test_generate_transaction():
transaction = generate_transaction()
assert isinstance(transaction, dict)
assert 'sender' in transaction
assert 'receiver' in transaction
assert 'amount' in transaction
assert 'timestamp' in t... | [
{
"docstring": "Generates a mock transaction with random data.",
"function_declaration": "def generate_transaction():",
"function_name": "generate_transaction",
"parameter_list": "()"
},
{
"docstring": "Generates a block of transactions.",
"function_declaration": "def generate_block(prev... | [
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\nimport random\n\ndef generate_transaction():\n \"\"\"\n Generate a single transaction with random details.\n \"\"\"\n sender = f\"user_{random.randint(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073584",
"row_id": 73584,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149223']"
} | 0.487153 | Filter_73584 | I | [
"generate_transaction",
"generate_block"
] | 2 | [
[
"generate_block",
"generate_transaction"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ebdcc031ee95ceaa924e1426337ae9598baf29f | 874758af6b56f7e9da248ffeca55c1abf809f7db | |||
v1.0 | instruct | Filter | Filter_73591_I | I need to find a prime number in a given range, and the range is specified by a start and end value. How can I write a Python function to find all prime numbers in that range? | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def find_primes_in_range(start, end):
"""
Find all prime numbers in the given range [start, end].
"""
... | from solution import is_prime, find_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(17) == True
assert is_prime(18) == False
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5)... | [
{
"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 the 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 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_2 | {
"original_instruction": "",
"prompt_id": "00073591",
"row_id": 73591,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149236']"
} | 0.570926 | Filter_73591 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aead44f62377bb06a043f8e9f45982b69626e9b9 | 7e1552023b8613e44d8bd711b9d87663a997da03 | |||
v1.0 | instruct | Filter | Filter_73621_I | Write a Python script to generate a list of dates for a given year, including leap year considerations, and store these dates in a CSV file. | import csv
from datetime import date, timedelta
def generate_dates_for_year(year):
"""
Generates a list of dates for a given year.
Accounts for leap years.
"""
start_date = date(year, 1, 1)
end_date = date(year, 12, 31)
delta = end_date - start_date
dates = [start_date + timedelta(days... | import os
from datetime import date
from solution import generate_dates_for_year, write_dates_to_csv
def test_generate_dates_for_non_leap_year():
dates = generate_dates_for_year(2021)
assert len(dates) == 365
assert dates[0] == date(2021, 1, 1)
assert dates[-1] == date(2021, 12, 31)
def test_generate_... | [
{
"docstring": "Generates a list of dates for a given year.\nAccounts for leap years.",
"function_declaration": "def generate_dates_for_year(year):",
"function_name": "generate_dates_for_year",
"parameter_list": "(year)"
},
{
"docstring": "Writes the list of dates for a given year to a speci... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nfrom datetime import datetime, timedelta\n\ndef generate_dates_for_year(year):\n \"\"\"\n Generates a list of dates for the given year.\n \n Args:\n year (int): The ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073621",
"row_id": 73621,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149288']"
} | 0.57949 | Filter_73621 | I | [
"generate_dates_for_year",
"write_dates_to_csv"
] | 2 | [
[
"write_dates_to_csv",
"generate_dates_for_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a92fb5ca7f390b8e75e905fa473b453a5e25305c | 3aaabfb250847819142a417d23479523bf0ac5bd | |||
v1.0 | instruct | Filter | Filter_73642_I | How can I create a simple TFTP server in Python? | from socket import *
import os
def handle_request(message, client_address, server_socket, storage_folder="tftp_storage"):
"""
Handle incoming TFTP request for reading a file.
"""
opcode = int.from_bytes(message[:2], byteorder='big')
if opcode == 1: # Read request (RRQ)
filename = message[2... | import pytest
import os
import socket
import threading
from time import sleep
from solution import tftp_server, handle_request
@pytest.fixture(scope='module')
def start_server():
tftp_thread = threading.Thread(target=tftp_server, kwargs={'port': 6969}, daemon=True)
tftp_thread.start()
sleep(1) # Give the ... | [
{
"docstring": "Handle incoming TFTP request for reading a file.",
"function_declaration": "def handle_request(message, client_address, server_socket, storage_folder='tftp_storage'):",
"function_name": "handle_request",
"parameter_list": "(message, client_address, server_socket, storage_folder='tftp... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport struct\nimport os\n\nclass SimpleTFTPServer:\n def __init__(self, host='0.0.0.0', port=69):\n self.host = host\n self.port = port\n self.block_siz... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073642",
"row_id": 73642,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149335']"
} | 0.489032 | Filter_73642 | I | [
"handle_request",
"tftp_server"
] | 2 | [
[
"tftp_server",
"handle_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9182e946bb40f1023af457384723c217e090d775 | 3f258b87fdbaf0bca8e0876b28002b269240b9b4 | |||
v1.0 | instruct | Filter | Filter_73652_I | What's the purpose of the `@write_binary` decorator in the PyTorch-based implementation of code generation using BART models? | import pickle
def write_binary(output_file):
"""
A decorator to write the output of a function to a binary file.
"""
def decorator_function(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open(output_file, 'wb') as f:
pickle.dump(... | import os
import pickle
from solution import write_binary, generate_data
def test_write_binary_decorator():
# Ensure the output file does not exist before test
output_file = 'output.bin'
if os.path.exists(output_file):
os.remove(output_file)
# Call the decorated function
expected_o... | [
{
"docstring": "A decorator to write the output of a function to a binary file.",
"function_declaration": "def write_binary(output_file):",
"function_name": "write_binary",
"parameter_list": "(output_file)"
},
{
"docstring": "Generates some data and returns it.\nFor the sake of example, let'... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\nimport pickle\n\ndef write_binary(filepath):\n \"\"\"\n A decorator to serialize the output of a function to a binary file.\n\n Args:\n - filepath (str): Path whe... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073652",
"row_id": 73652,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149347']"
} | 0.246275 | Filter_73652 | I | [
"write_binary",
"generate_data"
] | 2 | [
[
"generate_data",
"write_binary"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a2988607949d73205436c5f215d0e503b542aa2 | f524fba9281e85ca2b4984725b57a335445d840f | |||
v1.0 | instruct | Filter | Filter_73691_I | How can I implement a simple minimax algorithm for a Tic-Tac-Toe game in Python? | def minimax(board, depth, is_maximizing, player, opponent):
"""
Returns the best score for the player using the minimax algorithm.
"""
score = evaluate(board, player, opponent)
if score == 10:
return score - depth
if score == -10:
return score + depth
if not any(' ' in row f... | from solution import minimax, find_best_move, evaluate
def test_evaluate_player_wins():
board = [
['X', 'X', 'X'],
['O', ' ', 'O'],
[' ', ' ', ' ']
]
assert evaluate(board, 'X', 'O') == 10
def test_evaluate_opponent_wins():
board = [
['O', 'O', 'O'],
['X', ' ', ... | [
{
"docstring": "Returns the best score for the player using the minimax algorithm.",
"function_declaration": "def minimax(board, depth, is_maximizing, player, opponent):",
"function_name": "minimax",
"parameter_list": "(board, depth, is_maximizing, player, opponent)"
},
{
"docstring": "Retur... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimax(board, depth, is_maximizing, player, opponent):\n \"\"\"\n Returns the best score for the player using the minimax algorithm.\n \"\"\"\n score = evaluate(board, player,... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073691",
"row_id": 73691,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149447']"
} | 0.47987 | Filter_73691 | I | [
"minimax",
"find_best_move",
"evaluate"
] | 3 | [
[
"find_best_move",
"minimax"
],
[
"minimax",
"evaluate"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5cb0e7c71816924e509bfd54399e6a02fc9990ae | 64366987cd6b2eeb64bf683a8eb380a21f66c54f | |||
v1.0 | instruct | Filter | Filter_73693_I | How can I write a Python function to filter out all the prime numbers from a given list of integers and return a new list containing only those prime numbers? | def is_prime(number):
"""
Helper function to check if a number is prime.
"""
if number <= 1:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
def filter_primes(numbers):
"""
Filters out all the prime numbers... | from solution import filter_primes
def test_filter_primes_empty_list():
assert filter_primes([]) == []
def test_filter_primes_no_primes():
assert filter_primes([4, 6, 8, 9, 10]) == []
def test_filter_primes_all_primes():
assert filter_primes([2, 3, 5, 7, 11, 13]) == [2, 3, 5, 7, 11, 13]
def test_filter_... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(number):",
"function_name": "is_prime",
"parameter_list": "(number)"
},
{
"docstring": "Filters out all the prime numbers from a given list of integers.\n\nParameters:\nnumbers (list): List... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073693",
"row_id": 73693,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149455']"
} | 0.642841 | Filter_73693 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3953a7bf135f6a4c7a240ece3b861b5128f2a999 | 195ee0eadca4260c86275b5f6681aae4c1bdc8bc | |||
v1.0 | instruct | Filter | Filter_73709_I | How can I obtain the keyword density of a webpage using Python? | from bs4 import BeautifulSoup
import requests
from collections import Counter
import re
def get_webpage_text(url):
"""
Fetches the raw text content from a given URL.
"""
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
for script in... | from unittest.mock import patch, MagicMock
from solution import get_webpage_text, clean_and_tokenize, keyword_density
def test_get_webpage_text():
html_content = "<html><body><p>This is a test.</p></body></html>"
with patch('requests.get') as mock_get:
mock_get.return_value = MagicMock(status_code=200,... | [
{
"docstring": "Fetches the raw text content from a given URL.",
"function_declaration": "def get_webpage_text(url):",
"function_name": "get_webpage_text",
"parameter_list": "(url)"
},
{
"docstring": "Cleans the text by removing special characters and splits into words.",
"function_decla... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from bs4 import BeautifulSoup\nimport requests\nfrom collections import Counter\nimport re\n\ndef get_webpage_text(url):\n \"\"\"\n Fetches the raw text content from a given URL.\n \"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073709",
"row_id": 73709,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149485']"
} | 0.639368 | Filter_73709 | I | [
"get_webpage_text",
"clean_and_tokenize",
"keyword_density"
] | 3 | [
[
"keyword_density",
"clean_and_tokenize"
],
[
"keyword_density",
"get_webpage_text"
]
] | 2 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | 0b1c263026164d5ade71052f5bc23963ab51a73a | 9d195e82fd2d3a2b98f37d117ca457dc2c79dcf9 | |||
v1.0 | instruct | Filter | Filter_73722_I | How can I create a Python program to extract the titles of news articles from a given text containing URLs of news websites? | import requests
from bs4 import BeautifulSoup
def get_article_title(url):
"""
This function fetches the title of a news article from the given URL.
"""
try:
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses
soup = BeautifulSoup(resp... | from solution import get_article_title, extract_titles_from_text
def test_get_article_title():
url = "https://www.example.com"
title = get_article_title(url)
assert title == "Example Domain" # Expected title for example.com
def test_get_nonexistent_article_title():
url = "https://nonexistent-url.com"... | [
{
"docstring": "This function fetches the title of a news article from the given URL.",
"function_declaration": "def get_article_title(url):",
"function_name": "get_article_title",
"parameter_list": "(url)"
},
{
"docstring": "This function extracts URLs from the given text and fetches their ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom bs4 import BeautifulSoup\n\ndef get_article_title(url):\n \"\"\"\n This function fetches the title of a news article from the given URL.\n \"\"\"\n try:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073722",
"row_id": 73722,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149510']"
} | 0.629734 | Filter_73722 | I | [
"get_article_title",
"extract_titles_from_text"
] | 2 | [
[
"extract_titles_from_text",
"get_article_title"
]
] | 1 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | 12158c8a5dfc49ca762a8ac65c4682062edbde77 | a3f62089de6466232bf6f584e617a133dd6003e9 | |||
v1.0 | instruct | Filter | Filter_73732_I | Write a Python code to implement a Rock, Paper, Scissors game where the user plays against the computer. The game should allow the user to play multiple rounds, keep track of the score, and end the game when the user decides to stop. | import random
def get_computer_choice():
"""Randomly select either 'rock', 'paper', or 'scissors' for the computer."""
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
"""Determine the winner according to the rules of Rock, Paper... | from solution import determine_winner
def test_determine_winner_user_wins():
assert determine_winner('rock', 'scissors') == 'user'
assert determine_winner('scissors', 'paper') == 'user'
assert determine_winner('paper', 'rock') == 'user'
def test_determine_winner_computer_wins():
assert determine_winne... | [
{
"docstring": "Randomly select either 'rock', 'paper', or 'scissors' for the computer.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determine the winner according to the rules of Rock, Paper, Scisso... | [
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 play_round(player_choice):\n \"\"\"\n Plays a round of Rock, Paper, Scissors.\n Arguments:\n player_choice -- a string: 'rock', 'paper', or 'scissors'\n \n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073732",
"row_id": 73732,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149531']"
} | 0.505 | Filter_73732 | I | [
"get_computer_choice",
"determine_winner",
"play_round",
"rock_paper_scissors_game"
] | 4 | [
[
"play_round",
"determine_winner"
],
[
"play_round",
"get_computer_choice"
],
[
"rock_paper_scissors_game",
"play_round"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9fc8126f13eb1bd4f99de194e06553f41b49d97e | b493ad196026461af26921cff10b2dc8e9de64cb | |||
v1.0 | instruct | Filter | Filter_73790_I | I'm looking for a Python script that can take a list of usernames and generate a CSV file with hashed passwords for each username. The passwords should be randomly generated using a secure method and should use the SHA-256 hashing algorithm. How can I achieve this? | import csv
import hashlib
import os
def generate_password(length=12):
"""
Generate a random password of a specified length. Default is 12 characters.
"""
return os.urandom(length).hex()[:length]
def hash_password(password):
"""
Hash a password using SHA-256.
"""
sha256 = hashlib.sha256... | import os
import csv
from solution import generate_password, hash_password, generate_user_password_csv
def test_generate_password_length():
password = generate_password(16)
assert len(password) == 16
def test_generate_password_randomness():
password1 = generate_password(12)
password2 = generate_passwo... | [
{
"docstring": "Generate a random password of a specified length. Default is 12 characters.",
"function_declaration": "def generate_password(length=12):",
"function_name": "generate_password",
"parameter_list": "(length=12)"
},
{
"docstring": "Hash a password using SHA-256.",
"function_d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport hashlib\nimport os\nimport base64\n\ndef generate_random_password(length=12):\n \"\"\"\n Generates a random password of specified length.\n \"\"\"\n return base6... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073790",
"row_id": 73790,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149667']"
} | 0.570474 | Filter_73790 | I | [
"generate_password",
"hash_password",
"generate_user_password_csv"
] | 3 | [
[
"generate_user_password_csv",
"generate_password"
],
[
"generate_user_password_csv",
"hash_password"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8ef4ac2f3c1a8180417aafe1e47390e7e92ae511 | 42f0db6f999dcdad05fc814e0914a64bf117b2a0 | |||
v1.0 | instruct | Filter | Filter_73843_I | Hey Qwen, I need help with a Python script that monitors a directory for new files and then processes these files. Can you provide a basic example of how to achieve this? | import os
import time
def monitor_directory(directory_path, sleep_time=5):
"""
Monitors a directory for new files and processes them.
Args:
directory_path (str): The path of the directory to monitor.
sleep_time (int): Time in seconds between each polling.
"""
processed_files = set()
... | from solution import monitor_directory, process_file
import tempfile
import os
import threading
def test_process_file(capsys):
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file_name = temp_file.name
try:
process_file(temp_file_name)
captured = capsys.readouterr... | [
{
"docstring": "Monitors a directory for new files and processes them.\nArgs:\ndirectory_path (str): The path of the directory to monitor.\nsleep_time (int): Time in seconds between each polling.",
"function_declaration": "def monitor_directory(directory_path, sleep_time=5):",
"function_name": "monitor_... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport time\n\ndef monitor_directory(directory, process_file_callback):\n \"\"\"\n Monitors the given directory for new files and processes them using the provided callback fu... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073843",
"row_id": 73843,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149772']"
} | 0.502885 | Filter_73843 | I | [
"monitor_directory",
"process_file"
] | 2 | [
[
"monitor_directory",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3c4a3ac32ed06a36fbdd5979b2e43194b5479c17 | 7260018d0655aa312d22602855618af8151d9aa8 | |||
v1.0 | instruct | Filter | Filter_73861_I | Can you provide a Python code example that counts the occurrences of each number in a list and prints the results in a sorted format by the number itself? | def count_occurrences(nums):
"""
Counts the occurrences of each number in the list nums.
Args:
nums (list of int): List of integers to count occurrences from.
Returns:
dict: A dictionary containing the numbers as keys and their counts as values.
"""
counts = {}
for num in nums:... | from solution import count_occurrences, print_sorted_occurrences
from io import StringIO
import sys
def test_count_occurrences_empty_list():
assert count_occurrences([]) == {}
def test_count_occurrences_single_element():
assert count_occurrences([1]) == {1: 1}
def test_count_occurrences_multiple_elements():
... | [
{
"docstring": "Counts the occurrences of each number in the list nums.\n\nArgs:\nnums (list of int): List of integers to count occurrences from.\n\nReturns:\ndict: A dictionary containing the numbers as keys and their counts as values.",
"function_declaration": "def count_occurrences(nums):",
"function... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_occurrences(numbers):\n \"\"\"\n Counts the occurrences of each number in the list and returns the results \n in a sorted format by the number itself.\n \n :param numb... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073861",
"row_id": 73861,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149812']"
} | 0.669492 | Filter_73861 | I | [
"count_occurrences",
"print_sorted_occurrences"
] | 2 | [
[
"print_sorted_occurrences",
"count_occurrences"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | be8941c2ec9035b46126e17e69eaad3922fadde7 | 4c3d16e4ec81354dd30d9f9783b7d358bffe0519 | |||
v1.0 | instruct | Filter | Filter_73863_I | Can I create a Python function that generates a list of prime numbers within a given range using a list comprehension? | def is_prime(n):
"""
Returns True if n is a prime number, else False.
"""
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 primes_in_r... | from solution import is_prime, 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(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
def test_primes_in_range():... | [
{
"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 (inclusive) and end (exclusive).",
"function_declaration": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number 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": "00073863",
"row_id": 73863,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149816']"
} | 0.590786 | Filter_73863 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d096d7fe8653efb617afac61a98460fcbe5c94f8 | c72a6db1a8278ae51cdfa355ecfdbf77458865cf | |||
v1.0 | instruct | Filter | Filter_73865_I | Could you provide a Python code snippet that lists all the prime numbers between two given numbers, say 10 and 50? | 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 list_primes_between(start, end):
"""
Returns a list of prime numbers between... | from solution import is_prime, list_primes_between
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_prime(4) is False
assert is_prime(29) is True
assert is_prime(1) is False
assert is_prime(0) is False
assert is_prime(-5) is False
def test_list_primes_be... | [
{
"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 a list of prime numbers between 'start' and 'end' (inclusive).",
"function_declaration": "de... | [
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 \"\"\"Returns True if n is a prime number, else False.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073865",
"row_id": 73865,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149818']"
} | 0.637785 | Filter_73865 | I | [
"is_prime",
"list_primes_between"
] | 2 | [
[
"list_primes_between",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a1dcac2e16b53df3ff88c645d844c85708da0c07 | a263b3842cfec334b27a91ff015a4d7b04a4f546 | |||
v1.0 | instruct | Filter | Filter_73868_I | Can you provide a Python code to simulate a simple robot arm with two segments using the turtle graphics library? | import turtle
def draw_arm_segment(length):
"""
Draw a single segment of the robot arm.
Args:
- length (int): The length of the arm segment.
"""
turtle.forward(length)
def set_segment_angle(angle):
"""
Set the angle of a single segment of the robot arm.
Args:
- angle ... | import pytest
from solution import draw_arm_segment, set_segment_angle, draw_robot_arm
import turtle
def test_draw_arm_segment(monkeypatch):
drawn_forward_steps = []
def mock_forward(length):
drawn_forward_steps.append(length)
monkeypatch.setattr(turtle, 'forward', mock_forward)
draw_arm_segm... | [
{
"docstring": "Draw a single segment of the robot arm.\n\nArgs:\n- length (int): The length of the arm segment.",
"function_declaration": "def draw_arm_segment(length):",
"function_name": "draw_arm_segment",
"parameter_list": "(length)"
},
{
"docstring": "Set the angle of a single segment o... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef draw_arm_segment(t, length, angle):\n t.left(angle)\n t.forward(length)\n\ndef draw_robot_arm(base_x, base_y, length1, angle1, length2, angle2):\n t = turtle.Turt... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073868",
"row_id": 73868,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149829']"
} | 0.545613 | Filter_73868 | I | [
"draw_arm_segment",
"set_segment_angle",
"draw_robot_arm"
] | 3 | [
[
"draw_robot_arm",
"draw_arm_segment"
],
[
"draw_robot_arm",
"set_segment_angle"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e6c324cc86ff20c2aebbc8f87cffc926698bb9cc | ac276ee467f853b038a3d0d0250bf4931ebb9a38 | |||
v1.0 | instruct | Filter | Filter_73870_I | How can I handle a situation where I need to call a function conditionally in Python, based on the type of input? | def handle_input(input_value):
"""
Handles the input by calling different functions based on the type of input_value.
"""
if isinstance(input_value, int):
return handle_int(input_value)
elif isinstance(input_value, str):
return handle_str(input_value)
elif isinstance(input_value,... | from solution import handle_input
def test_handle_input_with_int():
assert handle_input(10) == 20
assert handle_input(-5) == -10
def test_handle_input_with_str():
assert handle_input("hello") == "olleh"
assert handle_input("world") == "dlrow"
def test_handle_input_with_list():
assert handle_input... | [
{
"docstring": "Handles the input by calling different functions based on the type of input_value.",
"function_declaration": "def handle_input(input_value):",
"function_name": "handle_input",
"parameter_list": "(input_value)"
},
{
"docstring": "Handle input of type int.",
"function_decla... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def handle_input(input_data):\n \"\"\"\n Calls specific functions based on the type of input_data.\n \n - If input_data is a string, it capitalizes it.\n - If input_data is a li... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073870",
"row_id": 73870,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149832']"
} | 0.466366 | Filter_73870 | I | [
"handle_input",
"handle_int",
"handle_str",
"handle_list"
] | 4 | [
[
"handle_input",
"handle_int"
],
[
"handle_input",
"handle_list"
],
[
"handle_input",
"handle_str"
]
] | 3 | [
"handle_input"
] | false | [] | false | pytest | true | [] | true | af93df9c0d943233fe96e1a6d20d96cb7fa44f3f | b7a337539831eeac9c230bd93fd276443205042b | |||
v1.0 | instruct | Filter | Filter_73917_I | Can you help me with a Python code to simulate a simple two-player game where players can choose to select either "rock", "paper", or "scissors"? The game continues until one player reaches a score of 3. The player who first reaches a score of 3 wins the game. | import random
def get_winner(player1_choice, player2_choice):
"""Determines the winner of a rock-paper-scissors game round."""
if player1_choice == player2_choice:
return None
elif (player1_choice == "rock" and player2_choice == "scissors") or \
(player1_choice == "scissors" and player2_ch... | from solution import get_winner
def test_get_winner_rock_beats_scissors():
assert get_winner("rock", "scissors") == 1
assert get_winner("scissors", "rock") == 2
def test_get_winner_scissors_beats_paper():
assert get_winner("scissors", "paper") == 1
assert get_winner("paper", "scissors") == 2
def test... | [
{
"docstring": "Determines the winner of a rock-paper-scissors game round.",
"function_declaration": "def get_winner(player1_choice, player2_choice):",
"function_name": "get_winner",
"parameter_list": "(player1_choice, player2_choice)"
},
{
"docstring": "Simulates a complete game where the f... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_winner(player1_choice, player2_choice):\n \"\"\"Determines the winner of a rock-paper-scissors game round.\"\"\"\n if player1_choice == player2_choice:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00073917",
"row_id": 73917,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149911']"
} | 0.442719 | Filter_73917 | I | [
"get_winner",
"play_game"
] | 2 | [
[
"play_game",
"get_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e07f5e11adce6da05051914978b860f92324690a | c2c1b9b024f31f61ac96dd84e6ae7750b89277d7 | |||
v1.0 | instruct | Filter | Filter_73921_I | Write a Python function to check if a given 4x4 matrix is a binary matrix (i.e., it only contains 0s and 1s). Additionally, the function should verify if this binary matrix is idempotent, meaning that the matrix squared is equal to the matrix itself. A matrix is said to be idempotent if for every element (i, j), the (i... | import numpy as np
def is_binary_matrix(matrix):
"""
Check if the given matrix is a binary matrix (i.e., contains only 0s and 1s).
"""
for row in matrix:
for element in row:
if element not in [0, 1]:
return False
return True
def is_idempotent(matrix):
"""
... | from solution import is_binary_and_idempotent
def test_valid_binary_idempotent_matrix():
matrix = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
]
assert is_binary_and_idempotent(matrix) == True
def test_valid_binary_non_idempotent_matrix():
matrix = [
... | [
{
"docstring": "Check if the given matrix is a binary matrix (i.e., contains only 0s and 1s).",
"function_declaration": "def is_binary_matrix(matrix):",
"function_name": "is_binary_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Check if the given matrix is idempotent.",
"functi... | [
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 is_binary_matrix(matrix):\n \"\"\"\n Checks if the given 4x4 matrix is a binary matrix (contains only 0s and 1s).\n \"\"\"\n for row in matrix:\n f... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073921",
"row_id": 73921,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_149922']"
} | 0.630887 | Filter_73921 | I | [
"is_binary_matrix",
"is_idempotent",
"is_binary_and_idempotent"
] | 3 | [
[
"is_binary_and_idempotent",
"is_binary_matrix"
],
[
"is_binary_and_idempotent",
"is_idempotent"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 0c577340170549c03df660353e29974df56be8fe | 34a22cdc5535c75fb25b4559f765262dc9ac7e8d | |||
v1.0 | instruct | Filter | Filter_73972_I | Can you explain the divide and conquer strategy in programming with an example? | def merge_sort(arr):
"""
Sorts the array using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
# Divide the array into two halves
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# Recursively sort both halves
left_sorted = merge_sort(... | from solution import merge_sort
def test_merge_sort_basic():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
def test_merge_sort_with_negative_numbers():
assert merge_sort([-1, -3, -2, 0, 2, 1, -5]) == [-5, -3, -2, -1, 0, 1, 2]
def test_merge_sort_with_repeated_numbers():
asse... | [
{
"docstring": "Sorts the array using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted arrays into a single sorted array.",
"function_declaration": "def merge(left, ri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n # Divide the array into two halves\n m... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00073972",
"row_id": 73972,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150029']"
} | 0.393096 | Filter_73972 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4aba61bda2281c7c1788c8058eaf85ad557da15f | 94081e06c75e26bcba914f88f5715ca33f4ef4a6 | |||
v1.0 | instruct | Filter | Filter_73989_I | Write a simple Python script to simulate a basic game of Rock, Paper, Scissors where the user plays against the computer. The computer's choice is randomly selected, and the user's choice is inputted via the console. The script should include functions to determine the winner and to handle user input. | import random
def get_computer_choice():
"""
Randomly selects Rock, Paper, or Scissors for the computer.
"""
choices = ["Rock", "Paper", "Scissors"]
return random.choice(choices)
def get_winner(user_choice, computer_choice):
"""
Determines the winner of the game.
"""
if user_choice... | from solution import get_computer_choice, get_winner
def test_get_winner_tie():
assert get_winner("Rock", "Rock") == "It's a tie!"
assert get_winner("Paper", "Paper") == "It's a tie!"
assert get_winner("Scissors", "Scissors") == "It's a tie!"
def test_get_winner_user_wins():
assert get_winner("Rock", ... | [
{
"docstring": "Randomly selects Rock, Paper, or Scissors for the computer.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of the game.",
"function_declaration": "def get_winn... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"\n Randomly returns 'rock', 'paper', or 'scissors'.\n \"\"\"\n choices = ['rock', 'paper', 'scissors']\n return random.choice... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00073989",
"row_id": 73989,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150061']"
} | 0.425573 | Filter_73989 | I | [
"get_computer_choice",
"get_winner",
"play_game"
] | 3 | [
[
"play_game",
"get_computer_choice"
],
[
"play_game",
"get_winner"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4c6fcb147ceacae8e5744f78f130842ad613873f | 49ebe1d509b5209ed9e7b16d0e4732d1b44bc679 | |||
v1.0 | instruct | Filter | Filter_74005_I | Hello! How can I create a simple text-based tic-tac-toe game in Python? | def print_board(board):
"""
Prints the current state of the tic-tac-toe board.
"""
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
"""
Checks if the player has won the game.
"""
# Check rows, columns and diagonals
for row in b... | from solution import print_board, check_winner, check_draw, switch_player, make_move
def test_print_board(capsys):
board = [['X', 'O', 'X'], ['O', 'X', 'O'], ['O', 'X', 'O']]
print_board(board)
captured = capsys.readouterr()
assert captured.out == "X | O | X\n-----\nO | X | O\n-----\nO | X | O\n-----\n... | [
{
"docstring": "Prints the current state of the tic-tac-toe board.",
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": "Checks if the player has won the game.",
"function_declaration": "def check_winner(board,... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def init_board():\n return [' '] * 9\n\ndef print_board(board):\n print(f\"{board[0]} | {board[1]} | {board[2]}\")\n print(\"--+---+--\")\n print(f\"{board[3]} | {board[4]} | {boar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074005",
"row_id": 74005,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150091']"
} | 0.406054 | Filter_74005 | I | [
"print_board",
"check_winner",
"check_draw",
"switch_player",
"make_move",
"tic_tac_toe"
] | 6 | [
[
"tic_tac_toe",
"check_draw"
],
[
"tic_tac_toe",
"check_winner"
],
[
"tic_tac_toe",
"make_move"
],
[
"tic_tac_toe",
"print_board"
],
[
"tic_tac_toe",
"switch_player"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 38499e1b51bc7994dc9b93fbf4939791bb4648e8 | 758a73d88a03204123c57c461155dd6fccc8fb77 | |||
v1.0 | instruct | Filter | Filter_74022_I | Write a simple MapReduce program in Python to count the frequency of each word in a text file. This program should read a text file, output the word frequency, and handle large files by using MapReduce techniques. | from collections import defaultdict
import multiprocessing
def map_function(chunk):
"""
Process a chunk of text and return word frequencies in the chunk.
"""
word_count = defaultdict(int)
for line in chunk:
words = line.strip().split()
for word in words:
word_count[word]... | from solution import map_function, reduce_function, map_reduce
import tempfile
def test_map_function():
chunk = ["Hello world", "Hello again"]
result = map_function(chunk)
assert result["Hello"] == 2
assert result["world"] == 1
assert result["again"] == 1
def test_reduce_function():
mappings =... | [
{
"docstring": "Process a chunk of text and return word frequencies in the chunk.",
"function_declaration": "def map_function(chunk):",
"function_name": "map_function",
"parameter_list": "(chunk)"
},
{
"docstring": "Combine the results of multiple mapped chunks into a single word frequency d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nfrom multiprocessing import Pool\n\ndef map_function(chunk):\n \"\"\"\n Map function that takes a chunk of text and counts occurrences of each word.\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074022",
"row_id": 74022,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150136']"
} | 0.691697 | Filter_74022 | I | [
"map_function",
"reduce_function",
"chunkify",
"map_reduce"
] | 4 | [
[
"map_reduce",
"chunkify"
],
[
"map_reduce",
"map_function"
],
[
"map_reduce",
"reduce_function"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1ed25b362cf5f4576dca7154af104beb5d3e82b6 | 95f2e85e9e372b22fc7e983078f5418a064c3142 | |||
v1.0 | instruct | Filter | Filter_74027_I | How can I create a multi-level nested dictionary from an XML document in Python? | import xml.etree.ElementTree as ET
def xml_to_dict(element):
"""
Converts an XML element and its children into a nested dictionary.
"""
if len(element) == 0:
# if element has no children
return element.text
result = {}
for child in element:
child_result = xml_to_dict(chi... | import pytest
from solution import parse_xml_string
def test_simple_xml():
xml = "<root><child>value</child></root>"
expected = {'root': {'child': 'value'}}
assert parse_xml_string(xml) == expected
def test_nested_xml():
xml = "<root><child><subchild>value</subchild></child></root>"
expected = {'r... | [
{
"docstring": "Converts an XML element and its children into a nested dictionary.",
"function_declaration": "def xml_to_dict(element):",
"function_name": "xml_to_dict",
"parameter_list": "(element)"
},
{
"docstring": "Parses an XML string and converts it into a nested dictionary.",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\n\ndef xml_to_dict(element):\n \"\"\"\n Recursively converts an XML Element and its children to a dictionary.\n \n Parameters:\n element (xml.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074027",
"row_id": 74027,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150150']"
} | 0.724145 | Filter_74027 | I | [
"xml_to_dict",
"parse_xml_string"
] | 2 | [
[
"parse_xml_string",
"xml_to_dict"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 34a6792260d8193f8061b6ecb5df631fc95c8baf | d5587f224167964ea7699a4c18dd0e5397cf7d06 | |||
v1.0 | instruct | Filter | Filter_74034_I | Write a Python code to simulate a simple game of rolling two dice and calculating the sum of the outcomes. The game should also determine if the sum is even or odd. Additionally, the game should simulate rolling the dice 10 times and keep a count of how many times the sum is even and how many times it is odd. | import random
def roll_dice():
"""
Simulate rolling two dice and return their sum.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def is_even(num):
"""
Check if a number is even.
"""
return num % 2 == 0
def dice_game(rounds=10):
"""
Simu... | from solution import roll_dice, is_even, dice_game
def test_roll_dice():
for _ in range(100): # Test multiple times due to randomness
result = roll_dice()
assert 2 <= result <= 12
def test_is_even():
assert is_even(2) == True
assert is_even(3) == False
assert is_even(0) == True
ass... | [
{
"docstring": "Simulate rolling two dice and return their sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Check if a number is even.",
"function_declaration": "def is_even(num):",
"function_name": "is_even",
... | [
0,
1
] | 1 | medium | 0.5 | {
"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 6-sided dice and returns their sum.\n \"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074034",
"row_id": 74034,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150174']"
} | 0.581965 | Filter_74034 | I | [
"roll_dice",
"is_even",
"dice_game"
] | 3 | [
[
"dice_game",
"is_even"
],
[
"dice_game",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dedfd0d2f7e319501706c4c162b2593c7e358de4 | e57b8f9a3bef98ec17f6e450da0d0d3bf52ac755 | |||
v1.0 | instruct | Filter | Filter_74053_I | Write a Python function that takes a list of integers as input and returns the sum of all the prime numbers in the list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. | 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 sum_of_primes
def test_sum_of_primes_all_primes():
assert sum_of_primes([2, 3, 5, 7]) == 17
def test_sum_of_primes_mixed():
assert sum_of_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 17
def test_sum_of_primes_no_primes():
assert sum_of_primes([1, 4, 6, 8, 9, 10, 12]) == 0
def test_sum... | [
{
"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 the sum of all prime numbers in the given list.",
"function_declaration": "def sum_of_primes(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(n):\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00074053",
"row_id": 74053,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150207']"
} | 0.701841 | Filter_74053 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a4f1437fb52fb8b4da1a7b9caf7948fc77280952 | 822bee44cb920b53a458781c4ee03048242bf862 | |||
v1.0 | instruct | Filter | Filter_74059_I | Can you provide a Python script that uses the `scipy.optimize` library to find the minimum of a given function? Certainly! Below is a Python script that demonstrates how to use the `scipy.optimize` library to find the minimum of a given function. For this example, let's consider the function \( f(x) = (x - 3)^2 + 4 \). | from scipy.optimize import minimize
def function_to_minimize(x):
"""
Function to be minimized: f(x) = (x - 3)^2 + 4
"""
return (x - 3)**2 + 4
def find_minimum():
"""
Finds the minimum of the function using scipy's minimize function.
"""
result = minimize(function_to_minimize, x0=[0]) ... | from solution import function_to_minimize, find_minimum
def test_function_to_minimize():
# At x=3, the function should return 4
assert function_to_minimize(3) == 4
# General checks
assert function_to_minimize(0) == 13 # (0-3)^2 + 4 = 9 + 4 = 13
assert function_to_minimize(-1) == 20 # (-1-3)^2 + 4... | [
{
"docstring": "Function to be minimized: f(x) = (x - 3)^2 + 4",
"function_declaration": "def function_to_minimize(x):",
"function_name": "function_to_minimize",
"parameter_list": "(x)"
},
{
"docstring": "Finds the minimum of the function using scipy's minimize function.",
"function_decl... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.optimize import minimize\n\ndef function_to_minimize(x):\n \"\"\"\n The function to find the minimum of. In this case, it is (x - 3)^2 + 4.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00074059",
"row_id": 74059,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150219']"
} | 0.492656 | Filter_74059 | I | [
"function_to_minimize",
"find_minimum"
] | 2 | [
[
"find_minimum",
"function_to_minimize"
]
] | 1 | [] | false | [] | false | pytest | true | [
"scipy"
] | false | b22f385c75df90c6fe44f66b71120fd7cc3041ad | 3b067c3d9ed0b02f29113026b43f3095afe3360b | |||
v1.0 | instruct | Filter | Filter_74066_I | Can you provide a Python function that simulates a simple blackjack game? The game should include a deck with 52 cards, two players, and basic rules where the dealer stands on 17 or higher. The player can hit or stand, and the game ends when both players have acted. The function should output the results of the game. | import random
def create_deck():
"""Creates a standard deck of 52 cards."""
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
return [{'rank': rank, 'suit': suit} for rank in ranks for suit in suits]
def calculate_hand_value(ha... | def test_create_deck():
deck = create_deck()
assert len(deck) == 52
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
for rank in ranks:
for suit in suits:
assert {'rank': rank, 'suit': suit} in deck
def ... | [
{
"docstring": "Creates a standard deck of 52 cards.",
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": "Calculates the value of a hand in blackjack.",
"function_declaration": "def calculate_hand_value(hand):",
"fu... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef create_deck():\n \"\"\"Creates a standard deck of 52 cards.\"\"\"\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\n suits = ['Hearts'... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00074066",
"row_id": 74066,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150228']"
} | 0.431882 | Filter_74066 | I | [
"create_deck",
"calculate_hand_value",
"blackjack"
] | 3 | [
[
"blackjack",
"calculate_hand_value"
],
[
"blackjack",
"create_deck"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | dea19e15b9e27696b685901ca68d527030e33f68 | 3f36f71c371632cc0dec780d219c2a204b1c7842 | |||
v1.0 | instruct | Filter | Filter_74086_I | Can you explain how the `map` function works in Python with a custom function and a list of strings, specifically converting each string to uppercase? | def to_uppercase(s):
"""
Converts a string to uppercase.
"""
return s.upper()
def convert_list_to_uppercase(strings):
"""
Applies the to_uppercase function to each element in the list of strings.
"""
return list(map(to_uppercase, strings)) | from solution import to_uppercase, convert_list_to_uppercase
def test_to_uppercase():
assert to_uppercase("hello") == "HELLO"
assert to_uppercase("world") == "WORLD"
assert to_uppercase("Python") == "PYTHON"
def test_convert_list_to_uppercase():
assert convert_list_to_uppercase(["hello", "world", "Pyt... | [
{
"docstring": "Converts a string to uppercase.",
"function_declaration": "def to_uppercase(s):",
"function_name": "to_uppercase",
"parameter_list": "(s)"
},
{
"docstring": "Applies the to_uppercase function to each element in the list of strings.",
"function_declaration": "def convert_l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def to_uppercase(s):\n \"\"\"\n Returns the input string in uppercase.\n \"\"\"\n return s.upper()\n\ndef convert_list_to_uppercase(string_list):\n \"\"\"\n Converts each str... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074086",
"row_id": 74086,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150269']"
} | 0.630328 | Filter_74086 | I | [
"to_uppercase",
"convert_list_to_uppercase"
] | 2 | [
[
"convert_list_to_uppercase",
"to_uppercase"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6fa8ae08692d5fa8ac7670ac68c5b11bef213f41 | 93712ac0bc7bb5f2ccd80268226b00c69e362a15 | |||
v1.0 | instruct | Filter | Filter_74106_I | Write a Python function that takes a string as input and returns the string in reverse order. Additionally, create a function that checks if the reversed string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. | def reverse_string(s):
"""
Returns the reverse of the input string s.
"""
return s[::-1]
def is_palindrome(s):
"""
Returns True if the input string s is a palindrome, otherwise False.
"""
reversed_s = reverse_string(s)
return s == reversed_s | from solution import reverse_string, is_palindrome
def test_reverse_string():
assert reverse_string("hello") == "olleh"
assert reverse_string("world") == "dlrow"
assert reverse_string("abcd") == "dcba"
assert reverse_string("") == ""
assert reverse_string("a") == "a"
def test_is_palindrome():
... | [
{
"docstring": "Returns the reverse of the input string s.",
"function_declaration": "def reverse_string(s):",
"function_name": "reverse_string",
"parameter_list": "(s)"
},
{
"docstring": "Returns True if the input string s is a palindrome, otherwise False.",
"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 reverse_string(s):\n \"\"\"\n Returns the string s in reverse order.\n \"\"\"\n return s[::-1]\n\ndef is_palindrome(s):\n \"\"\"\n Checks if the string s is a palindrome.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074106",
"row_id": 74106,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150311']"
} | 0.77147 | Filter_74106 | I | [
"reverse_string",
"is_palindrome"
] | 2 | [
[
"is_palindrome",
"reverse_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c16b16021e85b7fae1e51379d03d54a8ec40de6f | 5e100584dabc48bf8c3887b683a947c9212674b4 | |||
v1.0 | instruct | Filter | Filter_74118_I | Write a Python program to simulate a simple game of Rock, Paper, Scissors. The game should allow a user to play against the computer. The computer's choice should be randomly generated. The program should continue to prompt the user for their choice until they decide to quit by entering 'quit'. The program should also ... | import random
def get_computer_choice():
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def decide_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return 'tie'
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_cho... | from solution import get_computer_choice, decide_winner
def test_get_computer_choice():
choice = get_computer_choice()
assert choice in ['rock', 'paper', 'scissors']
def test_decide_winner():
assert decide_winner('rock', 'scissors') == 'user'
assert decide_winner('rock', 'paper') == 'computer'
ass... | [
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def decide_winner(user_choice, computer_choice):",
"function_name": "decide_winner",
"paramet... | [
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 generate the computer's choice.\n \"\"\"\n choices = ['rock', 'paper', 'scissors']\n return random.choice(choices... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074118",
"row_id": 74118,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150331']"
} | 0.508835 | Filter_74118 | I | [
"get_computer_choice",
"decide_winner",
"rock_paper_scissors_game"
] | 3 | [
[
"rock_paper_scissors_game",
"decide_winner"
],
[
"rock_paper_scissors_game",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2931f4a6c07aeee3e32e660d07e42861f3e5630c | 1d5cfb0a3cc24a36eaeacc24f51ffb4987f143bf | |||
v1.0 | instruct | Filter | Filter_74120_I | How can I use a Python script to scan for active HTTPS servers on a specific IP address range? | import itertools
import requests
import socket
def ip_range(start_ip, end_ip):
"""
Generate a range of IP addresses from start_ip to end_ip.
"""
start = list(map(int, start_ip.split('.')))
end = list(map(int, end_ip.split('.')))
temp = start
ip_range = []
ip_range.append(start_ip)
... | from solution import ip_range, scan_https_servers
def test_ip_range_single_ip():
assert ip_range("192.168.1.1", "192.168.1.1") == ["192.168.1.1"]
def test_ip_range_same_subnet():
assert ip_range("192.168.1.1", "192.168.1.3") == ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
def test_ip_range_different_subnets... | [
{
"docstring": "Generate a range of IP addresses from start_ip to end_ip.",
"function_declaration": "def ip_range(start_ip, end_ip):",
"function_name": "ip_range",
"parameter_list": "(start_ip, end_ip)"
},
{
"docstring": "Scan for active HTTPS servers within the specified range of IP address... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport ssl\n\ndef is_https_server_active(ip_address, port=443, timeout=3):\n \"\"\"\n Checks if an HTTPS server is active on the given IP address and port.\n \n Args... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074120",
"row_id": 74120,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150335']"
} | 0.674481 | Filter_74120 | I | [
"ip_range",
"scan_https_servers"
] | 2 | [
[
"scan_https_servers",
"ip_range"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 311bf7eda8526ea5e2b39751bed7f512c42ccd94 | 71e550971e94667fd4f5b2bb865732b2b3659acb | |||
v1.0 | instruct | Filter | Filter_74133_I | As an AI, I am processing a large dataset for a natural language processing task. The dataset contains thousands of documents, and each document has a varying number of paragraphs. My task is to split each document into sentences and then segment each sentence into words. How can I achieve this in Python without using ... | import re
def split_into_sentences(paragraph):
"""
Splits a paragraph into sentences using simple regex patterns.
"""
sentence_endings = re.compile(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\!)\s')
sentences = sentence_endings.split(paragraph)
return sentences
def segment_sentences_into_words(s... | from solution import split_into_sentences, segment_sentences_into_words, process_documents
def test_split_into_sentences():
paragraph = "This is a sentence. And this is another sentence! Is this a question? Yes, it is."
expected = ["This is a sentence.", "And this is another sentence!", "Is this a question?", ... | [
{
"docstring": "Splits a paragraph into sentences using simple regex patterns.",
"function_declaration": "def split_into_sentences(paragraph):",
"function_name": "split_into_sentences",
"parameter_list": "(paragraph)"
},
{
"docstring": "Segments a sentence into words using simple regex patte... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef split_into_sentences(text):\n \"\"\"\n Splits the provided text into sentences.\n \"\"\"\n sentence_endings = re.compile(r'[.!?]')\n sentences = sentence_ending... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074133",
"row_id": 74133,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150361']"
} | 0.66128 | Filter_74133 | I | [
"split_into_sentences",
"segment_sentences_into_words",
"process_documents"
] | 3 | [
[
"process_documents",
"segment_sentences_into_words"
],
[
"process_documents",
"split_into_sentences"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6c6259db4fd2a3cbcb854f0a3113e43ef269918a | 7426157e837dbc7cb1e44c142f93871e7a1e6a4d | |||
v1.0 | instruct | Filter | Filter_74144_I | Can you provide a Python code that simulates a simple card game where players draw cards from a deck and the player with the highest card wins? This game is played with a standard 52-card deck, and only one card is drawn per player. | import random
def create_deck():
"""Creates a standard 52-card deck."""
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = [(value, suit) for suit in suits for value in values]
return deck
def card_value(... | from solution import create_deck, card_value, draw_card, play_game
def test_create_deck():
deck = create_deck()
assert len(deck) == 52
assert ('Ace', 'Hearts') in deck
assert ('2', 'Clubs') in deck
def test_card_value():
assert card_value(('2', 'Hearts')) == 2
assert card_value(('10', 'Diamond... | [
{
"docstring": "Creates a standard 52-card deck.",
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": "Assigns a numeric value to a card.",
"function_declaration": "def card_value(card):",
"function_name": "card_valu... | [
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 draw_card():\n \"\"\"\n Draws a random card from a standard 52-card deck.\n Cards are represented as tuples (rank, suit).\n Rank: 2-10, 11 for Jack, 12 for Que... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074144",
"row_id": 74144,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150376']"
} | 0.472489 | Filter_74144 | I | [
"create_deck",
"card_value",
"draw_card",
"play_game"
] | 4 | [
[
"play_game",
"create_deck"
],
[
"play_game",
"draw_card"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 989bc001a12c288d9d00c44f3a11689c27c228ba | f7223a0fe665cff4d092fcdece15c3230531b6ae | |||
v1.0 | instruct | Filter | Filter_74145_I | If I use a Python script to monitor the battery level of my laptop, how can I implement a feature that sends a notification when the battery level falls below a certain threshold, say 20%? | import psutil
import os
def send_notification(message):
"""
Sends a desktop notification with the given message.
This function assumes a Linux environment with notify-send installed.
"""
os.system(f'notify-send "{message}"')
def monitor_battery(threshold=20):
"""
Monitors the battery level... | from unittest.mock import patch
import pytest
from solution import monitor_battery, send_notification
def test_send_notification():
with patch('os.system') as mocked_system:
send_notification("Test message")
mocked_system.assert_called_with('notify-send "Test message"')
def test_monitor_battery_be... | [
{
"docstring": "Sends a desktop notification with the given message.\nThis function assumes a Linux environment with notify-send installed.",
"function_declaration": "def send_notification(message):",
"function_name": "send_notification",
"parameter_list": "(message)"
},
{
"docstring": "Moni... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nfrom plyer import notification\nimport time\n\ndef check_battery(threshold):\n \"\"\"\n Checks the battery level and sends a notification if it falls below the threshold.\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074145",
"row_id": 74145,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150378']"
} | 0.43111 | Filter_74145 | I | [
"send_notification",
"monitor_battery"
] | 2 | [
[
"monitor_battery",
"send_notification"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | 8709a190b0cab9c06265df503dc8f998d318bdbd | 39b789223d6f09654a36d2677db2407c2bd41891 | |||
v1.0 | instruct | Filter | Filter_74156_I | I need help with writing a Python script to process a directory of text files. The script should read each file, count the number of words in the file, and then write the results to an output file. Each line in the output file should have the filename and its corresponding word count, separated by a colon and a space. ... | import os
def count_words_in_file(filepath):
"""
Counts the number of words in a given file.
Parameters:
filepath (str): The path to the file to read.
Returns:
int: The word count of the file.
"""
with open(filepath, 'r', encoding='utf-8') as file:
contents = file.read... | import os
import tempfile
from solution import count_words_in_file, process_directory
def create_temp_file(directory, filename, content):
"""
Creates a temporary file with the given content.
Parameters:
directory (str): The path to the directory.
filename (str): The name of the file.
conte... | [
{
"docstring": "Counts the number of words in a given file.\n\nParameters:\nfilepath (str): The path to the file to read.\n\nReturns:\nint: The word count of the file.",
"function_declaration": "def count_words_in_file(filepath):",
"function_name": "count_words_in_file",
"parameter_list": "(filepath... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef count_words_in_file(file_path):\n \"\"\"\n Reads a file and returns the number of words in the file.\n \"\"\"\n with open(file_path, 'r', encoding='utf-8') as file... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074156",
"row_id": 74156,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150409']"
} | 0.728553 | Filter_74156 | I | [
"count_words_in_file",
"process_directory"
] | 2 | [
[
"process_directory",
"count_words_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 858163db210d04e3c7f70a9e5d20b067e36415fd | f531fdb1663c4f067187a925622e0bfa4ae4b628 | |||
v1.0 | instruct | Filter | Filter_74157_I | Could you provide a Python script that filters a list of numbers and returns only those that are prime numbers? A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. | def is_prime(n):
"""
Determines if n is a prime number.
Parameters:
n (int): The number to check.
Returns:
bool: True if n is a prime number, else False.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
... | from solution import filter_prime_numbers
def test_no_primes_in_list():
assert filter_prime_numbers([0, 1, 4, 6, 8, 9, 10]) == []
def test_all_primes_in_list():
assert filter_prime_numbers([2, 3, 5, 7, 11]) == [2, 3, 5, 7, 11]
def test_mixed_primes_and_non_primes():
assert filter_prime_numbers([2, 3, 4, ... | [
{
"docstring": "Determines if n is a prime number.\n\nParameters:\n n (int): The number to check.\n \nReturns:\n bool: True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filte... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is prime.\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074157",
"row_id": 74157,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150411']"
} | 0.663779 | Filter_74157 | I | [
"is_prime",
"filter_prime_numbers"
] | 2 | [
[
"filter_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4a675dfa8876603b18f215443265131213db91be | 05b0c609a0c1de47f7ff52b0e4fc020c6f35b6a6 | |||
v1.0 | instruct | Filter | Filter_74168_I | Hello, I'm looking to implement a neural network from scratch using numpy for a simple XOR problem. Can you guide me through the process? | 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 with random values."""
... | import numpy as np
from solution import sigmoid, sigmoid_derivative, initialize_weights, forward_propagation, back_propagation, train, predict
def test_sigmoid():
assert np.allclose(sigmoid(0), 0.5)
assert np.allclose(sigmoid(np.array([-1, 0, 1])), [0.26894, 0.5, 0.73106], atol=1e-5)
def test_sigmoid_derivati... | [
{
"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... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\nclass SimpleNeuralNetwork:\n def __init__(self):\n # Seed the random number generator for consistency\n np.random.seed(42)\n\n # Initialize weight... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074168",
"row_id": 74168,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150428']"
} | 0.389361 | Filter_74168 | I | [
"sigmoid",
"sigmoid_derivative",
"initialize_weights",
"forward_propagation",
"back_propagation",
"train",
"predict"
] | 7 | [
[
"back_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"predict",
"forward_propagation"
],
[
"train",
"back_propagation"
],
[
"train",
"forward_propagation"
],
[
"train",
"initialize_weights"
]
] | 6 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 8f409f2b17278f430ea0bd1644cfd7e34f3f0fd9 | 5e9e03616bef50ba8edc81043f8de5076580c176 | |||
v1.0 | instruct | Filter | Filter_74193_I | Given a string `s` and a list of strings `dict`, find the longest word in the dictionary that is a subsequence of `s`. If there are multiple longest words, return the lexicographically smallest one. If no such word exists, return an empty string. | def is_subsequence(x, y):
"""
Check if y is a subsequence of x.
"""
it = iter(x)
return all(c in it for c in y)
def findLongestWord(s, d):
"""
Find the longest word in the dictionary that is a subsequence of the given string.
If there are multiple longest words, return the lexicographic... | from solution import is_subsequence, findLongestWord
def test_is_subsequence():
assert is_subsequence("abpcplea", "apple")
assert not is_subsequence("abpcplea", "monkey")
assert is_subsequence("abc", "abc")
assert is_subsequence("abcde", "ace")
assert not is_subsequence("abcde", "aec")
def test_fi... | [
{
"docstring": "Check if y is a subsequence of x.",
"function_declaration": "def is_subsequence(x, y):",
"function_name": "is_subsequence",
"parameter_list": "(x, y)"
},
{
"docstring": "Find the longest word in the dictionary that is a subsequence of the given string.\nIf there are multiple ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_subsequence(x, y):\n it = iter(y)\n return all(c in it for c in x)\n\ndef find_longest_word(s, dict):\n longest_word = ''\n for word in dict:\n if is_subsequence(word... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00074193",
"row_id": 74193,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150475']"
} | 0.725408 | Filter_74193 | I | [
"is_subsequence",
"findLongestWord"
] | 2 | [
[
"findLongestWord",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d5ae3d683b3c3ccfa49ddf0851e2f10a786f7e48 | 4b8ca4e3646882a5dea2f6ca09ae1d1f6615ff8c | |||
v1.0 | instruct | Filter | Filter_74208_I | I want to generate some Python code to simulate a simple hangman game. Can you provide a basic example? | import random
def get_random_word(word_list):
"""
Selects a random word from the given list of words.
"""
return random.choice(word_list)
def display_word_state(word, guessed_letters):
"""
Returns a string representing the current state of the guessed word.
"""
return ''.join(letter if... | from solution import get_random_word, display_word_state, is_word_guessed
def test_get_random_word():
word_list = ["python", "hangman", "challenge"]
word = get_random_word(word_list)
assert word in word_list
def test_display_word_state_initial():
word = "hangman"
guessed_letters = set()
assert... | [
{
"docstring": "Selects a random word from the given list of words.",
"function_declaration": "def get_random_word(word_list):",
"function_name": "get_random_word",
"parameter_list": "(word_list)"
},
{
"docstring": "Returns a string representing the current state of the guessed word.",
"... | [
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_random_word(word_list):\n \"\"\"\n Selects a random word from the given list of words.\n \"\"\"\n return random.choice(word_list)\n\ndef display_word_state... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00074208",
"row_id": 74208,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_150511']"
} | 0.404077 | Filter_74208 | I | [
"get_random_word",
"display_word_state",
"is_word_guessed",
"hangman"
] | 4 | [
[
"hangman",
"display_word_state"
],
[
"hangman",
"get_random_word"
],
[
"hangman",
"is_word_guessed"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 864c26bf9a8cb3b5299f4a554c918b32024fdeb9 | ab042dba77c633a1bf90ee4cc42255aa19196532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.