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_18297_I | Can you write a code for creating a simple chat system. Please use the socket library in python for network communication and threading library for handling multiple clients. | import socket
import threading
def handle_client(client_socket, clients):
"""
Handle communication with a connected client.
"""
try:
while True:
message = client_socket.recv(1024).decode('utf-8')
if not message:
break
broadcast_message(message... | import socket
import threading
import time
import pytest
# Assuming the chat server and client code is in a file named 'solution.py'
from solution import start_chat_server, start_chat_client
def test_chat_system(monkeypatch):
server_thread = threading.Thread(target=start_chat_server)
server_thread.daemon = Tr... | [
{
"docstring": "Handle communication with a connected client.",
"function_declaration": "def handle_client(client_socket, clients):",
"function_name": "handle_client",
"parameter_list": "(client_socket, clients)"
},
{
"docstring": "Broadcast a message to all connected clients except the send... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport threading\n\ndef handle_client(client_socket, addr):\n print(f\"[NEW CONNECTION] {addr} connected.\")\n \n while True:\n try:\n message = clien... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00018297",
"row_id": 18297,
"seed_ids": "['Llama-3.3-70B-Instruct_46367']"
} | 0.531717 | Filter_18297 | I | [
"handle_client",
"broadcast_message",
"start_chat_server",
"start_chat_client"
] | 4 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f5f40ef9a17cacbe3af23fe6d8dc3604a4c6fdc | 16f270b3da462d1c4707ae970a6533168eab780f | |||
v1.0 | instruct | Filter | Filter_18334_I | I have a list of permutations of a certain list of elements and I want to check if any of the permutations contain a certain sequence of elements.
For example, if my list of elements is [1,2,3] and my sequence is [1,2], I want to check if any of the permutations of the list contain the sequence [1,2].
I have been usi... | import itertools
def generate_permutations(elements):
"""
Generates all permutations of the given list of elements.
"""
perms = [''.join(map(str, p)) for p in itertools.permutations(elements)]
return perms
def does_permutation_contain_sequence(elements, sequence):
"""
Checks if any permuta... | from solution import generate_permutations, does_permutation_contain_sequence
def test_generate_permutations():
elements = [1, 2, 3]
expected_perms = ['123', '132', '213', '231', '312', '321']
assert generate_permutations(elements) == expected_perms
def test_does_permutation_contain_sequence():
assert... | [
{
"docstring": "Generates all permutations of the given list of elements.",
"function_declaration": "def generate_permutations(elements):",
"function_name": "generate_permutations",
"parameter_list": "(elements)"
},
{
"docstring": "Checks if any permutation of the elements contains the seque... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef generate_permutations(elements):\n \"\"\"\n Generates all permutations of a list of elements.\n\n Args:\n elements (list): List of elements\n\n Returns:\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00018334",
"row_id": 18334,
"seed_ids": "['Llama-3.3-70B-Instruct_46453']"
} | 0.565401 | Filter_18334 | I | [
"generate_permutations",
"does_permutation_contain_sequence"
] | 2 | [
[
"does_permutation_contain_sequence",
"generate_permutations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27d0aa520f23ec90e6adc6fa5c73ac0fee21421a | bf4481efc5bb997469516a1e3f33ae9e475e867e | |||
v1.0 | instruct | Filter | Filter_18347_I | I'm writing an app that needs to determine the best way to get from point A to point B. Let's assume we have an array of points of interest (unsorted, unique) and the cost of travel between any two points is the Euclidean distance between the points. The goal is to find the shortest possible route that visits every poi... | import math
from itertools import permutations
def euclidean_distance(point1, point2):
"""Calculates the Euclidean distance between two points."""
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def total_distance(perm):
"""Calculates the total distance of a given permutation of ... | from solution import euclidean_distance, total_distance, tsp_brute_force
def test_euclidean_distance():
assert math.isclose(euclidean_distance((0, 0), (3, 4)), 5)
assert math.isclose(euclidean_distance((0, 0), (0, 0)), 0)
assert math.isclose(euclidean_distance((1, 1), (4, 5)), 5)
def test_total_distance()... | [
{
"docstring": "Calculates the Euclidean distance between two points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Calculates the total distance of a given permutation of po... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom itertools import permutations\n\ndef euclidean_distance(point1, point2):\n \"\"\"Calculates the Euclidean distance between two points.\"\"\"\n return math.sqrt((point1[... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00018347",
"row_id": 18347,
"seed_ids": "['Llama-3.3-70B-Instruct_46473']"
} | 0.551774 | Filter_18347 | I | [
"euclidean_distance",
"total_distance",
"tsp_brute_force"
] | 3 | [
[
"total_distance",
"euclidean_distance"
],
[
"tsp_brute_force",
"total_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f0d77462f723e9829f22c42ee8a66f02aab4ce75 | f2cdf999b83f25c057f92d75efbc07e04af165ba | |||
v1.0 | instruct | Filter | Filter_18351_I | I want to write a module to export a set of selected user defined functions from a specific directory. Below is a simplified version of my python code.
```python
import os
import importlib.util
def import_module_from_path(module_path):
spec = importlib.util.spec_from_file_location("module.name", module_path)
... | import os
import importlib.util
import inspect
def import_module_from_path(module_path):
spec = importlib.util.spec_from_file_location("module.name", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def get_all_functions(module):
return [fun... | import os
from tempfile import TemporaryDirectory
import importlib.util
def test_export_selected_functions():
with TemporaryDirectory() as tmpdir:
# Create a module file with some functions
module_path = os.path.join(tmpdir, "test_module.py")
with open(module_path, 'w') as f:
f.... | [
{
"docstring": null,
"function_declaration": "def import_module_from_path(module_path):",
"function_name": "import_module_from_path",
"parameter_list": "(module_path)"
},
{
"docstring": null,
"function_declaration": "def get_all_functions(module):",
"function_name": "get_all_function... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def export_selected_functions(module, selected_function_names, export_path):\n \"\"\"\n Exports selected functions from a module to a new file.\n \n :param module: The module objec... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00018351",
"row_id": 18351,
"seed_ids": "['Llama-3.3-70B-Instruct_46488']"
} | 0.492265 | Filter_18351 | I | [
"import_module_from_path",
"get_all_functions",
"get_function_code",
"export_selected_functions"
] | 4 | [
[
"export_selected_functions",
"get_function_code"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d94e6e0127e4dd0091c533150f5f72850657750f | 882a0dd777c60bcab2a9a44bca6b132932a283cf | |||
v1.0 | instruct | Filter | Filter_18376_I | ### Python Script to monitor and send Email if the system's CPU usage goes beyond a certain threshold | import psutil
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to_email, from_email, from_email_password, smtp_server, smtp_port):
"""
Send an email with the specified subject and body.
"""
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
... | from unittest.mock import patch, MagicMock
import solution
TO_EMAIL = "to@example.com"
FROM_EMAIL = "from@example.com"
FROM_EMAIL_PASSWORD = "password"
SMTP_SERVER = "smtp.example.com"
SMTP_PORT = 587
@patch("solution.psutil.cpu_percent")
@patch("solution.send_email")
def test_check_cpu_usage_threshold_exceeded(mock_... | [
{
"docstring": "Send an email with the specified subject and body.",
"function_declaration": "def send_email(subject, body, to_email, from_email, from_email_password, smtp_server, smtp_port):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, from_email, from_email_passwor... | [
0,
0,
0,
1,
1,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"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\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_cpu_usage(threshold):\n \"\"\"\n Check the current CPU us... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00018376",
"row_id": 18376,
"seed_ids": "['Llama-3.3-70B-Instruct_46542']"
} | 0.629543 | Filter_18376 | I | [
"send_email",
"check_cpu_usage"
] | 2 | [
[
"check_cpu_usage",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | e52eb316dab89469ede2189ba885048a1603381d | 79df54d533733a463fd9ac3914c9944b6f7d36f0 | |||
v1.0 | instruct | Filter | Filter_18540_I | I have a 5x5 grid, I want to randomly place a 2x2 square in the grid such that it doesn't overlap with any existing 2x2 squares. I need to return the coordinates of the 2x2 square's top left corner.
Here's my code:
```python
import random
def get_available_positions(grid_size):
available_positions = []
for i... | import random
def get_valid_positions(grid, grid_size):
valid_positions = []
for i in range(grid_size - 1):
for j in range(grid_size - 1):
if is_valid_position(grid, (i, j)):
valid_positions.append((i, j))
return valid_positions
def is_valid_position(grid, position):
... | import pytest
from solution import is_valid_position, place_square, get_random_position, get_valid_positions
def test_is_valid_position():
grid = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
assert is_valid_position(grid, ... | [
{
"docstring": null,
"function_declaration": "def get_valid_positions(grid, grid_size):",
"function_name": "get_valid_positions",
"parameter_list": "(grid, grid_size)"
},
{
"docstring": null,
"function_declaration": "def is_valid_position(grid, position):",
"function_name": "is_valid... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_available_positions(grid, grid_size):\n available_positions = []\n for i in range(grid_size - 1):\n for j in range(grid_size - 1):\n if is_vali... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00018540",
"row_id": 18540,
"seed_ids": "['Llama-3.3-70B-Instruct_46924']"
} | 0.590576 | Filter_18540 | I | [
"get_valid_positions",
"is_valid_position",
"place_square",
"get_random_position",
"main"
] | 5 | [
[
"get_random_position",
"get_valid_positions"
],
[
"get_valid_positions",
"is_valid_position"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fd5769372dfd28742b99174a6557e39135c20623 | f9510dcec4ec80aaa79e88fdc29075234d5c0a19 | |||
v1.0 | instruct | Filter | Filter_18692_I | This is my prompt: Write a program that can solve a Rubik's Cube.
I have added, the constraints that the program should be performed in a relatively short period of time, around 20 to 30 seconds, and the algorithm used should be relatively simple.
Given these requirements, I want an analysis of the algorithm used and ... | def cross(cube):
"""
Solve the cross on the given face of the cube.
"""
# Simulated implementation
return "Cross solved"
def f2l(cube):
"""
Solve the first two layers of the cube.
"""
# Simulated implementation
return "First two layers solved"
def oll(cube):
"""
Orient ... | from solution import solve_rubiks_cube, cross, f2l, oll, pll
def test_cross():
assert cross("scrambled cube") == "Cross solved"
def test_f2l():
assert f2l("cross solved cube") == "First two layers solved"
def test_oll():
assert oll("f2l solved cube") == "Last layer oriented"
def test_pll():
assert p... | [
{
"docstring": "Solve the cross on the given face of the cube.",
"function_declaration": "def cross(cube):",
"function_name": "cross",
"parameter_list": "(cube)"
},
{
"docstring": "Solve the first two layers of the cube.",
"function_declaration": "def f2l(cube):",
"function_name": "f... | [
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import kociemba\n\ndef solve_rubiks_cube(cube_state):\n \"\"\"\n Solves a Rubik's Cube using the Two-Phase Algorithm.\n \n Parameters:\n cube_state (str... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00018692",
"row_id": 18692,
"seed_ids": "['Llama-3.3-70B-Instruct_47277']"
} | 0.419061 | Filter_18692 | I | [
"cross",
"f2l",
"oll",
"pll",
"solve_rubiks_cube"
] | 5 | [
[
"solve_rubiks_cube",
"cross"
],
[
"solve_rubiks_cube",
"f2l"
],
[
"solve_rubiks_cube",
"oll"
],
[
"solve_rubiks_cube",
"pll"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 52928249ed6f27ce4cba67d7cf6bd6ac299e1c4a | e9c655549fa6e3e147084ade861ee23bcebb6fab | |||
v1.0 | instruct | Filter | Filter_18764_I | ### Toxic Comment Classification
Toxic Comment Classification is the task of identifying toxic comments on social platforms. In this task, you will build a model to classify comments as toxic and non-toxic.
#### Problem Statement
Given a dataset of comments with corresponding labels (toxic or non-toxic), train a model ... | # Import necessary libraries
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from sklearn.naive_bayes import MultinomialNB
import warnings
# Suppress warnings for clean output
warnings.filterwarnin... | import pytest
from solution import load_and_preprocess_data, train_and_evaluate_model, classify_comments
# Testing Functions for Toxic Comment Classification
# Helper function to simulate a dataset
def create_dummy_dataset():
import pandas as pd
data = {
'comment': [
"You are a fool", ... | [
{
"docstring": "Load and preprocess dataset from the given file path.\n\nParameters:\nfilepath (str): Path to the dataset file\n\nReturns:\ntuple: Returns the features and labels split into training and testing sets",
"function_declaration": "def load_and_preprocess_data(filepath):",
"function_name": "l... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score\nfrom sklearn.naive... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00018764",
"row_id": 18764,
"seed_ids": "['Llama-3.3-70B-Instruct_47446']"
} | 0.547678 | Filter_18764 | I | [
"load_and_preprocess_data",
"train_and_evaluate_model",
"classify_comments"
] | 3 | [
[
"classify_comments",
"load_and_preprocess_data"
],
[
"classify_comments",
"train_and_evaluate_model"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | f9ff64da56c662581868cba1f72aafdfd9750c36 | 518b6fe1eed638b691acd1c7dafbbd3efe3eb038 | |||
v1.0 | instruct | Filter | Filter_18827_I | ### Introduction to Neural Networks
#### Introduction
Given a dataset of images, we can train a neural network to guess the correct digit. In this problem, we will use a simple neural network with 2 layers (one hidden layer).
The network can be defined as follows:
- The first layer is a linear layer with 784 inputs an... | import numpy as np
def relu(x):
return np.maximum(x, 0)
def d_relu(x):
return (x > 0).astype(int)
def softmax(x):
exp_x = np.exp(x - np.max(x))
return exp_x / exp_x.sum(axis=1, keepdims=True)
def cross_entropy(predictions, targets):
n_samples = predictions.shape[0]
res = predictions[range(n_... | import numpy as np
from solution import train_neural_network, relu, softmax, cross_entropy, forward_prop
def test_relu():
assert np.array_equal(relu(np.array([-1, 0, 1])), np.array([0, 0, 1]))
def test_softmax():
x = np.array([[1, 2, 3], [1, 2, 3]])
expected_output = np.array([[0.09003057, 0.24472847, 0.6... | [
{
"docstring": null,
"function_declaration": "def relu(x):",
"function_name": "relu",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def d_relu(x):",
"function_name": "d_relu",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declara... | [
0,
0,
0,
1,
1,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef relu(x):\n return np.maximum(x, 0)\n\ndef d_relu(x):\n return (x > 0).astype(float)\n\ndef softmax(x):\n exp_x = np.exp(x - np.max(x))\n return exp_x / np... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00018827",
"row_id": 18827,
"seed_ids": "['Llama-3.3-70B-Instruct_47602']"
} | 0.650886 | Filter_18827 | I | [
"relu",
"d_relu",
"softmax",
"cross_entropy",
"accuracy",
"forward_prop",
"back_prop",
"train_neural_network"
] | 8 | [
[
"back_prop",
"d_relu"
],
[
"forward_prop",
"relu"
],
[
"forward_prop",
"softmax"
],
[
"train_neural_network",
"accuracy"
],
[
"train_neural_network",
"back_prop"
],
[
"train_neural_network",
"cross_entropy"
],
[
"train_neural_network",
... | 7 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | df3d4ebcfb7387a9c9ae8b1ab5665b311295b98e | e4e2424a2aa3153d62766c2b83e13a20c812e687 | |||
v1.0 | instruct | Filter | Filter_18832_I | I am a high school student and I am using Python as my first programming language. I was assigned the task of making a simple text-based calculator. The program must use a dictionary to store the user's previous calculations.
Here is the code I have written so far:
```python
# Define a dictionary to store previous ca... | # Define a dictionary to store previous calculations
previous_calculations = {}
# Function to perform calculations
def perform_calculation(num1, num2, operator):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
... | from solution import perform_calculation, store_calculation, update_calculation, previous_calculations
def test_perform_calculation():
assert perform_calculation(3, 4, "+") == 7
assert perform_calculation(10, 5, "-") == 5
assert perform_calculation(2, 3, "*") == 6
assert perform_calculation(10, 2, "/")... | [
{
"docstring": null,
"function_declaration": "def perform_calculation(num1, num2, operator):",
"function_name": "perform_calculation",
"parameter_list": "(num1, num2, operator)"
},
{
"docstring": null,
"function_declaration": "def store_calculation(num1, num2, operator, result):",
"f... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Define a dictionary to store previous calculations\nprevious_calculations = {}\n\n# Function to perform calculations\ndef perform_calculation(num1, num2, operator):\n if operator == \"+\"... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00018832",
"row_id": 18832,
"seed_ids": "['Llama-3.3-70B-Instruct_47610']"
} | 0.542324 | Filter_18832 | I | [
"perform_calculation",
"store_calculation",
"update_calculation",
"main"
] | 4 | [
[
"update_calculation",
"perform_calculation"
],
[
"update_calculation",
"store_calculation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 853bbf22279930f462fa5561f092a1f764362eb2 | 245d96fe497d62b8785ae09c10c1683c3a4cafe5 | |||
v1.0 | instruct | Filter | Filter_18865_I | I've got a situation where I need to write a Python script to read a list of files from a directory, process the data, and then output the processed data to a new file. The directory contains a mix of different file types (csv, json, txt) and I'd like to handle each type differently. Can you help me provide a basic str... | import os
import csv
import json
def process_csv(file_path):
with open(file_path, mode='r') as file:
reader = csv.reader(file)
processed_data = [row for row in reader]
return processed_data
def process_json(file_path):
with open(file_path, mode='r') as file:
data = json.load(file)
... | import os
import json
import csv
from solution import process_csv, process_json, process_txt, process_directory, output_processed_data
def create_test_file(filepath, data):
with open(filepath, 'w') as file:
if filepath.endswith('.csv'):
writer = csv.writer(file)
for row in data:
... | [
{
"docstring": null,
"function_declaration": "def process_csv(file_path):",
"function_name": "process_csv",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def process_json(file_path):",
"function_name": "process_json",
"parameter_list": "(file_pa... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport pandas as pd\nimport json\n\ndef process_csv(file_path):\n # Read CSV file\n df = pd.read_csv(file_path)\n # Processing logic here\n # Example: drop NaN values\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00018865",
"row_id": 18865,
"seed_ids": "['Llama-3.3-70B-Instruct_47700']"
} | 0.601771 | Filter_18865 | I | [
"process_csv",
"process_json",
"process_txt",
"process_directory",
"output_processed_data"
] | 5 | [
[
"process_directory",
"process_csv"
],
[
"process_directory",
"process_json"
],
[
"process_directory",
"process_txt"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ec7bb9a64d158ca5d13db170c4f905e89e96d0e2 | 8db5a0fe0640fdd2abb36659be4087078c6ab7ab | |||
v1.0 | instruct | Filter | Filter_19083_I | I have some points of interest in 3D space and I want to classify them into clusters based on their 3D coordinates. I'm using the K-Means algorithm with Manhattan distance.
Here's my Python code:
```python
import numpy as np
def kmeans(X, k):
n = len(X)
# Randomly initialize centroids
centroids = X[np.ran... | import numpy as np
def manhattan_distance(a, b):
"""
Compute the Manhattan distance between two 3D points.
"""
return np.sum(np.abs(a - b))
def kmeans(X, k):
"""
Applies K-Means clustering using Manhattan distance.
Parameters:
X (numpy.ndarray): A 2D array where each row is a 3D p... | import numpy as np
from solution import kmeans, manhattan_distance
def test_manhattan_distance():
assert manhattan_distance(np.array([1, 2, 3]), np.array([4, 5, 6])) == 9
assert manhattan_distance(np.array([1, 2]), np.array([4, 2])) == 3
assert manhattan_distance(np.array([1, 2, 3]), np.array([1, 2, 3])) =... | [
{
"docstring": "Compute the Manhattan distance between two 3D points.",
"function_declaration": "def manhattan_distance(a, b):",
"function_name": "manhattan_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Applies K-Means clustering using Manhattan distance.\n\nParameters:\nX (numpy.... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef kmeans(X, k, max_iters=100):\n n = len(X)\n # Randomly initialize centroids\n centroids = X[np.random.choice(n, k, replace=False)]\n\n for _ in range(max_... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00019083",
"row_id": 19083,
"seed_ids": "['Llama-3.3-70B-Instruct_48230']"
} | 0.628219 | Filter_19083 | I | [
"manhattan_distance",
"kmeans"
] | 2 | [
[
"kmeans",
"manhattan_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 1268d4416f7bd0ee71bd0018c4d3dfccc784c5e4 | 90d63de9a95e06ad5d156cd44f5e7dc147109d6c | |||
v1.0 | instruct | Filter | Filter_19097_I | ### Question 1: Understanding Neural Networks
# Question 1:
# Define a function that calculates the ReLU (Rectified Linear Unit) activation function for a given input. The ReLU function is defined as f(x) = max(0, x).
def relu(x):
if x > 0:
return x
else:
return 0
# Question 2:
# Now let's i... | def relu(x):
"""
Calculates the ReLU (Rectified Linear Unit) activation function.
Returns max(0, x)
"""
return max(0, x)
def neural_network(x):
"""
Calculates the output of a simple neural network with:
- 1 input unit
- 1 hidden layer with 2 neurons
- 1 output neuron
We... | from solution import relu, neural_network
def test_relu():
assert relu(-1) == 0
assert relu(0) == 0
assert relu(1) == 1
assert relu(10) == 10
def test_neural_network():
assert neural_network(-1) == relu(relu(-0.5) * 0.2 + relu(-0.1) * 0.4 + 0.3)
assert neural_network(0) == relu(relu(0.1) * 0.2... | [
{
"docstring": "Calculates the ReLU (Rectified Linear Unit) activation function.\nReturns max(0, x)",
"function_declaration": "def relu(x):",
"function_name": "relu",
"parameter_list": "(x)"
},
{
"docstring": "Calculates the output of a simple neural network with:\n- 1 input unit\n- 1 hidden... | [
0,
0,
0,
1,
1,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def relu(x):\n \"\"\"\n Returns the result of the ReLU activation function: max(0, x).\n \"\"\"\n return max(0, x)\n\ndef neural_network(x):\n \"\"\"\n Calculates the output ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00019097",
"row_id": 19097,
"seed_ids": "['Llama-3.3-70B-Instruct_48260']"
} | 0.421178 | Filter_19097 | I | [
"relu",
"neural_network"
] | 2 | [
[
"neural_network",
"relu"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f6e8e4f8599f3627aaf348182745ae82261aa88c | 31b4d2dd29172504e24d129fbaff895bbe8c9ee6 | |||
v1.0 | instruct | Filter | Filter_19174_I | Building on the classic "guess my number" game, I'd like to create a game where the user thinks of a number between 1 and 100, and the computer tries to guess it in as few attempts as possible. The computer will ask for hints in the form of "too high" or "too low" after each guess.
To make things more interesting, let... | import random
def guess_number():
"""
Function to play a single round of the Guess My Number game where the computer tries to guess the user's number.
The user provides feedback if the guess is too high, too low, or correct.
"""
attempts = 0
min_value = 1
max_value = 100
while True:
... | import pytest
from unittest.mock import patch
from solution import guess_number, play_game
def test_guess_number_correct_on_first_try():
inputs = iter(['correct'])
with patch('builtins.input', lambda _: next(inputs)):
assert guess_number() == 1
def test_guess_number_too_high_then_correct():
inputs... | [
{
"docstring": "Function to play a single round of the Guess My Number game where the computer tries to guess the user's number.\nThe user provides feedback if the guess is too high, too low, or correct.",
"function_declaration": "def guess_number():",
"function_name": "guess_number",
"parameter_lis... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass GuessMyNumber:\n def __init__(self):\n self.total_attempts = 0\n self.rounds_played = 0\n\n def guess_number(self):\n attempts = 0\n mi... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00019174",
"row_id": 19174,
"seed_ids": "['Llama-3.3-70B-Instruct_48426']"
} | 0.600722 | Filter_19174 | I | [
"guess_number",
"play_game"
] | 2 | [
[
"play_game",
"guess_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b96477502f72cd4392a4dca340b270fc15effca3 | 1f959f00de0d78b560c3374863106efaf587767b | |||
v1.0 | instruct | Filter | Filter_19203_I | Let $n$ be a positive integer, and let $A = \{a_1, a_2, \ldots, a_n\}$ be a set of positive integers. Write a recursive function in Python to compute the greatest common divisor (GCD) of two positive integers, $m$ and $n$, and apply this function to every pair of integers in set $A$ to compute the GCD of all pairs and ... | from math import gcd
from itertools import combinations
def recursive_gcd(m, n):
"""
Function to compute the GCD of two positive integers using recursion.
"""
if n == 0:
return m
else:
return recursive_gcd(n, m % n)
def gcd_of_all_pairs(A):
"""
Function to compute the GCD o... | from solution import recursive_gcd, gcd_of_all_pairs
def test_recursive_gcd():
assert recursive_gcd(48, 18) == 6
assert recursive_gcd(101, 10) == 1
assert recursive_gcd(54, 24) == 6
assert recursive_gcd(0, 5) == 5
assert recursive_gcd(5, 0) == 5
def test_gcd_of_all_pairs():
assert gcd_of_all_p... | [
{
"docstring": "Function to compute the GCD of two positive integers using recursion.",
"function_declaration": "def recursive_gcd(m, n):",
"function_name": "recursive_gcd",
"parameter_list": "(m, n)"
},
{
"docstring": "Function to compute the GCD of every pair of integers in the set A\nand ... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(m, n):\n \"\"\"\n Computes the greatest common divisor (GCD) of two positive integers using recursion.\n \"\"\"\n if n == 0:\n return m\n return gcd(n, m % n)\n\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00019203",
"row_id": 19203,
"seed_ids": "['Llama-3.3-70B-Instruct_48500']"
} | 0.730448 | Filter_19203 | I | [
"recursive_gcd",
"gcd_of_all_pairs"
] | 2 | [
[
"gcd_of_all_pairs",
"recursive_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4694310bd3a76c56b2ae65494cfdda82fa5862d2 | 26777a0dbd5ad7dadfe2ff7308ed9e0821d1e980 | |||
v1.0 | instruct | Filter | Filter_19468_I | How do I apply gravity to a group of objects in a 3D space using python programming?
I need to help simulate the orbits of planets in a solar system.
This should be a simplified model and should not accurately represent every aspect of astrophysical reality.
A simple and intuitive implementation is desired.
You... | import numpy as np
class Planet:
def __init__(self, name, mass, position, velocity):
self.name = name
self.mass = mass
self.position = np.array(position, dtype=float)
self.velocity = np.array(velocity, dtype=float)
self.acceleration = np.array([0, 0, 0], dtype=float)
def co... | from solution import Planet, simulate
def test_gravitational_interaction_two_planets():
planet1 = Planet("Planet1", 1e24, [0, 0, 0], [0, 0, 0])
planet2 = Planet("Planet2", 1e24, [1e6, 0, 0], [0, 1, 0])
planets = [planet1, planet2]
simulate(planets, num_steps=1, dt=1)
assert planet1.position[0] !=... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\nclass Planet:\n def __init__(self, mass, position, velocity):\n self.mass = mass\n self.position = np.array(position, dtype=float)\n self.velocity... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00019468",
"row_id": 19468,
"seed_ids": "['Llama-3.3-70B-Instruct_49193']"
} | 0.459275 | Filter_19468 | I | [
"compute_gravitational_force",
"update_acceleration",
"update_velocity_and_position",
"simulate"
] | 4 | [
[
"simulate",
"update_acceleration"
],
[
"simulate",
"update_velocity_and_position"
],
[
"update_acceleration",
"compute_gravitational_force"
]
] | 3 | [] | false | [
"Planet"
] | true | pytest | true | [
"numpy"
] | false | b4858659ca97c142351566bd1ad956da5c63c620 | 65313ad36230517fd8246b62fdf12bd7cc6dd7df | |||
v1.0 | instruct | Filter | Filter_19557_I | I have been given a task to generate a convex hull using the Graham's scan algorithm. I have a set of 2D points and I want to generate a convex hull using Python.
Here's a sample set of points:
[(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3)]
I want to generate a convex hull that can give me the minimum con... | import math
# Function to calculate orientation of an ordered triplet
def orientation(p, q, r):
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
if val == 0:
return 0 # Collinear
return 1 if val > 0 else 2 # Clockwise or counterclockwise
def dist_sq(p1, p2):
return (p1[0] ... | import pytest
from solution import convex_hull
def test_smallest_convex_hull_possible():
assert convex_hull([(0, 0), (1, 1), (2, 2)]) == [(0, 0), (2, 2)]
def test_point_on_boundary():
points = [(0, 0), (1, 1), (2, 2), (1, 0), (0, 2)]
result = convex_hull(points)
assert set(result) == {(0, 0), (2, 2), ... | [
{
"docstring": null,
"function_declaration": "def orientation(p, q, r):",
"function_name": "orientation",
"parameter_list": "(p, q, r)"
},
{
"docstring": null,
"function_declaration": "def dist_sq(p1, p2):",
"function_name": "dist_sq",
"parameter_list": "(p1, p2)"
},
{
"d... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef orientation(p, q, r):\n \"\"\"\n Return orientation of the triplet (p, q, r).\n 0 -> p, q and r are collinear\n 1 -> Clockwise\n 2 -> Counterclockwise\n \"... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00019557",
"row_id": 19557,
"seed_ids": "['Llama-3.3-70B-Instruct_49363']"
} | 0.396194 | Filter_19557 | I | [
"orientation",
"dist_sq",
"convex_hull"
] | 3 | [
[
"convex_hull",
"dist_sq"
],
[
"convex_hull",
"orientation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0fbf44a03676cee1b62c4fc511d8e6f1403cdca6 | 4f5d3d6854bd4aa3751cae2e58648fee5b67ed2d | |||
v1.0 | instruct | Filter | Filter_19577_I | ### Description
Dr. Lee wants to assign an ID to each of his patients based on an alphabetical order. The ID will be a mix of capital letters and numbers. The ID should be unique and non repeating.
Here is how it should work:
- ID should start with a capital letter from A to Z
- After the capital letter, there should... | import string
from itertools import product, chain
def generate_id():
"""
Generate unique IDs following the described pattern.
"""
# One letter, 4 digits, one letter/one digit
for letter in string.ascii_uppercase:
for combination in product(string.digits, repeat=4):
yield f"{let... | import string
from solution import get_next_id, generate_id
def test_generate_id_format():
gen = generate_id()
for _ in range(100): # just checking first 100 ids
next_id = next(gen)
assert isinstance(next_id, str)
assert len(next_id) >= 5 # minimum length 5 for single letter and 4 di... | [
{
"docstring": "Generate unique IDs following the described pattern.",
"function_declaration": "def generate_id():",
"function_name": "generate_id",
"parameter_list": "()"
},
{
"docstring": "Return the next id in the sequence",
"function_declaration": "def get_next_id(ids):",
"functi... | [
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import string\nfrom itertools import product, chain\n\ndef generate_ids():\n \"\"\"\n Generate all unique ids according to the described pattern\n \"\"\"\n # Single letter followed... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00019577",
"row_id": 19577,
"seed_ids": "['Llama-3.3-70B-Instruct_49410']"
} | 0.621769 | Filter_19577 | I | [
"generate_id",
"get_next_id"
] | 2 | [
[
"get_next_id",
"generate_id"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f6b5e553b08e371484114869f729d3ca9b616e82 | 4363aacd06f59a38830beeab34b52ba040575aaf | |||
v1.0 | instruct | Filter | Filter_19580_I | Follow these instructions to write a short program:
Create a program that asks a user for their monthly expenses and income.
Use a dictionary to store the data (like {"Rent": 1000, "Utilities": 150, ...}).
Store the data in the user's file (like user123.json).
Store the expenses in another dictionary and calculate the ... | import json
def get_user_input():
print("Hello! Let's manage your budget.")
name = input("What is your name? ")
return name
def store_data(name, data):
while True:
print("\nDo you want to add an expense, add income, view budget, delete expense, or finish? (type 'expense', 'income', 'view', 'de... | import json
import os
from solution import get_user_input, store_data, save_to_file, load_from_file, calculate_budget
def test_store_data_expense():
data = {"expenses": {}, "income": 0}
name = "test_user"
data["expenses"]["Test Expense"] = 50
save_to_file(name, data)
loaded_data = load_from_file(na... | [
{
"docstring": null,
"function_declaration": "def get_user_input():",
"function_name": "get_user_input",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def store_data(name, data):",
"function_name": "store_data",
"parameter_list": "(name, data)"
},
{
... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef get_user_input():\n print(\"Hello! Let's calculate your budget.\")\n name = input(\"What is your name? \")\n return name\n\ndef store_data(name, expenses={}, income... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00019580",
"row_id": 19580,
"seed_ids": "['Llama-3.3-70B-Instruct_49416']"
} | 0.478658 | Filter_19580 | I | [
"get_user_input",
"store_data",
"save_to_file",
"load_from_file",
"calculate_budget",
"main"
] | 6 | [
[
"store_data",
"calculate_budget"
],
[
"store_data",
"save_to_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 55f206378751c1bf28307141380115bda7cf3926 | f51816cd97031398d314549ae93badbd7306abb0 | |||
v1.0 | instruct | Filter | Filter_19600_I | Please create a High Score list that meets the following requirements:
- Create a High Score list to keep track of the top 10 high scores for a game
- The list must be stored in a file (highscores.txt) that is created if it doesn't already exist
- The list must be sorted in descending order (highest score first)
-... | import os
def load_high_scores(filename="highscores.txt"):
high_scores = []
if os.path.isfile(filename):
with open(filename, "r") as file:
lines = file.readlines()
for line in lines:
name, score = line.strip().split(":")
high_scores.append((name, ... | import os
import pytest
from solution import load_high_scores, add_high_score, save_high_scores
TEST_FILE = "test_highscores.txt"
def setup_function(function):
if os.path.isfile(TEST_FILE):
os.remove(TEST_FILE)
def teardown_function(function):
if os.path.isfile(TEST_FILE):
os.remove(TEST_FILE... | [
{
"docstring": null,
"function_declaration": "def load_high_scores(filename='highscores.txt'):",
"function_name": "load_high_scores",
"parameter_list": "(filename='highscores.txt')"
},
{
"docstring": null,
"function_declaration": "def save_high_scores(high_scores, filename='highscores.tx... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\nhigh_scores = []\n\ndef load_high_scores():\n \"\"\"\n Load high scores from the file if it exists and store them in a global list.\n \"\"\"\n global high_scores\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00019600",
"row_id": 19600,
"seed_ids": "['Llama-3.3-70B-Instruct_49467']"
} | 0.531799 | Filter_19600 | I | [
"load_high_scores",
"save_high_scores",
"add_high_score"
] | 3 | [
[
"add_high_score",
"load_high_scores"
],
[
"add_high_score",
"save_high_scores"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 19527c1e029a00e039f34e2c0a2946b0d95babe7 | 16a278a18e6bf6cded8cf1d208ce8da26cd0180a | |||
v1.0 | instruct | Filter | Filter_19736_I | Here is a list of strings in the variable 'words'. Write a Python function that given a string, finds all the related strings in the list that are one edit away from the given string using Levenshtein distance = 1. | def levenshtein_distance(str1, str2):
"""
Computes the Levenshtein distance between two strings.
"""
if len(str1) < len(str2):
return levenshtein_distance(str2, str1)
if len(str2) == 0:
return len(str1)
previous_row = range(len(str2) + 1)
for i, c1 in enumerate(str1):
... | from solution import find_one_edit_away, levenshtein_distance
def test_levenshtein_distance():
assert levenshtein_distance("kitten", "sitting") == 3
assert levenshtein_distance("flaw", "lawn") == 2
assert levenshtein_distance("gumbo", "gambol") == 2
assert levenshtein_distance("book", "back") == 2
def... | [
{
"docstring": "Computes the Levenshtein distance between two strings.",
"function_declaration": "def levenshtein_distance(str1, str2):",
"function_name": "levenshtein_distance",
"parameter_list": "(str1, str2)"
},
{
"docstring": "Finds all words in the list that are one edit away from the t... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def one_edit_away(word, words):\n \"\"\"\n Given a word and a list of words, finds all the related strings in the list that are one edit away from the given word.\n \"\"\"\n def le... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00019736",
"row_id": 19736,
"seed_ids": "['Llama-3.3-70B-Instruct_49799']"
} | 0.642056 | Filter_19736 | I | [
"levenshtein_distance",
"find_one_edit_away"
] | 2 | [
[
"find_one_edit_away",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b2dd55a894f6508dcd218f401af53e5bf662210 | 31284cd3b81d3a1c859dbd8a8ae4b943da98e5a7 | |||
v1.0 | instruct | Filter | Filter_19750_I | I'm working on a project that requires me to monitor a Bitcoin price every minute and compare it to a specific price range. If the Bitcoin price is within the given range, it will send a notification. Is it possible to implement this kind of project using Python? | import time
import requests
def get_bitcoin_price():
"""
Fetches the current Bitcoin price in USD from CoinGecko API.
"""
response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
data = response.json()
return data['bitcoin']['usd']
def is_price_in_... | from solution import is_price_in_range
def test_is_price_in_range_within_range():
assert is_price_in_range(50000, 40000, 60000) == True
def test_is_price_in_range_below_range():
assert is_price_in_range(30000, 40000, 60000) == False
def test_is_price_in_range_above_range():
assert is_price_in_range(70000... | [
{
"docstring": "Fetches the current Bitcoin price in USD from CoinGecko API.",
"function_declaration": "def get_bitcoin_price():",
"function_name": "get_bitcoin_price",
"parameter_list": "()"
},
{
"docstring": "Checks if the price is within the specified range.",
"function_declaration": ... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport smtplib\nfrom time import sleep\n\ndef get_bitcoin_price():\n \"\"\"\n Fetch the current Bitcoin price using the CoinDesk API.\n \"\"\"\n response = request... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00019750",
"row_id": 19750,
"seed_ids": "['Llama-3.3-70B-Instruct_49839']"
} | 0.449731 | Filter_19750 | I | [
"get_bitcoin_price",
"is_price_in_range",
"notify_user",
"monitor_bitcoin_price"
] | 4 | [
[
"monitor_bitcoin_price",
"get_bitcoin_price"
],
[
"monitor_bitcoin_price",
"is_price_in_range"
],
[
"monitor_bitcoin_price",
"notify_user"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 053d7bcd8bacce87c5b2cf359e662a17cc4f841e | a598aaeced841f659be9644e25328a7d8599f773 | |||
v1.0 | instruct | Filter | Filter_19830_I | I have a fixed length string of 26 letters, where each letter is one of the 26 lowercase English letters. I would like to write a Python program that generates all possible 26 character permutations of these letters, without repetition, and also ensure the string does not contain any consecutive repeating characters.
... | import random
def has_consecutive_repeating_chars(s):
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
return True
return False
def generate_valid_permutation():
characters = list("abcdefghijklmnopqrstuvwxyz")
while True:
random.shuffle(characters)
permutation = "".... | from solution import generate_valid_permutation, has_consecutive_repeating_chars
def test_has_no_consecutive_repeating_chars():
sample_valid_strings = [
"abcdefghijklmnopqrstuvwxyz",
"zxywvutsrqponmlkjihgfedcba",
]
for s in sample_valid_strings:
assert not has_consecutive_repeating_... | [
{
"docstring": null,
"function_declaration": "def has_consecutive_repeating_chars(s):",
"function_name": "has_consecutive_repeating_chars",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def generate_valid_permutation():",
"function_name": "generate_valid_pe... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef generate_valid_permutations(s):\n \"\"\"\n Generates all valid permutations of a 26-character string without any\n consecutive repeating characters.\n \n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00019830",
"row_id": 19830,
"seed_ids": "['Llama-3.3-70B-Instruct_50031']"
} | 0.653579 | Filter_19830 | I | [
"has_consecutive_repeating_chars",
"generate_valid_permutation"
] | 2 | [
[
"generate_valid_permutation",
"has_consecutive_repeating_chars"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6bfecab6020f319c2d15b9193756cea2af829314 | 4d6f831b48e32743dc8ab19e9518dea4a2cfa415 | |||
v1.0 | instruct | Filter | Filter_19906_I | I have a seqeunce file in the format of paired-end reads, and I would like to merge them into single reads.
For example:
```
@1_1
CTGAATGCACTG
+
ABCDEF
@1_2
CTGAATGCACTG
+
DEFABC
```
And my desired output:
```
@1
CTGAATGCACTGDEFABC
+
ABCDEF
```
However, this must be done with the condition of matching read pairs, an... | import gzip
def reverse_complement(dna):
"""
Returns the reverse complement of the given DNA sequence.
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
return ''.join([complement[base] for base in dna[::-1]])
def merge_reads(read1_seq, read1_qual, read2_seq, read2_qual):
"""... | import pytest
from solution import reverse_complement, merge_reads
def test_reverse_complement():
assert reverse_complement("AGTC") == "GACT"
assert reverse_complement("A") == "T"
assert reverse_complement("CGA") == "TCG"
assert reverse_complement("NNNN") == "NNNN"
def test_merge_reads():
read1_se... | [
{
"docstring": "Returns the reverse complement of the given DNA sequence.",
"function_declaration": "def reverse_complement(dna):",
"function_name": "reverse_complement",
"parameter_list": "(dna)"
},
{
"docstring": "Merges a pair of reads into a single read with the second read reverse compl... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import gzip\n\ndef reverse_complement(dna):\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}\n return ''.join([complement[base] for base in dna[::-1]])\n\ndef merge_pair... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00019906",
"row_id": 19906,
"seed_ids": "['Llama-3.3-70B-Instruct_50209']"
} | 0.46089 | Filter_19906 | I | [
"reverse_complement",
"merge_reads",
"main"
] | 3 | [
[
"merge_reads",
"reverse_complement"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0d8b8e5589c0bc2308315bded6fdb6b0e719a3f4 | fa93e9855768e1e354d6440da96074aa88a9f220 | |||
v1.0 | instruct | Filter | Filter_19926_I | I've been trying to implement this algorithm and need some help.
Algorithm description:
There is a grid of lights (10x10) and each light is either on or off. The program generates a random initial state of the light grid. The user can then interact with the grid by clicking on a light to turn it on or off. The progr... | def count_neighbors(i, j, grid):
"""
Count the number of neighbors that are on around the light at position (i, j).
Args:
- i (int): Row index of the light.
- j (int): Column index of the light.
- grid (list of list of bool): The current state of the grid.
Returns:
- int: Numbe... | from solution import count_neighbors, generate_new_grid
def test_count_neighbors_all_off():
grid = [[False for _ in range(10)] for _ in range(10)]
assert count_neighbors(5, 5, grid) == 0
def test_count_neighbors_single_on():
grid = [[False for _ in range(10)] for _ in range(10)]
grid[4][5] = True # A... | [
{
"docstring": "Count the number of neighbors that are on around the light at position (i, j).\n\nArgs:\n- i (int): Row index of the light.\n- j (int): Column index of the light.\n- grid (list of list of bool): The current state of the grid.\n\nReturns:\n- int: Number of neighboring lights that are on.",
"f... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\nimport random\n\nclass LightGrid:\n def __init__(self, master):\n self.master = master\n self.lights = [[False for _ in range(10)] for _ in range(10)]\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00019926",
"row_id": 19926,
"seed_ids": "['Llama-3.3-70B-Instruct_50244']"
} | 0.494415 | Filter_19926 | I | [
"count_neighbors",
"generate_new_grid"
] | 2 | [
[
"generate_new_grid",
"count_neighbors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd138367ab79641261722051825e9533967a5612 | adb65209dbec5b3155eb74f7c73f654090f71879 | |||
v1.0 | instruct | Filter | Filter_20012_I | Here is a scenario for you:
Imagine you have a fair coin. You flip it 5 times, and each time you write down the outcome: heads (H) or tails (T). You do this for a total of 10 rounds.
Using the Python programming language, create a program that simulates this process, and then calculates and displays the following:
1.... | import random
def simulate_round():
"""
Simulate flipping a fair coin 5 times and return the outcomes, total heads, and total tails
"""
outcomes = [random.choice(['H', 'T']) for _ in range(5)]
total_heads = outcomes.count('H')
total_tails = outcomes.count('T')
return outcomes, total_heads, ... | import pytest
from solution import simulate_round
def test_simulate_round():
outcomes, heads, tails = simulate_round()
assert len(outcomes) == 5
assert heads + tails == 5
assert set(outcomes).issubset({'H', 'T'})
# Since simulate_10_rounds prints output to the console, rather than returning values,
# ... | [
{
"docstring": "Simulate flipping a fair coin 5 times and return the outcomes, total heads, and total tails",
"function_declaration": "def simulate_round():",
"function_name": "simulate_round",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def simulate_10_rounds... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef simulate_round():\n outcomes = [random.choice(['H', 'T']) for _ in range(5)]\n return outcomes\n\ndef simulate_10_rounds():\n total_heads = 0\n total_tails = 0... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020012",
"row_id": 20012,
"seed_ids": "['Llama-3.3-70B-Instruct_50448']"
} | 0.570386 | Filter_20012 | I | [
"simulate_round",
"simulate_10_rounds"
] | 2 | [
[
"simulate_10_rounds",
"simulate_round"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3ce4cca099aafdaa552a469119ddfde51445bfc8 | 7ab8b25158beee5be88e30a0c80aca946ae14114 | |||
v1.0 | instruct | Filter | Filter_20197_I | ### Day 2: 1201 Program Alarm
After navigating through the asteroid field, you've reached the half-duplex communications device on the lost probe and downloaded the internal chronometer of the ship. The chronometer has a corrupted legacy 1201 program that has been compiled into Intcode.
The program uses these opcodes:... | def process_intcode(intcode):
"""
Processes the Intcode list as per the 1201 Program Alarm logic.
:param intcode: List of integers representing the Intcode program.
:return: The modified Intcode list after processing.
"""
i = 0
while i < len(intcode):
opcode = intcode[i]
... | import pytest
from solution import process_intcode, sum_of_intcode_values_after_processing
def test_process_intcode():
assert process_intcode([1, 0, 0, 0, 99]) == [2, 0, 0, 0, 99]
assert process_intcode([2, 3, 0, 3, 99]) == [2, 3, 0, 6, 99]
assert process_intcode([2, 4, 4, 5, 99, 0]) == [2, 4, 4, 5, 99, 98... | [
{
"docstring": "Processes the Intcode list as per the 1201 Program Alarm logic.\n\n:param intcode: List of integers representing the Intcode program.\n:return: The modified Intcode list after processing.",
"function_declaration": "def process_intcode(intcode):",
"function_name": "process_intcode",
"... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def run_intcode_program(program):\n \"\"\"\n Runs the provided Intcode program.\n \n Args:\n program (list): The list of integers representing the Intcode program.\n\n Return... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00020197",
"row_id": 20197,
"seed_ids": "['Llama-3.3-70B-Instruct_50869']"
} | 0.500904 | Filter_20197 | I | [
"process_intcode",
"sum_of_intcode_values_after_processing"
] | 2 | [
[
"sum_of_intcode_values_after_processing",
"process_intcode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e76b9e34f48b988af4f3c2c4ff8aec89dbd307f2 | 8e1e53788f1a59379d0e82ee65550c407eaa78d6 | |||
v1.0 | instruct | Filter | Filter_20201_I | Here's the code I've written so far for a binary search algorithm in Python.
```python
def binary_search(array, target):
left = 0
right = len(array) - 1
while left <= right:
mid = (left + right) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
... | def is_sorted(arr):
if arr == sorted(arr):
return True, "asc"
elif arr == sorted(arr, reverse=True):
return True, "desc"
else:
return False, None
def binary_search(arr, target):
is_sorted_result, order = is_sorted(arr)
if not is_sorted_result:
arr.sort()
... | def test_is_sorted():
assert is_sorted([1, 2, 3, 4, 5]) == (True, "asc")
assert is_sorted([5, 4, 3, 2, 1]) == (True, "desc")
assert is_sorted([3, 5, 2, 1, 4]) == (False, None)
def test_binary_search_on_unsorted_array():
arr = [12, 20, 9, 8, 11, 26]
assert binary_search(arr, 20) == arr.index(20)
de... | [
{
"docstring": null,
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, target):",
"function_name": "binary_search",
"parameter_list": "(arr, target)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_sorted(arr):\n \"\"\"\n Check if the array is sorted and in which order.\n Returns a tuple (True/False, \"asc\"/\"desc\"/None).\n \"\"\"\n if arr == sorted(arr):\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020201",
"row_id": 20201,
"seed_ids": "['Llama-3.3-70B-Instruct_50875']"
} | 0.578843 | Filter_20201 | I | [
"is_sorted",
"binary_search"
] | 2 | [
[
"binary_search",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 73210a53f572c389543f089039283fc054033c92 | 575e1c9862a5184d9b5eab22f5e0bee430c92582 | |||
v1.0 | instruct | Filter | Filter_20309_I | I see that the "set encoding" method is not built into Python, but we can use the 'chardet' library. I'd like to use it to detect the encoding of a number of files in a directory.
Could you provide some example code for how to use the 'chardet' library for encoding detection for multiple files? | import os
import chardet
def detect_file_encoding(file_path):
"""
Detects the encoding of a single file.
Parameters:
file_path (str): The path to the file to detect encoding.
Returns:
str: The detected encoding of the file.
"""
with open(file_path, 'rb') as f:
raw_data... | import os
from unittest.mock import patch, mock_open
from solution import detect_file_encoding, detect_directory_encodings
def test_detect_file_encoding():
file_content = "This is a test file.".encode('utf-8')
with patch('builtins.open', mock_open(read_data=file_content)):
assert detect_file_encoding("... | [
{
"docstring": "Detects the encoding of a single file.\n\nParameters:\nfile_path (str): The path to the file to detect encoding.\n\nReturns:\nstr: The detected encoding of the file.",
"function_declaration": "def detect_file_encoding(file_path):",
"function_name": "detect_file_encoding",
"parameter_... | [
0,
0,
0,
1,
1,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport chardet\n\ndef detect_encoding(file_path):\n \"\"\"\n Detects the encoding of the given file.\n \n Parameters:\n file_path (str): Path to the file for which to... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00020309",
"row_id": 20309,
"seed_ids": "['Llama-3.3-70B-Instruct_51108']"
} | 0.657654 | Filter_20309 | I | [
"detect_file_encoding",
"detect_directory_encodings"
] | 2 | [
[
"detect_directory_encodings",
"detect_file_encoding"
]
] | 1 | [] | false | [] | false | pytest | true | [
"chardet"
] | false | e1a0c2f42e72156bbda85504d6f9fdd8fd6ea418 | 448b8f21de245bc05bb5b1efe7145cd5bedee504 | |||
v1.0 | instruct | Filter | Filter_20352_I | I have a python function that I want to add logging to. The function updates a database by deleting some data, deleting a user, and then adding new data for that same user. These actions should be logged in a file with the timestamp, the action, and user id.
Here are the examples of how the log messages should look l... | import logging
from datetime import datetime
# Function to update a database by performing three actions: delete data, delete user, and add data.
def update_database(user_id):
actions = ['delete-data', 'delete-user', 'add-data']
for action in actions:
log_action(action, user_id)
# Perform ... | import os
from solution import update_database
def test_update_database_logs():
# Clear the log file before test
open('log_file.log', 'w').close()
user_id = 12345
update_database(user_id)
with open('log_file.log', 'r') as log_file:
logs = log_file.read().strip().split('\n')
asser... | [
{
"docstring": null,
"function_declaration": "def update_database(user_id):",
"function_name": "update_database",
"parameter_list": "(user_id)"
},
{
"docstring": null,
"function_declaration": "def log_action(action, user_id):",
"function_name": "log_action",
"parameter_list": "(a... | [
0,
0,
0,
0,
0,
1,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import logging\n\n# Create a logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# Create a file handler which logs even debug messages\nfile_handler = logging.FileH... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00020352",
"row_id": 20352,
"seed_ids": "['Llama-3.3-70B-Instruct_51175']"
} | 0.604671 | Filter_20352 | I | [
"update_database",
"log_action"
] | 2 | [
[
"update_database",
"log_action"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4805601814691108cab2a0ad59abaac76f3b2c73 | 9e007a2c487f2a36e00642d94e82cf364d6d03c9 | |||
v1.0 | instruct | Filter | Filter_20375_I | ### Task 5: String Matching
String matching is a problem of finding all the occurrences of a pattern within a text.
Given a text and a pattern, find all occurrences of the pattern in the text and return the starting index of each occurrence.
If the pattern is empty, return an empty list.
For example, if the text is "... | import math
def gcd(a, b):
"""
Compute the greatest common divisor (GCD) of two numbers.
Args:
a (int): first number
b (int): second number
Returns:
int: the GCD of a and b
"""
return math.gcd(a, b)
def simplify_fraction(numerator, denominator):
"""
Si... | from solution import simplify_fraction
def test_simplify_fraction_positive():
assert simplify_fraction(8, 12) == (2, 3)
def test_simplify_fraction_negative():
assert simplify_fraction(-8, -12) == (-2, -3)
def test_simplify_fraction_mixed_signs():
assert simplify_fraction(8, -12) == (2, -3)
assert sim... | [
{
"docstring": "Compute the greatest common divisor (GCD) of two numbers.\n\nArgs:\n a (int): first number\n b (int): second number\n\nReturns:\n int: the GCD of a and b",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\n\ndef simplify_fraction(numerator, denominator):\n \"\"\"\n Simplify a fraction by dividing both numerator and denominator by their greatest common divisor (GCD).\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020375",
"row_id": 20375,
"seed_ids": "['Llama-3.3-70B-Instruct_51210']"
} | 0.646401 | Filter_20375 | I | [
"gcd",
"simplify_fraction"
] | 2 | [
[
"simplify_fraction",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f52b0bec90fa8ffa76b6fbfa2ceb83f23d77eb42 | c6a6169b3cd0dfa3d379a0811930b4a789e45b9d | |||
v1.0 | instruct | Filter | Filter_20489_I | I have decided to implement a recommendation system using a collaborative filtering approach. I have a large matrix where each row represents a user, each column represents an item, and the entry at the i-th row and j-th column is the user i's rating for item j. I want to build a basic system to generate recommendation... | import numpy as np
from scipy.spatial.distance import cosine
def get_similar_users(user_index, ratings, n):
"""
Get the indices of the n most similar users to the specified user based on cosine similarity.
:param user_index: Index of the user for whom we want to find similar users
:param ratings: ... | import numpy as np
from solution import get_similar_users, generate_recommendations
# Test data for a small rating matrix
test_ratings = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
])
def test_get_similar_users():
similar_users = get_similar_users(0, test_r... | [
{
"docstring": "Get the indices of the n most similar users to the specified user based on cosine similarity.\n\n:param user_index: Index of the user for whom we want to find similar users\n:param ratings: 2D numpy array (or list of lists) where each row is a user's ratings of items\n:param n: Number of similar... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.neighbors import NearestNeighbors\n\ndef get_similar_users(user_in... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00020489",
"row_id": 20489,
"seed_ids": "['Llama-3.3-70B-Instruct_51497']"
} | 0.581296 | Filter_20489 | I | [
"get_similar_users",
"generate_recommendations"
] | 2 | [
[
"generate_recommendations",
"get_similar_users"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | d29c728dcb917963b1c7fc54793cdcb7f42c1668 | 6fb9fff12800b8ed3669989da947b4e7ef0730c2 | |||
v1.0 | instruct | Filter | Filter_20564_I | ### Creating a Keyboard Input Game
#### Game Overview
For this game, create a program that asks the user for their choices, and then based on their choices, the player's life bar increases or decreases.
**Game Requirements:**
* The game starts with the player having **100 life points**.
* The player is presented with ... | def update_life_points(life_points, choice):
"""
Update the player's life points based on their choice.
Parameters:
life_points (int): The current life points of the player.
choice (int): The player's choice represented by a number (1, 2, or 3).
Returns:
int: The updated life point... | import pytest
from solution import update_life_points
def test_update_life_points_sandwich():
assert update_life_points(50, 1) == 60
def test_update_life_points_run():
assert update_life_points(50, 2) == 45
def test_update_life_points_nap():
assert update_life_points(50, 3) == 65
def test_update_life_po... | [
{
"docstring": "Update the player's life points based on their choice.\n\nParameters:\nlife_points (int): The current life points of the player.\nchoice (int): The player's choice represented by a number (1, 2, or 3).\n\nReturns:\nint: The updated life points after applying the choice effect.",
"function_de... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def game():\n life_points = 100\n\n choices = {\n '1': 10, # Eat a sandwich\n '2': -5, # Go for a run\n '3': 15 # Take a nap\n }\n\n while life_points >... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00020564",
"row_id": 20564,
"seed_ids": "['Llama-3.3-70B-Instruct_51662']"
} | 0.476838 | Filter_20564 | I | [
"update_life_points",
"play_game"
] | 2 | [
[
"play_game",
"update_life_points"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54bcc12527f2b034a970b7c1a65c4de1fdc7d030 | ed9c499587c551a0e3addd8b201acc9797f24b30 | |||
v1.0 | instruct | Filter | Filter_20588_I | ### Shortener: Develop a URL Shortener with Basic Error Handling
#### Overview
Create a simple URL shortener application using Python and a SQLite database to store the original URL and shortened URL mapping.
#### Requirements
- The application should accept a URL as an input and return a shortened URL.
- The shortened... | import sqlite3
import uuid
import re
from flask import Flask, request, jsonify
app = Flask(__name__)
# Initialize the SQLite database
def init_db():
conn = sqlite3.connect('url_shortener.db')
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS urls (
id INTEGER PRIMARY KEY AUTOINCREMENT... | import pytest
import sqlite3
from solution import app, is_valid_url, generate_short_code
def setup_module(module):
conn = sqlite3.connect('url_shortener.db')
c = conn.cursor()
c.execute('DELETE FROM urls')
conn.commit()
conn.close()
@pytest.fixture
def client():
with app.test_client() as clien... | [
{
"docstring": null,
"function_declaration": "def init_db():",
"function_name": "init_db",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_short_code():",
"function_name": "generate_short_code",
"parameter_list": "()"
},
{
"docstring":... | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nimport re\nimport sqlite3\nimport uuid\n\napp = Flask(__name__)\n\n# Database initialization\ndef init_db():\n conn = sqlite3.connect('url_shorten... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00020588",
"row_id": 20588,
"seed_ids": "['Llama-3.3-70B-Instruct_51727']"
} | 0.511786 | Filter_20588 | I | [
"init_db",
"generate_short_code",
"is_valid_url",
"add_url_to_db",
"get_short_code_for_url",
"shorten_url"
] | 6 | [
[
"shorten_url",
"add_url_to_db"
],
[
"shorten_url",
"generate_short_code"
],
[
"shorten_url",
"get_short_code_for_url"
],
[
"shorten_url",
"is_valid_url"
]
] | 4 | [] | false | [] | false | pytest | true | [
"flask"
] | false | f0f4c88d6761fb30a7d9b3b668840d519d484c28 | d011495a3b1523e7e85642e7dc1bc72ca23a2c86 | |||
v1.0 | instruct | Filter | Filter_20593_I | Here's my code which sends data to a server and gets a response.
```python
import requests
from pathlib import Path
from typing import Tuple
def send_and_receive(
endpoint: str,
payload: dict,
timeout: int = 30,
) -> Tuple:
"""Sends data to the server and gets a response."""
try:
with requ... | import requests
from typing import Tuple
def send_and_receive(
endpoint: str,
payload: dict,
timeout: int = 30,
) -> Tuple:
"""Sends data to the server and gets a response."""
try:
with requests.Session() as session:
response = session.post(
endpoint,
... | import pytest
from unittest.mock import patch, Mock
from solution import send_and_receive, send_requests_in_loop
def test_send_requests_in_loop():
endpoints = ["http://example.com/api1", "http://example.com/api2"]
payloads = [{"data": 1}, {"data": 2}]
mock_response_1 = Mock()
mock_response_1.json.... | [
{
"docstring": "Sends data to the server and gets a response.",
"function_declaration": "def send_and_receive(endpoint, payload, timeout=30):",
"function_name": "send_and_receive",
"parameter_list": "(endpoint, payload, timeout=30)"
},
{
"docstring": "Loops through given endpoints and payloa... | [
0,
0,
0,
0,
1,
1,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def send_and_receive_multiple(\n endpoints: list,\n payloads: list,\n timeout: int = 5\n) -> list:\n \"\"\"\n Sends data to multiple servers and gets responses.\n \n Args:... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00020593",
"row_id": 20593,
"seed_ids": "['Llama-3.3-70B-Instruct_51740']"
} | 0.547967 | Filter_20593 | I | [
"send_and_receive",
"send_requests_in_loop"
] | 2 | [
[
"send_requests_in_loop",
"send_and_receive"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 73bf75265aae762ed706d2a52befbbaa4e6ad7d6 | 3e0f9198b839e85032da1ed6b2ad8f21a907839d | |||
v1.0 | instruct | Filter | Filter_20609_I | I'll give you a password, and you write a script that checks whether a given string is the same as the password.
However, the **password needs to be obfuscated** for security reasons. There's a publicly available encryption algorithm (lets say, XOR with a public key) that generates a secure hash.
In this case, our ... | def obfuscate_password(password):
"""
Obfuscates the password by adding 3 to the ASCII value of each character.
Args:
password (str): The original password.
Returns:
str: The obfuscated password.
"""
obfuscated = ''.join(chr(ord(char) + 3) for char in password)
return obfus... | from solution import obfuscate_password, is_correct_password
def test_obfuscate_password():
assert obfuscate_password("abc") == "def"
assert obfuscate_password("123") == "456"
assert obfuscate_password("password") == "sdvvzrug"
def test_is_correct_password():
obfuscated = obfuscate_password("test")
... | [
{
"docstring": "Obfuscates the password by adding 3 to the ASCII value of each character.\n\nArgs:\npassword (str): The original password.\n\nReturns:\nstr: The obfuscated password.",
"function_declaration": "def obfuscate_password(password):",
"function_name": "obfuscate_password",
"parameter_list"... | [
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_correct_password(password_attempt, obfuscated_password):\n \"\"\"\n Checks whether the provided password_attempt is the correct password by comparing it\n to the obfuscated pas... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020609",
"row_id": 20609,
"seed_ids": "['Llama-3.3-70B-Instruct_51768']"
} | 0.431303 | Filter_20609 | I | [
"obfuscate_password",
"is_correct_password"
] | 2 | [
[
"is_correct_password",
"obfuscate_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77a5de2d61c16d6096e81010dbb69d38f1cd724a | 553bad56f6f294aa9cb7ac5fe209440d0ede3696 | |||
v1.0 | instruct | Filter | Filter_20655_I | Here's my amazing Tic-Tac-Toe game:
```python
import random
def print_board(board):
print(" " + board[0] + " | " + board[1] + " | " + board[2])
print("---+---+---")
print(" " + board[3] + " | " + board[4] + " | " + board[5])
print("---+---+---")
print(" " + board[6] + " | " + board[7] + " | " + boa... | import random
def print_board(board):
print(" " + board[0] + " | " + board[1] + " | " + board[2])
print("---+---+---")
print(" " + board[3] + " | " + board[4] + " | " + board[5])
print("---+---+---")
print(" " + board[6] + " | " + board[7] + " | " + board[8])
def check_win(board):
win_conditio... | from solution import check_win, minimax, computer_move
def test_check_win():
assert check_win(["X", "X", "X", " ", " ", " ", " ", " ", " "]) == "X"
assert check_win([" ", " ", " ", "O", "O", "O", " ", " ", " "]) == "O"
assert check_win(["X", " ", " ", "X", " ", " ", "X", " ", " "]) == "X"
assert check_... | [
{
"docstring": null,
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def check_win(board):",
"function_name": "check_win",
"parameter_list": "(board)"
},
{
"doc... | [
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef print_board(board):\n print(\" \" + board[0] + \" | \" + board[1] + \" | \" + board[2])\n print(\"---+---+---\")\n print(\" \" + board[3] + \" | \" + board[4] + \... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020655",
"row_id": 20655,
"seed_ids": "['Llama-3.3-70B-Instruct_51860']"
} | 0.568671 | Filter_20655 | I | [
"print_board",
"check_win",
"minimax",
"computer_move",
"game"
] | 5 | [
[
"computer_move",
"minimax"
],
[
"game",
"check_win"
],
[
"game",
"computer_move"
],
[
"game",
"print_board"
],
[
"minimax",
"check_win"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 08aae61aa51e2c7f2f1f398f5fbd56a7221b99d8 | 7856c223ce0676aba65a64673c7c997351633b5e | |||
v1.0 | instruct | Filter | Filter_20690_I | I am trying to write a Python program that can take a list of integers and produce a table of the integers and their prime factors. For example: if the input is `[12, 15, 18, 21]`, the output should be:
```
+--------+-----------------------+
| 12 | 2^2 * 3 |
| 15 | 2 * 3 * 5 |
| 18 | ... | def prime_factors(n):
i = 2
factors = {}
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors[i] = factors.get(i, 0) + 1
if n > 1:
factors[n] = factors.get(n, 0) + 1
return factors
def format_factors(factors):
return ' * '.join([f"... | from solution import prime_factors, format_factors
def test_prime_factors_single_prime():
assert prime_factors(13) == {13: 1}
def test_prime_factors_composite():
assert prime_factors(12) == {2: 2, 3: 1}
def test_prime_factors_large_number():
assert prime_factors(100) == {2: 2, 5: 2}
def test_format_fact... | [
{
"docstring": null,
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def format_factors(factors):",
"function_name": "format_factors",
"parameter_list": "(factors)"
},
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from tabulate import tabulate\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 n //= i\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00020690",
"row_id": 20690,
"seed_ids": "['Llama-3.3-70B-Instruct_51948']"
} | 0.476303 | Filter_20690 | I | [
"prime_factors",
"format_factors",
"print_factors"
] | 3 | [
[
"print_factors",
"format_factors"
],
[
"print_factors",
"prime_factors"
]
] | 2 | [] | false | [] | false | pytest | true | [
"tabulate"
] | false | 6cdaddf8ee115c4fdf5ca31fd6f2352c0626ebaa | 7778b1c1296feb2c554d6a98d30d183fad7eb4fc | |||
v1.0 | instruct | Filter | Filter_20705_I | Can I see the code for the Shallow Water Equations (SWE) in Python? | import numpy as np
def initialize_fields(nx, ny, h_init, u_init, v_init):
"""
Initialize the height (h), velocity in x-direction (u), and velocity in y-direction (v) fields.
Parameters:
nx, ny: number of grid points in the x and y directions.
h_init, u_init, v_init: initial values for height, ... | from solution import initialize_fields, compute_time_step, update_fields, shallow_water
import numpy as np
def test_initialize_fields():
h, u, v = initialize_fields(5, 5, 1.0, 0.0, 0.0)
assert h.shape == (5, 5) and np.all(h == 1.0)
assert u.shape == (5, 5) and np.all(u == 0.0)
assert v.shape == (5, 5) ... | [
{
"docstring": "Initialize the height (h), velocity in x-direction (u), and velocity in y-direction (v) fields.\n\nParameters:\nnx, ny: number of grid points in the x and y directions.\nh_init, u_init, v_init: initial values for height, u-velocity, and v-velocity fields.\n\nReturns:\nh, u, v: initialized fields... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef shallow_water_equations(h, u, v, dt, dx, dy, g=9.81):\n \"\"\"\n Simulate one step of the 2D Shallow Water Equations using finite difference method.\n \n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00020705",
"row_id": 20705,
"seed_ids": "['Llama-3.3-70B-Instruct_51981']"
} | 0.326461 | Filter_20705 | I | [
"initialize_fields",
"compute_time_step",
"update_fields",
"shallow_water"
] | 4 | [
[
"shallow_water",
"compute_time_step"
],
[
"shallow_water",
"initialize_fields"
],
[
"shallow_water",
"update_fields"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 61a48abb644f8c53c1dcba0f08d6365f4c2918d3 | 0d014c93edcc72423c504835f911cbf40a70d8e8 | |||
v1.0 | instruct | Filter | Filter_20747_I | Can you create a code that executes the following task: Write a program that takes a sentence as an input, identifies the adjectives (assuming you have a predefined list of adjectives) and replaces them with their synonyms. The program also keeps count of the original and modified sentences, and displays these counts.
... | import random
# Predefined list of adjectives and their synonyms
adjectives = ["good", "bad", "big", "small", "hot", "cold", "happy", "sad", "tall", "short"]
synonyms = {
"good": ["great", "excellent", "fine"],
"bad": ["terrible", "awful", "poor"],
"big": ["large", "huge", "enormous"],
"small": ["littl... | from solution import replace_adjectives
def test_replace_with_adjectives():
# Arrange
sentence = "I had a good day and it was very hot outside."
# Act
result, original_count, modified_count = replace_adjectives(sentence)
# Assert
assert original_count == 2
assert modified_count == 2
ass... | [
{
"docstring": null,
"function_declaration": "def replace_adjectives(sentence):",
"function_name": "replace_adjectives",
"parameter_list": "(sentence)"
},
{
"docstring": null,
"function_declaration": "def display_sentence_analysis(sentence):",
"function_name": "display_sentence_analy... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nadjectives = [\"good\", \"bad\", \"big\", \"small\", \"hot\", \"cold\", \"happy\", \"sad\", \"tall\", \"short\"]\nsynonyms = {\"good\": [\"great\", \"excellent\", \"fine\"], \... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00020747",
"row_id": 20747,
"seed_ids": "['Llama-3.3-70B-Instruct_52069']"
} | 0.530735 | Filter_20747 | I | [
"replace_adjectives",
"display_sentence_analysis"
] | 2 | [
[
"display_sentence_analysis",
"replace_adjectives"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e927da5422f2bc4eca298ab9e686cc6bc435ac5b | ee4c94016bb7c1b424934b585b97630e4736c5fb | |||
v1.0 | instruct | Filter | Filter_20902_I | Here are some features of a program that will manipulate and create musical notes
- The program must create notes
- It must have major and minor chords
- It will need a piano keyboard layout
- It must be able to transpose the chords
- It wants the ability to add embellishments to the chords, e.g. 7ths, suspended, d... | # music_theory.py
class Note:
def __init__(self, name, octave):
"""
Initialize a Note object.
Args:
name (str): The name of the note (A, A#, Bb, etc.)
octave (int): The octave of the note.
"""
self.name = name
self.octave = octave
def __... | from solution import Note, create_major_chord, create_minor_chord, create_piano_keyboard
def test_create_major_chord():
root_note = Note("C", 4)
major_chord = create_major_chord(root_note)
assert str(major_chord) == "Chord: C4, E4, G4"
def test_create_minor_chord():
root_note = Note("C", 4)
minor_... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Note:\n def __init__(self, name, octave):\n \"\"\"\n Initialize a Note object.\n\n Args:\n name (str): The name of the note (A, A#, Bb, etc.)\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020902",
"row_id": 20902,
"seed_ids": "['Llama-3.3-70B-Instruct_52436']"
} | 0.47426 | Filter_20902 | I | [
"find_note_index",
"create_major_chord",
"create_minor_chord",
"create_piano_keyboard"
] | 4 | [
[
"create_major_chord",
"find_note_index"
],
[
"create_minor_chord",
"find_note_index"
]
] | 2 | [] | false | [
"Note",
"Chord"
] | true | pytest | true | [] | true | c65c8582cf97a777d2b484daead7d44d636760e5 | 814e71d8e5769e546ee6dd70a63d19bca02edec4 | |||
v1.0 | instruct | Filter | Filter_20948_I | I have a list of file paths in a text file and want to count the total size of all the files for each unique top-level domain (TLD) in the list (e.g.: example.gov, example.com, example.net, etc.). I can assume that there is only 1 TLD per line in the file. I am unsure what programming language to use to accomplish this... | import os
def get_tld(file_path):
"""
Given a file path, extract and return the top-level domain (TLD) from it.
"""
domain = file_path.split('/')[0]
tld = domain.split('.')[-1]
return tld
def get_file_size(file_path):
"""
Given a file path, return the size of the file in bytes.
Ass... | from solution import get_tld, calculate_tld_total_sizes, save_tld_totals_to_file
def test_get_tld():
assert get_tld("example1.gov/path/to/file1.txt") == "gov"
assert get_tld("example2.com/path/to/file2.txt") == "com"
assert get_tld("example3.org/path/to/file3.txt") == "org"
def mock_get_file_size(file_pat... | [
{
"docstring": "Given a file path, extract and return the top-level domain (TLD) from it.",
"function_declaration": "def get_tld(file_path):",
"function_name": "get_tld",
"parameter_list": "(file_path)"
},
{
"docstring": "Given a file path, return the size of the file in bytes.\nAssumes that... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef calculate_tld_sizes(file_path):\n tld_sizes = {}\n \n with open(file_path, 'r') as f:\n for line in f:\n url = line.strip()\n tld = url.s... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00020948",
"row_id": 20948,
"seed_ids": "['Llama-3.3-70B-Instruct_52543']"
} | 0.537431 | Filter_20948 | I | [
"get_tld",
"get_file_size",
"calculate_tld_total_sizes",
"save_tld_totals_to_file"
] | 4 | [
[
"calculate_tld_total_sizes",
"get_file_size"
],
[
"calculate_tld_total_sizes",
"get_tld"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1f46715df9855061e821b7e9b76e5e4dfeaaa069 | 276317cb5eb90892a39f9773e815adddcf75a5ce | |||
v1.0 | instruct | Filter | Filter_21022_I | In this task, you'll write a Python program to find and print all numbers that are both abundant and odd within a given range of numbers. An abundant number is a number for which the sum of its proper divisors is greater than the number itself. | def is_abundant(n):
"""
Check if a number n is an abundant number.
"""
divisors = [i for i in range(1, n) if n % i == 0]
return sum(divisors) > n
def find_abundant_odd_numbers(start, end):
"""
Find and return a list of all odd abundant numbers within the given range [start, end].
"""
... | from solution import is_abundant, find_abundant_odd_numbers
def test_is_abundant():
assert is_abundant(12) == True
assert is_abundant(18) == True
assert is_abundant(28) == False
def test_find_abundant_odd_numbers_no_abundant():
assert find_abundant_odd_numbers(1, 15) == []
def test_find_abundant_odd_... | [
{
"docstring": "Check if a number n is an abundant number.",
"function_declaration": "def is_abundant(n):",
"function_name": "is_abundant",
"parameter_list": "(n)"
},
{
"docstring": "Find and return a list of all odd abundant numbers within the given range [start, end].",
"function_decla... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def proper_divisors(n):\n \"\"\"\n Returns a list of all proper divisors of n (numbers less than n which divide evenly into n).\n \"\"\"\n divisors = []\n for i in range(1, n //... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00021022",
"row_id": 21022,
"seed_ids": "['Llama-3.3-70B-Instruct_52720']"
} | 0.592561 | Filter_21022 | I | [
"is_abundant",
"find_abundant_odd_numbers"
] | 2 | [
[
"find_abundant_odd_numbers",
"is_abundant"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a28958d2a2cf70061b05bc4bdb267ab0ea6befa | 712b6e46c65d630e24396e139b6c8eceff45d4a0 | |||
v1.0 | instruct | Filter | Filter_21252_I | I would like to create a color grading tool for movies and videos using python. This task seems quite complex, can you provide me with a small introduction, a simple implementation, and a general overview of how you would approach this task. | import cv2
import numpy as np
def apply_color_grading(frame, alpha=1.2, beta=20):
"""
Applies a simple color grading to a frame.
Parameters:
- frame: Input video frame (numpy array).
- alpha: Contrast control (1.0-3.0).
- beta: Brightness control (0-100).
Returns:
- Graded frame.
... | import numpy as np
from solution import apply_color_grading
def test_apply_color_grading_basic():
frame = np.ones((100, 100, 3), dtype=np.uint8) * 50
graded_frame = apply_color_grading(frame, alpha=1.0, beta=0)
assert np.array_equal(frame, graded_frame), "The frame should remain unchanged with alpha=1.0 an... | [
{
"docstring": "Applies a simple color grading to a frame.\n\nParameters:\n- frame: Input video frame (numpy array).\n- alpha: Contrast control (1.0-3.0).\n- beta: Brightness control (0-100).\n\nReturns:\n- Graded frame.",
"function_declaration": "def apply_color_grading(frame, alpha=1.2, beta=20):",
"f... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\n\ndef load_video(video_path):\n cap = cv2.VideoCapture(video_path)\n if not cap.isOpened():\n raise ValueError(\"Error opening video file\")\n return cap\n\ndef app... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00021252",
"row_id": 21252,
"seed_ids": "['Llama-3.3-70B-Instruct_53221']"
} | 0.369078 | Filter_21252 | I | [
"apply_color_grading",
"color_grade_video"
] | 2 | [
[
"color_grade_video",
"apply_color_grading"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 5aefa4dc937f253903282b328a20adbd1a721a9e | 27b981edbfd2be33320a70f7cf52d06d3a22f06e | |||
v1.0 | instruct | Filter | Filter_21461_I | ### Writing a Program to Solve a Two-Body Problem
In orbit.py, we'll create a program to solve the two-body problem. The program will use the Scipy `integrate.odeint` function, which solves a system of ordinary differential equations.
```python
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyp... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Gravitational constant
G = 6.67430e-11 # [m^3 kg^-1 s^-2]
def deriv(X, t, m1, m2):
X = np.array(X, dtype=float)
r1 = X[:2]
v1 = X[2:4]
r2 = X[4:6]
v2 = X[6:]
dr1dt = v1
dv1dt = -G * m2 * (r1 - r2)... | from solution import deriv, solve_two_body_problem
import numpy as np
def test_deriv_shape():
X0 = [3.844e8, 0, 0, 1.022e3, -3.844e8, 0, 0, -1.022e3]
t = 0
m1 = 5.97237e24
m2 = 7.348e22
result = deriv(X0, t, m1, m2)
assert result.shape == (8,), f"Expected shape (8,) but got {result.shape}"
... | [
{
"docstring": null,
"function_declaration": "def deriv(X, t, m1, m2):",
"function_name": "deriv",
"parameter_list": "(X, t, m1, m2)"
},
{
"docstring": "Solves the two-body problem for masses m1 and m2, initial condition X0 and times t.",
"function_declaration": "def solve_two_body_probl... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# Gravitational constant\nG = 6.67430e-11 # [m^3 kg^-1 s^-2]\n\n# Function that returns dy/dt\ndef d... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00021461",
"row_id": 21461,
"seed_ids": "['Llama-3.3-70B-Instruct_53752']"
} | 0.458673 | Filter_21461 | I | [
"deriv",
"solve_two_body_problem"
] | 2 | [
[
"solve_two_body_problem",
"deriv"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | c4ccf89df22e768a7033c82cfd715d0c18375393 | 4711b60c848be68a5203d8218f794867bcc0833a | |||
v1.0 | instruct | Filter | Filter_21491_I | I have a string that has specific hexadecimal values in it. I'd like to be able to convert them into decimal and put back the string with the converted values.
Example Input:
"This is a #ff0000 value and #123456 value"
Example Output:
"This is a 16777215 value and 11946830 value"
Here's what I've attempted thus... | import re
def hex_to_dec(hex_val):
"""
Convert a hexadecimal string (without #) to decimal.
"""
return str(int(hex_val, 16))
def replace_hex(input_str):
"""
Replace all hexadecimal color codes in a string (formatted as #RRGGBB)
with their decimal equivalents.
"""
return re.sub(r'#(... | from solution import replace_hex
def test_replace_hex_basic():
input_string = "This is a #ff0000 value and #123456 value"
expected_output = "This is a 16711680 value and 1193046 value"
assert replace_hex(input_string) == expected_output
def test_replace_hex_multiple_occurrences():
input_string = "Hex ... | [
{
"docstring": "Convert a hexadecimal string (without #) to decimal.",
"function_declaration": "def hex_to_dec(hex_val):",
"function_name": "hex_to_dec",
"parameter_list": "(hex_val)"
},
{
"docstring": "Replace all hexadecimal color codes in a string (formatted as #RRGGBB)\nwith their decima... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef hex_to_dec(hex_val):\n \"\"\"\n Converts a hexadecimal string (without the #) to its decimal equivalent.\n \"\"\"\n return str(int(hex_val, 16))\n\ndef replace_hex... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00021491",
"row_id": 21491,
"seed_ids": "['Llama-3.3-70B-Instruct_53833']"
} | 0.58072 | Filter_21491 | I | [
"hex_to_dec",
"replace_hex"
] | 2 | [
[
"replace_hex",
"hex_to_dec"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c08e97a048e86cefeae9c3d8b768f5fa8248322a | e08b76030bcfc889457a0b2b83e99590eb647015 | |||
v1.0 | instruct | Filter | Filter_21545_I | ### Smooth Numbers
A smooth number is a positive integer which is not divisible by any prime number except for the primes less than or equal to a certain number called the "limit".
Let's implement it in Python.
```python
# smooth_numbers.py
def smooth_numbers(n, limit):
"""Return a list of smooth numbers up to... | def is_smooth(num, limit, primes):
for prime in primes:
while num % prime == 0:
num //= prime
return num == 1
def find_primes_up_to(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for start in range(2, int(limit**0.5) + 1):
if sieve[start]:
f... | from solution import smooth_numbers
def test_smooth_numbers_limit_2():
assert smooth_numbers(10, 2) == [1, 2, 4, 8]
def test_smooth_numbers_limit_3():
assert smooth_numbers(10, 3) == [1, 2, 3, 4, 6, 8, 9]
def test_smooth_numbers_limit_5():
assert smooth_numbers(15, 5) == [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ... | [
{
"docstring": null,
"function_declaration": "def is_smooth(num, limit, primes):",
"function_name": "is_smooth",
"parameter_list": "(num, limit, primes)"
},
{
"docstring": null,
"function_declaration": "def find_primes_up_to(limit):",
"function_name": "find_primes_up_to",
"parame... | [
0,
0,
0,
1,
0,
0,
0,
1,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "from sympy import isprime\n\ndef smooth_numbers(n, limit):\n \"\"\"\n Return a list of smooth numbers up to n using the primes <= limit.\n \n Parameters:\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00021545",
"row_id": 21545,
"seed_ids": "['Llama-3.3-70B-Instruct_53954']"
} | 0.555096 | Filter_21545 | I | [
"is_smooth",
"find_primes_up_to",
"smooth_numbers"
] | 3 | [
[
"smooth_numbers",
"find_primes_up_to"
],
[
"smooth_numbers",
"is_smooth"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 834a5118e437be9f2ef2d0653b7742c908bdcbc2 | 235de36e490a4b2b3792a09d88090642c8897de6 | |||
v1.0 | instruct | Filter | Filter_21636_I | I want to create a sinogram of an object and backproject the original object from it. Below is a python code snippet performing the projection and backprojection. However, the object is required to be in the form of a 1D or 2D numpy array. My problem is the object I have is a 3D numpy array. Is there any way to extend ... | import numpy as np
from scipy.ndimage import rotate
def create_sinogram_2d(object_2d):
"""
Create a sinogram from 2D object using Radon transform.
"""
angles = np.linspace(0., 180., max(object_2d.shape), endpoint=False)
sinogram = np.stack([rotate(object_2d, angle, reshape=False) for angle in angle... | import numpy as np
from solution import create_sinogram_3d, backproject_3d
def test_create_sinogram_3d():
# Create a simple 3D object
object_3d = np.zeros((4, 4, 4))
object_3d[1:3, 1:3, 1:3] = 1
# Create sinogram
sinogram_3d = create_sinogram_3d(object_3d)
# Verify dimensions
assert sinog... | [
{
"docstring": "Create a sinogram from 2D object using Radon transform.",
"function_declaration": "def create_sinogram_2d(object_2d):",
"function_name": "create_sinogram_2d",
"parameter_list": "(object_2d)"
},
{
"docstring": "Backproject the sinogram to get the original 2D object.",
"fun... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.ndimage import rotate\n\ndef project_2d(image, angles):\n \"\"\"\n Project a 2D numpy array from various angles.\n\n Parameters:\n - image: 2D numpy ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00021636",
"row_id": 21636,
"seed_ids": "['Llama-3.3-70B-Instruct_54170']"
} | 0.465877 | Filter_21636 | I | [
"create_sinogram_2d",
"backproject_2d",
"create_sinogram_3d",
"backproject_3d"
] | 4 | [
[
"backproject_3d",
"backproject_2d"
],
[
"create_sinogram_3d",
"create_sinogram_2d"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 7c678dc8f1e73e9af31a7d507a0a0cf238d728bc | e25ef56c5bcde6cd5f87d3f126a4b06017fc832d | |||
v1.0 | instruct | Filter | Filter_21651_I | Another palindrome number exercise:
Can you write a program to find the longest palindromic substring of a given string? The example:
- if the input string is "babad" , then output is "bab"
- if the input string is "cbbd", then output is "bb"
The program should be able to handle the right output for different length... | def longest_palindromic_substring(s: str) -> str:
"""
Returns the longest palindromic substring in the input string.
Args:
s (str): The input string.
Returns:
str: The longest palindromic substring.
"""
# Handle edge case for None or empty string input
if s is None or len(s... | from solution import longest_palindromic_substring
def test_palindrome_general_cases():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
assert longest_palindromic_substring("cbbd") == "bb"
assert longest_palindromic_substring("a") == "a"
assert longest_palindromic_substring("ac") in ["a... | [
{
"docstring": "Returns the longest palindromic substring in the input string.\n\nArgs:\ns (str): The input string.\n\nReturns:\nstr: The longest palindromic substring.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_lis... | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n Returns the longest palindromic substring in the input string.\n \n Args:\n s (str): The input string.\n \n Re... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00021651",
"row_id": 21651,
"seed_ids": "['Llama-3.3-70B-Instruct_54206']"
} | 0.694707 | Filter_21651 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c65b7c4e04fb778aacd5bbab8703212348f81d7a | f420c584044a45bebaccef2d4aef44ddf2e1e1f9 | |||
v1.0 | instruct | Filter | Filter_21906_I | Here is the task description:
Task name: Particle filter
Implement a particle filter for estimating the state of a system with non-linear
dynamics. The system is modeled using continuous time
equations. Assume the input is speed (v) and orientation (θ) of a vehicle,
measured by GPS. The state is position (x) and (y) of... | import numpy as np
# Constants
NUM_PARTICLES = 1000
X_RANGE = (0, 10)
Y_RANGE = (0, 5)
SIGMA_X = 0.5
SIGMA_Y = 0.5
# Initialize particles
def initialize_particles(num_particles, x_range, y_range):
particles = np.zeros((num_particles, 2))
particles[:, 0] = np.random.uniform(x_range[0], x_range[1], num_particle... | from solution import initialize_particles, evaluate_likelihood, particle_filter_step, run_particle_filter
import numpy as np
def test_initialize_particles():
particles = initialize_particles(10, (0, 10), (0, 5))
assert particles.shape == (10, 2)
assert np.all(particles[:, 0] >= 0) and np.all(particles[:, 0... | [
{
"docstring": null,
"function_declaration": "def initialize_particles(num_particles, x_range, y_range):",
"function_name": "initialize_particles",
"parameter_list": "(num_particles, x_range, y_range)"
},
{
"docstring": null,
"function_declaration": "def evaluate_likelihood(particles, z,... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\nclass ParticleFilter:\n def __init__(self, num_particles, x_range, y_range, sigma_x, sigma_y):\n self.num_particles = num_particles\n self.x_range = x_ra... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00021906",
"row_id": 21906,
"seed_ids": "['Llama-3.3-70B-Instruct_54873']"
} | 0.506441 | Filter_21906 | I | [
"initialize_particles",
"evaluate_likelihood",
"particle_filter_step",
"run_particle_filter"
] | 4 | [
[
"particle_filter_step",
"evaluate_likelihood"
],
[
"run_particle_filter",
"initialize_particles"
],
[
"run_particle_filter",
"particle_filter_step"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b9e24600dc3ed408fa0fb5e037cb799ade6d61b7 | 912ad48efe0a6a2e0aad2f648be1dbcf686825b2 | |||
v1.0 | instruct | Filter | Filter_21916_I | I've been using the Slovan library to power changing the color of an image in real time in the internet browser. But recently, I've noticed that the library doesn't have the functionality to change the saturation of the image. I need help figuring out how to accomplish this.
In order to determine the hue, saturation ... | def rgb_to_hsv(r, g, b):
# Unpack pixel values
r, g, b = r / 255.0, g / 255.0, b / 255.0
# Compute mx, mn, df
mx = max(r, g, b)
mn = min(r, g, b)
df = mx - mn
# Check for special cases of hue
if mx == mn:
h = 0
# Red is the maximum value
elif mx == r:
h ... | from solution import rgb_to_hsv, hsv_to_rgb, change_image_saturation
def test_rgb_to_hsv():
assert rgb_to_hsv(255, 0, 0) == (0, 1.0, 1.0)
assert rgb_to_hsv(0, 255, 0) == (120, 1.0, 1.0)
assert rgb_to_hsv(0, 0, 255) == (240, 1.0, 1.0)
assert rgb_to_hsv(255, 255, 255) == (0, 0.0, 1.0)
assert rgb_to_h... | [
{
"docstring": null,
"function_declaration": "def rgb_to_hsv(r, g, b):",
"function_name": "rgb_to_hsv",
"parameter_list": "(r, g, b)"
},
{
"docstring": null,
"function_declaration": "def hsv_to_rgb(h, s, v):",
"function_name": "hsv_to_rgb",
"parameter_list": "(h, s, v)"
},
{
... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rgb_to_hsv(r, g, b):\n r, g, b = r / 255.0, g / 255.0, b / 255.0\n mx = max(r, g, b)\n mn = min(r, g, b)\n df = mx - mn\n if mx == mn:\n h = 0\n elif mx == r:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00021916",
"row_id": 21916,
"seed_ids": "['Llama-3.3-70B-Instruct_54895']"
} | 0.346304 | Filter_21916 | I | [
"rgb_to_hsv",
"hsv_to_rgb",
"change_image_saturation"
] | 3 | [
[
"change_image_saturation",
"hsv_to_rgb"
],
[
"change_image_saturation",
"rgb_to_hsv"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cec3b239929a36e47586a1c4d839b5e36ba1474d | 5211443aa75eaf39ed2a8636f965797a250311be | |||
v1.0 | instruct | Filter | Filter_22032_I | You'll be given a programming problem to solve. The goal is to use recursion to determine the square of a given input integer.
**Square of Integer using Recursion
=================================
You need to write a recursive function `square` that takes a single integer `n` as input and returns its square. The fun... | def square(n):
"""
Returns the square of n using recursion.
"""
if n == 0:
return 0
if n < 0:
n = -n
return square_recursive(n, n)
def square_recursive(n, original_n):
if n == 1:
return original_n
return original_n + square_recursive(n - 1, original_n) | from solution import square
def test_square_positive_numbers():
assert square(5) == 25
assert square(3) == 9
assert square(1) == 1
def test_square_negative_numbers():
assert square(-5) == 25
assert square(-3) == 9
assert square(-1) == 1
def test_square_zero():
assert square(0) == 0
def t... | [
{
"docstring": "Returns the square of n using recursion.",
"function_declaration": "def square(n):",
"function_name": "square",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def square_recursive(n, original_n):",
"function_name": "square_recursive",
"pa... | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def square(n):\n \"\"\"\n Function to calculate the square of an integer using recursion.\n \"\"\"\n def add(a, b):\n # Helper function to add 'a' and 'b' using recursion\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022032",
"row_id": 22032,
"seed_ids": "['Llama-3.3-70B-Instruct_55179']"
} | 0.605488 | Filter_22032 | I | [
"square",
"square_recursive"
] | 2 | [
[
"square",
"square_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 44f72397d846abbc3eade69f46b7a0f8eb2c2faf | ce4e31897379d8f9603f465a3e0fa7fcffd82fe6 | |||
v1.0 | instruct | Filter | Filter_22041_I | ### Word Ladder
#### Problem Description
A word ladder is a sequence of words where each word is one edit away from the previous word. An edit is either inserting a character, removing a character, or replacing a character. The task is to find a word ladder between two given words.
#### Example
For example, a word lad... | from collections import deque
def is_valid_word(word, dictionary):
"""
Check if a word is in the dictionary.
"""
return word in dictionary
def get_neighbors(word, dictionary):
"""
Get all possible edits of a word.
"""
neighbors = set()
word_length = len(word)
for i in range(wor... | from solution import is_valid_word, get_neighbors, word_ladder
def test_is_valid_word():
dictionary = {"hot", "dot", "dog"}
assert is_valid_word("hot", dictionary) == True
assert is_valid_word("hit", dictionary) == False
def test_get_neighbors():
dictionary = {"hot", "dot", "dog"}
assert get_neigh... | [
{
"docstring": "Check if a word is in the dictionary.",
"function_declaration": "def is_valid_word(word, dictionary):",
"function_name": "is_valid_word",
"parameter_list": "(word, dictionary)"
},
{
"docstring": "Get all possible edits of a word.",
"function_declaration": "def get_neighbo... | [
0,
0,
0,
0,
1,
1,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List, Set\n\ndef is_valid_word(word: str, dictionary: Set[str]) -> bool:\n \"\"\"Check if a word is in the dictionary.\"\"\"\n return wo... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00022041",
"row_id": 22041,
"seed_ids": "['Llama-3.3-70B-Instruct_55205']"
} | 0.566562 | Filter_22041 | I | [
"is_valid_word",
"get_neighbors",
"word_ladder"
] | 3 | [
[
"get_neighbors",
"is_valid_word"
],
[
"word_ladder",
"get_neighbors"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8dcc1552b5f1cc158f503003c97dc88cefe15672 | 1afb382ed4ca333ffff8fd73475b39d4f216b38f | |||
v1.0 | instruct | Filter | Filter_22093_I | I am developing an application where users can write posts with images. Now I want to analyze the image to get some related data such as image dominant color, and after processing, how I can re arrange image to make a perfect square image maintaining the color.
Can you guide me?
Here you is a high-level overview of... | from PIL import Image
import numpy as np
import cv2
from sklearn.cluster import KMeans
import requests
from io import BytesIO
def load_image_from_url(url):
# Load the image from the URL
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img = img.convert('RGB') # Ensure image is ... | from PIL import Image
from solution import load_image_from_url, get_dominant_color, pad_image_to_square, process_image
import requests
def test_load_image_from_url():
url = "https://picsum.photos/200/300"
image = load_image_from_url(url)
assert isinstance(image, Image.Image)
def test_get_dominant_color():... | [
{
"docstring": null,
"function_declaration": "def load_image_from_url(url):",
"function_name": "load_image_from_url",
"parameter_list": "(url)"
},
{
"docstring": "Returns the dominant color of the image.",
"function_declaration": "def get_dominant_color(image, k=4):",
"function_name"... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nfrom PIL import Image\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport requests\nfrom io import BytesIO\n\ndef detect_dominant_color(image, k=4):\n \"\"\"\n De... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022093",
"row_id": 22093,
"seed_ids": "['Llama-3.3-70B-Instruct_55340']"
} | 0.429829 | Filter_22093 | I | [
"load_image_from_url",
"get_dominant_color",
"pad_image_to_square",
"process_image"
] | 4 | [
[
"process_image",
"get_dominant_color"
],
[
"process_image",
"load_image_from_url"
],
[
"process_image",
"pad_image_to_square"
]
] | 3 | [] | false | [] | false | pytest | true | [
"PIL",
"cv2",
"numpy",
"requests",
"sklearn"
] | false | 380ea320bcb3b8b0c682ce4618baa6e621ce38ed | a6cc3122e6b2529f319eb051ee1c28ff5d4318a8 | |||
v1.0 | instruct | Filter | Filter_22226_I | I wrote a simple quiz game that asks a series of questions to the players. The game is played by one or more players, and the game is only won if all players answer all questions correctly. The game is won when every player has answered every question correctly.
I am looking for suggestions for interesting ways to add... | import random
class Player:
def __init__(self, name):
self.name = name
self.score = 0
def get_player_names():
players = []
num_players = int(input("Enter the number of players: "))
for _ in range(num_players):
name = input("Enter player name: ")
players.append(Player(na... | from solution import Player, ask_question, get_player_names, quiz_game
def test_player_initialization():
player = Player("Alice")
assert player.name == "Alice"
assert player.score == 0
def test_ask_question_correct(monkeypatch):
player = Player("Bob")
question = "What is 2 + 2?"
answer = "4"
... | [] | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass Player:\n def __init__(self, name):\n self.name = name\n self.score = 0\n\ndef get_player_names():\n \"\"\"\n Function to get player names from th... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022226",
"row_id": 22226,
"seed_ids": "['Llama-3.3-70B-Instruct_55642']"
} | 0.472971 | Filter_22226 | I | [
"get_player_names",
"ask_question",
"quiz_game"
] | 3 | [
[
"quiz_game",
"ask_question"
],
[
"quiz_game",
"get_player_names"
]
] | 2 | [] | false | [
"Player"
] | true | pytest | true | [] | true | 01d4014b0d61af1516bf15a2750eceb1cc9d0413 | e217101a420e655040657f9e47699bd44d70cd24 | |||
v1.0 | instruct | Filter | Filter_22271_I | I'm right on a data science interview and currently I'm stuck on a question about string manipulation. I need to write an efficient solution to the following problem:
Write a function that takes a string as input, find all substrings that are palindromes (including single characters) and return them in a list.
Exampl... | def is_palindrome(string):
"""Helper function to check if a string is a palindrome."""
return string == string[::-1]
def get_all_substrings(input_string):
"""Generate all possible substrings from a given string."""
substrings = []
for i in range(len(input_string)):
for j in range(i + 1, len... | from solution import is_palindrome, get_all_substrings, find_palindromic_substrings
def test_is_palindrome():
assert is_palindrome("a") == True
assert is_palindrome("aa") == True
assert is_palindrome("ab") == False
assert is_palindrome("aba") == True
assert is_palindrome("abc") == False
def test_g... | [
{
"docstring": "Helper function to check if a string is a palindrome.",
"function_declaration": "def is_palindrome(string):",
"function_name": "is_palindrome",
"parameter_list": "(string)"
},
{
"docstring": "Generate all possible substrings from a given string.",
"function_declaration": ... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(string):\n \"\"\"Helper function to check if a string is a palindrome.\"\"\"\n return string == string[::-1]\n\ndef get_all_substrings(input_string):\n \"\"\"Generat... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00022271",
"row_id": 22271,
"seed_ids": "['Llama-3.3-70B-Instruct_55778']"
} | 0.717683 | Filter_22271 | I | [
"is_palindrome",
"get_all_substrings",
"find_palindromic_substrings"
] | 3 | [
[
"find_palindromic_substrings",
"get_all_substrings"
],
[
"find_palindromic_substrings",
"is_palindrome"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0bcc95f14b64524ad8f7478de3cdaa42bf3c5c35 | 9bece435dad4075acabd99b210d958a6d32448c4 | |||
v1.0 | instruct | Filter | Filter_22374_I | Here is a tab-delimited file called data.txt:
2 human 50
3 cat 5
4 mouse 10
I need to write a Python script that will count the maximum occurrences of a word in each line.
For example, for this particular file, the output will be:
2
2
2
Because the maximum occurrences of a word in the first line is "huma... | def count_max_word_occurrences(line):
"""
Given a line from a text file, returns the number of words, equivalent to the total number of words in that line.
"""
words = line.split()
return len(words)
def process_file(file_path):
with open(file_path, 'r') as file:
results = []
for... | from solution import count_max_word_occurrences, process_file
def test_count_max_word_occurrences():
assert count_max_word_occurrences("2 human 50") == 3
assert count_max_word_occurrences("3 cat 5") == 3
assert count_max_word_occurrences("4 mouse 10") == 3
assert count_max_word_occurrences("dog cat cat... | [
{
"docstring": "Given a line from a text file, returns the number of words, equivalent to the total number of words in that line.",
"function_declaration": "def count_max_word_occurrences(line):",
"function_name": "count_max_word_occurrences",
"parameter_list": "(line)"
},
{
"docstring": nul... | [
0,
0,
0,
0,
1,
1,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_max_word_occurrences(line):\n words = line.split()\n word_count = {}\n for word in words:\n if word in word_count:\n word_count[word] += 1\n else:\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00022374",
"row_id": 22374,
"seed_ids": "['Llama-3.3-70B-Instruct_56043']"
} | 0.635835 | Filter_22374 | I | [
"count_max_word_occurrences",
"process_file"
] | 2 | [
[
"process_file",
"count_max_word_occurrences"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d7ec1120a87cdf4d6c709fdd10a944ab94373131 | c674dba29f198ca0d7ae2fdd97dccd7ba948a27a | |||
v1.0 | instruct | Filter | Filter_22514_I | I have a dictionary of causality where I need to implement a depth-first search (DFS) to resolve all possible causality paths from a specific event to a target event.
The causality dictionary is defined as follows:
```
causality = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": ["F"],
"D": ["G"],
"E": ["H"... | def find_paths(causality, start, path):
"""
A helper function for DFS to find all paths from the start node to any leaf node.
"""
path = path + [start]
# If current node has no children (is a leaf node), return the path
if not causality[start]:
return [path]
paths = []
for node... | from solution import all_paths_to_leaves
def test_all_paths_to_leaves():
causality = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": ["F"],
"D": ["G"],
"E": ["H", "I"],
"F": [],
"G": [],
"H": [],
"I": []
}
start = "A"
expected_paths = [
... | [
{
"docstring": "A helper function for DFS to find all paths from the start node to any leaf node.",
"function_declaration": "def find_paths(causality, start, path):",
"function_name": "find_paths",
"parameter_list": "(causality, start, path)"
},
{
"docstring": null,
"function_declaration... | [
0,
0,
0,
1,
1,
0,
1,
1,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def find_paths(causality, start, end, path=[]):\n \"\"\"\n Perform a DFS to find all paths from start to end.\n \"\"\"\n path = path + [start]\n\n # If ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022514",
"row_id": 22514,
"seed_ids": "['Llama-3.3-70B-Instruct_56382']"
} | 0.449029 | Filter_22514 | I | [
"find_paths",
"all_paths_to_leaves"
] | 2 | [
[
"all_paths_to_leaves",
"find_paths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 717098be18c504db60067b66f1f54b85137c3d23 | a333cd76c53292eb00a25700aa0550ae2a8a1012 | |||
v1.0 | instruct | Filter | Filter_22516_I | ### SW Version
This is a revised version of the software that only changes the highlighting function. The highlighting function shall be able to highlight all instances of an inputted word.
### Changes to the Highlighting Function
* **Chaining with || operator**: The highlighting function shall be able to handle mu... | import re
from difflib import SequenceMatcher
def is_similar(word1, word2, max_distance=2):
"""
Determines if two words are similar within a maximum edit distance.
Parameters:
word1 (str): The first word.
word2 (str): The second word.
max_distance (int): The maximum edit distance allowed f... | from solution import highlight_text
def test_single_word_highlight():
assert highlight_text("The quick brown fox jumps over the lazy dog", "the") == "**The** quick brown fox jumps over **the** lazy dog"
def test_multiple_words_highlight():
assert highlight_text("The quick brown fox jumps over the lazy dog", "... | [
{
"docstring": "Determines if two words are similar within a maximum edit distance.\n\nParameters:\nword1 (str): The first word.\nword2 (str): The second word.\nmax_distance (int): The maximum edit distance allowed for words to be considered similar.\n\nReturns:\nbool: True if the words are similar within the m... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom typing import List\n\ndef generate_regex(word: str) -> str:\n \"\"\"\n Generates a regex pattern for the given word considering typos.\n \"\"\"\n # Escaping special... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022516",
"row_id": 22516,
"seed_ids": "['Llama-3.3-70B-Instruct_56387']"
} | 0.463921 | Filter_22516 | I | [
"is_similar",
"highlight_text"
] | 2 | [
[
"highlight_text",
"is_similar"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2449b97b9317cf7c13cee7b4c1eda44c49d387a3 | 5c316395092327275cdda652b0993d6461dc9232 | |||
v1.0 | instruct | Filter | Filter_22576_I | You'll be asked to create a function `closest_pair` that takes in a list of points as input and returns the closest pair of points.
Example:
Input:
points = [(0, 0), (3, 4), (6, 8), (1, 1)]
Output:
((0, 0), (1, 1))
The points with the minimum distance are (0, 0) and (1, 1) which are 1.41 units apart.
**Task:**
Cr... | import math
def distance(p1, p2):
return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def closest_pair(points):
min_distance = float('inf')
closest = None
for i in range(len(points)):
for j in range(i + 1, len(points)):
d = distance(points[i], points[j])
if d < mi... | from solution import closest_pair
def test_closest_pair_case1():
points = [(0, 0), (3, 4), (6, 8), (1, 1)]
result = closest_pair(points)
assert result == ((0, 0), (1, 1))
def test_closest_pair_case2():
points = [(0, 0), (5, 5), (3, 4), (1, 2)]
result = closest_pair(points)
assert result in [((... | [
{
"docstring": null,
"function_declaration": "def distance(p1, p2):",
"function_name": "distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def closest_pair(points):",
"function_name": "closest_pair",
"parameter_list": "(points)"
}
] | [
0,
0,
0,
1,
0,
1,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef closest_pair(points):\n \"\"\"\n Returns the closest pair of points from the given list of points.\n Each point is represented as a tuple (x, y).\n \"\"\"\n d... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00022576",
"row_id": 22576,
"seed_ids": "['Llama-3.3-70B-Instruct_56525']"
} | 0.686455 | Filter_22576 | I | [
"distance",
"closest_pair"
] | 2 | [
[
"closest_pair",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b849b72beed17bbd5d73d8aaf8f34627d68a6273 | 8e06f0dbec7cad8809ffb56ccbd72e3240babb67 | |||
v1.0 | instruct | Filter | Filter_22600_I | I have a function called GenerateSignal which is used to create random signal time series with the specified size. Now I want to create a new function called AugmentData which takes a signal and augment it.
```python
import numpy as np
def GenerateSignal(size):
t = np.arange(size)
signal = np.sin(2 * np.pi *... | import numpy as np
def GenerateSignal(size):
t = np.arange(size)
signal = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 20 * t)
noise = 0.1 * np.random.randn(size)
return signal + noise
def TimeWarp(signal, speed_rate):
if speed_rate <= 0:
raise ValueError("speed_rate must be great... | from solution import GenerateSignal, AugmentData, TimeWarp
import numpy as np
def test_generate_signal_length():
signal = GenerateSignal(1000)
assert len(signal) == 1000
def test_timewarp_speed_rate_1():
np.random.seed(0)
signal = GenerateSignal(10)
warped_signal = TimeWarp(signal, 1)
assert n... | [
{
"docstring": null,
"function_declaration": "def GenerateSignal(size):",
"function_name": "GenerateSignal",
"parameter_list": "(size)"
},
{
"docstring": null,
"function_declaration": "def TimeWarp(signal, speed_rate):",
"function_name": "TimeWarp",
"parameter_list": "(signal, sp... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef GenerateSignal(size):\n t = np.arange(size)\n signal = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 20 * t)\n noise = 0.1 * np.random.randn(size)\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022600",
"row_id": 22600,
"seed_ids": "['Llama-3.3-70B-Instruct_56577']"
} | 0.482353 | Filter_22600 | I | [
"GenerateSignal",
"TimeWarp",
"AugmentData"
] | 3 | [
[
"AugmentData",
"TimeWarp"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 579585b52ef44c5c34577dadaff7ef507acc808f | 6e5825226202b0b9d7882f30dbd9ff2ba9bbb2b4 | |||
v1.0 | instruct | Filter | Filter_22652_I | ### Overview of the Approach
The overall goal is to create an operational framework that can effectively handle the production of a given text, by using a set of predefined production rules.
This framework should be able to generate a random set of production rules, apply them in a sequence to produce the given text,... | import random
grammar = {
"N": "cat | dog | elephant",
"V": "ran | jumped | danced",
"Adj": "big | small | happy"
}
# Create a dictionary to store the production rules
rules = {
"S": ["N V", "N Adj V", "Adj N V"]
}
# Get the possible values for a symbol
def get_values(grammar, symbol):
return gra... | from solution import generate_sentence, grammar, rules
def test_generate_sentence_with_NV_rule():
random.seed(0) # Set seed for reproducibility
sentence = generate_sentence(rules, grammar, "N V")
words = sentence.split()
assert len(words) == 2 # Should have two words
assert words[0] in get_values... | [
{
"docstring": null,
"function_declaration": "def get_values(grammar, symbol):",
"function_name": "get_values",
"parameter_list": "(grammar, symbol)"
},
{
"docstring": null,
"function_declaration": "def get_random_value(values):",
"function_name": "get_random_value",
"parameter_l... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ngrammar = {\n \"N\": \"cat | dog | elephant\",\n \"V\": \"ran | jumped | danced\",\n \"Adj\": \"big | small | happy\"\n}\n\nrules = {\n \"S\": [\"N V\", \"N Adj V\... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00022652",
"row_id": 22652,
"seed_ids": "['Llama-3.3-70B-Instruct_56716']"
} | 0.567939 | Filter_22652 | I | [
"get_values",
"get_random_value",
"generate_sentence"
] | 3 | [
[
"generate_sentence",
"get_random_value"
],
[
"generate_sentence",
"get_values"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fe294550b726e1481b3d2be4706cc1f3a3dd843e | 357a70d9710c8100879b1ec2f1a0bebc7830a271 | |||
v1.0 | instruct | Filter | Filter_22704_I | I have a project that requires me to create a progress bar with colors (RGB color model) to display the proportion of a specific widget on a screen. My team lead instructed me to create a function that will help manage the progress of this widget.
Here is a sample input data:
```python
data = {
"widget_name": "my... | import shutil
def rgb_to_ansi(rgb):
""" Converts an RGB tuple to ANSI escape code for terminal colors. """
return f"\033[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m"
def display_progress_bar(data):
widget_name = data["widget_name"]
total_widgets = data["total_widgets"]
widgets_completed = data["widgets_compl... | from solution import display_progress_bar
import pytest
import shutil
def test_display_progress_bar(capsys):
data = {
"widget_name": "my_widget",
"total_widgets": 100,
"widgets_completed": 50,
"rgb_completed": (0, 255, 0), # Green color
"rgb_uncompleted": (255, 0, 0) # Red... | [
{
"docstring": "Converts an RGB tuple to ANSI escape code for terminal colors. ",
"function_declaration": "def rgb_to_ansi(rgb):",
"function_name": "rgb_to_ansi",
"parameter_list": "(rgb)"
},
{
"docstring": null,
"function_declaration": "def display_progress_bar(data):",
"function_na... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport shutil\n\ndef display_progress_bar(data):\n widget_name = data[\"widget_name\"]\n total_widgets = data[\"total_widgets\"]\n widgets_completed = data[\"widgets_compl... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022704",
"row_id": 22704,
"seed_ids": "['Llama-3.3-70B-Instruct_56823']"
} | 0.511433 | Filter_22704 | I | [
"rgb_to_ansi",
"display_progress_bar"
] | 2 | [
[
"display_progress_bar",
"rgb_to_ansi"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfff1b8cb4c6d71baea1ccd9344d95035256d7c1 | 819adb4854aa1a1d4bb6d8507bc83cada33ecc1d | |||
v1.0 | instruct | Filter | Filter_22776_I | Given a directed graph represented as an adjacency list, write a function `is_uniquely_colorable` to check whether the given graph is uniquely colorable. A graph is said to be uniquely colorable if it can be colored in exactly one way using the minimum number of colors required to color the graph.
### Note:
1. You can... | from typing import List, Dict
from collections import defaultdict
def is_cyclic(graph: Dict[int, List[int]], node: int, visited: List[bool], rec_stack: List[bool]) -> bool:
"""
Helper function to detect a cycle in the graph.
"""
visited[node] = True
rec_stack[node] = True
for neighbor in graph... | from solution import is_uniquely_colorable
def test_no_edges():
assert is_uniquely_colorable(3, []) == True
def test_single_node():
assert is_uniquely_colorable(1, []) == True
def test_linear_graph():
assert is_uniquely_colorable(3, [[1, 2], [2, 3]]) == True
def test_cyclic_graph():
assert is_unique... | [
{
"docstring": "Helper function to detect a cycle in the graph.",
"function_declaration": "def is_cyclic(graph, node, visited, rec_stack):",
"function_name": "is_cyclic",
"parameter_list": "(graph, node, visited, rec_stack)"
},
{
"docstring": "Checks whether a given directed graph is uniquel... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import defaultdict\n\ndef is_uniquely_colorable(n: int, edges: List[List[int]]) -> bool:\n \"\"\"\n Checks whether a given directed graph is uni... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00022776",
"row_id": 22776,
"seed_ids": "['Llama-3.3-70B-Instruct_56981']"
} | 0.558469 | Filter_22776 | I | [
"is_cyclic",
"is_uniquely_colorable"
] | 2 | [
[
"is_uniquely_colorable",
"is_cyclic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | af0064b1b8d9eece62c5bdea97824e05aecfa0b8 | 9775fdd03b5e67640e8527a92b4aa961590c3aab | |||
v1.0 | instruct | Filter | Filter_22781_I | ### Functions and Fractals
#### Functions in the Complex Plane
Functions in the complex plane behave much like their real-valued counterparts, however it's essential to consider them as transformations of the complex plane. For instance, consider the function $f(z) = z^2$. This function squares each point in the comple... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def mandelbrot(c, max_iter):
z = c
for n in range(max_iter):
if abs(z) > 2:
return n
z = z * z + c
return max_iter
def draw_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):
... | from solution import mandelbrot, draw_mandelbrot, update
def test_mandelbrot_convergence():
assert mandelbrot(0 + 0j, 256) == 256
assert mandelbrot(2 + 2j, 256) < 256
def test_draw_mandelbrot():
xmin, xmax, ymin, ymax = -2.0, 1.0, -1.5, 1.5
width, height, max_iter = 100, 100, 256
r1, r2, mandelbro... | [
{
"docstring": null,
"function_declaration": "def mandelbrot(c, max_iter):",
"function_name": "mandelbrot",
"parameter_list": "(c, max_iter)"
},
{
"docstring": null,
"function_declaration": "def draw_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):",
"function_name": "dra... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ndef mandelbrot(c, max_iter):\n z = c\n for n in range(max_iter):\n if abs(z) > 2:\... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00022781",
"row_id": 22781,
"seed_ids": "['Llama-3.3-70B-Instruct_56993']"
} | 0.294028 | Filter_22781 | I | [
"mandelbrot",
"draw_mandelbrot",
"update",
"animate_mandelbrot"
] | 4 | [
[
"animate_mandelbrot",
"draw_mandelbrot"
],
[
"animate_mandelbrot",
"update"
],
[
"draw_mandelbrot",
"mandelbrot"
],
[
"update",
"draw_mandelbrot"
]
] | 4 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 61c83f43abc76d50ecefe1ae39fa6e7d76e51acc | 5c6219aa56079ec44b151d5fd4c07bed7615a710 | |||
v1.0 | instruct | Filter | Filter_22953_I | ###PART 1: Understanding the Problem
The problem requires writing a program to switch two nodes (any two nodes) in a binary tree and then determining whether the tree is symmetric. The definition of a symmetric binary tree is as follows:
- A binary tree is symmetric when, if you draw a line through the center node goin... | class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(root, key):
if root is None:
return Node(key)
else:
if root.key < key:
root.right = insert(root.right, key)
else:
root.left = insert(root... | from solution import Node, insert, is_symmetric, switch_nodes
def test_is_symmetric():
root = None
nodes = [50, 30, 70, 20, 40, 60, 80]
for key in nodes:
root = insert(root, key)
assert not is_symmetric(root)
symmetric_root = Node(1)
symmetric_root.left = Node(2)
symmetric_root... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n\ndef insert(root, key):\n if root is None:\n return Node(key)... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00022953",
"row_id": 22953,
"seed_ids": "['Llama-3.3-70B-Instruct_57364']"
} | 0.615819 | Filter_22953 | I | [
"insert",
"is_symmetric",
"is_mirror",
"switch_nodes",
"print_tree"
] | 5 | [
[
"is_symmetric",
"is_mirror"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 93a0b00102db2ef7af9254dca887c0a6f3851220 | f19265de27e49c77f3baa13c5b1e6b74449484f0 | |||
v1.0 | instruct | Filter | Filter_23275_I | Can you write a Python module that provides a function to find the closest pair of points out of a list of points in N-dimensional space? | import math
from itertools import combinations
def euclidean_distance(point1, point2):
"""
Calculate and return the Euclidean distance between two points in N-dimensional space.
"""
return math.sqrt(sum((x-y)**2 for x, y in zip(point1, point2)))
def closest_pair_of_points(points):
"""
Finds an... | from solution import closest_pair_of_points
def test_closest_pair_of_points_simple():
points = [(0, 0), (1, 1), (4, 5), (7, 2)]
assert closest_pair_of_points(points) == (((0, 0), (1, 1)), math.sqrt(2))
def test_closest_pair_of_points_3d():
points = [(1, 2, 3), (4, 5, 6), (1, 3, 2), (2, 4, 6)]
asse... | [
{
"docstring": "Calculate and return the Euclidean distance between two points in N-dimensional space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Finds and returns the clo... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points in N-dimensional space.\n \"\"\"\n return ma... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023275",
"row_id": 23275,
"seed_ids": "['Llama-3.3-70B-Instruct_58043']"
} | 0.621982 | Filter_23275 | I | [
"euclidean_distance",
"closest_pair_of_points"
] | 2 | [
[
"closest_pair_of_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd72dd1b9b363819907e4dbf5da698c4d79aa6fc | bdd9f420d1a97bdd7b65d0cfdc408b063548e7ef | |||
v1.0 | instruct | Filter | Filter_23279_I | Here's a question for you:
Given a list of intervals where each interval has the form [start, end] (for example, [10, 70] or [-10, 10]), remove all intervals that have an overlap with any given interval.
Example: given two intervals, [1, 3] and [2, 4], there is an overlap between them because 2 is inside of both int... | def remove_and_merge(intervals, given_interval):
new_intervals = []
current_interval = None
for interval in intervals:
if not does_overlap(given_interval, interval):
if current_interval is None:
current_interval = interval[:]
else:
current_int... | from solution import remove_and_merge
def test_no_overlap():
intervals = [[1, 3], [4, 6], [8, 10], [15, 20]]
given_interval = [9, 12]
result = remove_and_merge(intervals, given_interval)
assert result == [[1, 6], [15, 20]]
def test_all_overlap():
intervals = [[1, 10], [5, 8], [8, 12]]
given_in... | [
{
"docstring": null,
"function_declaration": "def remove_and_merge(intervals, given_interval):",
"function_name": "remove_and_merge",
"parameter_list": "(intervals, given_interval)"
},
{
"docstring": null,
"function_declaration": "def does_overlap(interval1, interval2):",
"function_n... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def remove_and_merge(intervals, given_interval):\n new_intervals = []\n current_interval = None\n\n for interval in intervals:\n if not does_overlap(given_interval, interval):\... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00023279",
"row_id": 23279,
"seed_ids": "['Llama-3.3-70B-Instruct_58054']"
} | 0.662742 | Filter_23279 | I | [
"remove_and_merge",
"does_overlap",
"merge_intervals"
] | 3 | [
[
"remove_and_merge",
"does_overlap"
],
[
"remove_and_merge",
"merge_intervals"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d205a6c74c03602701ad5e00b9c087e9bda4b517 | 037026f94d3adc5afd701a9e66ce2ac83b957041 | |||
v1.0 | instruct | Filter | Filter_23296_I | Here is the code I have written so far. I'm trying to create a simple game where the user can play against the computer. The game is simple: the computer generates a random number between 1 and 10 and the user has to guess the number. If the user guesses the number correctly, they win; if they guess incorrectly, the co... | import random
def get_computer_number():
"""Generate a random number between 1 and 10"""
return random.randint(1, 10)
def get_user_guess():
"""Get the user's guess"""
while True:
try:
guess = int(input("Guess the number: "))
if 1 <= guess <= 10:
return g... | # Since the game involves user input and random number generation,
# testing should use mocks to simulate these interactions.
import pytest
from unittest.mock import patch
from solution import get_computer_number, get_user_guess, play_game
def test_get_computer_number():
with patch('random.randint', return_value=5... | [
{
"docstring": "Generate a random number between 1 and 10",
"function_declaration": "def get_computer_number():",
"function_name": "get_computer_number",
"parameter_list": "()"
},
{
"docstring": "Get the user's guess",
"function_declaration": "def get_user_guess():",
"function_name":... | [
0,
0,
0,
1,
1,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_number():\n \"\"\"Generate a random number between 1 and 10\"\"\"\n return random.randint(1, 10)\n\ndef get_user_guess():\n \"\"\"Get the user's gues... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023296",
"row_id": 23296,
"seed_ids": "['Llama-3.3-70B-Instruct_58106']"
} | 0.610163 | Filter_23296 | I | [
"get_computer_number",
"get_user_guess",
"play_game"
] | 3 | [
[
"play_game",
"get_computer_number"
],
[
"play_game",
"get_user_guess"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | bc1eddc6db057c6e80a0ce736a6361f51eb6fdc3 | 87bd514d91ba8f8537640ca55d2573a2cd33e80c | |||
v1.0 | instruct | Filter | Filter_23300_I | Here's a Python code snippet that creates a list of all possible combinations of its elements:
```python
import itertools
def all_combinations(input_list):
result = []
for r in range(1, len(input_list) + 1):
result.extend(itertools.combinations(input_list, r))
return result
input_list = ["apple",... | import itertools
def all_combinations(input_list):
result = []
for r in range(1, len(input_list) + 1):
result.extend(itertools.combinations(input_list, r))
return result
def combinations_of_combinations(input_list, combination_length):
all_combos = all_combinations(input_list)
return list(... | from solution import all_combinations, combinations_of_combinations
def test_all_combinations():
input_list = ["apple", "banana", "cherry"]
expected_output = [
('apple',), ('banana',), ('cherry',),
('apple', 'banana'), ('apple', 'cherry'), ('banana', 'cherry'),
('apple', 'banana', 'ch... | [
{
"docstring": null,
"function_declaration": "def all_combinations(input_list):",
"function_name": "all_combinations",
"parameter_list": "(input_list)"
},
{
"docstring": null,
"function_declaration": "def combinations_of_combinations(input_list, combination_length):",
"function_name"... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef combinations_of_combinations(input_list, length):\n initial_combinations = [\n comb for r in range(1, len(input_list) + 1)\n for comb in itertools.comb... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00023300",
"row_id": 23300,
"seed_ids": "['Llama-3.3-70B-Instruct_58111']"
} | 0.716494 | Filter_23300 | I | [
"all_combinations",
"combinations_of_combinations"
] | 2 | [
[
"combinations_of_combinations",
"all_combinations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 227e794405bc018574cb3961d0b93fcf9c901480 | 4f56f883b3290290864e0f34c24ff8b6242bc33f | |||
v1.0 | instruct | Filter | Filter_23350_I | Here is a code I found online, how can I modify this algorithm to make a true ransac algorithm implementation.
```python
import random
import numpy as np
def calculate_model_error(point, line):
# calculate perpendicular distance
a, b, c = line
numerator = abs(a*point[0] + b*point[1] + c)
denominator =... | import random
import numpy as np
def calculate_model_error(point, line):
"""
Calculate the perpendicular distance from a point to a line.
"""
a, b, c = line
numerator = abs(a * point[0] + b * point[1] + c)
denominator = np.sqrt(a**2 + b**2)
error = numerator / denominator
return error
... | import numpy as np
from solution import ransac
# Mock numpy's random function to generate deterministic test data
def mock_randint(low, high, size):
return np.array([[-10, -10], [-10, 10], [10, -10], [10, 10], [0,0]])
# Inject the mock_randint into numpy
np.random.randint = mock_randint
def test_ransac_on_noisy_... | [
{
"docstring": "Calculate the perpendicular distance from a point to a line.",
"function_declaration": "def calculate_model_error(point, line):",
"function_name": "calculate_model_error",
"parameter_list": "(point, line)"
},
{
"docstring": "Randomly select k points from the given points.",
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\n\ndef calculate_model_error(point, line):\n a, b, c = line\n numerator = abs(a*point[0] + b*point[1] + c)\n denominator = np.sqrt(a**2 + b**2)\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00023350",
"row_id": 23350,
"seed_ids": "['Llama-3.3-70B-Instruct_58228']"
} | 0.497533 | Filter_23350 | I | [
"calculate_model_error",
"select_points",
"fit_model",
"ransac",
"main"
] | 5 | [
[
"ransac",
"calculate_model_error"
],
[
"ransac",
"fit_model"
],
[
"ransac",
"select_points"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 5d7ec4d41798b779f3048cd224dfc65a5d7e6b44 | 0e292611383ca7594157e00c7b07eb65be5522c2 | |||
v1.0 | instruct | Filter | Filter_23527_I | Here is a code that is supposed to be finding the closest pair of points among a set of points in a 2D plane. But the code doesn't produce the expected output.
```python
import math
def distance(point1, point2):
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def brute_force_closest... | import math
def distance(point1, point2):
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def brute_force_closest_pair(points):
min_distance = float('inf')
closest_pairs = []
n = len(points)
for i in range(n):
for j in range(i + 1, n):
dist = dista... | from solution import closest_pair
def test_one_pair_of_points():
points = [(0, 0), (1, 1)]
expected_pairs = [((0, 0), (1, 1))]
closest_points, min_distance = closest_pair(points)
assert closest_points == expected_pairs
assert min_distance == 1.4142135623730951
def test_multiple_pairs_with_min_dist... | [
{
"docstring": null,
"function_declaration": "def distance(point1, point2):",
"function_name": "distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def brute_force_closest_pair(points):",
"function_name": "brute_force_closest_pair",
"p... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(point1, point2):\n return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)\n\ndef brute_force_closest_pairs(points):\n min_distance = fl... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00023527",
"row_id": 23527,
"seed_ids": "['Llama-3.3-70B-Instruct_58679']"
} | 0.639788 | Filter_23527 | I | [
"distance",
"brute_force_closest_pair",
"closest_pair",
"main"
] | 4 | [
[
"brute_force_closest_pair",
"distance"
],
[
"closest_pair",
"brute_force_closest_pair"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fa30acfade103fb68fef82ac8604e513f1dbb02c | 9b70b0456e800ff33cd2ff6a38130b77f697210a | |||
v1.0 | instruct | Filter | Filter_23535_I | I have a list of driver's license numbers that I would like to anonymize by replacing certain digits with a placeholder ("*") to hide the sensitive information, while still keeping enough information to distinguish between individual licenses.
Consider the following list of driver's license numbers:
1. SMG123456
2... | def anonymize_license(license_number):
"""
Anonymizes a driver's license number by keeping the first 2 characters,
the last character and replacing the rest with '*'.
"""
if len(license_number) < 3:
raise ValueError("License number should be at least 3 characters long")
return licen... | from solution import anonymize_license, anonymize_license_list
def test_anonymize_license():
assert anonymize_license("SMG123456") == "SM******6"
assert anonymize_license("SMG987654") == "SM******4"
assert anonymize_license("SMG111111") == "SM******1"
assert anonymize_license("SMG222222") == "SM******2... | [
{
"docstring": "Anonymizes a driver's license number by keeping the first 2 characters,\nthe last character and replacing the rest with '*'.",
"function_declaration": "def anonymize_license(license_number):",
"function_name": "anonymize_license",
"parameter_list": "(license_number)"
},
{
"do... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def anonymize_license(license_numbers):\n \"\"\"\n Anonymizes a list of driver's license numbers by keeping the first 2 and last character,\n and replacing the rest of the characters ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00023535",
"row_id": 23535,
"seed_ids": "['Llama-3.3-70B-Instruct_58692']"
} | 0.477534 | Filter_23535 | I | [
"anonymize_license",
"anonymize_license_list"
] | 2 | [
[
"anonymize_license_list",
"anonymize_license"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e0e7119754bd61cd77fa25a90f381df570c7e864 | 60909b2df3066930545a6c98ee9d7dd96d058f45 | |||
v1.0 | instruct | Filter | Filter_23542_I | ### Important Notes
- Please go through the problem description carefully.
- Try to come up with a correct and efficient solution.
- If you are using any online resources, please cite them.
- Test your code thoroughly before providing the final output.
- Make sure to include all necessary details in the explanation.
#... | from collections import defaultdict
def calculate_frequency(string):
"""
Calculate the frequency of each character in the string.
Parameters:
string (str): The input string.
Returns:
dict: A dictionary with characters as keys and their frequencies as values.
"""
frequency = de... | def test_find_minimum_window_exact_string():
assert find_minimum_window("aabccc") == "aabccc"
def test_find_minimum_window_single_char():
assert find_minimum_window("a") == "a"
def test_find_minimum_window_repeated_chars():
assert find_minimum_window("ababababab") == "ababababab"
def test_find_minimum_wi... | [
{
"docstring": "Calculate the frequency of each character in the string.\n\nParameters:\nstring (str): The input string.\n\nReturns:\ndict: A dictionary with characters as keys and their frequencies as values.",
"function_declaration": "def calculate_frequency(string):",
"function_name": "calculate_freq... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\n\ndef calculate_frequency(string):\n \"\"\"\n Calculate the frequency of each character in the string.\n \n Parameters:\n string (str): The ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023542",
"row_id": 23542,
"seed_ids": "['Llama-3.3-70B-Instruct_58711']"
} | 0.632993 | Filter_23542 | I | [
"calculate_frequency",
"find_minimum_window"
] | 2 | [
[
"find_minimum_window",
"calculate_frequency"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d6826c6156a832a6e1bbd4d5970b92a5816ad693 | 509543707fded07a61df8491dab7037579d1c20a | |||
v1.0 | instruct | Filter | Filter_23614_I | Given a sequence of words, determine the shortest possible chain of words from a given starting word to a given ending word.
A chain of words is defined as a sequence of words where each word is one edit distance away from the previous word.
The edit distance between two words is the minimum number of single-character ... | from collections import deque
def bfs_shortest_chain(start, end, word_dict):
"""
Returns the shortest chain of words from start to end where each word in the chain is one edit distance away from the previous word.
"""
if start == end:
return [start]
queue = deque([[start]])
visited... | def test_bfs_shortest_chain_basic_case():
word_list = ["hot", "dot", "dog", "lot", "log", "cog"]
word_dict = set(word_list)
start = "hit"
end = "cog"
result = bfs_shortest_chain(start, end, word_dict)
# Valid result can be ['hit', 'hot', 'dot', 'dog', 'cog'], ['hit', 'hot', 'lot', 'log', 'cog']
... | [
{
"docstring": "Returns the shortest chain of words from start to end where each word in the chain is one edit distance away from the previous word.",
"function_declaration": "def bfs_shortest_chain(start, end, word_dict):",
"function_name": "bfs_shortest_chain",
"parameter_list": "(start, end, word... | [
0,
0,
0,
0,
0,
1,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_shortest_chain(start, end, word_dict):\n if end not in word_dict:\n return []\n\n queue = deque([[start]])\n visited = set(start)\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023614",
"row_id": 23614,
"seed_ids": "['Llama-3.3-70B-Instruct_58860']"
} | 0.568698 | Filter_23614 | I | [
"bfs_shortest_chain",
"generate_next_words"
] | 2 | [
[
"bfs_shortest_chain",
"generate_next_words"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c872fa6206d6458d4d5056f9aa8814df909724b6 | b4a0cde9b88b7d1d5cd868c69450b8fd9e68ae92 | |||
v1.0 | instruct | Filter | Filter_23628_I | I was working on my science project in which an Arudino is being used to control a robot. As per the project, the Arudino is supposed to create graphs of the robot's movements and position of its various joints.
To make this happen, I am thinking of using matplotlib which is a python library as it is popular and powe... | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
def get_arduino_data():
"""
Simulate reading from Arduino by returning a random number.
(Replace this function with actual reading from Arduino).
"""
return random.randint(0, 10)
def update_plot(frame, line, dat... | from solution import get_arduino_data, update_plot
def test_get_arduino_data():
data = [get_arduino_data() for _ in range(100)]
assert all(0 <= value <= 10 for value in data)
def test_update_plot():
data = []
line = type('line', (object,), {'set_ydata': lambda self, y: None, 'set_xdata': lambda self, ... | [
{
"docstring": "Simulate reading from Arduino by returning a random number.\n(Replace this function with actual reading from Arduino).",
"function_declaration": "def get_arduino_data():",
"function_name": "get_arduino_data",
"parameter_list": "()"
},
{
"docstring": "Update the plot line with... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport serial\nimport time\n\ndef read_arduino_data(serial_port):\n \"\"\"\n Read data from the Arduino via ser... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00023628",
"row_id": 23628,
"seed_ids": "['Llama-3.3-70B-Instruct_58894']"
} | 0.408737 | Filter_23628 | I | [
"get_arduino_data",
"update_plot",
"real_time_plot"
] | 3 | [
[
"real_time_plot",
"get_arduino_data"
],
[
"real_time_plot",
"update_plot"
],
[
"update_plot",
"get_arduino_data"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | 6c698ea841a70ee7e42af8c231d6ad37d52918b0 | 30d70248787134ac4fcd649703780fc4ed4f4069 | |||
v1.0 | instruct | Filter | Filter_23650_I | Here is a Python code for a simple game where you're in a fantasy world and you need to win territories by solving a math problem to conquer a territory:
```python
import random
def get_problem():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operation = random.choice(['+', '-', '*'])
retur... | import random
def get_problem(difficulty):
if difficulty == 'Easy':
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operation = random.choice(['+', '-'])
elif difficulty == 'Medium':
num1 = random.randint(1, 20)
num2 = random.randint(1, 20)
operation = ... | from solution import get_problem, solve_problem
def test_get_problem_easy():
num1, num2, operation = get_problem('Easy')
assert 1 <= num1 <= 10
assert 1 <= num2 <= 10
assert operation in ['+', '-']
def test_get_problem_medium():
num1, num2, operation = get_problem('Medium')
assert 1 <= num1 <=... | [
{
"docstring": null,
"function_declaration": "def get_problem(difficulty):",
"function_name": "get_problem",
"parameter_list": "(difficulty)"
},
{
"docstring": null,
"function_declaration": "def solve_problem(num1, num2, operation):",
"function_name": "solve_problem",
"parameter_... | [
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import random\n\ndef get_problem(difficulty):\n if difficulty == 'Easy':\n num1 = random.randint(1, 10)\n num2 = random.randint(1, 10)\n operat... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00023650",
"row_id": 23650,
"seed_ids": "['Llama-3.3-70B-Instruct_58937']"
} | 0.541481 | Filter_23650 | I | [
"get_problem",
"solve_problem",
"game"
] | 3 | [
[
"game",
"get_problem"
],
[
"game",
"solve_problem"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 21691407e433fb65b28dadf7eb5978e18398e9a4 | 43e236a414d95a783bb5a150c99cc573e01774d0 | |||
v1.0 | instruct | Filter | Filter_23656_I | ### Introduction
Algorithms for solving optimization problems often rely on exploring the problem space, moving through it in an informed manner to find the optimal solution. One method to achieve this involves representing possible solutions as a lattice (or grid) of points, and using an energy (or fitness) function ... | import numpy as np
# Set seed for reproducibility
np.random.seed(42)
def f(x, y, z):
"""
Energy function to be optimized.
"""
return np.exp(-((x-1)**2 + (y-2)**2 + (z-3)**2))
def optimize_function():
# Initialize x, y, z
x, y, z = 10, 10, 10
energy = f(x, y, z)
min_x, min_y, min_... | from solution import f, optimize_function
import numpy as np
def test_f():
assert np.isclose(f(1, 2, 3), 1.0, atol=1e-5)
assert np.isclose(f(0, 0, 0), np.exp(-14), atol=1e-5)
assert np.isclose(f(10, 10, 10), np.exp(-218), atol=1e-5)
def test_optimize_function():
np.random.seed(42) # Ensure reproducib... | [
{
"docstring": "Energy function to be optimized.",
"function_declaration": "def f(x, y, z):",
"function_name": "f",
"parameter_list": "(x, y, z)"
},
{
"docstring": null,
"function_declaration": "def optimize_function():",
"function_name": "optimize_function",
"parameter_list": "(... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\n# Set seed for reproducibility\nnp.random.seed(42)\n\ndef f(x, y, z):\n \"\"\"\n Energy function to be optimized.\n \"\"\"\n return np.exp(-((x-1)**2 + (y-2)*... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00023656",
"row_id": 23656,
"seed_ids": "['Llama-3.3-70B-Instruct_58952']"
} | 0.480436 | Filter_23656 | I | [
"f",
"optimize_function"
] | 2 | [
[
"optimize_function",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 6550023479759a4408bc637877e3d8f8474b6279 | bdeac3ad57baa91b17d336ba0abcfae06fa645ca | |||
v1.0 | instruct | Filter | Filter_23748_I | Here's a reference solution for a minimax algorithm in Python:
```python
def minimax(board, depth, is_maximizing):
if is_win(board) or depth == 0:
return evaluate_board(board)
if is_maximizing:
best_value = -float('inf')
for move in get_possible_moves(board):
new_board = mak... | def minimax_alpha_beta(board, depth, is_maximizing, alpha, beta):
"""
Implements the minimax algorithm with alpha-beta pruning.
Args:
board (list): Current state of the board.
depth (int): Maximum depth for the search.
is_maximizing (bool): True if the current level is maximizing, else Fals... | from solution import minimax_alpha_beta, is_win, evaluate_board, get_possible_moves, make_move
def test_minimax_alpha_beta():
# Test specific scenarios for the minimax_alpha_beta function
board = ['initial_state']
depth = 3
alpha = -float('inf')
beta = float('inf')
# Scenario: No winning state... | [
{
"docstring": "Implements the minimax algorithm with alpha-beta pruning.\n\nArgs:\nboard (list): Current state of the board.\ndepth (int): Maximum depth for the search.\nis_maximizing (bool): True if the current level is maximizing, else False.\nalpha (float): The best value that the maximizer currently can gu... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimax_alpha_beta(board, depth, is_maximizing, alpha, beta):\n if is_win(board) or depth == 0:\n return evaluate_board(board)\n\n if is_maximizing:\n best_value = -flo... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00023748",
"row_id": 23748,
"seed_ids": "['Llama-3.3-70B-Instruct_59178']"
} | 0.392669 | Filter_23748 | I | [
"minimax_alpha_beta",
"is_win",
"evaluate_board",
"get_possible_moves",
"make_move"
] | 5 | [
[
"minimax_alpha_beta",
"evaluate_board"
],
[
"minimax_alpha_beta",
"get_possible_moves"
],
[
"minimax_alpha_beta",
"is_win"
],
[
"minimax_alpha_beta",
"make_move"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 094ef265899d6deea51cbbfa3ef02624bee59fda | cf82bea93af8c2942b4f30d0f2779712904a1664 | |||
v1.0 | instruct | Filter | Filter_23785_I | Write a code that allows you to configure, compile and run an ML model using command line arguments.
Here's an example of the expected API:
```bash
python3 ml_script.py --model_name <model_name> --hyperparams <hyperparams> --train_data <train_data> --test_data <test_data>
```
You'll need to consider the following hyp... | import argparse
import json
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
def load_data(file_path):
data = []
labels = []
with open(file_path, 'r') as f:
for line in f:
item = json.loads(line)
labels.append(ite... | import json
import numpy as np
import os
import pytest
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
# Assume `solution.py` has been imported and the `train_and_evaluate` function is accessible
from solution import train_and_evaluate, load_data
# Helper functions for test... | [
{
"docstring": null,
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def train_and_evaluate(model_name, hyperparams_path, train_data_path, test_data_path):",
"function_... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport json\nimport numpy as np\nimport tensorflow as tf\n\ndef load_data(file_path):\n features, labels = [], []\n with open(file_path, 'r') as file:\n for line ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00023785",
"row_id": 23785,
"seed_ids": "['Llama-3.3-70B-Instruct_59268']"
} | 0.433441 | Filter_23785 | I | [
"load_data",
"train_and_evaluate"
] | 2 | [
[
"train_and_evaluate",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 961645c372f20e7c4cd0df00e0fc4330e0200da1 | 463df89859f9562eaa14929babb9a77853bfb029 | |||
v1.0 | instruct | Filter | Filter_23857_I | ### Game Project: Hangman
#### Project Overview
Hangman is a guessing game where one player thinks of a word, and the other player tries to guess the word by suggesting letters. For each incorrect guess, a part of a hangman's gallows is drawn. The game continues until the word is guessed or the gallows is complete and ... | import random
HANGMAN_PICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O ... | import pytest
from solution import getRandomWord, displayBoard, getGuess, playAgain, hangman, words
def test_getRandomWord():
word = getRandomWord(words)
assert word in words
def test_displayBoard(capsys):
missedLetters = 'a'
correctLetters = 'o'
secretWord = 'fox'
displayBoard(HANGMAN_PICS, m... | [
{
"docstring": null,
"function_declaration": "def getRandomWord(wordList):",
"function_name": "getRandomWord",
"parameter_list": "(wordList)"
},
{
"docstring": null,
"function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):",
"function_name":... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def play_hangman(HANGMAN_PICS, words):\n correct_letters = ''\n missed_letters = ''\n secret_word = getRandomWord(words)\n game_over = False\n\n while True:\n displayBoar... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00023857",
"row_id": 23857,
"seed_ids": "['Llama-3.3-70B-Instruct_59435']"
} | 0.500489 | Filter_23857 | I | [
"getRandomWord",
"displayBoard",
"getGuess",
"playAgain",
"hangman"
] | 5 | [
[
"hangman",
"displayBoard"
],
[
"hangman",
"getGuess"
],
[
"hangman",
"getRandomWord"
],
[
"hangman",
"playAgain"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 35939739cb40ddb50fbb3ddc93556bca6ac46d54 | 557f77d9b6aea325d09384e4b93f3a2e24e228ca | |||
v1.0 | instruct | Filter | Filter_23928_I | I have a binary tree node with the structure of (id, value, left, right) where id, left and right are integers and value is a string. I want to convert the binary tree to a forest of binary search trees, where the 'value' node is the key of the binary search tree. The conversion should be that for each node, if it does... | class TreeNode:
def __init__(self, id, value, left=None, right=None):
self.id = id
self.value = value
self.left = left
self.right = right
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_into_bs... | from solution import TreeNode, convert_binary_tree_to_forest, insert_into_bst
def test_insert_into_bst():
bst = BSTNode('m')
insert_into_bst(bst, 'a')
insert_into_bst(bst, 'z')
assert bst.left.value == 'a'
assert bst.right.value == 'z'
def test_convert_single_node_tree():
tree = TreeNode(1, 'm... | [] | [
0,
0,
0,
1,
0,
1,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, node_id, value, left=None, right=None):\n self.node_id = node_id\n self.value = value\n self.left = left\n self.right = righ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00023928",
"row_id": 23928,
"seed_ids": "['Llama-3.3-70B-Instruct_59609']"
} | 0.372921 | Filter_23928 | I | [
"insert_into_bst",
"convert_binary_tree_to_forest"
] | 2 | [
[
"convert_binary_tree_to_forest",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode",
"BSTNode"
] | true | pytest | true | [] | true | be8e68328cf24b9a6e035ae0a47e6d3fef51901f | 14de2b7ad8f71393ae69df669a2baa3b24c0b350 | |||
v1.0 | instruct | Filter | Filter_24102_I | Given a square matrix, find the element which is the k-th smallest (or largest) in the matrix, while each element in the matrix could itself be an array of integers (or lists in python).
### Example
For the given matrix:
```python
matrix = [[1, 2, 3], [4, [5, 6]], 7, 8, [9]]
```
Find the 5th smallest element in the ab... | def flatten_matrix_recursive(matrix):
"""Flattens a nested list (matrix) recursively."""
result = []
for element in matrix:
if isinstance(element, list):
result.extend(flatten_matrix_recursive(element))
else:
result.append(element)
return result
def kth_smallest_... | from solution import kth_smallest_element_recursive, kth_smallest_element_iterative
def test_kth_smallest_element_recursive():
matrix = [[1, 2, 3], [4, [5, 6]], 7, 8, [9]]
assert kth_smallest_element_recursive(matrix, 5) == 5
assert kth_smallest_element_recursive(matrix, 1) == 1
assert kth_smallest_ele... | [
{
"docstring": "Flattens a nested list (matrix) recursively.",
"function_declaration": "def flatten_matrix_recursive(matrix):",
"function_name": "flatten_matrix_recursive",
"parameter_list": "(matrix)"
},
{
"docstring": "Finds the k-th smallest element in the matrix using a recursive approac... | [
0,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flatten_matrix_recursive(matrix):\n \"\"\"\n Recursively flattens a nested list.\n \"\"\"\n flat_list = []\n for elem in matrix:\n if isinstance(elem, list):\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024102",
"row_id": 24102,
"seed_ids": "['Llama-3.3-70B-Instruct_60024']"
} | 0.590816 | Filter_24102 | I | [
"flatten_matrix_recursive",
"kth_smallest_element_recursive",
"flatten_matrix_iterative",
"kth_smallest_element_iterative"
] | 4 | [
[
"kth_smallest_element_iterative",
"flatten_matrix_iterative"
],
[
"kth_smallest_element_recursive",
"flatten_matrix_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c2648a846595609b5b42a5e8cc9572518b81adfd | 895f26a106fe13b799decafdcd0d8cd856d84a45 | |||
v1.0 | instruct | Filter | Filter_24178_I | I propose the following dataset for color image processing:
Dataset = {I1, I2, ..., In}
Where each image Ii may have one of the following types of noise:
- Gaussian noise
- Salt and Pepper noise
- Poisson noise
- Speckle noise
I need guidance on a noise type classifier in Python for this dataset.
Here to define th... | import numpy as np
import cv2
from scipy.stats import skew, kurtosis
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
def extract_features(image):
"""
Extract statistical features from the image.
"""
features = []
# Convert th... | from solution import extract_features, augment_data, prepare_and_train_classifier, classify_noise
import numpy as np
def test_extract_features():
dummy_image = np.random.randint(0, 255, (32, 32, 3), dtype=np.uint8)
features = extract_features(dummy_image)
assert len(features) == 15 # Should capture 5 feat... | [
{
"docstring": "Extract statistical features from the image.",
"function_declaration": "def extract_features(image):",
"function_name": "extract_features",
"parameter_list": "(image)"
},
{
"docstring": null,
"function_declaration": "def augment_data(images, labels):",
"function_name"... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport cv2\nfrom skimage.feature import greycomatrix, greycoprops\nfrom skimage import io, img_as_float\nfrom scipy.stats import kurtosis, skew\nfrom sklearn.ensemble impor... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00024178",
"row_id": 24178,
"seed_ids": "['Llama-3.3-70B-Instruct_60164']"
} | 0.366364 | Filter_24178 | I | [
"extract_features",
"augment_data",
"prepare_and_train_classifier",
"classify_noise"
] | 4 | [
[
"classify_noise",
"extract_features"
],
[
"prepare_and_train_classifier",
"augment_data"
],
[
"prepare_and_train_classifier",
"extract_features"
]
] | 3 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy",
"scipy",
"sklearn"
] | false | 920cf495ef5c14c121f3e925d1bfb7ca6d6863e9 | 09e9cec881ac017b6692e8f3e525d9732ca3d882 | |||
v1.0 | instruct | Filter | Filter_24226_I | Given the function:
$$
f(x)=\left( x^2 + \frac{16}{x^2} \right) \sin x - 4 \left( \frac{1}{x} + x \right) \cos x
$$
Develop a Python program that determines the roots of the function using numerical methods, particularly Newton-Raphson method for finding the roots. | import numpy as np
from scipy.optimize import newton
def f(x):
"""
Given function f(x).
"""
return (x**2 + 16/x**2) * np.sin(x) - 4 * (1/x + x) * np.cos(x)
def f_prime(x):
"""
Derivative of the given function f(x).
Calculated using symbolic differentiation.
"""
return (x**2 + 16/x*... | import pytest
from solution import f, find_root
def test_root_near_initial_guess_1():
root = find_root(1)
assert np.isclose(f(root), 0, atol=1e-6) # Check that f(root) is close to 0
def test_root_near_initial_guess_2():
root = find_root(2)
assert np.isclose(f(root), 0, atol=1e-6) # Check that f(root... | [
{
"docstring": "Given function f(x).",
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": "Derivative of the given function f(x).\nCalculated using symbolic differentiation.",
"function_declaration": "def f_prime(x):",
"function_name"... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom scipy.optimize import newton\n\ndef f(x):\n \"\"\"\n The function f(x) as defined in the problem.\n \"\"\"\n return (x**2 + 16/x**2) * math.sin(x) - 4 * (1/x + x)... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024226",
"row_id": 24226,
"seed_ids": "['Llama-3.3-70B-Instruct_60257']"
} | 0.462462 | Filter_24226 | I | [
"f",
"f_prime",
"find_root"
] | 3 | [
[
"find_root",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 0f6a483f9b8b7119e4606554bac6da08edfc2a0d | b9d92a6702595d5162badfa8bff8298db4fcd801 | |||
v1.0 | instruct | Filter | Filter_24265_I | ### Your task is to write the code for the decorator that the comment below suggests.
```python
# Decorator to implement retry functionality
def retry(tries=3, delay=1, exempt=set()):
# TODO: implement this decorator
pass
```
### Your task is to split the argument `tries` into two arguments: `max_attempts` and... | import time
import random
def retry(max_attempts=3, num_retries=3, delay=1, exempt=set(), callback=None):
def decorator_retry(func):
def wrapper(*args, **kwargs):
attempts = 0
retries = 0
while attempts < max_attempts:
try:
... | from solution import retry, dice_roll
def test_dice_roll_success():
result = None
for _ in range(100):
try:
result = dice_roll()
if result % 2 != 0:
break
except RuntimeError as e:
print(e)
assert result % 2 != 0
def test_dice_roll_retry_... | [
{
"docstring": null,
"function_declaration": "def retry(max_attempts=3, num_retries=3, delay=1, exempt=set(), callback=None):",
"function_name": "retry",
"parameter_list": "(max_attempts=3, num_retries=3, delay=1, exempt=set(), callback=None)"
},
{
"docstring": null,
"function_declaratio... | [
0,
0,
0,
1,
1,
0,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom functools import wraps\n\ndef retry(max_attempts=3, num_retries=3, delay=1, exempt=set(), callback=None):\n def decorator(func):\n @wraps(func)\n def wrapper... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00024265",
"row_id": 24265,
"seed_ids": "['Llama-3.3-70B-Instruct_60339']"
} | 0.508233 | Filter_24265 | I | [
"retry",
"dice_roll"
] | 2 | [
[
"dice_roll",
"retry"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6bcb059a397d63d794ebc0d157792f41d089e23f | 7c19ea7506eb6e581318aba673cacc34b20a3eed | |||
v1.0 | instruct | Filter | Filter_24276_I | This task requires generating procedural dungeon layout algorithms (genetic algorithm and ant colony optimization algorithm) to create wow-like procedural generated dungeons.
To create these algorithms, it can be helpful to watch tutorials or instructional videos that explain how to implement genetic and ant colony al... | import random
ROOM_TYPES = ['empty', 'treasure', 'monster']
DUNGEON_SIZE = 100
ROOM_SIZE = 5
POPULATION_SIZE = 100
MUTATION_RATE = 0.1
TOURNAMENT_SIZE = 5
NUMBER_OF_GENERATIONS = 100
CROSSOVER_RATE = 0.7
class Room:
def __init__(self, x, y, room_type):
self.x = x
self.y = y
self.room_type ... | from solution import Room, Dungeon, create_random_dungeon, crossover, mutate, genetic_algorithm
def test_create_random_dungeon():
dungeon = create_random_dungeon()
assert isinstance(dungeon, Dungeon)
assert len(dungeon.rooms) > 0
for room in dungeon.rooms:
assert isinstance(room, Room)
... | [] | [
0,
0,
0,
1,
0,
0,
1,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass Room:\n EMPTY = 0\n TREASURE = 1\n MONSTER = 2\n\n def __init__(self, x, y, w, h, room_type):\n self.x = x\n self.y = y\n self.width = w... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00024276",
"row_id": 24276,
"seed_ids": "['Llama-3.3-70B-Instruct_60372']"
} | 0.520248 | Filter_24276 | I | [
"create_random_dungeon",
"crossover",
"mutate",
"select_parent",
"genetic_algorithm"
] | 5 | [
[
"genetic_algorithm",
"create_random_dungeon"
],
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select_parent"
]
] | 4 | [] | false | [
"Room",
"Dungeon"
] | true | pytest | true | [] | true | 9277b7fbcb1ae2a86fad303cdc81e79980cd3044 | b6f1cecd91ca4ddbf398700ae4e1eec371a759f0 | |||
v1.0 | instruct | Filter | Filter_24289_I | Consider a bounding box around a video frame with cornes at (10, 10), (100, 10), (100, 100), (10, 100).
Implement the detection of nesting in your favourite programming language. Given a list of other bounding boxes (represented by 4-tuples specifying the top-left and bottom-right corners, e.g., (x1,y1,x2,y2)) , retu... | def is_box_inside(main_box, other_box):
"""
Check if other_box is completely inside main_box.
:param main_box: tuple, boundary of main box represented as (x1, y1, x2, y2)
:param other_box: tuple, boundary of other box represented as (x1, y1, x2, y2)
:return: bool, True if other_box is inside main_bo... | from solution import is_box_inside, find_nested_boxes
def test_is_box_inside():
main_box = (10, 10, 100, 100)
assert is_box_inside(main_box, (10, 11, 11, 12)) == True
assert is_box_inside(main_box, (15, 15, 20, 20)) == True
assert is_box_inside(main_box, (5, 5, 120, 120)) == False
assert is_box_ins... | [
{
"docstring": "Check if other_box is completely inside main_box.\n:param main_box: tuple, boundary of main box represented as (x1, y1, x2, y2)\n:param other_box: tuple, boundary of other box represented as (x1, y1, x2, y2)\n:return: bool, True if other_box is inside main_box, else False",
"function_declara... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_box_inside(main_box, box):\n \"\"\"\n Check if a given box is inside the main box.\n \n :param main_box: Tuple with 4 values representing the main box (x1, y1, x2, y2).\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00024289",
"row_id": 24289,
"seed_ids": "['Llama-3.3-70B-Instruct_60396']"
} | 0.482938 | Filter_24289 | I | [
"is_box_inside",
"find_nested_boxes"
] | 2 | [
[
"find_nested_boxes",
"is_box_inside"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b65f0aa24bc5eded7d6387a6e95bc597a0f091a5 | a85e7d3cec67b759d9411bf79fb59f5248ab6601 | |||
v1.0 | instruct | Filter | Filter_24357_I | How do I make a Gaussian filter in Python without using the built-in Gaussian filter functions from libraries such as OpenCV or SciPy? | import numpy as np
def gaussian_kernel(size, sigma):
"""
Generates a square Gaussian kernel.
Parameters:
size (int): The size of the kernel. It should be an odd number.
sigma (float): The standard deviation of the Gaussian distribution.
Returns:
numpy.ndarray: A 2D array represent... | import numpy as np
from solution import gaussian_kernel, gaussian_filter
def test_gaussian_kernel_sum():
size = 5
sigma = 1.0
kernel = gaussian_kernel(size, sigma)
assert np.isclose(np.sum(kernel), 1.0), "Gaussian kernel should sum to 1"
def test_gaussian_kernel_symmetry():
size = 5
sigma = 1.... | [
{
"docstring": "Generates a square Gaussian kernel.\n\nParameters:\nsize (int): The size of the kernel. It should be an odd number.\nsigma (float): The standard deviation of the Gaussian distribution.\n\nReturns:\nnumpy.ndarray: A 2D array representing the Gaussian kernel.",
"function_declaration": "def gau... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef gaussian_kernel(size, sigma=1):\n \"\"\"\n Generates a Gaussian kernel.\n \n Parameters:\n size (int): The size of the kernel (must be odd).\n sigma... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00024357",
"row_id": 24357,
"seed_ids": "['Llama-3.3-70B-Instruct_60563']"
} | 0.538133 | Filter_24357 | I | [
"gaussian_kernel",
"gaussian_filter"
] | 2 | [
[
"gaussian_filter",
"gaussian_kernel"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | f14e56e1fe8edb61d11e29e9c376aa1e71ed4fdc | ff5dd1b1009035cfaa575a9b0721c070213e69fd | |||
v1.0 | instruct | Filter | Filter_24361_I | Here are a few utility programs that attempt to extract rifle and handgun ammunition data from a list and organize them. Note that the goals are self-documenting (# comments).
```python
# The goals are:
# 1) Extract type-specific ammo data from list (separate rifle and handgun)
# 2) Sort data in ascending order ... | GR = 'gr'
METRIC_TO_IMPERIAL = {
'gr': 'gram',
}
IMPERIAL_TO_METRIC = {
'gr': 'g',
}
def process_ammo_data(input_list):
"""Process the provided ammo data into categorized and sorted output."""
rifle_list = []
handgun_list = []
# go through each ammo data point
for ammo_data in input_list:
... | from solution import process_ammo_data, convert_to_metric, get_speed
def test_convert_to_metric():
# Test conversion from grain to gram
assert convert_to_metric('357 mag ammo, handgun, 158gr, 1000fps') == '357 mag ammo, handgun, 10.24g, 1000fps'
assert convert_to_metric('44 mag ammo, rifle, 240gr, 1400fps'... | [
{
"docstring": "Process the provided ammo data into categorized and sorted output.",
"function_declaration": "def process_ammo_data(input_list):",
"function_name": "process_ammo_data",
"parameter_list": "(input_list)"
},
{
"docstring": "Attempt to convert units in the ammo data to metric uni... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# The goals are:\n# 1) Extract type-specific ammo data from list (separate rifle and handgun)\n# 2) Sort data in ascending order within types\n# 3) Convert cal to metric\n\n# Here's t... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00024361",
"row_id": 24361,
"seed_ids": "['Llama-3.3-70B-Instruct_60576']"
} | 0.386284 | Filter_24361 | I | [
"process_ammo_data",
"convert_to_metric",
"get_speed"
] | 3 | [
[
"process_ammo_data",
"convert_to_metric"
],
[
"process_ammo_data",
"get_speed"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 92226f9190363af18ab912bf0e4676330af1bc08 | 2a1c8b571597a0e07202b72b08e4c4141de63ab9 | |||
v1.0 | instruct | Filter | Filter_24390_I | My algorithm searches all possible boards (Source and Target state) in a grid with dimensions $n \times 3$ to find the optimal solution to a sliding-tile puzzle. However, as $n$ increases, my algorithm becomes inefficient because it has to generate and check all these possible board configurations. I'd like to modify m... | class Node:
def __init__(self, state, parent, move, cost, heuristic):
self.state = state
self.parent = parent
self.move = move
self.cost = cost
self.heuristic = heuristic
@property
def total_cost(self):
return self.cost + self.heuristic
def manhattan_distan... | from solution import Node, a_star, print_path, manhattan_distance
def test_manhattan_distance():
state = [
[1, 2, 3],
[4, 0, 5]
]
goal_state = [
[1, 2, 3],
[4, 5, 0]
]
assert manhattan_distance(state, goal_state) == 1
def test_a_star_shortest_path():
source_stat... | [] | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\nclass Node:\n def __init__(self, state, parent, move, cost, heuristic):\n self.state = state\n self.parent = parent\n self.move = move\n self.cos... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00024390",
"row_id": 24390,
"seed_ids": "['Llama-3.3-70B-Instruct_60646']"
} | 0.507235 | Filter_24390 | I | [
"manhattan_distance",
"get_neighbors",
"a_star",
"print_path"
] | 4 | [
[
"a_star",
"get_neighbors"
],
[
"a_star",
"manhattan_distance"
],
[
"get_neighbors",
"manhattan_distance"
]
] | 3 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 4cd1791eea134cfcb1e02ba8a3b8d13d0ffa9e51 | 8128935781a3beee51486232d7082b678519c9c2 | |||
v1.0 | instruct | Filter | Filter_24489_I | ### Developing a Pocket Change Game
The _Pocket Change_ game is an interactive game where players advance from one stage to the next by answering mathematical challenges. You are tasked with developing this game. For this, you would need to create functions for different mathematical operations.
Here is how a game st... | def get_target_number(stage_number, initial_value):
"""
Calculate target number for the given stage.
"""
return initial_value * (2 ** stage_number)
def perform_operation(current_number, operation, number):
"""
Perform the chosen operation on the current number.
"""
if operation == '+':
... | import pytest
from solution import get_target_number, perform_operation
def test_get_target_number():
assert get_target_number(0, 6) == 6
assert get_target_number(1, 6) == 12
assert get_target_number(2, 6) == 24
assert get_target_number(3, 6) == 48
def test_perform_operation_addition():
assert per... | [
{
"docstring": "Calculate target number for the given stage.",
"function_declaration": "def get_target_number(stage_number, initial_value):",
"function_name": "get_target_number",
"parameter_list": "(stage_number, initial_value)"
},
{
"docstring": "Perform the chosen operation on the current... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def pocket_changeGame(stage_number: int, current_number: int, initial_value: int) -> None:\n \"\"\"\n Function to simulate Pocket Change game\n :param stage_number: number of the curr... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00024489",
"row_id": 24489,
"seed_ids": "['Llama-3.3-70B-Instruct_60894']"
} | 0.545313 | Filter_24489 | I | [
"get_target_number",
"perform_operation",
"pocket_changeGame"
] | 3 | [
[
"pocket_changeGame",
"get_target_number"
],
[
"pocket_changeGame",
"perform_operation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 02d8a4fcd25dd9b553776a12c81d107474c1762c | e0181e275d24dad4076875ee1b9211988e1ee3ef | |||
v1.0 | instruct | Filter | Filter_24518_I | I have a function `superImportantFunction` that needs to be shared across multiple modules in a python package.
The function doesn't necessary need to be in a separate file (at the top-level can have global scope) but it's to be used in several modules in the same package without having to repeat it in each module.
... | def superImportantFunction():
"""
A super important function to be used across multiple modules.
"""
return "Super Important Result"
# Example of usage in another module
def use_super_important_function():
"""
Use `superImportantFunction` and return its result.
"""
return superImportant... | # test_super_important_function.py
from solution import superImportantFunction, use_super_important_function
def test_super_important_function_returns_expected_string():
assert superImportantFunction() == "Super Important Result"
def test_use_super_important_function():
assert use_super_important_function() =... | [
{
"docstring": "A super important function to be used across multiple modules.",
"function_declaration": "def superImportantFunction():",
"function_name": "superImportantFunction",
"parameter_list": "()"
},
{
"docstring": "Use `superImportantFunction` and return its result.",
"function_d... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# shared.py\ndef superImportantFunction():\n \"\"\"\n This is a super important function available across the package.\n \"\"\"\n return \"Super important result\"",
"test_code... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024518",
"row_id": 24518,
"seed_ids": "['Llama-3.3-70B-Instruct_60970']"
} | 0.485609 | Filter_24518 | I | [
"superImportantFunction",
"use_super_important_function"
] | 2 | [
[
"use_super_important_function",
"superImportantFunction"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd0ef2b6c3b98197fdb60353e536d75c9e7f54c2 | b6efe56b05e17096f7a6a1d80ae099d70c35be3b | |||
v1.0 | instruct | Filter | Filter_24519_I | Using Python, how would I trigger a function to call (**_athom_**) after a button is clicked while also pushing a specific string message to a tkinter text box when that button is clicked? | import tkinter as tk
def athom():
print("Function athom called")
def on_button_click(textbox, message):
athom()
textbox.insert(tk.END, message + "\n")
def create_gui():
root = tk.Tk()
root.title("Button Click Example")
textbox = tk.Text(root, height=10, width=50)
textbox.pack()
butt... | import pytest
from solution import athom, on_button_click
class MockTextbox:
def __init__(self):
self.content = ""
def insert(self, position, message):
self.content += message
def test_athom(capsys):
athom()
captured = capsys.readouterr()
assert captured.out == "Function athom... | [
{
"docstring": null,
"function_declaration": "def athom():",
"function_name": "athom",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def on_button_click(textbox, message):",
"function_name": "on_button_click",
"parameter_list": "(textbox, message)"
},
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\n\ndef athom():\n \"\"\"\n This function will be called after the button is clicked.\n \"\"\"\n text_box.insert(tk.END, \"Button clicked: athom function called... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024519",
"row_id": 24519,
"seed_ids": "['Llama-3.3-70B-Instruct_60973']"
} | 0.37515 | Filter_24519 | I | [
"athom",
"on_button_click",
"create_gui"
] | 3 | [
[
"create_gui",
"on_button_click"
],
[
"on_button_click",
"athom"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4a9b9aea61d9053603df5ea42e6860bf5a2777c0 | 6ed93a135071410eaa8cfe7eec0caefc53b9d198 | |||
v1.0 | instruct | Filter | Filter_24533_I | You may have heard of fractals, which are complex shapes that can be composed of smaller versions of the same shape, resulting in intricate patterns. Fractals can be found in nature and also in art. In this example, we will focus on the fractal image encoded within a matrix where each entry can have one of seven colors... | import numpy as np
import matplotlib.pyplot as plt
# Define the base pattern and recursive pattern
BASE_PATTERN = np.array([
['R', 'R'],
['B', 'B']
])
RECURSIVE_PATTERN = np.array([
['R', 'R', 'G', 'G'],
['R', 'R', 'G', 'G'],
['B', 'B', 'Y', 'Y'],
['B', 'B', 'Y', 'Y']
])
COLOR_MAP = {
'R'... | import numpy as np
from solution import create_fractal_matrix, COLOR_MAP
def test_base_case():
expected = np.array([
['R', 'R'],
['B', 'B']
])
result = create_fractal_matrix(2)
assert np.array_equal(result, expected), f"Expected: {expected}, but got: {result}"
def test_recursive_case_4... | [
{
"docstring": null,
"function_declaration": "def create_fractal_matrix(size):",
"function_name": "create_fractal_matrix",
"parameter_list": "(size)"
},
{
"docstring": null,
"function_declaration": "def plot_fractal(size):",
"function_name": "plot_fractal",
"parameter_list": "(si... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Mapping of letters to colors.\ncolor_map = {\n 'R': 'red',\n 'G': 'green',\n 'Y': 'yellow',\n 'B':... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024533",
"row_id": 24533,
"seed_ids": "['Llama-3.3-70B-Instruct_61005']"
} | 0.534225 | Filter_24533 | I | [
"create_fractal_matrix",
"plot_fractal"
] | 2 | [
[
"plot_fractal",
"create_fractal_matrix"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 2da9bdf88bea52584099f53f1dc791ed1302749b | 1540b034f1ddc8a56442afa8bb62799cd253c405 | |||
v1.0 | instruct | Filter | Filter_24559_I | ### Achievement Description
The Bird Lounge is an exclusive VIP members-only zone. To decide who gets in, the bouncer uses a points system determined by the properties of the digits of the members' birthday (day and month, e.g. 6th of June is 6/6), which are used to create an unlock combination. The points for a birthd... | def calculate_points(day, month):
"""
Calculate points from a given day and month.
:param day: The day of the month.
:param month: The month as a number.
:return: The total points for the given day and month.
"""
points = 0
# Calculate points from the day
day_str = str(day)
for... | from solution import calculate_points, authenticate
def test_calculate_points_single_digit():
assert calculate_points(1, 1) == 2 # 1 for day '1' and 1 for month '1'
def test_calculate_points_two_digit():
assert calculate_points(10, 10) == 12 # '10' -> 5+1 for day, '10' -> 5+1 for month
def test_calculate_p... | [
{
"docstring": "Calculate points from a given day and month.\n\n:param day: The day of the month.\n:param month: The month as a number.\n:return: The total points for the given day and month.",
"function_declaration": "def calculate_points(day, month):",
"function_name": "calculate_points",
"paramet... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_points(day, month):\n \"\"\"\n Calculate points from a given day and month.\n\n :param day: The day of the month.\n :param month: The month as a number.\n :return:... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00024559",
"row_id": 24559,
"seed_ids": "['Llama-3.3-70B-Instruct_61057']"
} | 0.536793 | Filter_24559 | I | [
"calculate_points",
"authenticate"
] | 2 | [
[
"authenticate",
"calculate_points"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8e7e9614e78b66a37ee4d5dafb18cc7ea4492b1 | 07cd0d1b88868634bfdba0fad8b7818140ce19b7 | |||
v1.0 | instruct | Filter | Filter_24579_I | Implement a SimHash based plagiarism detection algorithm which will compare a pair of documents and return a similarity score. | import hashlib
def hash_function(text):
return hashlib.md5(text.encode('utf-8')).hexdigest()
def text_to_vector(text):
words = text.split()
vec = [0] * 128 # MD5 hash is 128-bit
for word in words:
hash_value = int(hash_function(word), 16)
for i in range(128):
bitmask = 1 <... | def test_hash_function():
assert hash_function("hello") == hashlib.md5("hello".encode('utf-8')).hexdigest()
def test_text_to_vector():
vec = text_to_vector("hello world")
assert len(vec) == 128
assert all(isinstance(x, int) for x in vec)
def test_vector_to_simhash():
vec = [1, -1] * 64 # alternat... | [
{
"docstring": null,
"function_declaration": "def hash_function(text):",
"function_name": "hash_function",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def text_to_vector(text):",
"function_name": "text_to_vector",
"parameter_list": "(text)"
},
... | [
0,
0,
0,
0,
0,
1,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef simhash(text):\n \"\"\"\n Compute the SimHash value for a given text.\n \"\"\"\n # Split the text into words\n words = text.split()\n \n # Define the... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024579",
"row_id": 24579,
"seed_ids": "['Llama-3.3-70B-Instruct_61102']"
} | 0.440937 | Filter_24579 | I | [
"hash_function",
"text_to_vector",
"vector_to_simhash",
"hamming_distance",
"simhash",
"similarity_score"
] | 6 | [
[
"simhash",
"text_to_vector"
],
[
"simhash",
"vector_to_simhash"
],
[
"similarity_score",
"hamming_distance"
],
[
"similarity_score",
"simhash"
],
[
"text_to_vector",
"hash_function"
]
] | 5 | [] | false | [] | false | pytest | false | [] | true | d14589e07a190ced946a99418bb026c1debf0970 | 3f56c7f5c36e7102665fe50735054417e77e47db | |||
v1.0 | instruct | Filter | Filter_24727_I | I think you're not very good at implementing manual tests for final answers. Your predecessor once said to me it should take about 10-15 minutes to complete most problems.
I'd like to review and write my own step-by-step solutions for some problems that involve integer or string manipulations, algorithm design, and c... | from math import gcd
def lcm(x, y):
"""
Calculate the Least Common Multiple of two integers.
"""
return x * y // gcd(x, y)
def count_concat_ways(a, b):
"""
Count the total number of valid concatenations of `a` and `b` that form a repeating pattern of minimal length.
"""
len_a = len(a)
... | def test_lcm():
assert lcm(5, 3) == 15
assert lcm(6, 8) == 24
assert lcm(7, 7) == 7
assert lcm(12, 15) == 60
def test_count_concat_ways():
assert count_concat_ways("abc", "abcabc") == 1
assert count_concat_ways("abab", "ab") == 1
assert count_concat_ways("abcdef", "xyz") == 0
assert cou... | [
{
"docstring": "Calculate the Least Common Multiple of two integers.",
"function_declaration": "def lcm(x, y):",
"function_name": "lcm",
"parameter_list": "(x, y)"
},
{
"docstring": "Count the total number of valid concatenations of `a` and `b` that form a repeating pattern of minimal length... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_shortest_repeating_pattern(s):\n \"\"\"\n Returns the shortest repeating pattern for the given string s.\n \"\"\"\n n = len(s)\n for i in range(1, n + 1):\n if n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00024727",
"row_id": 24727,
"seed_ids": "['Llama-3.3-70B-Instruct_61415']"
} | 0.530597 | Filter_24727 | I | [
"lcm",
"count_concat_ways"
] | 2 | [
[
"count_concat_ways",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9c097d6dffc1adffca60c7d6d8560367dcfad66e | bae776f8377c16c7f3e25e62288eccef4dfe59eb | |||
v1.0 | instruct | Filter | Filter_24806_I | ### Zombie Pigmen Coordinates
Given the sequence of latitude and longitude coordinates:
(P37.7749, -122.4194), (P-33.8863, 151.1757), (P34.0522, -118.2437),
(P-30.0936, 17.9654), (P25.0617, 85.3131)
Pigmen soldiers pass through a process
that get the string representation of a coordinate, and it changes it accordin... | def transform_coordinate(latitude, longitude):
"""
Transforms the coordinate string according to the given rules.
Parameters:
- latitude: float
- longitude: float
Returns:
- Transformed coordinate string
"""
if latitude > 0 and longitude < 0:
change_type = 'A (+30)'
eli... | from solution import transform_coordinate, process_coordinates
def test_transform_coordinate_A():
assert transform_coordinate(37.7749, -122.4194) == 'A (+30)'
assert transform_coordinate(34.0522, -118.2437) == 'A (+30)'
def test_transform_coordinate_B():
assert transform_coordinate(-33.8863, 151.1757) == ... | [
{
"docstring": "Transforms the coordinate string according to the given rules.\n\nParameters:\n- latitude: float\n- longitude: float\n\nReturns:\n- Transformed coordinate string",
"function_declaration": "def transform_coordinate(latitude, longitude):",
"function_name": "transform_coordinate",
"para... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def transform_coordinates(coordinates):\n transformed_coordinates = []\n for coordinate in coordinates:\n lat_str, long_str = coordinate.strip('P').split(', ')\n latitude =... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00024806",
"row_id": 24806,
"seed_ids": "['Llama-3.3-70B-Instruct_61576']"
} | 0.539585 | Filter_24806 | I | [
"transform_coordinate",
"process_coordinates"
] | 2 | [
[
"process_coordinates",
"transform_coordinate"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26ee6cad3ad35d51cf596043082b3c7d961b7f82 | 6cd9e7d85c6ca83e76c161a76cc7ab8bcea57dc0 | |||
v1.0 | instruct | Filter | Filter_24814_I | ### Vending Machine Selection Program
#### Overview
The vending machine selection program is a console-based application that allows users to select a product from a list of pre-defined products and then pay for it. The program will validate the user's selection and payment then dispense the product after a successful ... | products = [
{"name": "Soda", "price": 1.00},
{"name": "Diet Soda", "price": 1.00},
{"name": "Chips", "price": 0.50},
{"name": "Popcorn", "price": 0.50},
{"name": "Cookies", "price": 1.50},
{"name": "Candy Bar", "price": 0.75},
{"name": "Gum", "price": 0.25},
{"name": "Mints", "price": 0... | def test_display_products(capfd):
display_products()
out, err = capfd.readouterr()
assert "Available products:" in out
assert "1. Soda: $1.00" in out
assert "10. Water: $1.25" in out
def test_get_product_selection(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: '3')
assert get... | [
{
"docstring": "Display available products",
"function_declaration": "def display_products():",
"function_name": "display_products",
"parameter_list": "()"
},
{
"docstring": "Get product selection from user",
"function_declaration": "def get_product_selection():",
"function_name": "g... | [
0,
0,
0,
1,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def vending_machine_simulation():\n products = [\n {\"name\": \"Soda\", \"price\": 1.00},\n {\"name\": \"Diet Soda\", \"price\": 1.00},\n {\"name\": \"Chips\", \"price\... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00024814",
"row_id": 24814,
"seed_ids": "['Llama-3.3-70B-Instruct_61602']"
} | 0.576747 | Filter_24814 | I | [
"display_products",
"get_product_selection",
"get_quantity",
"get_deposit_amount",
"vending_machine"
] | 5 | [
[
"vending_machine",
"display_products"
],
[
"vending_machine",
"get_deposit_amount"
],
[
"vending_machine",
"get_product_selection"
],
[
"vending_machine",
"get_quantity"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 0da13fbd4bd3731592b5dadd8c825acc89b9bc59 | 0f642332808fb3d5f15ef7af1fe59d57d9c7e000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.