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_18217_I | I have a program which captures the packets coming into the system.
Can you provide a simple python program for me that logs to the terminal without saving data and prints the packet size in bytes, source and destination IP and port number, total packets captured, and the protocol (TCP, UDP, ICMP etc.)? | import socket
import struct
def get_protocol_name(protocol_number):
if protocol_number == 1:
return "ICMP"
elif protocol_number == 6:
return "TCP"
elif protocol_number == 17:
return "UDP"
else:
return "OTHER"
def capture_packets():
total_packets = 0
s = socket.... | import pytest
from solution import get_protocol_name
def test_get_protocol_name_tcp():
assert get_protocol_name(6) == "TCP"
def test_get_protocol_name_udp():
assert get_protocol_name(17) == "UDP"
def test_get_protocol_name_icmp():
assert get_protocol_name(1) == "ICMP"
def test_get_protocol_name_other():... | [
{
"docstring": null,
"function_declaration": "def get_protocol_name(protocol_number):",
"function_name": "get_protocol_name",
"parameter_list": "(protocol_number)"
},
{
"docstring": null,
"function_declaration": "def capture_packets():",
"function_name": "capture_packets",
"param... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport struct\n\ndef log_packet(packet, total_packets):\n # Unpack IP header\n ip_header = struct.unpack('!BBHHHBBH4s4s', packet[0:20])\n \n version_ihl = ip_header[... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018217",
"row_id": 18217,
"seed_ids": "['Llama-3.3-70B-Instruct_46179']"
} | 0.453984 | Filter_18217 | I | [
"get_protocol_name",
"capture_packets"
] | 2 | [
[
"capture_packets",
"get_protocol_name"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 70e676c3d61b27f75b4c1c8da6a2b02b5f637de5 | 8bac9e40238ea6dce835417c0db453e494e2c256 | |||
v1.0 | instruct | Filter | Filter_18225_I | I have two neural networks, one is a 2-class classifier and the other is a 5-class classifier. I want to train them together in a multi-task learning framework so that they can learn from each other. I have a dataset of images, where each image has a 2-class label and a 5-class label. My question is:
- How do I defin... | import torch
import torch.nn as nn
import torch.nn.functional as F
class Classifier2(nn.Module):
def __init__(self):
super(Classifier2, self).__init__()
self.fc1 = nn.Linear(128, 64)
self.fc2 = nn.Linear(64, 2)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(... | import torch
from solution import CombinedModel, combined_loss_function, training_step
def test_combined_model_forward_pass():
model = CombinedModel()
input_data = torch.randn(1, 3, 32, 32) # Batch size of 1, 3 channels, 32x32 image
output2, output5 = model(input_data)
assert output2.shape == (1, 2), ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nclass Classifier2(nn.Module):\n def __init__(self):\n super(Classifier2, self).__init__()\n self.fc1 = n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018225",
"row_id": 18225,
"seed_ids": "['Llama-3.3-70B-Instruct_46198']"
} | 0.420933 | Filter_18225 | I | [
"combined_loss_function",
"training_step"
] | 2 | [
[
"training_step",
"combined_loss_function"
]
] | 1 | [] | false | [
"Classifier2",
"Classifier5",
"Backbone",
"CombinedModel"
] | true | pytest | true | [
"torch"
] | false | 740eb63b3460098ca94373da3462ef566e985b4c | b8e8d877836a7845ed1dc8d16976b1096b6e19e2 | |||
v1.0 | instruct | Filter | Filter_18227_I | I'll put a brief description of a code you can use to generate a type of fractal. I'll give you the number of iterations to perform. Then you'll write a code to generate that fractal using python with the matplotlib library.
Here's my description:
Imagine a fractal where you start with a line segment of length 1. In e... | import matplotlib.pyplot as plt
def draw_fractal(ax, x0, y0, x1, y1, iterations):
if iterations == 0:
ax.plot([x0, x1], [y0, y1], color='blue')
else:
dx = (x1 - x0) / 3
dy = (y1 - y0) / 3
x2 = x0 + dx
y2 = y0 + dy
x3 = (x1 + x2) / 2 - (y1 - y2) * (3 ** 0.5) / 6
... | def test_draw_fractal():
fig, ax = plt.subplots()
ax.set_aspect('equal')
draw_fractal(ax, 0, 0, 1, 0, 4)
segments = ax.lines
assert len(segments) > 0 # Ensuring lines were drawn
# Optionally, could save figure and compare to expected output, but matplotlib output comparison is complex
def test... | [
{
"docstring": null,
"function_declaration": "def draw_fractal(ax, x0, y0, x1, y1, iterations):",
"function_name": "draw_fractal",
"parameter_list": "(ax, x0, y0, x1, y1, iterations)"
},
{
"docstring": null,
"function_declaration": "def generate_fractal(iterations):",
"function_name"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\n\ndef draw_koch_segment(start, end, iterations, ax):\n if iterations == 0:\n # If no more iterations, draw the line segment\n ax.plot([start[0... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018227",
"row_id": 18227,
"seed_ids": "['Llama-3.3-70B-Instruct_46200']"
} | 0.491912 | Filter_18227 | I | [
"draw_fractal",
"generate_fractal"
] | 2 | [
[
"generate_fractal",
"draw_fractal"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib"
] | false | cd7677ab90d7f357e912bd632e69e921ce5de2ea | dcee9cc2b0efd5c1716e9c3573eba27ba63f7c63 | |||
v1.0 | instruct | Filter | Filter_18231_I | Here are the requirements for a Blackjack game:
- The deck has 52 cards.
- There are 4 suits, and 13 ranks per suit.
- The ranks are: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.
- Each card has a point value:
- Numbered cards are worth their number.
- Face cards (Jack, Queen, King) are worth 10 points.... | import random
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __repr__(self):
return f"{self.rank} of {self.suit}"
class Deck:
def __init__(self):
self.cards = []
self.suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
self.... | from solution import Card, Deck, Hand, Player, Dealer, get_winner
def test_card_creation():
card = Card("Hearts", "King")
assert card.suit == "Hearts"
assert card.rank == "King"
def test_deck_creation():
deck = Deck()
assert len(deck.cards) == 52
assert deck.cards[0].suit in {'Hearts', 'Diamon... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass Card:\n def __init__(self, suit, rank):\n self.suit = suit\n self.rank = rank\n\n def __repr__(self):\n return f\"{self.rank} of {self.suit}\"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018231",
"row_id": 18231,
"seed_ids": "['Llama-3.3-70B-Instruct_46208']"
} | 0.518874 | Filter_18231 | I | [
"get_winner",
"play_game"
] | 2 | [
[
"play_game",
"get_winner"
]
] | 1 | [] | false | [
"Card",
"Deck",
"Hand",
"Player",
"Dealer"
] | true | pytest | true | [] | true | dbc68f2ebfabb541d1cfeff251554be835657ffb | ca9a929019d5df5c86c73c47b8793bee511e9027 | |||
v1.0 | instruct | Filter | Filter_18248_I | How do I send a variable from one function to another function in Python? | def function_a():
"""
Example function that assigns a value to a variable
"""
variable = "Hello, World!"
function_b(variable)
def function_b(variable):
"""
Receives a variable and prints its value
Args:
variable (str): The variable to be received and used in this function
"... | from solution import function_a
def test_function_b_prints_variable(capsys):
function_a()
captured = capsys.readouterr()
assert captured.out == "Hello, World!\n" | [
{
"docstring": "Example function that assigns a value to a variable",
"function_declaration": "def function_a():",
"function_name": "function_a",
"parameter_list": "()"
},
{
"docstring": "Receives a variable and prints its value\n\nArgs:\nvariable (str): The variable to be received and used ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def function_a():\n \"\"\"\n Function A generates a variable with some value and returns it.\n \"\"\"\n variable = 42\n return variable\n\ndef function_b(variable):\n \"\"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018248",
"row_id": 18248,
"seed_ids": "['Llama-3.3-70B-Instruct_46256']"
} | 0.455161 | Filter_18248 | I | [
"function_a",
"function_b"
] | 2 | [
[
"function_a",
"function_b"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f0624bf55c08bf41f115697d2751bc312e89cb3 | 5b53d9316636fcf954758ad6f01abcc57e6e7ba1 | |||
v1.0 | instruct | Filter | Filter_18260_I | I wrote a simple Python script that reads data from a sensor and performs two tasks:
1. Prints out the readings in real-time
2. Saves the readings to a CSV file.
Now, I would like to add a third task:
3. Visualize the data in real-time as it is being generated.
To keep things simple, let's assume the sensor data is ... | import csv
import time
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def read_sensor_data():
"""
Simulates reading data from a sensor by generating a random number.
"""
import random
return random.random()
def save_to_csv(filename, reading):
"""
Saves the s... | from solution import read_sensor_data, save_to_csv, update_plot
import os
import csv
def test_read_sensor_data():
reading = read_sensor_data()
assert isinstance(reading, float)
assert 0 <= reading <= 1
def test_save_to_csv():
filename = 'test_sensor_readings.csv'
reading = 0.5
save_to_csv(file... | [
{
"docstring": "Simulates reading data from a sensor by generating a random number.",
"function_declaration": "def read_sensor_data():",
"function_name": "read_sensor_data",
"parameter_list": "()"
},
{
"docstring": "Saves the sensor reading to a CSV file.",
"function_declaration": "def s... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport time\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\ndef read_sensor_data():\n \"\"\"\n Simulates reading data from a sensor by gen... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018260",
"row_id": 18260,
"seed_ids": "['Llama-3.3-70B-Instruct_46285']"
} | 0.488776 | Filter_18260 | I | [
"read_sensor_data",
"save_to_csv",
"update_plot",
"main"
] | 4 | [
[
"update_plot",
"read_sensor_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | c46355a55f583c2cbf0f79b2d08519b17397d781 | 131cd5e053380bc2c13a94f8ace259a34cdab3c2 | |||
v1.0 | instruct | Filter | Filter_18293_I | I have a boolean function `f(x, y, z)` and I would like to generate all possible input combinations for the three boolean variables `x`, `y`, and `z`.
Here is a code that generates the combinations:
```python
import itertools
def generate_input_combinations():
variables = [True, False]
combinations = list(it... | import itertools
def generate_input_combinations():
variables = [True, False]
combinations = list(itertools.product(variables, repeat=3))
return combinations
def f(x, y, z):
"""
A sample boolean function.
"""
return (x and y) or z
def evaluate_function_for_combinations():
combinations... | from solution import generate_input_combinations, f, evaluate_function_for_combinations
def test_generate_input_combinations():
expected_combinations = [
(True, True, True),
(True, True, False),
(True, False, True),
(True, False, False),
(False, True, True),
(False, ... | [
{
"docstring": null,
"function_declaration": "def generate_input_combinations():",
"function_name": "generate_input_combinations",
"parameter_list": "()"
},
{
"docstring": "A sample boolean function.",
"function_declaration": "def f(x, y, z):",
"function_name": "f",
"parameter_li... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef generate_input_combinations():\n variables = [True, False]\n combinations = list(itertools.product(variables, repeat=3))\n return combinations\n\ndef f(x, y, z... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018293",
"row_id": 18293,
"seed_ids": "['Llama-3.3-70B-Instruct_46359']"
} | 0.623879 | Filter_18293 | I | [
"generate_input_combinations",
"f",
"evaluate_function_for_combinations"
] | 3 | [
[
"evaluate_function_for_combinations",
"f"
],
[
"evaluate_function_for_combinations",
"generate_input_combinations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f5708a091cbabf5c3292685443beb448af12f1d3 | ddb6c79a1e474e845c9fca1b2260f29020e95619 | |||
v1.0 | instruct | Filter | Filter_18310_I | Given a list of intervals, check if a number exist in any of those intervals.
Example:
Input : [[1, 3], [5, 7], [2, 4], [6, 8]]
Output:
Is 3 in any interval : Yes
Is 4 in any interval : Yes
Is 5 in any interval : Yes
Is 6 in any interval : Yes
Is 7 in any interval : Yes
Is 8 in any interval : Yes
//The above output... | def check_interval(intervals, num):
for interval in intervals:
if interval[0] <= num <= interval[1]:
return True
return False
def check_numbers_in_intervals(intervals):
max_val = max([max(interval) for interval in intervals])
numbers_to_check = [i for i in range(1, max_val + 1)]
... | from solution import check_numbers_in_intervals
def test_check_numbers_in_intervals():
intervals = [[1, 3], [5, 7], [2, 4], [6, 8]]
expected_result = {
1: True, 2: True, 3: True, 4: True, 5: True, 6: True, 7: True, 8: True
}
assert check_numbers_in_intervals(intervals) == expected_result
d... | [
{
"docstring": null,
"function_declaration": "def check_interval(intervals, num):",
"function_name": "check_interval",
"parameter_list": "(intervals, num)"
},
{
"docstring": null,
"function_declaration": "def check_numbers_in_intervals(intervals):",
"function_name": "check_numbers_in... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def check_interval(intervals, num):\n \"\"\"\n Checks if a number is within any of the given intervals.\n \"\"\"\n for interval in intervals:\n if interval[0] <= num <= inte... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018310",
"row_id": 18310,
"seed_ids": "['Llama-3.3-70B-Instruct_46399']"
} | 0.649909 | Filter_18310 | I | [
"check_interval",
"check_numbers_in_intervals"
] | 2 | [
[
"check_numbers_in_intervals",
"check_interval"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f1ff5780bd60e9f26b6c550b8d1ddaed16aac0b | 7a42f2d37590b60f5420e33f04af5b457ac03b4c | |||
v1.0 | instruct | Filter | Filter_18329_I | Write an example of how to use the Python turtle module to create a simple game of Tic-Tac-Toe. | import turtle
# Function to draw the Tic Tac Toe board
def draw_board():
turtle.speed(0)
turtle.penup()
turtle.goto(-100, 300)
turtle.pendown()
turtle.goto(-100, -300)
turtle.penup()
turtle.goto(100, 300)
turtle.pendown()
turtle.goto(100, -300)
turtle.penup()
turtle.goto(-30... | def test_draw_board():
"""
Ensure there are four lines drawn for the grid. We'll check visual confirmation.
"""
def test_draw_x():
"""
Ensure X is drawn correctly. We'll check visual confirmation.
"""
def test_draw_o():
"""
Ensure O is drawn correctly. We'll check visual confirmation.
... | [
{
"docstring": null,
"function_declaration": "def draw_board():",
"function_name": "draw_board",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def draw_x(x, y):",
"function_name": "draw_x",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\n# Create the screen\nscreen = turtle.Screen()\nscreen.title(\"Tic-Tac-Toe\")\nscreen.bgcolor(\"white\")\n\n# Create the drawing pen\npen = turtle.Turtle()\npen.color(\"black\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018329",
"row_id": 18329,
"seed_ids": "['Llama-3.3-70B-Instruct_46437']"
} | 0.607946 | Filter_18329 | I | [
"draw_board",
"draw_x",
"draw_o",
"click_handler",
"main"
] | 5 | [
[
"click_handler",
"draw_o"
],
[
"click_handler",
"draw_x"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | eb6ef9c8bdf5c9b8d9b72a25b741d924e2adbaab | f3c1f0ca0bf50134ca36a87b9bb420bb10171089 | |||
v1.0 | instruct | Filter | Filter_18339_I | With the help of the function `getFriends`, update the `user` object with the user's friends.
```python
def getFriends(user_id):
# this function returns a list of user's friends
friends = [
{"id": 2, "name": "John"},
{"id": 3, "name": "Sally"}
]
return friends
user = {
"id": 1,
"name": "Adam",
"f... | def getFriends(user_id):
"""
Returns a list of the user's friends.
"""
friends = [
{"id": 2, "name": "John"},
{"id": 3, "name": "Sally"}
]
return friends
def update_user_with_friends(user):
"""
Updates the user object with its friends.
"""
user_id = user["id"]
... | from solution import update_user_with_friends
def test_update_user_with_friends():
user = {
"id": 1,
"name": "Adam",
"friends": []
}
updated_user = update_user_with_friends(user)
assert len(updated_user["friends"]) == 2
assert updated_user["friends"][0] == {"id": 2, "name": ... | [
{
"docstring": "Returns a list of the user's friends.",
"function_declaration": "def getFriends(user_id):",
"function_name": "getFriends",
"parameter_list": "(user_id)"
},
{
"docstring": "Updates the user object with its friends.",
"function_declaration": "def update_user_with_friends(us... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def getFriends(user_id):\n # this function returns a list of user's friends\n friends = [\n {\"id\": 2, \"name\": \"John\"},\n {\"id\": 3, \"name\": \"Sally\"}\n ]\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018339",
"row_id": 18339,
"seed_ids": "['Llama-3.3-70B-Instruct_46461']"
} | 0.381955 | Filter_18339 | I | [
"getFriends",
"update_user_with_friends"
] | 2 | [
[
"update_user_with_friends",
"getFriends"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8597fdb1717c9b2794d97ae63b90a5e99833fe1 | 9abbafdce83a12066c133fd751552198578e2dba | |||
v1.0 | instruct | Filter | Filter_18343_I | ### API Details
#### Overview
Our API provides a way to manage a customer's loyalty points.
- It allows to create, retrieve, update, and delete customer loyalty points.
- Each customer is uniquely identified by a `customer_id`.
- When a customer makes a purchase, their loyalty points are updated.
- When a customer acc... | from flask import Flask, request, jsonify
from datetime import datetime
app = Flask(__name__)
# Sample in-memory data store (in a real application, use a database)
loyalty_points = {}
rewards = {
1: {"reward_name": "Discount", "points_required": 100, "reward_description": "10% discount on next purchase"},
2: ... | import pytest
from solution import app
from datetime import datetime
import json
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_create_loyalty_points(client):
new_customer = {"customer_id": "123", "points": 50}
response = client.post('/loyalty/points', data=j... | [
{
"docstring": null,
"function_declaration": "def create_loyalty_points():",
"function_name": "create_loyalty_points",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_loyalty_points(customer_id):",
"function_name": "get_loyalty_points",
"parameter_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nfrom datetime import datetime\n\napp = Flask(__name__)\n\n# Sample in-memory data store (in a real application, use a database)\nloyalty_points = {}\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018343",
"row_id": 18343,
"seed_ids": "['Llama-3.3-70B-Instruct_46467']"
} | 0.528057 | Filter_18343 | I | [
"create_loyalty_points",
"get_loyalty_points",
"update_loyalty_points",
"delete_loyalty_points",
"get_rewards",
"get_reward",
"award_rewards"
] | 7 | [
[
"create_loyalty_points",
"award_rewards"
],
[
"update_loyalty_points",
"award_rewards"
]
] | 2 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 385eafab0783de34b67c051b3565e8fc96c1db5a | c4b2e8008374a27c8be001a3fe4c818bfd4e61ec | |||
v1.0 | instruct | Filter | Filter_18348_I | I would like to create an interactive story where the user is presented with a choice and then the story continues based on that choice. I want to use Python for this.
Here is an example of what I'm looking for:
You are in a dark room. There is a door to your north and a small table to your east. On the table is a sm... | def start_room():
while True:
print("You are in a dark room. There is a door to your north and a small table to your east. On the table is a small, leather-bound book.")
print("Do you:")
print("A) Go north")
print("B) Investigate the book")
print("C) Search the room")
... | import pytest
from unittest.mock import patch
from solution import start_room, north_room, investigate_book, search_room
# Helper function to simulate user inputs and check outputs
def run_and_capture_output(func, inputs):
with patch('builtins.input', side_effect=inputs), patch('builtins.print') as mock_print:
... | [
{
"docstring": null,
"function_declaration": "def start_room():",
"function_name": "start_room",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def north_room():",
"function_name": "north_room",
"parameter_list": "()"
},
{
"docstring": null,
"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_room():\n while True:\n print(\"You are in a dark room. There is a door to your north and a small table to your east. On the table is a small, leather-bound book.\")\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018348",
"row_id": 18348,
"seed_ids": "['Llama-3.3-70B-Instruct_46474']"
} | 0.419869 | Filter_18348 | I | [
"start_room",
"north_room",
"investigate_book",
"search_room",
"main"
] | 5 | [
[
"start_room",
"investigate_book"
],
[
"start_room",
"north_room"
],
[
"start_room",
"search_room"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7b207bd7e27bbb54b09368a7ba103f5f1171a8c9 | 9ca9c138b721a7c6871f00beadc845f35a9ff6b5 | |||
v1.0 | instruct | Filter | Filter_18352_I | I've been searching for a solution that allows me to iterate through an enum in Python. The problem I'm facing is that I need to loop over each enum member and execute a function with the name of the enum member as an argument. Here's a basic representation of what I'm trying to achieve:
```
from enum import Enum
cla... | from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
def function_to_call(color_name):
print(f"Processing {color_name}")
def iterate_enum_and_execute():
for color in Color:
function_to_call(color.name) | from io import StringIO
import sys
from solution import Color, function_to_call, iterate_enum_and_execute
def test_print_function(capsys):
function_to_call("RED")
captured = capsys.readouterr()
assert captured.out == "Processing RED\n"
def test_iterate_enum_and_execute(capsys):
iterate_enum_and_execut... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from enum import Enum\n\nclass Color(Enum):\n RED = 1\n GREEN = 2\n BLUE = 3\n\ndef function_to_call(color_name):\n print(f\"Processing {color_name}\")\n\ndef iterate_and_call_func... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018352",
"row_id": 18352,
"seed_ids": "['Llama-3.3-70B-Instruct_46493']"
} | 0.60669 | Filter_18352 | I | [
"function_to_call",
"iterate_enum_and_execute"
] | 2 | [
[
"iterate_enum_and_execute",
"function_to_call"
]
] | 1 | [] | false | [
"Color"
] | true | pytest | true | [] | true | f957d8a4b15cfb4fd63fbf857ef2085f02ed3d91 | 39077cfcf3790dc7c6072dc874a2830fed22ae5d | |||
v1.0 | instruct | Filter | Filter_18414_I | I want to create an application that will display the top N most frequently occurring words in a text. The application should be able to:
1. Read text from a file.
2. Split the text into words.
3. Remove stop words and punctuation.
4. Convert words to lowercase.
5. Count the frequency of each word.
6. Display the top ... | import re
from collections import Counter
def read_text_from_file(file_path):
with open(file_path, 'r') as file:
return file.read()
def split_text_into_words(text):
return re.findall(r'\b\w+\b', text.lower())
def remove_stop_words(words, stop_words):
return [word for word in words if word not in ... | from solution import read_text_from_file, split_text_into_words, remove_stop_words, count_word_frequencies, get_top_n_frequent_words, top_n_frequent_words
def test_split_text_into_words():
text = "Hello, world! This is a test."
words = split_text_into_words(text)
assert words == ["hello", "world", "this", ... | [
{
"docstring": null,
"function_declaration": "def read_text_from_file(file_path):",
"function_name": "read_text_from_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def split_text_into_words(text):",
"function_name": "split_text_into_words",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport string\n\ndef read_file(file_path):\n \"\"\"\n Reads the text from a file and returns it as a single string.\n \"\"\"\n with open(file_path,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018414",
"row_id": 18414,
"seed_ids": "['Llama-3.3-70B-Instruct_46636']"
} | 0.704125 | Filter_18414 | I | [
"read_text_from_file",
"split_text_into_words",
"remove_stop_words",
"count_word_frequencies",
"get_top_n_frequent_words",
"top_n_frequent_words"
] | 6 | [
[
"top_n_frequent_words",
"count_word_frequencies"
],
[
"top_n_frequent_words",
"get_top_n_frequent_words"
],
[
"top_n_frequent_words",
"read_text_from_file"
],
[
"top_n_frequent_words",
"remove_stop_words"
],
[
"top_n_frequent_words",
"split_text_into_words"
... | 5 | [] | false | [] | false | pytest | true | [] | true | fd458e5dc159ba106a7efc8c248fda173343431a | 76af6ff59db75d3528e526e5f7a35474aed12617 | |||
v1.0 | instruct | Filter | Filter_18446_I | I have written a Python function to solve the following task:
Given an input of a list of positive integers, create an array of boolean values that represent whether each integer in the list is an "amicable pair" with another number in the list.
An "amicable pair" is two different numbers so related that the sum of ... | from functools import lru_cache
def proper_divisors_sum(n):
"""Return sum of proper divisors for a number."""
return sum(i for i in range(1, n) if n % i == 0)
def is_amicable_pair(num, nums):
"""Check if a number has an amicable pair in the list."""
divisors_sum = proper_divisors_sum(num)
return d... | def test_proper_divisors_sum():
assert proper_divisors_sum(220) == 284
assert proper_divisors_sum(284) == 220
assert proper_divisors_sum(10) == 8
assert proper_divisors_sum(12) == 16
assert proper_divisors_sum(1) == 0
def test_is_amicable_pair():
nums = [220, 284, 10, 15]
assert is_amicable... | [
{
"docstring": "Return sum of proper divisors for a number.",
"function_declaration": "def proper_divisors_sum(n):",
"function_name": "proper_divisors_sum",
"parameter_list": "(n)"
},
{
"docstring": "Check if a number has an amicable pair in the list.",
"function_declaration": "def is_am... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import lru_cache\n\ndef proper_divisors_sum(n):\n \"\"\"Return sum of proper divisors for a number.\"\"\"\n return sum(i for i in range(1, n) if n % i == 0)\n\ndef is_amic... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018446",
"row_id": 18446,
"seed_ids": "['Llama-3.3-70B-Instruct_46718']"
} | 0.643407 | Filter_18446 | I | [
"proper_divisors_sum",
"is_amicable_pair",
"proper_divisors_sums",
"has_amicable_pair"
] | 4 | [
[
"has_amicable_pair",
"is_amicable_pair"
],
[
"has_amicable_pair",
"proper_divisors_sums"
],
[
"is_amicable_pair",
"proper_divisors_sum"
],
[
"proper_divisors_sums",
"proper_divisors_sum"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | c35ee43fe05ab37edad6a0fd3159af5da1046755 | bb7fc9efb33939350abd5dc8c2aea4997a1c476d | |||
v1.0 | instruct | Filter | Filter_18464_I | Write a code in Python to find the width of the binary tree using BFS and DFS approach.
Width of the binary tree is the maximum number of nodes at any level. | from collections import deque, defaultdict
def width_of_binary_tree_bfs(root):
"""
Returns the maximum width of the binary tree using BFS.
"""
if not root:
return 0
max_width = 0
queue = deque([(root, 0)]) # (node, depth)
while queue:
level_length = len(queue)
... | from solution import width_of_binary_tree_bfs, width_of_binary_tree_dfs, TreeNode
def test_width_of_binary_tree_bfs():
# Constructing following binary tree
# 1
# / \
# 2 3
# / \ \
# 4 5 8
# / \
# 6 7
root = TreeNode(1)
... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef width_of_binary_tree_bfs(root):\n \"\"\"\n Returns the maximum width of the binary tree using BFS.\n \"\"\"\n if not root:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018464",
"row_id": 18464,
"seed_ids": "['Llama-3.3-70B-Instruct_46750']"
} | 0.554755 | Filter_18464 | I | [
"width_of_binary_tree_bfs",
"dfs",
"width_of_binary_tree_dfs"
] | 3 | [
[
"width_of_binary_tree_dfs",
"dfs"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 714ee797969083513b771ffc56a737430589903f | db93e7bc13f98cfc6ccb6ebaab4b7e6442287543 | |||
v1.0 | instruct | Filter | Filter_18465_I | This is the third in a series of challenges.
Create a password cracking tool that attempts all combinations of words from a dictionary against a given hash.
**Only write the code for the dictionary attack (no GUI, just a command-line interface)**
### Requirements
* The hash is provided as a SHA-256 hash
* A dictionar... | import argparse
import concurrent.futures
import hashlib
def hash_word(word):
"""Hashes a given word using SHA-256 and returns the hexadecimal digest."""
return hashlib.sha256(word.encode('utf-8')).hexdigest()
def crack_password(dictionary_file, target_hash):
try:
with open(dictionary_file, 'r') a... | import hashlib
from solution import crack_password, hash_word
def test_hash_word():
assert hash_word('password') == '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'
def test_crack_password(tmp_path):
dictionary_file = tmp_path / "dictionary.txt"
with open(dictionary_file, 'w') as file:
... | [
{
"docstring": "Hashes a given word using SHA-256 and returns the hexadecimal digest.",
"function_declaration": "def hash_word(word):",
"function_name": "hash_word",
"parameter_list": "(word)"
},
{
"docstring": null,
"function_declaration": "def crack_password(dictionary_file, target_has... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport concurrent.futures\nimport hashlib\n\ndef hash_word(word):\n \"\"\"Hashes a given word using SHA-256 and returns the hexadecimal digest.\"\"\"\n return hashlib.sh... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018465",
"row_id": 18465,
"seed_ids": "['Llama-3.3-70B-Instruct_46755']"
} | 0.579791 | Filter_18465 | I | [
"hash_word",
"crack_password",
"main"
] | 3 | [
[
"crack_password",
"hash_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | deb8e4d41b3fb323212b821840dcd969fb44bc63 | 276ecbc830ea7440d3d70256111b94206c3abd88 | |||
v1.0 | instruct | Filter | Filter_18502_I | ### Pure Functional Programming
## Step-by-step analysis of the problem:
1. **Understanding Pure Functions**: A pure function is one that has no side effects and always returns the same output given the same inputs. It does not depend on any external state and does not modify any external state.
2. **Understanding th... | def rectangle_area(length, width):
"""
Returns the area of a rectangle given its length and width.
"""
return length * width
def rectangle_perimeter(length, width):
"""
Returns the perimeter of a rectangle given its length and width.
"""
return 2 * (length + width)
def scale_rectangle(... | from solution import rectangle_area, rectangle_perimeter, scale_rectangle, apply_operations
def test_rectangle_area():
assert rectangle_area(3, 4) == 12
assert rectangle_area(5, 7) == 35
def test_rectangle_perimeter():
assert rectangle_perimeter(3, 4) == 14
assert rectangle_perimeter(5, 7) == 24
def ... | [
{
"docstring": "Returns the area of a rectangle given its length and width.",
"function_declaration": "def rectangle_area(length, width):",
"function_name": "rectangle_area",
"parameter_list": "(length, width)"
},
{
"docstring": "Returns the perimeter of a rectangle given its length and widt... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import Tuple\n\ndef calculate_area(length: float, width: float) -> float:\n \"\"\"\n Calculates the area of a rectangle given its length and width.\n \"\"\"\n return le... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018502",
"row_id": 18502,
"seed_ids": "['Llama-3.3-70B-Instruct_46847']"
} | 0.527741 | Filter_18502 | I | [
"rectangle_area",
"rectangle_perimeter",
"scale_rectangle",
"apply_operations"
] | 4 | [
[
"apply_operations",
"rectangle_area"
],
[
"apply_operations",
"rectangle_perimeter"
],
[
"apply_operations",
"scale_rectangle"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2867c3f406e679af1408135569c73d390855a414 | fa198b456fe60ac01ee24db1a6471c87587b8b82 | |||
v1.0 | instruct | Filter | Filter_18529_I | I want to solve a problem where I have two lists in python. Each element of each list is a string. The strings are actually URLs. I want to compare these lists and find identical URLs. I can do that with a simple set intersection. However, I want to also identify URLs that are "similar". A "similar" URL is one where th... | from urllib.parse import urlparse
def normalize_url(url):
parsed_url = urlparse(url)
# Remove query parameters and fragments
normalized_url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
# Remove trailing slashes and enforce lowercase for comparison
normalized_url = normalized_url.... | from solution import find_similar_urls
def test_exact_urls():
list1 = ["https://example.com/path", "https://example.com/about"]
list2 = ["https://example.com/path", "https://example.com/about", "https://example.com/contact"]
result = find_similar_urls(list1, list2, exact=True)
assert set(result) == {"h... | [
{
"docstring": null,
"function_declaration": "def normalize_url(url):",
"function_name": "normalize_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def find_similar_urls(list1, list2, exact=False):",
"function_name": "find_similar_urls",
"paramete... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from urllib.parse import urlparse\n\ndef normalize_url(url, exact):\n parsed_url = urlparse(url)\n\n # Remove query parameters and fragments, and normalize the URL for comparison\n no... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018529",
"row_id": 18529,
"seed_ids": "['Llama-3.3-70B-Instruct_46895']"
} | 0.564959 | Filter_18529 | I | [
"normalize_url",
"find_similar_urls"
] | 2 | [
[
"find_similar_urls",
"normalize_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a4d39932698eee4725f59c1323411a614d21e21a | 6c4fe58dc41b11cac28820ffe9bec2056f8891a1 | |||
v1.0 | instruct | Filter | Filter_18555_I | I've got the following code in Python that generates prime numbers:
```python
def is_prime(num):
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def prime_generator():
num = 2
while True:
if is_prime(num):
y... | def is_prime(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def prime_generator():
"""
Generator function that yields an infinite ... | from solution import is_prime, prime_generator
def test_is_prime():
# Test small prime numbers
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
# Test small non-prime numbers
assert is_prime(1) == False
assert is_prime(4) == False
assert is_prime(6) == F... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generator function that yields an infinite sequence of prime numbers.",
"function_declaration"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Determines if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018555",
"row_id": 18555,
"seed_ids": "['Llama-3.3-70B-Instruct_46961']"
} | 0.643544 | Filter_18555 | I | [
"is_prime",
"prime_generator"
] | 2 | [
[
"prime_generator",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 279dce6b57f155fbfbc8470cdec15f26d8eaf0cc | a5796092dcc9138ab6c0f377a57d6b872da651f8 | |||
v1.0 | instruct | Filter | Filter_18582_I | I've been working on a personal project using Python. I'm looking for a way to convert a given string made of alphabet characters into Morse code. How would I do this?
To make the conversion, I need to create a mapping between English characters and Morse code sequences. Then I will need to convert the string into Mo... | # Step 1: Define the Morse code mapping
MORSE_CODE_DICT = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U':... | from solution import char_to_morse, string_to_morse
def test_char_to_morse():
assert char_to_morse('A') == '.-'
assert char_to_morse('b') == '-...'
assert char_to_morse('3') == '...--'
assert char_to_morse(' ') == '/'
assert char_to_morse('Z') == '--..'
assert char_to_morse('@') == '' # Not in... | [
{
"docstring": "Converts a single English character to Morse code.\n\n:param char: A single English character (A-Z, 0-9 or space)\n:return: The Morse code representation of the character",
"function_declaration": "def char_to_morse(char):",
"function_name": "char_to_morse",
"parameter_list": "(char)... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Step 1: Define the Morse code mapping\nMORSE_CODE_DICT = {\n 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',\n 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018582",
"row_id": 18582,
"seed_ids": "['Llama-3.3-70B-Instruct_47014']"
} | 0.595254 | Filter_18582 | I | [
"char_to_morse",
"string_to_morse"
] | 2 | [
[
"string_to_morse",
"char_to_morse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 03698ca63e40c6d2e20015f4ad0419a8a57c4c97 | 91ffd6adf689996cf63de1d5cecee48e0aa66c3c | |||
v1.0 | instruct | Filter | Filter_18597_I | Here are the details of the game:
- The game is a 2-player game.
- The game involves flipping a coin.
- The game is played in rounds. Each round, one player flips the coin.
- The game ends after a specified number of rounds.
- The winner is the player who correctly guesses the outcome of the other player's coin flip.
... | import random
def flip_coin():
"""Simulate a coin flip, returning either 'Heads' or 'Tails'."""
return random.choice(['Heads', 'Tails'])
def update_game_state(game_state, round_number, player_number, flip_outcome):
"""Update the game state with the outcome of the coin flip."""
game_state['current_roun... | import random
from solution import flip_coin, update_game_state, get_initial_game_state, determine_outcome_game_start
def test_flip_coin():
outcomes = {'Heads', 'Tails'}
for _ in range(100):
assert flip_coin() in outcomes
def test_get_initial_game_state():
initial_state = get_initial_game_state()
... | [
{
"docstring": "Simulate a coin flip, returning either 'Heads' or 'Tails'.",
"function_declaration": "def flip_coin():",
"function_name": "flip_coin",
"parameter_list": "()"
},
{
"docstring": "Update the game state with the outcome of the coin flip.",
"function_declaration": "def update_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef flip_coin():\n \"\"\"Simulate a coin flip, returning either 'Heads' or 'Tails'.\"\"\"\n return random.choice(['Heads', 'Tails'])\n\ndef update_game_state(game_state,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018597",
"row_id": 18597,
"seed_ids": "['Llama-3.3-70B-Instruct_47059']"
} | 0.515387 | Filter_18597 | I | [
"flip_coin",
"update_game_state",
"get_initial_game_state",
"determine_outcome_game_start"
] | 4 | [
[
"determine_outcome_game_start",
"flip_coin"
],
[
"determine_outcome_game_start",
"get_initial_game_state"
],
[
"determine_outcome_game_start",
"update_game_state"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 966f68a6a9ecc12ea5849f75a7cfbbe7edf8c04c | e0f9a5cce5b09b4bce32204f67041013b6e9af9d | |||
v1.0 | instruct | Filter | Filter_18611_I | I have a binary tree where each node has a value and a boolean flag, and I want to generate all permutations of values in this binary tree. How can I do that? | import itertools
class TreeNode:
def __init__(self, value, flag, left=None, right=None):
self.value = value
self.flag = flag
self.left = left
self.right = right
def get_all_values(root):
"""
Return a list of all values from the binary tree.
"""
if root is None:
... | from solution import TreeNode, get_all_values, generate_all_permutations
def test_get_all_values():
# Tree:
# 1
# / \
# 2 3
root = TreeNode(1, True, TreeNode(2, False), TreeNode(3, True))
assert get_all_values(root) == [2, 1, 3]
def test_generate_all_permutations():
# Tree: ... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\nclass TreeNode:\n def __init__(self, value, flag, left=None, right=None):\n self.value = value\n self.flag = flag\n self.left = le... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018611",
"row_id": 18611,
"seed_ids": "['Llama-3.3-70B-Instruct_47090']"
} | 0.438328 | Filter_18611 | I | [
"get_all_values",
"generate_all_permutations"
] | 2 | [
[
"generate_all_permutations",
"get_all_values"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | d04e5a1b63f36ed1f652dae577f4e8f8261a07bb | 8cc4c117e4452ef8a5d6e7a077410497c9405b72 | |||
v1.0 | instruct | Filter | Filter_18621_I | I am a senior studying computer science and I am required to take a course in algorithms. I've been tasked with implementing some algorithms from scratch. The following is the prompt for my assignment:
Implement the merge sort algorithm to sort an array of integers in ascending order.
Here is the pseudo code for the m... | def merge_sort(arr):
"""
Sorts an array of integers in ascending order using the merge sort algorithm.
Parameters:
arr (list of int): The list of integers to be sorted.
Returns:
list of int: The sorted list of integers.
"""
if len(arr) <= 1:
return arr
mid = le... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5,... | [
{
"docstring": "Sorts an array of integers in ascending order using the merge sort algorithm.\n\nParameters:\n arr (list of int): The list of integers to be sorted.\n\nReturns:\n list of int: The sorted list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sor... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Recursively sorts an array of integers in ascending order\n using the Merge Sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018621",
"row_id": 18621,
"seed_ids": "['Llama-3.3-70B-Instruct_47114']"
} | 0.581433 | Filter_18621 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10f66dbc9f39cdbf65e21d25e47d3b0161cdde59 | 5601d1cf54caa3cf490938c35c1a68fb4fdf38f3 | |||
v1.0 | instruct | Filter | Filter_18650_I | I want to create a simple game where users can guess a number between 1 and 100. The system will then tell them if their guess is higher or lower than the number I have in mind. I want to write this in Python. How can I do it? | import random
def guess_number(user_guess, actual_number):
"""
Compare the user's guess to the actual number and return feedback.
Parameters:
user_guess (int): User's guess number.
actual_number (int): The actual number to guess.
Returns:
str: 'Higher', 'Lower', or 'Correct' based on the ... | from solution import guess_number
def test_guess_number_higher():
actual_number = 50
user_guess = 30
assert guess_number(user_guess, actual_number) == 'Higher'
def test_guess_number_lower():
actual_number = 50
user_guess = 70
assert guess_number(user_guess, actual_number) == 'Lower'
def test_... | [
{
"docstring": "Compare the user's guess to the actual number and return feedback.\n\nParameters:\nuser_guess (int): User's guess number.\nactual_number (int): The actual number to guess.\n\nReturns:\nstr: 'Higher', 'Lower', or 'Correct' based on the comparison.",
"function_declaration": "def guess_number(u... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass NumberGuessingGame:\n def __init__(self, lower=1, upper=100):\n \"\"\"\n Initialize the game with a random number between lower and upper bounds.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018650",
"row_id": 18650,
"seed_ids": "['Llama-3.3-70B-Instruct_47190']"
} | 0.576433 | Filter_18650 | I | [
"guess_number",
"start_game"
] | 2 | [
[
"start_game",
"guess_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a9448798683c94fd9fc583aa1d9d7297342d29d4 | 9effb2430eb63b430bc654f2c7b326ce884e7a31 | |||
v1.0 | instruct | Filter | Filter_18696_I | I've heard of the Kolmogorov complexity of a string, which is the length of the shortest program that can output that string. However, I don't understand how to estimate it.
Can you provide a sample program in a simple language, say Python, that can help estimate the Kolmogorov complexity of a given string by trying d... | import itertools
def estimate_kolmogorov_complexity(s, charset="abcdefghijklmnopqrstuvwxyz "):
"""
Estimates the Kolmogorov complexity of the string s by finding the shortest
Python program (in terms of length) that can generate the string s.
:param s: The input string
:param charset: The char... | from solution import estimate_kolmogorov_complexity
def test_estimate_kolmogorov_complexity_simple():
assert estimate_kolmogorov_complexity("a", charset="abcd") == 1 # Program: 'a'
def test_estimate_kolmogorov_complexity_space():
assert estimate_kolmogorov_complexity(" ", charset="ab ") == 1 # Program: ' '
... | [
{
"docstring": "Estimates the Kolmogorov complexity of the string s by finding the shortest\nPython program (in terms of length) that can generate the string s.\n\n:param s: The input string\n:param charset: The character set to use for generating the program (default is lowercase English letters and space)\n:r... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef estimate_kolmogorov_complexity(s, max_length=10):\n \"\"\"\n Estimate the Kolmogorov complexity of a given string by trying different combinations of a character ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018696",
"row_id": 18696,
"seed_ids": "['Llama-3.3-70B-Instruct_47285']"
} | 0.437982 | Filter_18696 | I | [
"estimate_kolmogorov_complexity",
"run_program"
] | 2 | [
[
"estimate_kolmogorov_complexity",
"run_program"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 408ccbe687bc1ad9f35cf19a1c589d6007569ef1 | 7d3fcc6f57eea2d5174c422f351ec6bc4737c65b | |||
v1.0 | instruct | Filter | Filter_18701_I | This is what I have so far:
```
import string
import random
def generate_password(length):
all_characters = string.ascii_letters + string.digits + string.punctuation
if length < 8:
print("Password length must be at least 8 characters.")
return
password = ''.join(random.choice(all_characters... | import string
import random
def generate_password(length):
"""
Generate a random password ensuring it has at least one digit, one lowercase letter,
one uppercase letter, and one special character.
"""
if length < 8:
raise ValueError("Password length must be at least 8 characters.")
... | from solution import generate_password, generate_password_list
import string
import pytest
def test_generate_password_length():
password = generate_password(8)
assert len(password) == 8
password = generate_password(12)
assert len(password) == 12
def test_generate_password_criteria():
password = ge... | [
{
"docstring": "Generate a random password ensuring it has at least one digit, one lowercase letter, \none uppercase letter, and one special character.",
"function_declaration": "def generate_password(length):",
"function_name": "generate_password",
"parameter_list": "(length)"
},
{
"docstri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import string\nimport random\n\ndef generate_password(length):\n if length < 8:\n raise ValueError(\"Password length must be at least 8 characters.\")\n \n all_characters = str... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018701",
"row_id": 18701,
"seed_ids": "['Llama-3.3-70B-Instruct_47292']"
} | 0.739087 | Filter_18701 | I | [
"generate_password",
"generate_password_list"
] | 2 | [
[
"generate_password_list",
"generate_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e6871e9fe44499a1bb16b2b2de9c8c9fc70ca9a5 | fb10b04e85dcc8e802a25139d15a611fdf477b28 | |||
v1.0 | instruct | Filter | Filter_18704_I | Please write a code snippet in Python that encrypts and decrypts a message using a Caesar cipher with a shift of 3. | def caesar_encrypt(message, shift=3):
"""
Encrypts the message using Caesar cipher with the given shift.
"""
encrypted_message = []
for char in message:
if char.isalpha():
shift_amount = 65 if char.isupper() else 97
encrypted_message.append(chr((ord(char) - shift_amou... | from solution import caesar_encrypt, caesar_decrypt
def test_caesar_encrypt_basic():
assert caesar_encrypt('abc') == 'def'
assert caesar_encrypt('xyz') == 'abc'
def test_caesar_decrypt_basic():
assert caesar_decrypt('def') == 'abc'
assert caesar_decrypt('abc') == 'xyz'
def test_caesar_encrypt_with_ca... | [
{
"docstring": "Encrypts the message using Caesar cipher with the given shift.",
"function_declaration": "def caesar_encrypt(message, shift=3):",
"function_name": "caesar_encrypt",
"parameter_list": "(message, shift=3)"
},
{
"docstring": "Decrypts the message using Caesar cipher with the giv... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_encrypt(text, shift):\n \"\"\"\n Encrypts a message using a Caesar cipher with a shift of 3.\n \"\"\"\n result = \"\"\n for char in text:\n # Encrypt uppercase... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018704",
"row_id": 18704,
"seed_ids": "['Llama-3.3-70B-Instruct_47300']"
} | 0.652592 | Filter_18704 | I | [
"caesar_encrypt",
"caesar_decrypt"
] | 2 | [
[
"caesar_decrypt",
"caesar_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c2b21b64f7debba5f9bd5b7b2bd5ec1727608166 | 60a3c47fa705ae2e660088b36a267c951f27f3a3 | |||
v1.0 | instruct | Filter | Filter_18728_I | I have written a solution for a problem. The problem is to write an algorithm that encrypts and decrypts a string of text using a Caesar Cipher. The Caesar Cipher is one of the simplest (and easiest cracked) encryption methods. It is a Substitution Cipher that involves replacing each letter in the message with a differ... | def caesar_encrypt(text, shift=3):
"""
Encrypt a text using Caesar Cipher with a fixed shift.
Args:
text (str): the input text to encrypt.
shift (int): the fixed shift to use (default is 3).
Returns:
str: the encrypted text.
"""
encrypted_text = []
for char in text... | from solution import caesar_encrypt, caesar_decrypt
def test_caesar_encrypt_basic():
assert caesar_encrypt("HELLO") == "KHOOR"
def test_caesar_decrypt_basic():
assert caesar_decrypt("KHOOR") == "HELLO"
def test_caesar_encrypt_with_non_alphabetic_characters():
assert caesar_encrypt("HELLO, WORLD!") == "KH... | [
{
"docstring": "Encrypt a text using Caesar Cipher with a fixed shift.\n\nArgs:\ntext (str): the input text to encrypt.\nshift (int): the fixed shift to use (default is 3).\n\nReturns:\nstr: the encrypted text.",
"function_declaration": "def caesar_encrypt(text, shift=3):",
"function_name": "caesar_encr... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_encrypt(text, shift=3):\n \"\"\"\n Encrypts the text using Caesar Cipher with a shift of 3.\n \"\"\"\n encrypted_text = \"\"\n for char in text:\n if char.isal... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018728",
"row_id": 18728,
"seed_ids": "['Llama-3.3-70B-Instruct_47358']"
} | 0.566056 | Filter_18728 | I | [
"caesar_encrypt",
"caesar_decrypt"
] | 2 | [
[
"caesar_decrypt",
"caesar_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 655227345159d6dd024888b27b7a3631fd552c6b | a786c5b5f631efc2038fffc3f10a01c58c977801 | |||
v1.0 | instruct | Filter | Filter_18760_I | Here is a piece of code that takes a list of integers, and for each integer, it checks if it's positive or negative, and returns a boolean value based on whether the number is positive or not.
```python
def is_positive(number):
if number > 0:
return True
else:
return False
```
My task is to wr... | def is_positive(number):
"""
Returns True if the number is positive, otherwise False.
"""
return number > 0
def apply_is_positive(numbers):
"""
Applies the is_positive function to each number in the list.
Args:
numbers (list of int): The list of integers to check.
Returns:... | from solution import is_positive, apply_is_positive
def test_is_positive_with_positive_number():
assert is_positive(5) == True
def test_is_positive_with_negative_number():
assert is_positive(-3) == False
def test_is_positive_with_zero():
assert is_positive(0) == False
def test_apply_is_positive_with_mix... | [
{
"docstring": "Returns True if the number is positive, otherwise False.",
"function_declaration": "def is_positive(number):",
"function_name": "is_positive",
"parameter_list": "(number)"
},
{
"docstring": "Applies the is_positive function to each number in the list.\n\nArgs:\nnumbers (list ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_positive(number):\n \"\"\"\n Returns True if the number is positive, otherwise False.\n \"\"\"\n if number > 0:\n return True\n else:\n return False\n\ndef ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018760",
"row_id": 18760,
"seed_ids": "['Llama-3.3-70B-Instruct_47438']"
} | 0.523736 | Filter_18760 | I | [
"is_positive",
"apply_is_positive"
] | 2 | [
[
"apply_is_positive",
"is_positive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85ddcd3484802b672c5b7b9154fc5ad6725bd288 | 63f5d5a41acaac0c639d2b0d1400f0d6ac3155da | |||
v1.0 | instruct | Filter | Filter_18789_I | I'll give you an array of integers representing a binary tree where for every value:
- 1 represents a leaf node
- 0 represents an internal node
- -1 represents null (i.e., an empty child node)
For example, given this array [1, 1, 1, 0, 0, 0, -1, -1, -1, -1, 0]
The binary tree would look like this:
```
0
/ \
... | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def construct_tree(tree_array, index):
if index >= len(tree_array) or tree_array[index] == -1:
return None, index
node = TreeNode(tree_array[index])
if tree_array[i... | from solution import construct_and_traverse
def test_construct_and_traverse_simple():
tree_array = [1, 1, 1, 0, 0, 0, -1, -1, -1, -1, 0]
# Expected DFS Order: 1 1 1 0 0 0
construct_and_traverse(tree_array, 0)
def test_construct_and_traverse_with_null_nodes():
tree_array = [0, 1, 1, 0, -1, -1, 1]
... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef construct_tree(tree_array, index):\n if index >= len(... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018789",
"row_id": 18789,
"seed_ids": "['Llama-3.3-70B-Instruct_47516']"
} | 0.510888 | Filter_18789 | I | [
"construct_tree",
"dfs_traverse",
"construct_and_traverse"
] | 3 | [
[
"construct_and_traverse",
"construct_tree"
],
[
"construct_and_traverse",
"dfs_traverse"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | d6a02a35bd02898b451d39dbc688478f6b833e27 | c96025fed74445b5bc1559c1b6fcf2c950db3a72 | |||
v1.0 | instruct | Filter | Filter_18801_I | I was tasked with implementing the wheat field problem using dynamic programming. The problem is as follows:
You are given a field of wheat with a 2D array representing the height of the wheat at each position.
The goal is to find a rectangle within this field with the maximum area. A rectangle is defined as having a... | def max_histogram_area(hist):
stack = []
max_area = 0
index = 0
while index < len(hist):
if not stack or hist[stack[-1]] <= hist[index]:
stack.append(index)
index += 1
else:
top_of_stack = stack.pop()
area = (hist[top_of_stack] *
... | from solution import max_rectangle_area
def test_max_rectangle_area():
assert max_rectangle_area([[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 0, 0]]) == 8
assert max_rectangle_area([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]) == 6
assert max_rectangle_area([[0]]) == 0
asse... | [
{
"docstring": null,
"function_declaration": "def max_histogram_area(hist):",
"function_name": "max_histogram_area",
"parameter_list": "(hist)"
},
{
"docstring": null,
"function_declaration": "def max_rectangle_area(field):",
"function_name": "max_rectangle_area",
"parameter_list... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_histogram_area(heights):\n \"\"\"\n Helper function to calculate the largest rectangle area in a histogram.\n \"\"\"\n stack = []\n max_area = 0\n index = 0\n whil... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018801",
"row_id": 18801,
"seed_ids": "['Llama-3.3-70B-Instruct_47548']"
} | 0.564308 | Filter_18801 | I | [
"max_histogram_area",
"max_rectangle_area"
] | 2 | [
[
"max_rectangle_area",
"max_histogram_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fcd48bf4d02611815827d3a9b9dda3ae9a9b6e56 | 39d4c68d5df272789e07a77535d2a9f38e012deb | |||
v1.0 | instruct | Filter | Filter_18802_I | Here's my GitHub repository: https://github.com/username/repo
Please help me create an automation script for a specific task.
I don't know which language to use and need some guidance.
Let's say, I have a repository where I have multiple folders (i.e., folders A, B, C, etc.), and each of these folders contains many te... | import os
import hashlib
def find_duplicate_files(base_path):
"""
Finds duplicate files across multiple directories within base_path.
Parameters:
- base_path (str): The path to the base directory containing subfolders with text files.
Returns:
- dict: A dictionary where the key is the... | import os
import hashlib
import pytest
from solution import find_duplicate_files, write_duplicates_to_file, hash_file
def test_hash_file(tmpdir):
file1 = tmpdir.join("file1.txt")
file1.write("This is a test file")
expected_hash = hashlib.md5(b"This is a test file").hexdigest()
assert hash_file(str(fil... | [
{
"docstring": "Finds duplicate files across multiple directories within base_path.\n\nParameters:\n- base_path (str): The path to the base directory containing subfolders with text files.\n\nReturns:\n- dict: A dictionary where the key is the hash of the file contents and the value is a list of file paths with... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\n\ndef get_file_hash(file_path):\n \"\"\"\n Generates the hash of the file located at file_path.\n \"\"\"\n hasher = hashlib.md5()\n with open(file_pat... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018802",
"row_id": 18802,
"seed_ids": "['Llama-3.3-70B-Instruct_47549']"
} | 0.548048 | Filter_18802 | I | [
"find_duplicate_files",
"hash_file",
"write_duplicates_to_file"
] | 3 | [
[
"find_duplicate_files",
"hash_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4dd3c34d6e8e8bbc1e7fc4f8d5d39e7667434559 | c5b2ffa0ee8355ea0c511880bc5baa18a4a189e6 | |||
v1.0 | instruct | Filter | Filter_18803_I | I have a MITx 6.00.1x course in edX, and I have a question about one of the problem sets.
Let L be a linked list, and let f be a function that takes a linked list as input and returns the length of the linked list.
Define a function g that takes a linked list as input, and returns the length of the longuest proper ... | class Node:
def __init__(self, value):
self.value = value
self.next = None
def f(lst):
"""
Returns the length of the linked list.
"""
length = 0
current = lst
while current:
length += 1
current = current.next
return length
def g(lst):
"""
Returns... | import pytest
from solution import Node, g
def test_single_node():
lst = Node(5)
assert g(lst) == 0
def test_two_nodes():
lst = Node(5)
lst.next = Node(3)
assert g(lst) == 1
def test_three_nodes():
lst = Node(5)
lst.next = Node(3)
lst.next.next = Node(7)
assert g(lst) == 2
def te... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef f(lst):\n length = 0\n current = lst\n while current:\n length += 1\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018803",
"row_id": 18803,
"seed_ids": "['Llama-3.3-70B-Instruct_47550']"
} | 0.557937 | Filter_18803 | I | [
"f",
"g"
] | 2 | [
[
"g",
"f"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 2c65452030830a6739bae01c7fccc84776aa5989 | 4efae6170260a15534ddf6cea532194bc8c00959 | |||
v1.0 | instruct | Filter | Filter_18814_I | Here's what I've done so far:
```python
import os
import re
import operator
from functools import reduce
EPISODE_DIR = "/path/to/episodes"
EPISODE_FILE_EXTENSIONS = [".mp4", ".mkv", ".avi"]
def get_file_list():
file_list = [os.path.join(EPISODE_DIR, f) for f in os.listdir(EPISODE_DIR) if os.path.isfile(os.path.jo... | import os
import re
import operator
from functools import reduce
EPISODE_DIR = "/path/to/episodes"
EPISODE_FILE_EXTENSIONS = [".mp4", ".mkv", ".avi"]
def get_file_list():
file_list = [os.path.join(EPISODE_DIR, f) for f in os.listdir(EPISODE_DIR) if os.path.isfile(os.path.join(EPISODE_DIR, f))]
return file_lis... | import os
import pytest
from solution import get_total_size_of_episode_files, EPISODE_DIR, EPISODE_FILE_EXTENSIONS
@pytest.fixture
def mock_filesystem(monkeypatch):
test_files = {
"/path/to/episodes/S01E01.mp4": 1000,
"/path/to/episodes/S01E02.mkv": 2000,
"/path/to/episodes/S01E03.avi": 150... | [
{
"docstring": null,
"function_declaration": "def get_file_list():",
"function_name": "get_file_list",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def has_valid_extension(file_path):",
"function_name": "has_valid_extension",
"parameter_list": "(file_pa... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport re\nimport operator\nfrom functools import reduce\n\nEPISODE_DIR = \"/path/to/episodes\"\nEPISODE_FILE_EXTENSIONS = [\".mp4\", \".mkv\", \".avi\"]\n\ndef get_file_list():\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018814",
"row_id": 18814,
"seed_ids": "['Llama-3.3-70B-Instruct_47582']"
} | 0.598664 | Filter_18814 | I | [
"get_file_list",
"has_valid_extension",
"is_episode_file",
"get_episode_files",
"get_season_from_path",
"get_episode_from_path",
"get_total_size_of_episode_files"
] | 7 | [
[
"get_episode_files",
"get_file_list"
],
[
"get_episode_files",
"is_episode_file"
],
[
"get_total_size_of_episode_files",
"get_episode_files"
],
[
"is_episode_file",
"has_valid_extension"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | dc5a4c5c71f80807605cd87e3c3e8b267e469927 | fd93e0e964e64195672e59bb95efa25b38fe7c29 | |||
v1.0 | instruct | Filter | Filter_18817_I | Here's a problem I'm trying to solve. I have two text files: one is an English-to-French dictionary, and the other is a list of English words. How can I use Python to look up the translations of these words using the dictionary file? | def load_dictionary(dict_file_path):
english_to_french = {}
with open(dict_file_path, 'r') as file:
for line in file:
english, french = line.strip().split(':')
english_to_french[english.strip()] = french.strip()
return english_to_french
def translate_words(dict_file_path, wo... | import tempfile
def test_load_dictionary():
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b"hello:bonjour\nworld:monde\n")
temp_file_path = temp_file.name
dictionary = load_dictionary(temp_file_path)
assert dictionary == {"hello": "bonjour", "world": "monde"}... | [
{
"docstring": null,
"function_declaration": "def load_dictionary(dict_file_path):",
"function_name": "load_dictionary",
"parameter_list": "(dict_file_path)"
},
{
"docstring": null,
"function_declaration": "def translate_words(dict_file_path, words_file_path):",
"function_name": "tra... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def load_dictionary(dictionary_file):\n \"\"\"\n Load dictionary from the dictionary_file.\n \n Args:\n dictionary_file (str): The file path to the English-to-French dictionary.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018817",
"row_id": 18817,
"seed_ids": "['Llama-3.3-70B-Instruct_47588']"
} | 0.566482 | Filter_18817 | I | [
"load_dictionary",
"translate_words"
] | 2 | [
[
"translate_words",
"load_dictionary"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9c9f347bc5aa6180f0794e37ac8c4bd02cd30e90 | 96fc70df3e7b9ade508deda26622365911a2fd5e | |||
v1.0 | instruct | Filter | Filter_18821_I | I will provide a sample program in Python and would like you to explain how it works.
Here's the code:
```python
import numpy as np
def encrypt_char(c):
# Define the encryption function for a character
shift = 3
if c.isalpha():
ascii_offset = 65 if c.isupper() else 97
return chr((ord(c) -... | def encrypt_char(c):
"""
Encrypt a single character using a Caesar cipher with a shift of 3 places.
"""
shift = 3
if c.isalpha():
ascii_offset = 65 if c.isupper() else 97
return chr((ord(c) - ascii_offset + shift) % 26 + ascii_offset)
else:
return c
def encrypt_text(text... | def test_encrypt_char():
assert encrypt_char('A') == 'D'
assert encrypt_char('B') == 'E'
assert encrypt_char('Y') == 'B'
assert encrypt_char('a') == 'd'
assert encrypt_char('x') == 'a'
assert encrypt_char('z') == 'c'
assert encrypt_char('1') == '1' # Non-alphabet character should remain the... | [
{
"docstring": "Encrypt a single character using a Caesar cipher with a shift of 3 places.",
"function_declaration": "def encrypt_char(c):",
"function_name": "encrypt_char",
"parameter_list": "(c)"
},
{
"docstring": "Encrypt a text string using a Caesar cipher with a shift of 3 places.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef encrypt_char(c):\n \"\"\"\n Encrypt a single character using a Caesar cipher.\n \"\"\"\n shift = 3\n if c.isalpha():\n ascii_offset = 65 if c.is... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018821",
"row_id": 18821,
"seed_ids": "['Llama-3.3-70B-Instruct_47593']"
} | 0.714416 | Filter_18821 | I | [
"encrypt_char",
"encrypt_text",
"decrypt_char",
"decrypt_text"
] | 4 | [
[
"decrypt_text",
"decrypt_char"
],
[
"encrypt_text",
"encrypt_char"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 606c38c1d1718c46391cc511f43355baad4eacae | 08edeaed6d641c2c463a1b0ff780ac7bf7b0972f | |||
v1.0 | instruct | Filter | Filter_18845_I | Below is a code to find the roots of a quadratic equation of the form ax^2 + bx + c = 0.
```python
import math
def calculate_discriminant(a, b, c):
"""
Calculate the discriminant of a quadratic equation.
Parameters:
a (float): coefficient of x^2
b (float): coefficient of x
c (float): constant... | import cmath
def calculate_discriminant(a, b, c):
"""
Calculate the discriminant of a quadratic equation.
Parameters:
a (float): coefficient of x^2
b (float): coefficient of x
c (float): constant term
Returns:
float: discriminant
"""
discriminant = b ** 2 - 4 * a * c
retur... | import cmath
from solution import calculate_discriminant, find_roots, print_roots
def test_calculate_discriminant():
assert calculate_discriminant(1, -3, 2) == 1
assert calculate_discriminant(1, 2, 5) == -16
def test_find_roots_real():
roots = find_roots(1, -3, 2)
assert roots == (2.0, 1.0)
def test_... | [
{
"docstring": "Calculate the discriminant of a quadratic equation.\n\nParameters:\na (float): coefficient of x^2\nb (float): coefficient of x\nc (float): constant term\n\nReturns:\nfloat: discriminant",
"function_declaration": "def calculate_discriminant(a, b, c):",
"function_name": "calculate_discrimi... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cmath\n\ndef calculate_discriminant(a, b, c):\n \"\"\"\n Calculate the discriminant of a quadratic equation.\n\n Parameters:\n a (float): coefficient of x^2\n b (float): ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018845",
"row_id": 18845,
"seed_ids": "['Llama-3.3-70B-Instruct_47638']"
} | 0.723517 | Filter_18845 | I | [
"calculate_discriminant",
"find_roots",
"print_roots"
] | 3 | [
[
"find_roots",
"calculate_discriminant"
],
[
"print_roots",
"find_roots"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b00fd40f3f844ab8489b20157a1fa0aa8eb4db20 | 92735edc655d4cba53ff7660f831f9ed7691c842 | |||
v1.0 | instruct | Filter | Filter_18854_I | Here is a code that i wrote to generate all possible combinations of a given string
```python
def generateCombinations(string):
# Base case
if len(string) == 0:
return ['']
# Recursive case
result = []
for i, char in enumerate(string):
remainingString = string[:i] + string[i+1:]
... | def generateCombinations(string):
"""
A generator function to yield all possible combinations
of the given string.
"""
# Base case
if len(string) == 0:
yield ''
return
# Recursive case
for i, char in enumerate(string):
remainingString = string[:i] + string[i+1:]
... | from solution import generateCombinations, write_and_print_combinations
import os
def test_generate_combinations():
# Test for an empty string
combinations = list(generateCombinations(''))
assert combinations == ['']
# Test for a single-character string
combinations = list(generateCombinations... | [
{
"docstring": "A generator function to yield all possible combinations\nof the given string.",
"function_declaration": "def generateCombinations(string):",
"function_name": "generateCombinations",
"parameter_list": "(string)"
},
{
"docstring": null,
"function_declaration": "def write_an... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generateCombinations(string):\n \"\"\"\n Generator function to yield all combinations of a given string.\n\n Args:\n string (str): The input string to generate combinations fro... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018854",
"row_id": 18854,
"seed_ids": "['Llama-3.3-70B-Instruct_47665']"
} | 0.576781 | Filter_18854 | I | [
"generateCombinations",
"write_and_print_combinations"
] | 2 | [
[
"write_and_print_combinations",
"generateCombinations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 175f54593ed3d9721b2ea57b0bb03edd971b8802 | 9c290dd21ffea074ac342c18aab510e26618c7a6 | |||
v1.0 | instruct | Filter | Filter_18871_I | I have a text file named "example.txt" containing the following text:
"2 12 6 3 1 10 15 2 8"
Can you help me find the kth smallest element in this file using Python?
Here are the steps I want you to follow:
1. Read the file and store the contents in a list
2. Sort the list
3. Ask the user for the value of k
4. Print ... | def read_file(filename):
"""
Reads the contents of the given file and returns a list of integers.
"""
with open(filename, 'r') as file:
data = file.read()
return list(map(int, data.split()))
def find_kth_smallest(filename, k):
"""
Returns the kth smallest element in the file.
""... | from solution import read_file, find_kth_smallest
def test_read_file():
# Create a temporary test file
with open('test_example.txt', 'w') as f:
f.write('2 12 6 3 1 10 15 2 8')
assert read_file('test_example.txt') == [2, 12, 6, 3, 1, 10, 15, 2, 8]
def test_find_kth_smallest():
# Create a t... | [
{
"docstring": "Reads the contents of the given file and returns a list of integers.",
"function_declaration": "def read_file(filename):",
"function_name": "read_file",
"parameter_list": "(filename)"
},
{
"docstring": "Returns the kth smallest element in the file.",
"function_declaration... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_kth_smallest_element(filename, k):\n \"\"\"\n Find the kth smallest element in a file containing space-separated integers.\n \n Parameters:\n filename (str): The name o... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018871",
"row_id": 18871,
"seed_ids": "['Llama-3.3-70B-Instruct_47719']"
} | 0.601508 | Filter_18871 | I | [
"read_file",
"find_kth_smallest"
] | 2 | [
[
"find_kth_smallest",
"read_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9dfa480d7634c9e8141fd1e784f91b6bd4bf4701 | b0935a24b18125337edead3100de1c71d57e5f31 | |||
v1.0 | instruct | Filter | Filter_18882_I | I have two CSV files, which I need to compare. One of them contains the current data (`current.csv`), and the other contains the historical data (`historical.csv`). The current data is updated constantly, and the historical data contains all the transactions that were ever done.
The user should be able to select the ... | import csv
import tkinter as tk
from tkinter import filedialog
def get_csv_structure(file):
with open(file, 'r') as csv_file:
reader = csv.reader(csv_file)
headers = next(reader, None)
first_row = next(reader, None)
num_columns = len(first_row) if first_row else 0
return (header... | import csv
import os
import pytest
from solution import compare_csv, get_csv_structure, validate_csv_files
def setup_csv(content, filename):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(content)
def test_get_csv_structure():
setup_csv([['header1', 'h... | [
{
"docstring": null,
"function_declaration": "def get_csv_structure(file):",
"function_name": "get_csv_structure",
"parameter_list": "(file)"
},
{
"docstring": null,
"function_declaration": "def validate_csv_files(struct1, struct2):",
"function_name": "validate_csv_files",
"param... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport tkinter as tk\nfrom tkinter import filedialog\n\ndef get_csv_structure(file):\n with open(file, 'r') as csv_file:\n reader = csv.reader(csv_file)\n headers ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018882",
"row_id": 18882,
"seed_ids": "['Llama-3.3-70B-Instruct_47743']"
} | 0.627333 | Filter_18882 | I | [
"get_csv_structure",
"validate_csv_files",
"compare_csv",
"select_file",
"main"
] | 5 | [
[
"compare_csv",
"get_csv_structure"
],
[
"compare_csv",
"validate_csv_files"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0483c752978538da9e37ce531be4df7dc82a80e5 | 4d211a9dd7c5896543aa1248e6418bcca3cdafef | |||
v1.0 | instruct | Filter | Filter_18920_I | Here's the Python code for a simplified chatbot that I've been working on:
```python
import os
import re
def ask_question(prompt):
print(f"{prompt}")
response = input().lower()
return response
def get_name():
name = ask_question("What is your name?")
print(f"Nice to meet you {name}!")
return n... | import os
import re
def ask_question(prompt):
print(f"{prompt}")
response = input().lower()
return response
def get_name():
name = ask_question("What is your name?")
print(f"Nice to meet you {name}!")
return name
def get_age():
while True:
age = ask_question("How old are you?")
... | from unittest.mock import patch
import builtins
# To test the chatbot, mock the input and output using patch
def test_get_name():
with patch('builtins.input', return_value='Alice'):
assert get_name() == 'alice'
def test_get_age():
with patch('builtins.input', side_effect=['fourteen', '14']):
... | [
{
"docstring": null,
"function_declaration": "def ask_question(prompt):",
"function_name": "ask_question",
"parameter_list": "(prompt)"
},
{
"docstring": null,
"function_declaration": "def get_name():",
"function_name": "get_name",
"parameter_list": "()"
},
{
"docstring":... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport re\n\ndef ask_question(prompt):\n print(f\"{prompt}\")\n response = input().lower()\n return response\n\ndef get_name():\n name = ask_question(\"What is your name... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018920",
"row_id": 18920,
"seed_ids": "['Llama-3.3-70B-Instruct_47833']"
} | 0.391108 | Filter_18920 | I | [
"ask_question",
"get_name",
"get_age",
"get_location",
"talk_about_hobbies",
"talk_about_favorites",
"main"
] | 7 | [
[
"get_age",
"ask_question"
],
[
"get_location",
"ask_question"
],
[
"get_name",
"ask_question"
],
[
"talk_about_favorites",
"ask_question"
],
[
"talk_about_hobbies",
"ask_question"
]
] | 5 | [] | false | [] | false | pytest | false | [] | true | 1742066267f525fee73cf61b176f78590f8fcfa5 | 3aa7541bd0b120df3222ff3a97711c100c54af22 | |||
v1.0 | instruct | Filter | Filter_18927_I | ### GitHub Desktop and Browser Client
#### Task Overview
Your task is to create an installer program that can download and install the GitHub desktop client, as well as the browser client.
Here are the steps that the installer should follow:
1. **Download GitHub Desktop Setup**: Download the GitHub Desktop setup ex... | import os
import platform
import requests
import subprocess
import tempfile
# Constants
GITHUB_DESKTOP_URLS = {
'Windows': "https://central.github.com/deployments/desktop/desktop/latest/win32",
'Darwin': "https://central.github.com/deployments/desktop/desktop/latest/darwin",
'Linux': "https://central.githu... | import os
import platform
import pytest
import subprocess
from unittest.mock import patch, mock_open
from solution import download_file, download_github_desktop, install_github_desktop
# Mock request
class MockResponse:
@staticmethod
def raise_for_status():
pass
@staticmethod
def content():
... | [
{
"docstring": null,
"function_declaration": "def download_file(url, filename):",
"function_name": "download_file",
"parameter_list": "(url, filename)"
},
{
"docstring": null,
"function_declaration": "def download_github_desktop():",
"function_name": "download_github_desktop",
"p... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\nimport platform\n\n# URLs for downloading GitHub Desktop client\nURLS = {\n \"Windows\": \"https://central.github.com/deployments/desktop/desktop/latest/win32\",... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018927",
"row_id": 18927,
"seed_ids": "['Llama-3.3-70B-Instruct_47849']"
} | 0.488412 | Filter_18927 | I | [
"download_file",
"download_github_desktop",
"download_browser_client_extension",
"install_github_desktop",
"install_browser_client_extension",
"main"
] | 6 | [
[
"download_browser_client_extension",
"download_file"
],
[
"download_github_desktop",
"download_file"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | bc7c652eaa9dc72253adee8425d0d5a4b06601ea | 57a7b48cfe1a8250e0b116e4e236faad7a29c426 | |||
v1.0 | instruct | Filter | Filter_18942_I | I have a computer with 2 cores and I want to use the entire CPU capacity to process a piece of data, which can be divided into four equal parts. I need to design an efficient algorithm that can handle this task using multi-threading.
Note: For a simple understanding, let's assume that each part will take 5 seconds to... | import threading
import time
from concurrent.futures import ThreadPoolExecutor
def process_part(part_id):
print(f"Processing part {part_id}")
time.sleep(5) # simulate processing time
print(f"Part {part_id} is processed")
def process_data_in_parallel():
# Use ThreadPoolExecutor to manage a pool of thr... | from solution import process_data_in_parallel
import time
def test_process_data_in_parallel():
start_time = time.time()
process_data_in_parallel()
end_time = time.time()
# The total processing should take around 10 seconds, accounting for 2 parts processed
# in parallel, then the next 2 parts ... | [
{
"docstring": null,
"function_declaration": "def process_part(part_id):",
"function_name": "process_part",
"parameter_list": "(part_id)"
},
{
"docstring": null,
"function_declaration": "def process_data_in_parallel():",
"function_name": "process_data_in_parallel",
"parameter_lis... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import threading\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_part(part_id):\n print(f\"Processing part {part_id}\")\n time.sleep(5) # simulate process... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018942",
"row_id": 18942,
"seed_ids": "['Llama-3.3-70B-Instruct_47875']"
} | 0.529706 | Filter_18942 | I | [
"process_part",
"process_data_in_parallel"
] | 2 | [
[
"process_data_in_parallel",
"process_part"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da1209f628e157caac92c8a23fcff6aa7a6a55f0 | 401d9a0df65c247df163c4e41f441c4963b4d6ee | |||
v1.0 | instruct | Filter | Filter_18946_I | I have a list of names in a list called "names". How can I create a button that will randomly select one of those names and display it in the label of the button. | import tkinter as tk
import random
def random_select(names):
"""
Randomly select a name from the list of names.
"""
return random.choice(names)
def create_app(names):
"""
Create a GUI application that selects a random name from the provided list and displays it on a button.
"""
def on_... | from solution import random_select
import pytest
def test_random_select_single_name():
single_name_list = ["Alice"]
assert random_select(single_name_list) == "Alice"
def test_random_select_multiple_names():
names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
selected_name = random_select(names)
as... | [
{
"docstring": "Randomly select a name from the list of names.",
"function_declaration": "def random_select(names):",
"function_name": "random_select",
"parameter_list": "(names)"
},
{
"docstring": "Create a GUI application that selects a random name from the provided list and displays it on... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\nimport random\n\ndef randomize_name():\n selected_name = random.choice(names)\n button.config(text=selected_name)\n\n# Example list of names\nnames = [\"Alice\", \"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018946",
"row_id": 18946,
"seed_ids": "['Llama-3.3-70B-Instruct_47882']"
} | 0.453855 | Filter_18946 | I | [
"random_select",
"create_app"
] | 2 | [
[
"create_app",
"random_select"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da15f32fe5a695173f552fc566cff60c2c721963 | a3c06798750bc5761bcf01f86b9bf4340e22056f | |||
v1.0 | instruct | Filter | Filter_18955_I | Here is the problem:
Write a program in Python that takes a floating-point number as input and prints out whether the number is a power of two or not.
Example Outputs:
Input: 8
Output: Yes, the number is a power of two.
Input: 10
Output: No, the number is not a power of two.
This is the code I have so far:
```
i... | import math
def is_power_of_two(n):
"""
Returns True if n is a power of two, and False otherwise.
"""
if n <= 0:
return False
# Using logarithmic identity to check if n is a power of 2
log_n_base_2 = math.log2(n)
return log_n_base_2.is_integer()
def check_power_of_two(n):
"""
... | from solution import is_power_of_two, check_power_of_two
def test_is_power_of_two():
assert is_power_of_two(1) == True # 2^0
assert is_power_of_two(2) == True # 2^1
assert is_power_of_two(4) == True # 2^2
assert is_power_of_two(8) == True # 2^3
assert is_power_of_two(16) == True # 2^4
asser... | [
{
"docstring": "Returns True if n is a power of two, and False otherwise.",
"function_declaration": "def is_power_of_two(n):",
"function_name": "is_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": "Given a floating point number n, returns a string indicating if n is a power of two.",... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_power_of_two(n):\n \"\"\"\n Determines whether a given floating-point number is a power of two or not.\n \n Parameters:\n n (float): The number to check.\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018955",
"row_id": 18955,
"seed_ids": "['Llama-3.3-70B-Instruct_47914']"
} | 0.710048 | Filter_18955 | I | [
"is_power_of_two",
"check_power_of_two"
] | 2 | [
[
"check_power_of_two",
"is_power_of_two"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f596611eb246cdace138c80c14882eeb597516b7 | 18df155ef4947a4724dda5c04f4ec8630cb01e00 | |||
v1.0 | instruct | Filter | Filter_18982_I | ### Initial Setup
- Create a new GitHub repository called `python-exercises` and add a `.gitignore` file with the following content: `*.pyc`, `__pycache__/`, `*.gitignore`.
- Create a new directory called `exercises` in your local machine.
- Navigate to the `exercises` directory and initialize a new git repository usin... | # exercise1.py
def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def get_primes(n):
"""Get all prime numbers up to n."""
primes = []
for i in range(2, n + 1):
... | from solution import is_prime, get_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(97) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5) == False
def test_get_primes():
asser... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Get all prime numbers up to n.",
"function_declaration": "def get_primes(n):",
"function_name": "get_primes",
"paramet... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# exercise1.py\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00018982",
"row_id": 18982,
"seed_ids": "['Llama-3.3-70B-Instruct_47975']"
} | 0.477344 | Filter_18982 | I | [
"is_prime",
"get_primes",
"main"
] | 3 | [
[
"get_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0ea5328c856e43419eefa790b1d5272a66d8a10c | 42fc15a586d3f4fc4195cf7acb14b517aaa496ab | |||
v1.0 | instruct | Filter | Filter_19016_I | Here is a simple implementation of a merge sort algorithm:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 a... | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= r... | def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_array():
assert merge_sort([5, 4, 3, 2, 1]) =... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Perform merge sort on a list of elements.\n\n Parameters:\n arr (list): A list of elements to be sorted.\n\n Returns:\n list: A sorted list.\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019016",
"row_id": 19016,
"seed_ids": "['Llama-3.3-70B-Instruct_48057']"
} | 0.587498 | Filter_19016 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bca7ebcb51dc6df7fc37ce3a4637d3d2da1d9adb | 16b4279452471bf88df4b13c2dccf788ed98780b | |||
v1.0 | instruct | Filter | Filter_19024_I | ### Grading System for a Course
The grading system for a course assigns students a score from 1 to 100, and then converts this score into a letter grade according to the following scale:
- A: 90 - 100
- B: 80 - 89
- C: 70 - 79
- D: 60 - 69
- F: 0 - 59
Write a Python program that takes a score as input and prints out ... | def check_score(score):
"""
Checks if the score is within the valid range of 1 to 100.
"""
if score < 1 or score > 100:
return False
return True
def determine_grade(score):
"""
Determines the letter grade based on the given score.
"""
if score >= 90:
return 'A'
e... | from solution import check_score, determine_grade, get_grade
def test_check_score_within_range():
assert check_score(50) == True
assert check_score(100) == True
assert check_score(1) == True
assert check_score(0) == False
assert check_score(101) == False
def test_determine_grade():
assert dete... | [
{
"docstring": "Checks if the score is within the valid range of 1 to 100.",
"function_declaration": "def check_score(score):",
"function_name": "check_score",
"parameter_list": "(score)"
},
{
"docstring": "Determines the letter grade based on the given score.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def check_score(score):\n \"\"\"\n Checks if the given score is within the valid range (1 to 100).\n Returns True if valid, False otherwise.\n \"\"\"\n if score < 1 or score > 1... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019024",
"row_id": 19024,
"seed_ids": "['Llama-3.3-70B-Instruct_48087']"
} | 0.774543 | Filter_19024 | I | [
"check_score",
"determine_grade",
"get_grade"
] | 3 | [
[
"get_grade",
"check_score"
],
[
"get_grade",
"determine_grade"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d1d159b01e426c064271adf12e259336681f8705 | 1222a30f9382ea418b4d896bc17443b2e0213250 | |||
v1.0 | instruct | Filter | Filter_19033_I | I've created a new programming language called "Nuvolish". Nuvolish is designed to be easy to learn and use, even for beginners. It's a modern, dynamically-typed language with a focus on simplicity and readability. I'd like to create a "Hello World" program in Nuvolish. Since I haven't fully designed the language yet, ... | # Mimicking the proposed Nuvolish functionality in Python for testing purposes
def print_statement(message):
"""
Mimics the print functionality in Nuvolish.
"""
print(message)
def greet(name):
"""
Mimics the greet function in Nuvolish.
"""
print_statement(f"Hello, {name}!")
def hello_... | def test_hello_world_nuvolish(capsys):
hello_world_nuvolish()
captured = capsys.readouterr()
expected_output = (
"Hello, World!\n"
"0\n"
"1\n"
"2\n"
"3\n"
"4\n"
"You are an admin!\n"
"Hello, John!\n"
"1\n"
"John\n"
... | [
{
"docstring": "Mimics the print functionality in Nuvolish.",
"function_declaration": "def print_statement(message):",
"function_name": "print_statement",
"parameter_list": "(message)"
},
{
"docstring": "Mimics the greet function in Nuvolish.",
"function_declaration": "def greet(name):",... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def interpret_nuvolish(code):\n \"\"\"\n Interprets and executes a Nuvolish language script given as a string.\n \"\"\"\n vars = {}\n \n def eval_expr(expr):\n try:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019033",
"row_id": 19033,
"seed_ids": "['Llama-3.3-70B-Instruct_48119']"
} | 0.36663 | Filter_19033 | I | [
"print_statement",
"greet",
"hello_world_nuvolish"
] | 3 | [
[
"greet",
"print_statement"
],
[
"hello_world_nuvolish",
"greet"
],
[
"hello_world_nuvolish",
"print_statement"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 6bf193578ea1700ebd2cec5d9ba28c6e036fba81 | 8feadbfc7b1544dac7a30b8cfe029c616731cb89 | |||
v1.0 | instruct | Filter | Filter_19054_I | I'm trying to write a program to manage a tiny school, let's say with less than 100 students, and about 10 staff members. I'm looking for an easy-to-use interface, possibly with a menu-based system, for the administrators to manage student and staff information, as well as handle other school-related tasks.
I propose... | import json
import os
DATA_FILE = 'school_data.json'
def load_data():
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as file:
return json.load(file)
else:
return {"students": [], "staff": []}
def save_data(data):
with open(DATA_FILE, 'w') as file:
json.dump(da... | from solution import (add_student, add_staff, delete_student, delete_staff,
update_student, update_staff, search_students,
search_staff, display_students, display_staff)
import os
import json
DATA_FILE = 'school_data.json'
def setup_module(module):
test_data = {
... | [
{
"docstring": null,
"function_declaration": "def load_data():",
"function_name": "load_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def save_data(data):",
"function_name": "save_data",
"parameter_list": "(data)"
},
{
"docstring": null,
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\nclass SchoolManager:\n def __init__(self, filename):\n self.filename = filename\n self.load_data()\n\n def load_data(self):\n try:\n with o... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019054",
"row_id": 19054,
"seed_ids": "['Llama-3.3-70B-Instruct_48169']"
} | 0.477313 | Filter_19054 | I | [
"load_data",
"save_data",
"add_student",
"add_staff",
"delete_student",
"delete_staff",
"update_student",
"update_staff",
"search_students",
"search_staff",
"display_students",
"display_staff"
] | 12 | [
[
"add_staff",
"load_data"
],
[
"add_staff",
"save_data"
],
[
"add_student",
"load_data"
],
[
"add_student",
"save_data"
],
[
"delete_staff",
"load_data"
],
[
"delete_staff",
"save_data"
],
[
"delete_student",
"load_data"
],
[
"... | 16 | [] | false | [] | false | pytest | true | [] | true | 408bff1bfc878c25dbcf0d16cbc416b285163803 | 15c68f6a83ca7bb20a62d52a4420ed765f0df9cf | |||
v1.0 | instruct | Filter | Filter_19061_I | I have created a module that takes a byte string as input and returns its SHA-256 hash. However, I would like to add a feature that allows the user to specify a ciphertext of an encrypted hash and have the function decrypt the ciphertext to obtain the original hash and then verify if the input byte string matches the d... | import hashlib
from cryptography.fernet import Fernet
def compute_sha256(input_bytes):
"""
Computes the SHA-256 hash of input byte string.
"""
sha256 = hashlib.sha256()
sha256.update(input_bytes)
return sha256.hexdigest()
def encrypt_sha256_hash(hash_str, key):
"""
Encrypts the SHA-256... | from solution import compute_sha256, encrypt_sha256_hash, decrypt_and_verify_hash
from cryptography.fernet import Fernet
def test_compute_sha256():
assert compute_sha256(b"hello") == hashlib.sha256(b"hello").hexdigest()
def test_encrypt_sha256_hash():
key = Fernet.generate_key()
hash_str = compute_sha256(... | [
{
"docstring": "Computes the SHA-256 hash of input byte string.",
"function_declaration": "def compute_sha256(input_bytes):",
"function_name": "compute_sha256",
"parameter_list": "(input_bytes)"
},
{
"docstring": "Encrypts the SHA-256 hash using a symmetric key.",
"function_declaration":... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nfrom Crypto.Cipher import AES\nimport base64\nimport os\n\ndef sha256_hash(byte_string):\n \"\"\"\n Returns the SHA-256 hash of the given byte string.\n \"\"\"\n re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019061",
"row_id": 19061,
"seed_ids": "['Llama-3.3-70B-Instruct_48182']"
} | 0.601193 | Filter_19061 | I | [
"compute_sha256",
"encrypt_sha256_hash",
"decrypt_and_verify_hash"
] | 3 | [
[
"decrypt_and_verify_hash",
"compute_sha256"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cryptography"
] | false | e17116c7258e223f320a48d977ec44b4512dd5e4 | d3f1e7645ebdcd83e95fabcdf86d0da62e9451a2 | |||
v1.0 | instruct | Filter | Filter_19067_I | I want a code that can convert binary number to decimal number and decimal number to binary number in Python.
Here are the details of what the code should do:
1. The code should contain two functions: binary_to_decimal() and decimal_to_binary().
2. The code should first ask the user for input whether they want to co... | def binary_to_decimal(binary):
"""
Converts a binary number (as a string) to a decimal number.
"""
return int(binary, 2)
def decimal_to_binary(decimal):
"""
Converts a decimal number (as an integer) to a binary number (as a string).
"""
return bin(decimal)[2:]
def convert():
while ... | from solution import binary_to_decimal, decimal_to_binary
def test_binary_to_decimal():
assert binary_to_decimal("0") == 0
assert binary_to_decimal("1") == 1
assert binary_to_decimal("10") == 2
assert binary_to_decimal("101") == 5
assert binary_to_decimal("111") == 7
assert binary_to_decimal("1... | [
{
"docstring": "Converts a binary number (as a string) to a decimal number.",
"function_declaration": "def binary_to_decimal(binary):",
"function_name": "binary_to_decimal",
"parameter_list": "(binary)"
},
{
"docstring": "Converts a decimal number (as an integer) to a binary number (as a str... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_to_decimal(binary_str):\n \"\"\"\n Converts a binary number (given as a string) to its decimal equivalent.\n \"\"\"\n return int(binary_str, 2)\n\n\ndef decimal_to_binar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019067",
"row_id": 19067,
"seed_ids": "['Llama-3.3-70B-Instruct_48198']"
} | 0.817565 | Filter_19067 | I | [
"binary_to_decimal",
"decimal_to_binary",
"convert"
] | 3 | [
[
"convert",
"binary_to_decimal"
],
[
"convert",
"decimal_to_binary"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2eafc98b96c1d2c8f823d36544b4b544df38df95 | bdc9dc42d4d298c9ea4bc2db865e4c26bfc63535 | |||
v1.0 | instruct | Filter | Filter_19069_I | I have a text file that I want to colorize based on keywords found within it, and I was wondering how to best accomplish this with Python.
Here are the specifics:
- The text file contains paragraphs of plain text.
- I want to highlight specific keywords within the text using specific colors.
- The keywords and their c... | import re
def colorize_text(text, color_dict):
"""
Colorize the text based on the keywords and their corresponding colors in the color_dict.
:param text: The input text to be colorized
:param color_dict: Dictionary with keywords as keys and ANSI color codes as values
:return: Colorized text
... | import pytest
from solution import colorize_text, read_and_colorize
from unittest.mock import mock_open, patch
def test_colorize_text_basic():
text = "hello world"
color_dict = {"hello": "\033[31m", "world": "\033[32m"}
expected_output = "\033[31mhello\033[0m \033[32mworld\033[0m"
assert colorize_text(... | [
{
"docstring": "Colorize the text based on the keywords and their corresponding colors in the color_dict.\n\n:param text: The input text to be colorized\n:param color_dict: Dictionary with keywords as keys and ANSI color codes as values\n:return: Colorized text",
"function_declaration": "def colorize_text(t... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from termcolor import colored\nimport re\n\ndef colorize_text(input_file, output_file, keywords_colors):\n \"\"\"\n Reads a text file, colorizes specified keywords, and writes the result... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019069",
"row_id": 19069,
"seed_ids": "['Llama-3.3-70B-Instruct_48200']"
} | 0.527746 | Filter_19069 | I | [
"colorize_text",
"read_and_colorize"
] | 2 | [
[
"read_and_colorize",
"colorize_text"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35201704dfbb9e30b30bc7bcd83c97b4d8998d72 | 0be16fa536b20605bb22bad536157119d752659b | |||
v1.0 | instruct | Filter | Filter_19074_I | Given a set of strings, find the maximum length substring without repeating characters in each string and return a dictionary where the keys are the input strings and the values are the maximum length substrings without repeating characters.
### Example:
Input: `["abcabcbb", "bbbbbb", "pwwkew", "abcdef"]`
Output: `{ "... | from collections import defaultdict
def length_of_longest_substring(s):
"""
Finds the longest substring without repeating characters in a given string s.
Returns the longest substring without repeating characters.
"""
left = 0
right = 0
seen = defaultdict(int)
max_length = 0
max_sub... | from solution import length_of_longest_substring, longest_substrings
def test_length_of_longest_substring():
assert length_of_longest_substring("abcabcbb") == "abc"
assert length_of_longest_substring("bbbbbb") == "b"
assert length_of_longest_substring("pwwkew") == "wke"
assert length_of_longest_substri... | [
{
"docstring": "Finds the longest substring without repeating characters in a given string s.\nReturns the longest substring without repeating characters.",
"function_declaration": "def length_of_longest_substring(s):",
"function_name": "length_of_longest_substring",
"parameter_list": "(s)"
},
{... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def length_of_longest_substring(s):\n \"\"\"\n Finds the maximum length substring without repeating characters in a given string s.\n \"\"\"\n left = 0\n max_length = 0\n max... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019074",
"row_id": 19074,
"seed_ids": "['Llama-3.3-70B-Instruct_48212']"
} | 0.744679 | Filter_19074 | I | [
"length_of_longest_substring",
"longest_substrings"
] | 2 | [
[
"longest_substrings",
"length_of_longest_substring"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a951da7fe74c4f051054c37b8e4d373019871b7 | 319ce1152724176c2cd249ad7811e57a12dff36b | |||
v1.0 | instruct | Filter | Filter_19075_I | I've been asked to solve the problem: Write a Huffman coding algorithm for text encoding and decoding.
**Task Requirements:**
* Generate Huffman codes for the given text by calculating the frequency of each character.
* Use a priority queue to create the Huffman tree.
* Write a function to encode the text using the ... | import heapq
from collections import defaultdict
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def calculate_frequency(text):
frequency = defau... | from solution import calculate_frequency, build_huffman_tree, build_huffman_codes, encode_text, decode_text, huffman_coding
def test_calculate_frequency():
text = "aabbcc"
freq = calculate_frequency(text)
assert freq['a'] == 2
assert freq['b'] == 2
assert freq['c'] == 2
def test_build_huffman_tree... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import defaultdict\n\nclass Node:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n self.left = None\n sel... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019075",
"row_id": 19075,
"seed_ids": "['Llama-3.3-70B-Instruct_48214']"
} | 0.491448 | Filter_19075 | I | [
"calculate_frequency",
"build_huffman_tree",
"build_huffman_codes",
"encode_text",
"decode_text",
"huffman_coding"
] | 6 | [
[
"huffman_coding",
"build_huffman_codes"
],
[
"huffman_coding",
"build_huffman_tree"
],
[
"huffman_coding",
"calculate_frequency"
],
[
"huffman_coding",
"decode_text"
],
[
"huffman_coding",
"encode_text"
]
] | 5 | [] | false | [
"Node"
] | true | pytest | true | [] | true | a5272357b60d3339290c94b73fa322374a2ad3ed | 5d6a7f5f6750c7d0a81bfb7ed0b233cb697b6a37 | |||
v1.0 | instruct | Filter | Filter_19076_I | I have an algorithm that needs to sort a set of words based on the alphabetical order of their corresponding numerical representations (not the standard alphabetical order).
To clarify, each word will be converted into a numerical representation (e.g., "one" becomes 1, "two" becomes 2, etc.), and then sorted according... | def convert_to_number(word):
"""
Converts word representation of number into float, including decimal and negative numbers.
"""
word_to_number = {
'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,
'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9,
'ten': 10, 'minus one':... | from solution import convert_to_number, sort_words
def test_convert_to_number():
assert convert_to_number('one') == 1
assert convert_to_number('minus one') == -1
assert convert_to_number('two point five') == 2.5
assert convert_to_number('minus two point five') == -2.5
assert convert_to_number('zero... | [
{
"docstring": "Converts word representation of number into float, including decimal and negative numbers.",
"function_declaration": "def convert_to_number(word):",
"function_name": "convert_to_number",
"parameter_list": "(word)"
},
{
"docstring": "Sorts the list of words based on the numeri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def convert_to_number(word):\n \"\"\"Converts word representation of number into float.\"\"\"\n word_to_number = {\n 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019076",
"row_id": 19076,
"seed_ids": "['Llama-3.3-70B-Instruct_48215']"
} | 0.66108 | Filter_19076 | I | [
"convert_to_number",
"sort_words"
] | 2 | [
[
"sort_words",
"convert_to_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d612a96d20d21c50ebf0a445d3df7a0025781534 | 0dc44727cab30c16023c8363578fec905d912815 | |||
v1.0 | instruct | Filter | Filter_19088_I | I want to write a program that takes two input files and outputs the difference between them. I'm thinking of using a hash table to store the data from the first file and then iterate through the second file to find the differences. | def load_data_to_hash(file_path):
"""
Load data from the file into a hash set.
:param file_path: Path to the file
:return: A set containing the data from the file
"""
data_set = set()
with open(file_path, 'r') as file:
for line in file:
data_set.add(line.strip())
ret... | from solution import load_data_to_hash, find_differences
def test_load_data_to_hash(tmp_path):
file_path = tmp_path / "file1.txt"
file_content = """line1
line2
line3"""
file_path.write_text(file_content)
expected_data = {"line1", "line2", "line3"}
assert load_data_to_hash(file_path) ==... | [
{
"docstring": "Load data from the file into a hash set.\n\n:param file_path: Path to the file\n:return: A set containing the data from the file",
"function_declaration": "def load_data_to_hash(file_path):",
"function_name": "load_data_to_hash",
"parameter_list": "(file_path)"
},
{
"docstrin... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def file_difference(file1, file2):\n \"\"\"\n Returns the difference between two files.\n \"\"\"\n \n with open(file1, 'r') as f1, open(file2, 'r') as f2:\n file1_content... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019088",
"row_id": 19088,
"seed_ids": "['Llama-3.3-70B-Instruct_48245']"
} | 0.596653 | Filter_19088 | I | [
"load_data_to_hash",
"find_differences"
] | 2 | [
[
"find_differences",
"load_data_to_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | adeb8b36edf1b0c2bba21dc6b14dc9079b25cf20 | b8b82aea11bd14632e3792bdfdbba57291bcb433 | |||
v1.0 | instruct | Filter | Filter_19096_I | Here is the code that I'm using to convert an image from RGB to grayscale:
```python
import cv2
import numpy as np
def convert_to_grayscale(image_path):
image = cv2.imread(image_path)
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return grayscale_image
```
I want to add a function that uses the... | import cv2
import numpy as np
def convert_to_grayscale(image_path):
image = cv2.imread(image_path)
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return grayscale_image
def create_negative_image(image_path):
grayscale_image = convert_to_grayscale(image_path)
negative_image = 255 - grays... | from solution import convert_to_grayscale, create_negative_image
import numpy as np
import cv2
def test_convert_to_grayscale():
# Create a synthetic image for testing
synthetic_image = np.zeros((100, 100, 3), dtype=np.uint8)
synthetic_image.fill(150)
cv2.imwrite('synthetic_image.jpg', synthetic_image)
... | [
{
"docstring": null,
"function_declaration": "def convert_to_grayscale(image_path):",
"function_name": "convert_to_grayscale",
"parameter_list": "(image_path)"
},
{
"docstring": null,
"function_declaration": "def create_negative_image(image_path):",
"function_name": "create_negative_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport numpy as np\n\ndef convert_to_grayscale(image_path):\n \"\"\"\n Convert an image from the given image path to grayscale.\n\n Parameters:\n image_path (str): Path... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019096",
"row_id": 19096,
"seed_ids": "['Llama-3.3-70B-Instruct_48258']"
} | 0.622369 | Filter_19096 | I | [
"convert_to_grayscale",
"create_negative_image"
] | 2 | [
[
"create_negative_image",
"convert_to_grayscale"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 950f62ed8011d009808c6ea76ff34fbb244b4f36 | 3e8cbdd9cd316bdad9ffdaae8b5e4728d01685d5 | |||
v1.0 | instruct | Filter | Filter_19103_I | This is a Python program that prints all numbers from 1 to 100 that are divisible by either 3 or 5.
```python
def find_divisible_numbers(n):
"""
This function generates all numbers from 1 to n that are divisible by either 3 or 5.
Args:
n (int): The upper limit of the range of numbers to check.
... | def is_divisible_by_3_or_5(number):
"""
Check if the given number is divisible by either 3 or 5.
Args:
number (int): The number to check.
Returns:
bool: True if the number is divisible by either 3 or 5, False otherwise.
"""
return number % 3 == 0 or number % 5 == 0
def find_di... | from solution import is_divisible_by_3_or_5, find_divisible_numbers, main
def test_is_divisible_by_3_or_5():
assert is_divisible_by_3_or_5(3) == True
assert is_divisible_by_3_or_5(5) == True
assert is_divisible_by_3_or_5(15) == True
assert is_divisible_by_3_or_5(7) == False
def test_find_divisible_num... | [
{
"docstring": "Check if the given number is divisible by either 3 or 5.\n\nArgs:\n number (int): The number to check.\n\nReturns:\n bool: True if the number is divisible by either 3 or 5, False otherwise.",
"function_declaration": "def is_divisible_by_3_or_5(number):",
"function_name": "is_divisi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_divisible_by_3_or_5(number):\n \"\"\"\n Check if the given number is divisible by either 3 or 5.\n\n Args:\n number (int): The number to check.\n\n Returns:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019103",
"row_id": 19103,
"seed_ids": "['Llama-3.3-70B-Instruct_48268']"
} | 0.594411 | Filter_19103 | I | [
"is_divisible_by_3_or_5",
"find_divisible_numbers",
"main"
] | 3 | [
[
"find_divisible_numbers",
"is_divisible_by_3_or_5"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8941b39b67e99ffa5cf24c047851ba5b8d8d7208 | b0186c8a7780ea81ac56a095ed0ef982cbe013c0 | |||
v1.0 | instruct | Filter | Filter_19116_I | I have a large number of JPEG images that I need to process. The images are all the same size and are named sequentially, e.g. `image0001.jpg`, `image0002.jpg`, etc. I'd like to create a script that can find the average color of each image and save the result as a text file. I intended to use Python for this task, but ... | import os
from pathlib import Path
def read_jpeg_image(image_path):
"""
Dummy function to represent JPEG reading.
In reality, decoding JPEG without external libraries is not possible.
"""
raise NotImplementedError("JPEG decoding is not possible with built-in libraries only")
def process_images(ima... | import pytest
def test_process_images():
# Testing this functionality is not possible without actual implementation
pass
def test_read_jpeg_image():
with pytest.raises(NotImplementedError):
read_jpeg_image("image0001.jpg")
def test_calculate_average_color():
with pytest.raises(NotImplementedE... | [
{
"docstring": "Dummy function to represent JPEG reading.\nIn reality, decoding JPEG without external libraries is not possible.",
"function_declaration": "def read_jpeg_image(image_path):",
"function_name": "read_jpeg_image",
"parameter_list": "(image_path)"
},
{
"docstring": "Process all J... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image\nimport os\n\ndef calculate_average_color(image_path):\n \"\"\"\n Calculate the average color of the image.\n \"\"\"\n with Image.open(image_path) as img:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019116",
"row_id": 19116,
"seed_ids": "['Llama-3.3-70B-Instruct_48293']"
} | 0.533376 | Filter_19116 | I | [
"read_jpeg_image",
"process_images",
"calculate_average_color"
] | 3 | [
[
"process_images",
"calculate_average_color"
],
[
"process_images",
"read_jpeg_image"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 74c38211e82b9b6e48836fa4263a5bcf15afbc29 | d7a056f234ba55f182e05e2f83a53fc89369434b | |||
v1.0 | instruct | Filter | Filter_19117_I | ### Forward and Backward Pass of a Network
The forward pass of the neural network calculates the output of the network given the input and weights of the network. The backward pass, also known as backpropagation, is the process by which the error is propagated backwards through the network and the weights are updated. ... | import numpy as np
def relu(x):
return np.maximum(0, x)
def relu_derivative(x):
return np.where(x > 0, 1, 0)
def forward_pass(input_data, weights, biases):
hidden_input = np.dot(input_data, weights[0]) + biases[0]
hidden_output = relu(hidden_input)
final_input = np.dot(hidden_output, weights[1]) ... | from solution import backward_pass
import numpy as np
def test_backward_pass():
weights = [
np.array([[0.1, 0.2], [0.3, 0.4]]),
np.array([[0.5, 0.6], [0.7, 0.8]])
]
biases = [
np.array([0.1, 0.2]),
np.array([0.1, 0.2])
]
input_data = np.array([
[0.1... | [
{
"docstring": null,
"function_declaration": "def relu(x):",
"function_name": "relu",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def relu_derivative(x):",
"function_name": "relu_derivative",
"parameter_list": "(x)"
},
{
"docstring": null,
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef relu(x):\n \"\"\"\n Applies the ReLU activation function element-wise.\n \"\"\"\n return np.maximum(0, x)\n\ndef relu_derivative(x):\n \"\"\"\n Calc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019117",
"row_id": 19117,
"seed_ids": "['Llama-3.3-70B-Instruct_48295']"
} | 0.508761 | Filter_19117 | I | [
"relu",
"relu_derivative",
"forward_pass",
"backward_pass"
] | 4 | [
[
"backward_pass",
"forward_pass"
],
[
"backward_pass",
"relu_derivative"
],
[
"forward_pass",
"relu"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | d54cabcc7632071ee03b687cbfa4ee3a9fd73a62 | 07f693e16609dedfe3c4cf012c84a16e91557cdd | |||
v1.0 | instruct | Filter | Filter_19125_I | In this problem, we will be working with a binary tree. Specifically, we will be using a min-heap binary tree where all parent nodes are less than or equal to their children. Given a list of integers, we will be implementing an algorithm to build a min-heap from the list. The process will involve the following steps:
... | class MinHeapNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def heapify_down(heap):
if heap is None:
return
min_node = heap
if heap.left and heap.left.val < min_node.val:
min_node = heap.left
if heap.right and ... | from solution import MinHeapNode, build_min_heap
def tree_to_list(root):
if not root:
return []
result = []
nodes = [root]
while nodes:
node = nodes.pop(0)
result.append(node.val)
if node.left:
nodes.append(node.left)
if node.right:
n... | [] | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class MinHeapNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\ndef heapify_down(heap):\n if heap is None:\n return\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019125",
"row_id": 19125,
"seed_ids": "['Llama-3.3-70B-Instruct_48310']"
} | 0.638221 | Filter_19125 | I | [
"heapify_down",
"insert",
"build_min_heap"
] | 3 | [
[
"build_min_heap",
"insert"
],
[
"insert",
"heapify_down"
]
] | 2 | [] | false | [
"MinHeapNode"
] | true | pytest | true | [] | true | c8291fdf5f4fad4ffaed176ff0cdc39015c7e9f1 | be7a2dce40c285c0cae3eaa5b0edac71665144d5 | |||
v1.0 | instruct | Filter | Filter_19132_I | I have a set of points on a plane and I want to find out which points are closest to a given point (the target). I need an efficient algorithm to solve this problem.
Here are the steps I'd like to implement:
- take the target point and a set of points
- find the k nearest neighbors (or points) to the target point
- r... | from heapq import nsmallest
from math import sqrt
def euclidean_distance(point1, point2):
"""
Returns the Euclidean distance between two points in 2D space.
"""
return sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def k_nearest_neighbors(target, points, k):
"""
Returns the ... | from solution import euclidean_distance, k_nearest_neighbors
def test_euclidean_distance():
assert euclidean_distance((0, 0), (3, 4)) == 5.0
assert euclidean_distance((1, 1), (4, 5)) == 5.0
assert euclidean_distance((2, 3), (2, 3)) == 0.0
def test_k_nearest_neighbors():
points = [(1, 2), (3, 4), (5, 6... | [
{
"docstring": "Returns the Euclidean distance between two points in 2D space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Returns the k nearest points to the target point.... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\"\"\n Calculate the Euclidean distance between two... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019132",
"row_id": 19132,
"seed_ids": "['Llama-3.3-70B-Instruct_48325']"
} | 0.641546 | Filter_19132 | I | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 012dd644fb29ab4217a585bdc4afb48f542d732a | 824d405f07b3dad7887c609100d2295594e62f30 | |||
v1.0 | instruct | Filter | Filter_19158_I | Your task is to create a Python program that takes two integers as input from the user, checks if both integers are positive, and then multiplies them. If the integers are not positive, print an error message and ask for the integers again. You should keep asking for input until two positive integers are entered. | def get_positive_integer(prompt):
"""
Prompt the user for an integer and check if it is positive.
Args:
prompt (str): The prompt message for the user input.
Returns:
int: A positive integer.
"""
while True:
try:
num = int(input(prompt))
if num > ... | from solution import get_positive_integer, multiply_positive_integers
def test_get_positive_integer(monkeypatch):
inputs = iter([0, -10, 5])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
assert get_positive_integer("Enter a positive integer: ") == 5
def test_multiply_positive_integers(monk... | [
{
"docstring": "Prompt the user for an integer and check if it is positive.\n\nArgs:\nprompt (str): The prompt message for the user input.\n\nReturns:\nint: A positive integer.",
"function_declaration": "def get_positive_integer(prompt):",
"function_name": "get_positive_integer",
"parameter_list": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_positive_integer(prompt):\n \"\"\"\n Repeatedly prompt the user for a positive integer until valid input is given.\n \"\"\"\n while True:\n try:\n number ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019158",
"row_id": 19158,
"seed_ids": "['Llama-3.3-70B-Instruct_48385']"
} | 0.639572 | Filter_19158 | I | [
"get_positive_integer",
"multiply_positive_integers"
] | 2 | [
[
"multiply_positive_integers",
"get_positive_integer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c1a0dfa7d62ac30ece2e9dd7fd81188bf0ab7a0 | 8da7c620fb55c621100124b8183c135334a696cb | |||
v1.0 | instruct | Filter | Filter_19182_I | Imagine you've been tasked with developing an algorithm and writing a program (in Python) to investigate the behavior of a specific type of mathematical function, specifically the growth rates of functions of the form $f(x) = x^n$, where n is a real number.
Your goal is to analyze how the growth rate of this function... | import numpy as np
import matplotlib.pyplot as plt
def calculate_function(x, n):
"""
Evaluates the function f(x) = x^n for a given value of n.
Args:
x (float): The input value.
n (float): The exponent.
Returns:
float: The result of the function evaluation.
"""
return x ** n
def g... | from solution import calculate_function
def test_calculate_function_positive_exponent():
assert calculate_function(2, 3) == 8
assert calculate_function(3, 2) == 9
assert calculate_function(4, 1) == 4
def test_calculate_function_zero_exponent():
assert calculate_function(2, 0) == 1
assert calculate... | [
{
"docstring": "Evaluates the function f(x) = x^n for a given value of n.\n\nArgs:\nx (float): The input value.\nn (float): The exponent.\n\nReturns:\nfloat: The result of the function evaluation.",
"function_declaration": "def calculate_function(x, n):",
"function_name": "calculate_function",
"para... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef calculate_function(x, n):\n \"\"\"\n Evaluates the function f(x) = x^n for a given value of n.\n\n Args:\n x (float): The... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019182",
"row_id": 19182,
"seed_ids": "['Llama-3.3-70B-Instruct_48441']"
} | 0.612362 | Filter_19182 | I | [
"calculate_function",
"generate_x_values",
"plot_function",
"main"
] | 4 | [
[
"plot_function",
"calculate_function"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | be7c818d76e7fbbcb458e8f7fbd5fcb22d97068d | 52f62b45900f015261582e274d3cf6be59419959 | |||
v1.0 | instruct | Filter | Filter_19227_I | I understand that there is an explicit solution to the logistic equation, but I would like to compare that with a numerical solution. I'd like you to create a code to solve this logistic differential equation:
dy/dt = r*y*(1-y/K)
Where y is the population size, r is the intrinsic growth rate and K is the carrying capac... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def logistic_growth(y, t, r, K):
"""
Logistic growth differential equation.
Parameters:
y : float
Current population size
t : float
Time
r : float
Intrinsic growth rate
K : flo... | def test_logistic_growth():
assert np.isclose(logistic_growth(10, 0, 0.1, 100), 0.9)
assert np.isclose(logistic_growth(50, 0, 0.1, 100), 2.5)
assert np.isclose(logistic_growth(100, 0, 0.1, 100), 0)
def test_solve_logistic_ode():
t = np.linspace(0, 10, 100)
y = solve_logistic_ode(10, t, 0.1, 100)
... | [
{
"docstring": "Logistic growth differential equation.\n\nParameters:\ny : float\n Current population size\nt : float\n Time\nr : float\n Intrinsic growth rate\nK : float\n Carrying capacity\n\nReturns:\ndydt : float\n Rate of change of population size",
"function_declaration": "def logistic_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\ndef logistic(y, t, r, K):\n \"\"\"\n Logistic equation: dy/dt = r*y*(1-y/K)\n \"\"\"\n re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019227",
"row_id": 19227,
"seed_ids": "['Llama-3.3-70B-Instruct_48554']"
} | 0.329121 | Filter_19227 | I | [
"logistic_growth",
"solve_logistic_ode"
] | 2 | [
[
"solve_logistic_ode",
"logistic_growth"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"scipy"
] | false | b7717c8121cda316fdecf25fceafb2870781c3ce | 2c61e001b2d9ada9738017e0d3cf6909f04ba3b9 | |||
v1.0 | instruct | Filter | Filter_19228_I | ### Card Shuffling and Dealing
I have a deck of 52 cards. I want to write a Python program to shuffle the deck, deal out two hands of 5 cards each, and determine the best 5-card poker hand possible from each hand.
### Step-by-step analysis of the problem:
1. **Create the deck**: Generate a deck of cards with all suits... | import random
from collections import namedtuple
# Define Card nametuple as it is helpful for creating cards
Card = namedtuple('Card', ['rank', 'suit'])
# Function to create a deck of 52 cards
def create_deck():
ranks = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
suits = 'Hearts Diamonds Clubs Spades'.split()
de... | from solution import create_deck, shuffle_deck, deal_hands, evaluate_hand, poker_game
def test_create_deck():
deck = create_deck()
assert len(deck) == 52
assert isinstance(deck[0], tuple)
def test_shuffle_deck():
deck = create_deck()
shuffled_deck = shuffle_deck(deck.copy())
assert sorted(shuf... | [
{
"docstring": null,
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def shuffle_deck(deck):",
"function_name": "shuffle_deck",
"parameter_list": "(deck)"
},
{
"docstring... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom itertools import combinations\n\n# Define the card ranks and suits\nSUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\nRANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10'... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019228",
"row_id": 19228,
"seed_ids": "['Llama-3.3-70B-Instruct_48556']"
} | 0.670341 | Filter_19228 | I | [
"create_deck",
"shuffle_deck",
"deal_hands",
"evaluate_hand",
"poker_game"
] | 5 | [
[
"poker_game",
"create_deck"
],
[
"poker_game",
"deal_hands"
],
[
"poker_game",
"evaluate_hand"
],
[
"poker_game",
"shuffle_deck"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | cae327f0abb4a7a8d4b402f7b43ced2bd4b25306 | c3d613920a18e63061f312119b8e3d279248c765 | |||
v1.0 | instruct | Filter | Filter_19240_I | I'm interested in creating a piece of Python code that will allow me to create, modify, and delete users in a dictionary where each key is the username and each value is another dictionary containing details such as first name, last name, email, and password.
Here's a basic structure I started with:
```
users = {}
# ... | import re
users = {}
def is_valid_email(email):
"""Check if the given email is valid."""
email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(email_regex, email)
def create_user(username, first_name, last_name, email, password):
"""
Create a new user with the given de... | from solution import create_user, modify_user, delete_user, display_users, search_user
def test_create_user():
assert create_user("user1", "John", "Doe", "john@example.com", "password123") == "User created successfully."
assert create_user("user1", "Jane", "Smith", "jane@example.com", "password456") == "Userna... | [
{
"docstring": "Check if the given email is valid.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "Create a new user with the given details.",
"function_declaration": "def create_user(username, firs... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\nusers = {}\n\ndef is_valid_email(email):\n \"\"\"Check if the email address is valid.\"\"\"\n email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'\n return ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019240",
"row_id": 19240,
"seed_ids": "['Llama-3.3-70B-Instruct_48590']"
} | 0.579168 | Filter_19240 | I | [
"is_valid_email",
"create_user",
"modify_user",
"delete_user",
"display_users",
"search_user"
] | 6 | [
[
"create_user",
"is_valid_email"
],
[
"modify_user",
"is_valid_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ca16db6cc50bf81c051e4f65d9655a3a8a2cc7fe | 4dfc1b1068185be60af651eea9e8de47466e83ee | |||
v1.0 | instruct | Filter | Filter_19246_I | This is a continuation of our previous conversation. We previously established that we were going to use a trained discriminative model to classify mp3s into two categories: "music" or "not music". The model was trained on a dataset of labeled examples, where each example is an mp3 file.
Can you go one step further a... | import numpy as np
import librosa
import joblib
def extract_features(file_path):
"""
Extracts audio features from an mp3 file.
Args:
file_path (str): Path to the mp3 file.
Returns:
np.array: Extracted features.
"""
y, sr = librosa.load(file_path, sr=None)
# Extract Me... | from solution import extract_features, classify_mp3
import numpy as np
from unittest.mock import patch, mock_open
def test_extract_features():
# Mocking librosa.load and librosa.feature.mfcc
with patch('librosa.load') as mocked_load:
with patch('librosa.feature.mfcc') as mocked_mfcc:
# Mock... | [
{
"docstring": "Extracts audio features from an mp3 file.\n\nArgs:\nfile_path (str): Path to the mp3 file.\n\nReturns:\nnp.array: Extracted features.",
"function_declaration": "def extract_features(file_path):",
"function_name": "extract_features",
"parameter_list": "(file_path)"
},
{
"docst... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport librosa\nimport joblib\n\ndef extract_audio_features(mp3_path):\n \"\"\"\n Extracts relevant audio features from an mp3 file.\n \n Args:\n mp3_path (s... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019246",
"row_id": 19246,
"seed_ids": "['Llama-3.3-70B-Instruct_48603']"
} | 0.340012 | Filter_19246 | I | [
"extract_features",
"classify_mp3"
] | 2 | [
[
"classify_mp3",
"extract_features"
]
] | 1 | [] | false | [] | false | pytest | true | [
"joblib",
"librosa",
"numpy"
] | false | 22c5644a4c64b64c8f1673bfd7927eafcaeb4990 | c19a3de99b5d8076050634f423a26b88a7cdbd50 | |||
v1.0 | instruct | Filter | Filter_19264_I | Create a program called Gender Detector that uses the user's input to detect whether the user is a male or female based on their first name. The gender detector uses a predefined list of male and female names to make a prediction.
There is a list of names that are commonly known as male names and a list of names that... | def load_names():
"""
Load the predefined lists of male and female names.
"""
male_names = ["John", "Michael", "William", "James", "Robert", "Richard", "Charles", "Thomas", "Ronald", "Harold", "Gary", "Steven", "Larry", "Joseph", "Edward", "Brian", "Kevin", "Mark", "Paul", "Andrew", "Donald", "George", ... | from solution import load_names, detect_gender
def test_load_names():
male_names, female_names = load_names()
assert "John" in male_names
assert "Emily" in female_names
assert "Michael" in male_names
assert "Madison" in female_names
def test_detect_gender_male():
assert detect_gender("John") =... | [
{
"docstring": "Load the predefined lists of male and female names.",
"function_declaration": "def load_names():",
"function_name": "load_names",
"parameter_list": "()"
},
{
"docstring": "Predict the gender based on the predefined list of names.",
"function_declaration": "def detect_gend... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def load_names():\n \"\"\"\n Load the predefined lists of male and female names.\n Returns:\n male_names (list): List of commonly known male names.\n female_names (list)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019264",
"row_id": 19264,
"seed_ids": "['Llama-3.3-70B-Instruct_48662']"
} | 0.55216 | Filter_19264 | I | [
"load_names",
"detect_gender",
"main"
] | 3 | [
[
"detect_gender",
"load_names"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3002ca31bd4083704588b8f6be0dbc437b7816ac | ed1c52541711de1aeb5fca4cb95b783bb9c8004c | |||
v1.0 | instruct | Filter | Filter_19265_I | ### Overview of Task
Implement a function that checks if a given string contains valid credit card numbers and returns them. The function should handle the following card types: Visa, Mastercard, American Express, Diners Club, Discover, and JCB.
### Requirements
* Handle different credit card types with their respec... | import re
def luhn_algorithm(card_number):
"""
Implements the Luhn algorithm to validate a credit card number.
"""
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = sum(odd_digits... | def test_visa_valid():
assert check_credit_card_numbers("My Visa card number is 4111-1111-1111-1111.") == ["4111111111111111"]
def test_mastercard_valid():
assert check_credit_card_numbers("My Mastercard number is 5500-0000-0000-0004.") == ["5500000000000004"]
def test_american_express_valid():
assert che... | [
{
"docstring": "Implements the Luhn algorithm to validate a credit card number.",
"function_declaration": "def luhn_algorithm(card_number):",
"function_name": "luhn_algorithm",
"parameter_list": "(card_number)"
},
{
"docstring": null,
"function_declaration": "def check_credit_card_number... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_luhn_valid(card_number):\n \"\"\"Use Luhn algorithm to validate the card number.\"\"\"\n sum_ = 0\n num_digits = len(card_number)\n oddeven = num_digits & 1\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019265",
"row_id": 19265,
"seed_ids": "['Llama-3.3-70B-Instruct_48664']"
} | 0.511127 | Filter_19265 | I | [
"luhn_algorithm",
"check_credit_card_numbers"
] | 2 | [
[
"check_credit_card_numbers",
"luhn_algorithm"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 4644e32d4164d54d7c0e55e18f18500687f75135 | 4397f4095aa766d1eb05103c7cb91ff4b88f17ca | |||
v1.0 | instruct | Filter | Filter_19292_I | ### Object Oriented Programming with Python
#### Decorators
Decorators are a powerful feature in Python that allows programmers to modify the behavior of function or class without changing its implementation.
Here's a basic decorator:
```python
def my_decorator(func):
def wrapper():
print("Something is ... | import time
from functools import wraps
def average_time_decorator(num_runs):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
total_time = 0.0
for _ in range(num_runs):
start_time = time.time()
result = func(*args, **kwargs)
... | from solution import average_time_decorator
import time
@average_time_decorator(num_runs=3)
def fast_function():
return "fast"
@average_time_decorator(num_runs=3)
def slow_function():
time.sleep(1)
return "slow"
def test_fast_function():
result = fast_function()
assert result == "fast"
def test_... | [
{
"docstring": null,
"function_declaration": "def average_time_decorator(num_runs):",
"function_name": "average_time_decorator",
"parameter_list": "(num_runs)"
},
{
"docstring": null,
"function_declaration": "def example_func():",
"function_name": "example_func",
"parameter_list"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom functools import wraps\n\ndef average_time_decorator(runs):\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n total_time = 0... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019292",
"row_id": 19292,
"seed_ids": "['Llama-3.3-70B-Instruct_48748']"
} | 0.596409 | Filter_19292 | I | [
"average_time_decorator",
"example_func"
] | 2 | [
[
"example_func",
"average_time_decorator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5de3d5593c5257c1c85ce4163decc649895224a9 | cbcc276a40b3f6e2497c7ec740c64e0ba08bb417 | |||
v1.0 | instruct | Filter | Filter_19293_I | I have a first-order linear differential equation (a system of equations) which is expressed in matrix form like this:
dY/dt = M(t)Y, where M(t) is a 3x3 matrix and Y is a 3x1 column vector.
I know that the solution is given by the expression:
Y(t) = Φ(t)Y(0),
where Y(0) is the initial condition and Φ(t) is the tran... | import numpy as np
from scipy.integrate import odeint
def model(state, t, M):
"""
Defines the model for the system of differential equations.
:param state: Array of state variables.
:param t: Time variable.
:param M: Function that returns the 3x3 matrix M(t).
:return: Derivative of state with r... | from solution import model, solve_system
import numpy as np
def test_model_simple():
M = lambda t: np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # Identity matrix
state = np.array([1, 1, 1])
t = 0
dYdt = model(state, t, M)
assert np.array_equal(dYdt, state) # dY/dt = Y for identity matrix M
def te... | [
{
"docstring": "Defines the model for the system of differential equations.\n:param state: Array of state variables.\n:param t: Time variable.\n:param M: Function that returns the 3x3 matrix M(t).\n:return: Derivative of state with respect to time.",
"function_declaration": "def model(state, t, M):",
"f... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import solve_ivp\n\ndef model(t, Y, M_func):\n \"\"\"\n The system of differential equations in the form dY/dt = M(t)Y.\n\n Args:\n t (floa... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019293",
"row_id": 19293,
"seed_ids": "['Llama-3.3-70B-Instruct_48750']"
} | 0.291361 | Filter_19293 | I | [
"model",
"solve_system"
] | 2 | [
[
"solve_system",
"model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | e714315a0ac033ce7599cf4624e307084cbc4e33 | 448aac606f1e3bf5e6f52cf8683314e571593d70 | |||
v1.0 | instruct | Filter | Filter_19305_I | I've been searching for a solution for days and have come up with nothing. I'm trying to make a password generator that generates a random password for the user, which also checks for the strength of the password. I want the password to have the following criteria:
It must be at least 8 characters long, it must contai... | import string
import secrets
def generate_password(length):
"""
Generates a random password of specified length.
The generated password will meet the following criteria:
- At least 8 characters long
- Contains at least one lowercase letter
- Contains at least one uppercase letter
- Contains... | import pytest
from solution import generate_password, password_strength
def test_generate_password_length():
password = generate_password(8)
assert len(password) == 8
password = generate_password(12)
assert len(password) == 12
def test_generate_password_criteria():
password = generate_password(12... | [
{
"docstring": "Generates a random password of specified length.\nThe generated password will meet the following criteria:\n- At least 8 characters long\n- Contains at least one lowercase letter\n- Contains at least one uppercase letter\n- Contains at least one digit\n- Contains at least one special character",... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import string\nimport secrets\n\ndef generate_password(length):\n \"\"\"\n Generates a random password that meets the following criteria:\n - At least 8 characters long\n - Contain... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019305",
"row_id": 19305,
"seed_ids": "['Llama-3.3-70B-Instruct_48766']"
} | 0.661542 | Filter_19305 | I | [
"generate_password",
"password_strength"
] | 2 | [
[
"generate_password",
"password_strength"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a4f7925d4ca586d320fad00cf44cfc73c0192ac | 3d3d22c82f1025dae7792da608c060063e81e0fb | |||
v1.0 | instruct | Filter | Filter_19306_I | ### Write a complete Python code to create a simple RESTful API using Flask to convert Fahrenheit to Celsius and vice versa | from flask import Flask, request, jsonify
app = Flask(__name__)
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5.0/9.0
def celsius_to_fahrenheit(celsius):
return (celsius * 9.0/5.0) + 32
@app.route('/convert', methods=['GET'])
def convert_temperature():
temp_type = request.args.get('t... | import pytest
from solution import fahrenheit_to_celsius, celsius_to_fahrenheit, app
def test_fahrenheit_to_celsius():
assert fahrenheit_to_celsius(32) == 0
assert fahrenheit_to_celsius(212) == 100
assert fahrenheit_to_celsius(98.6) == pytest.approx(37, 0.1)
def test_celsius_to_fahrenheit():
assert ce... | [
{
"docstring": null,
"function_declaration": "def fahrenheit_to_celsius(fahrenheit):",
"function_name": "fahrenheit_to_celsius",
"parameter_list": "(fahrenheit)"
},
{
"docstring": null,
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahren... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\ndef fahrenheit_to_celsius(fahrenheit):\n return (fahrenheit - 32) * 5.0/9.0\n\ndef celsius_to_fahrenheit(celsius):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019306",
"row_id": 19306,
"seed_ids": "['Llama-3.3-70B-Instruct_48768']"
} | 0.539206 | Filter_19306 | I | [
"fahrenheit_to_celsius",
"celsius_to_fahrenheit",
"convert_temperature"
] | 3 | [
[
"convert_temperature",
"celsius_to_fahrenheit"
],
[
"convert_temperature",
"fahrenheit_to_celsius"
]
] | 2 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 8551f5b680b500107e2a941fd7c1c6743b9a7ea2 | 08d381522751375b2554657fbb5f5d0bf93bfab7 | |||
v1.0 | instruct | Filter | Filter_19310_I | I have a list of addresses and phone numbers. I need to send emails to a set of selected ones. How can I automate this task using Python? | import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
def send_email(to_address, subject, message_body, from_address, from_name, smtp_server, smtp_port, login, password):
"""
Sends an email using the provided SMTP server and creden... | from solution import send_email, send_bulk_emails
import pytest
def test_send_email(monkeypatch):
class MockSMTP:
def __init__(self, smtp_server, smtp_port):
self.server = smtp_server
self.port = smtp_port
self.logged_in = False
def starttls(self):
p... | [
{
"docstring": "Sends an email using the provided SMTP server and credentials.\n\nParameters:\n to_address (str): Recipient's email address.\n subject (str): Subject of the email.\n message_body (str): Body of the email.\n from_address (str): Sender's email address.\n from_name (str): Sender's na... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef send_email(subject, body, to_email, from_email, smtp_server, smtp_port, login, passw... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019310",
"row_id": 19310,
"seed_ids": "['Llama-3.3-70B-Instruct_48774']"
} | 0.451264 | Filter_19310 | I | [
"send_email",
"send_bulk_emails"
] | 2 | [
[
"send_bulk_emails",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f1d6f2f502262d99788133db688c04c445a0638 | a365551ae46b31687452943cc804d70ce2cf109b | |||
v1.0 | instruct | Filter | Filter_19315_I | ### User Instructions
After creating the Command Line Interface (CLI) for the quiz, you will need to add more features to make the question easier or harder based on the user's performance. Here are some details to implement this functionality:
- Each question will have a difficulty level assigned to it (easy, medium, ... | import json
# Define the quiz data
quiz_data = {
"easy": [
{"question": "What is the capital of France?", "answer": "Paris"},
{"question": "What is 2 + 2?", "answer": "4"}
],
"medium": [
{"question": "What is the largest planet in our Solar System?", "answer": "Jupiter"},
{"... | import pytest
from solution import get_question, update_difficulty, check_answer
def test_get_question():
assert 'question' in get_question('easy')
assert 'question' in get_question('medium')
assert 'question' in get_question('hard')
def test_update_difficulty():
assert update_difficulty('easy', True)... | [
{
"docstring": "Fetch a question based on the given difficulty level.",
"function_declaration": "def get_question(difficulty):",
"function_name": "get_question",
"parameter_list": "(difficulty)"
},
{
"docstring": "Update the difficulty level based on the correctness of the user answer.",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\n# Define the quiz data\nquiz_data = {\n \"easy\": [\n {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n {\"question\": \"What is 2+2?... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019315",
"row_id": 19315,
"seed_ids": "['Llama-3.3-70B-Instruct_48791']"
} | 0.397486 | Filter_19315 | I | [
"get_question",
"update_difficulty",
"check_answer",
"run_quiz"
] | 4 | [
[
"run_quiz",
"check_answer"
],
[
"run_quiz",
"get_question"
],
[
"run_quiz",
"update_difficulty"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9d69cb08ca0d8f19d465e2090221e85a4aaf6327 | 0552793eb86c59aa82ef0a996966685c92420e06 | |||
v1.0 | instruct | Filter | Filter_19354_I | I've been trying to generate a Sudoku game in Python with the help of a backtracking algorithm, but my solution doesn't seem to be generating valid Sudoku puzzles. The rules for Sudoku are that each row and each column must contain each of the numbers 1-9 without repetition, and each 3x3 box must also contain each of t... | import random
def is_valid(board, row, col, num):
# Check the row
for x in range(9):
if board[row][x] == num:
return False
# Check the column
for x in range(9):
if board[x][col] == num:
return False
# Check the box
start_row, start_col = row - row % 3, ... | from solution import is_valid, generate_sudoku
def test_is_valid():
test_board = [[0] * 9 for _ in range(9)]
assert is_valid(test_board, 0, 0, 1) == True
test_board[0][0] = 1
assert is_valid(test_board, 0, 1, 1) == False
assert is_valid(test_board, 1, 0, 1) == False
assert is_valid(test_board, ... | [
{
"docstring": null,
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": null,
"function_declaration": "def generate_sudoku(board):",
"function_name": "generate_sudoku",
"paramete... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_valid(board, row, col, num):\n # Check the row\n for x in range(9):\n if board[row][x] == num:\n return False\n\n # Check the column\n for... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019354",
"row_id": 19354,
"seed_ids": "['Llama-3.3-70B-Instruct_48902']"
} | 0.462879 | Filter_19354 | I | [
"is_valid",
"generate_sudoku",
"print_board"
] | 3 | [
[
"generate_sudoku",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf2deec3bb9e9f25fb7c6969ee49a23ce83dc220 | 76ef018335c6038a64d45b7f38b4f91ffd289364 | |||
v1.0 | instruct | Filter | Filter_19365_I | ### Hangman Game
# The goal of this program is to create a simple game of Hangman where the user can play and guess a word by suggesting letters.
# The word to be guessed should be chosen randomly from a predefined list of words.
# The user should have a limited number of attempts to guess the word.
# To implement thi... | import random
def select_random_word(words):
return random.choice(words)
def initialize_game_data(chosen_word):
unique_letters = set(chosen_word)
correct_guesses = set()
incorrect_guesses = set()
attempts = 6
return unique_letters, correct_guesses, incorrect_guesses, attempts
def display_curr... | import pytest
from unittest.mock import patch
from solution import (
select_random_word, initialize_game_data, display_current_state,
process_guess, check_win
)
# Mock data
mock_words = ['apple', 'banana', 'cherry']
def test_select_random_word():
assert select_random_word(mock_words) in mock_words
def t... | [
{
"docstring": null,
"function_declaration": "def select_random_word(words):",
"function_name": "select_random_word",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def initialize_game_data(chosen_word):",
"function_name": "initialize_game_data",
"pa... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef choose_random_word(words_list):\n \"\"\"\n Choose a random word from the given list of words.\n \n :param words_list: List of words to choose from.\n :retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019365",
"row_id": 19365,
"seed_ids": "['Llama-3.3-70B-Instruct_48930']"
} | 0.565349 | Filter_19365 | I | [
"select_random_word",
"initialize_game_data",
"display_current_state",
"process_guess",
"check_win",
"hangman_game"
] | 6 | [
[
"hangman_game",
"check_win"
],
[
"hangman_game",
"display_current_state"
],
[
"hangman_game",
"initialize_game_data"
],
[
"hangman_game",
"process_guess"
],
[
"hangman_game",
"select_random_word"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | f28e1bf938c07464ffa5eb10842c5ddca2ce0081 | f5db33bdde5eb507f95c4cdc63fce3e0e35bb81a | |||
v1.0 | instruct | Filter | Filter_19369_I | ### Task
Write a simple Python script that lets a user play against the computer in a game of Rock-Paper-Scissors.
At the beginning of the game, the user should be asked if they want to play against the computer or another player.
Then based on their choice, the game should continue accordingly.
```python
# Importin... | import random
# Defining the choices and their corresponding values
choices = ["rock", "paper", "scissors"]
# Defining a function to determine the winner
def determine_winner(player1_choice, player2_choice):
if player1_choice == player2_choice:
return "It's a tie!"
if player1_choice == "rock":
... | from solution import determine_winner, get_computer_choice
def test_determine_winner_tie():
assert determine_winner("rock", "rock") == "It's a tie!"
assert determine_winner("paper", "paper") == "It's a tie!"
assert determine_winner("scissors", "scissors") == "It's a tie!"
def test_determine_winner_player1... | [
{
"docstring": null,
"function_declaration": "def determine_winner(player1_choice, player2_choice):",
"function_name": "determine_winner",
"parameter_list": "(player1_choice, player2_choice)"
},
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Defining the choices and their corresponding values\nchoices = [\"rock\", \"paper\", \"scissors\"]\n\n# Defining a function to determine the winner\ndef determine_winner(pla... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019369",
"row_id": 19369,
"seed_ids": "['Llama-3.3-70B-Instruct_48951']"
} | 0.576234 | Filter_19369 | I | [
"determine_winner",
"get_computer_choice",
"get_user_choice",
"play_against_computer",
"play_against_player",
"main"
] | 6 | [
[
"play_against_computer",
"determine_winner"
],
[
"play_against_computer",
"get_computer_choice"
],
[
"play_against_computer",
"get_user_choice"
],
[
"play_against_player",
"determine_winner"
],
[
"play_against_player",
"get_user_choice"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | a4902a559748908dd26a1e8b224c2068bdde116f | f104c6fdffa2f67e2b56a135df7b6eb5383b2f57 | |||
v1.0 | instruct | Filter | Filter_19397_I | Here is the Python code to find the greatest common divisor (GCD) of two integers using the Euclidean algorithm:
```python
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
```
Using this function, write a code to find the GCD of three numbers.
Here are some test cases:
- gcd3(2, 4, 6) returns 2
-... | def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def gcd3(a, b, c):
# Check if inputs are valid
if not all(isinstance(x, int) and x >= 0 for x in [a, b, c]):
raise ValueError("All inputs must be non-negative integers.")
# Calculate GCD of three numbers
return gcd(gcd(a... | import pytest
from solution import gcd, gcd3
def test_gcd_positive_numbers():
assert gcd(48, 18) == 6
assert gcd(10, 15) == 5
def test_gcd_with_zero():
assert gcd(0, 5) == 5
assert gcd(5, 0) == 5
def test_gcd_same_numbers():
assert gcd(7, 7) == 7
def test_gcd3_basic_cases():
assert gcd3(2, 4... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def gcd3(a, b, c):",
"function_name": "gcd3",
"parameter_list": "(a, b, c)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm.\n \"\"\"\n while b != 0:\n a, b = b, a % b\n return a\n\ndef... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019397",
"row_id": 19397,
"seed_ids": "['Llama-3.3-70B-Instruct_49025']"
} | 0.766514 | Filter_19397 | I | [
"gcd",
"gcd3"
] | 2 | [
[
"gcd3",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 078f47c4507ebe68701154c6349aeae0e7f46ddd | e363bf7af5a76314fb9ccec881be8ab9f99802af | |||
v1.0 | instruct | Filter | Filter_19399_I | I have two lists of coordinates that I want to pair up based on distance. I'd like to implement this in Python.
Here are the details:
- List A has 10 elements and List B has 10 elements.
- The distance between a point in List A and a point in List B should be less than 5.
- The pair should be unique, i.e., a point in... | import math
from itertools import permutations
def calculate_distance(point1, point2):
"""
Returns the distance between two points.
"""
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def find_pairs(list_a, list_b):
"""
Returns the best pairs of points from two lists ... | import pytest
from solution import calculate_distance, find_pairs
def test_calculate_distance():
assert math.isclose(calculate_distance((0,0), (3,4)), 5)
def test_find_pairs():
list_a = [(0, 0), (10, 10), (1, 1), (4, 4), (10, 1),
(5, 5), (5, 5), (2, 2), (3, 3), (7, 7)]
list_b = [(0, 4), (3, ... | [
{
"docstring": "Returns the distance between two points.",
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Returns the best pairs of points from two lists based on the distance c... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom itertools import permutations\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Returns the distance between two points.\n \"\"\"\n return math.sqrt((point1[0... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019399",
"row_id": 19399,
"seed_ids": "['Llama-3.3-70B-Instruct_49030']"
} | 0.601167 | Filter_19399 | I | [
"calculate_distance",
"find_pairs"
] | 2 | [
[
"find_pairs",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed0caf778cf029aa176be7798ceb7fe8237fa715 | fb37d1be51b0301a0db46f0c3b9fd3616c747a8e | |||
v1.0 | instruct | Filter | Filter_19401_I | Here is the code I have, and I would like to ask for some help with implementing lazy loading.
```python
import heapq
from dataclasses import dataclass
from typing import Any
class DownloadError(Exception):
pass
@dataclass
class Endpoint:
def download(self) -> bytes:
# Simulate a network delay
... | import heapq
from dataclasses import dataclass
from typing import Any
class DownloadError(Exception):
pass
@dataclass
class Endpoint:
def download(self) -> bytes:
# Simulate a network delay
import time
time.sleep(1) # Sleep for 1 second
return b"Downloaded content"
def proces... | import pytest
from solution import Endpoint, download_all, download_all_lazy
def test_download_all():
endpoints = [Endpoint() for _ in range(3)]
results = download_all(endpoints)
assert results == [b"Downloaded content", b"Downloaded content", b"Downloaded content"]
def test_download_all_with_empty_list()... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom dataclasses import dataclass\nfrom typing import Any\n\nclass DownloadError(Exception):\n pass\n\n@dataclass\nclass Endpoint:\n def download(self) -> bytes:\n #... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019401",
"row_id": 19401,
"seed_ids": "['Llama-3.3-70B-Instruct_49035']"
} | 0.427528 | Filter_19401 | I | [
"process_endpoint",
"download_all",
"download_all_lazy"
] | 3 | [
[
"download_all",
"process_endpoint"
]
] | 1 | [] | false | [
"DownloadError",
"Endpoint"
] | true | pytest | true | [] | true | 0379081cab4e1288f8f8a84b91d8c16cbba8a436 | 12777ada5d9b1f9aeb97c1a0a5925449c754e67e | |||
v1.0 | instruct | Filter | Filter_19437_I | I'd like to write a script that finds the closest pair of points in an n-dimensional space. I've implemented a brute force algorithm in Python, and I've heard of a divide-and-conquer algorithm that has a better time complexity. Can you help me implement it? | import math
def euclidean_distance(point1, point2):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def closest_pair_recursive(points_sorted_by_axis, axis):
if len(points_sorted_by_axis) <= 3:
return brute_force(points_sorted_by_axis)
mid = len(points_sorted_by_axis) // 2
... | from solution import closest_pair
def test_closest_pair_1d():
points = [(0,), (1,), (2,), (3,)]
p1, p2, dist = closest_pair(points)
assert dist == 1.0
def test_closest_pair_2d():
points = [(0, 0), (1, 1), (2, 2), (3, 3)]
p1, p2, dist = closest_pair(points)
assert dist == math.sqrt(2)
def test... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def closest_pair_recursive(points_sorted_by_axis, axis):",
"function_na... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(point1, point2):\n \"\"\"\n Returns the Euclidean distance between two points in n-dimensional space.\n \"\"\"\n return math.sqrt(sum((x - y) ** 2 for x... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019437",
"row_id": 19437,
"seed_ids": "['Llama-3.3-70B-Instruct_49132']"
} | 0.56958 | Filter_19437 | I | [
"euclidean_distance",
"closest_pair_recursive",
"brute_force",
"closest_pair"
] | 4 | [
[
"brute_force",
"euclidean_distance"
],
[
"closest_pair",
"closest_pair_recursive"
],
[
"closest_pair_recursive",
"brute_force"
],
[
"closest_pair_recursive",
"euclidean_distance"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | be8259afc48b68a42302bfecb84e83dbcd16bb3a | 6ea08d7b3d9c14ca7458df4821ce853e3d29ce2b | |||
v1.0 | instruct | Filter | Filter_19453_I | I will provide a reference solution for the problem of finding the k-th smallest element in an unsorted array. I'd like to to explain the solution, provide a concise implementation in python and discuss potential improvements. | def partition(arr, left, right, pivot_index):
pivot_value = arr[pivot_index]
# Move pivot to end
arr[pivot_index], arr[right] = arr[right], arr[pivot_index]
store_index = left
for i in range(left, right):
if arr[i] < pivot_value:
arr[store_index], arr[i] = arr[i], arr[store_inde... | def test_find_kth_smallest_normal_cases():
assert find_kth_smallest([3, 2, 1, 5, 4], 1) == 1
assert find_kth_smallest([3, 2, 1, 5, 4], 2) == 2
assert find_kth_smallest([3, 2, 1, 5, 4], 3) == 3
assert find_kth_smallest([3, 2, 1, 5, 4], 4) == 4
assert find_kth_smallest([3, 2, 1, 5, 4], 5) == 5
def te... | [
{
"docstring": null,
"function_declaration": "def partition(arr, left, right, pivot_index):",
"function_name": "partition",
"parameter_list": "(arr, left, right, pivot_index)"
},
{
"docstring": null,
"function_declaration": "def quickselect(arr, left, right, k):",
"function_name": "q... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef quickselect(arr, k):\n \"\"\"\n Find the k-th smallest element in an unsorted array.\n \"\"\"\n if not 1 <= k <= len(arr):\n raise ValueError(\"k is out... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019453",
"row_id": 19453,
"seed_ids": "['Llama-3.3-70B-Instruct_49161']"
} | 0.592197 | Filter_19453 | I | [
"partition",
"quickselect",
"find_kth_smallest"
] | 3 | [
[
"find_kth_smallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | fc5a7d71b12d73bf2b2214fe24f916f0b38ccdd4 | 34bb48ef32797266d49bed4f7d9ae0c0ec37fdb2 | |||
v1.0 | instruct | Filter | Filter_19470_I | I've been given a new task at work that involves analyzing data from a document, but the document uses a mix of numbering systems, including Roman numerals, letters, and regular numbers. The document contains a lot of data and I need a way to quickly extract and convert all the numbers into a single, consistent format.... | import re
def roman_to_int(s):
"""
Converts a Roman numeral string to an integer.
"""
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev_value = 0
for char in reversed(s):
value = roman[char]
if value < prev_value:
total -= v... | from solution import roman_to_int, letter_to_int, extract_and_convert_numbers, read_and_convert_file
def test_roman_to_int():
assert roman_to_int('I') == 1
assert roman_to_int('IV') == 4
assert roman_to_int('X') == 10
assert roman_to_int('C') == 100
assert roman_to_int('MMXX') == 2020
def test_l... | [
{
"docstring": "Converts a Roman numeral string to an integer.",
"function_declaration": "def roman_to_int(s):",
"function_name": "roman_to_int",
"parameter_list": "(s)"
},
{
"docstring": "Converts a single letter to an integer (A=1, B=2, ..., Z=26).",
"function_declaration": "def letter... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef roman_to_int(s):\n roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n num = 0\n for i in range(len(s)):\n if i > 0 and roman[s[i]] > r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019470",
"row_id": 19470,
"seed_ids": "['Llama-3.3-70B-Instruct_49196']"
} | 0.522175 | Filter_19470 | I | [
"roman_to_int",
"letter_to_int",
"extract_and_convert_numbers",
"read_and_convert_file"
] | 4 | [
[
"extract_and_convert_numbers",
"letter_to_int"
],
[
"extract_and_convert_numbers",
"roman_to_int"
],
[
"read_and_convert_file",
"extract_and_convert_numbers"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5e401a745acd8ee4bc5e637eaa99b2dc1dc0eb2b | 3f8ab6b250ed34851144e990f5497d8e90ae2a6c | |||
v1.0 | instruct | Filter | Filter_19471_I | ### Overview of the Problem
We are tasked with writing a Python program that implements a roulette game. The game will ask the user to place a bet, spin the wheel, and then determine if the user has won or lost based on their bet.
### Roulette Game Rules
- The roulette wheel contains 38 pockets, numbered 0 to 37.
- Th... | import random
# Constants for the game
RED_NUMBERS = {1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36}
BLACK_NUMBERS = {2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35}
ALL_NUMBERS = set(range(38))
def get_user_bet():
"""Get the user's bet amount."""
while True:
tr... | import pytest
from unittest.mock import patch
from solution import (get_user_bet, get_bet_type, get_number_bet,
get_color_bet, spin_wheel, determine_color,
calculate_payout)
def test_get_user_bet():
with patch('builtins.input', return_value='100'):
assert get_u... | [
{
"docstring": "Get the user's bet amount.",
"function_declaration": "def get_user_bet():",
"function_name": "get_user_bet",
"parameter_list": "()"
},
{
"docstring": "Get the user's bet type (number or color).",
"function_declaration": "def get_bet_type():",
"function_name": "get_bet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Constants for the game\nRED_NUMBERS = {1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36}\nBLACK_NUMBERS = {2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 2... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019471",
"row_id": 19471,
"seed_ids": "['Llama-3.3-70B-Instruct_49198']"
} | 0.70079 | Filter_19471 | I | [
"get_user_bet",
"get_bet_type",
"get_number_bet",
"get_color_bet",
"spin_wheel",
"determine_color",
"calculate_payout",
"roulette_game"
] | 8 | [
[
"calculate_payout",
"determine_color"
],
[
"roulette_game",
"calculate_payout"
],
[
"roulette_game",
"determine_color"
],
[
"roulette_game",
"get_bet_type"
],
[
"roulette_game",
"get_color_bet"
],
[
"roulette_game",
"get_number_bet"
],
[
... | 8 | [] | false | [] | false | pytest | true | [] | true | 3f5630c6573b5fc02821f46ef5de4d9b87cbe854 | b6fa3ec0fa61377c3c4f8e69ea71afdcd61108ef | |||
v1.0 | instruct | Filter | Filter_19480_I | I have a list of URLs that I'd like to run a script on to extract the domain name and serial number (if it exists) from the URL path.
For example, given the URLs:
```
https://www.example.com/path/to/resource/12345
https://subdomain.example.com-other/path/to/resource/67890
https://example.io/path/to/resource/
https://... | import re
from urllib.parse import urlparse
def extract_domain_and_serial(url):
"""
Extracts the domain name and serial number (if it exists) from the URL path.
Args:
url (str): The URL to extract information from.
Returns:
dict: A dictionary with keys 'domain' and 'serial_number'.
... | from solution import extract_domain_and_serial, process_urls
def test_extract_domain_and_serial_with_serial_number():
assert extract_domain_and_serial("https://www.example.com/path/to/resource/12345") == {
'domain': 'www.example.com',
'serial_number': '12345'
}
def test_extract_domain_and_ser... | [
{
"docstring": "Extracts the domain name and serial number (if it exists) from the URL path.\n\nArgs:\nurl (str): The URL to extract information from.\n\nReturns:\ndict: A dictionary with keys 'domain' and 'serial_number'.",
"function_declaration": "def extract_domain_and_serial(url):",
"function_name":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom urllib.parse import urlparse\n\ndef extract_info(url):\n \"\"\"\n Extracts the domain and serial number from the given URL.\n\n Parameters:\n url (str): The URL to ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019480",
"row_id": 19480,
"seed_ids": "['Llama-3.3-70B-Instruct_49221']"
} | 0.576857 | Filter_19480 | I | [
"extract_domain_and_serial",
"process_urls"
] | 2 | [
[
"process_urls",
"extract_domain_and_serial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 63c9c5b263f7c4549143fb7a47c8aac1552b808e | 59ff4792b89415109c812ad646bc8762d8a1e25e | |||
v1.0 | instruct | Filter | Filter_19482_I | You've been tasked with creating a function `create_largest_number` that takes an array of integers as input and returns the largest number that can be formed by concatenating the integers in the array. The integers can be concatenated in any order. | from functools import cmp_to_key
def compare(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
def create_largest_number(nums):
"""
Given a list of non-negative integers nums, arrange them such that they form the largest number.
"""
nums... | from solution import create_largest_number
def test_single_digit_numbers():
assert create_largest_number([3, 1, 4, 1, 5, 9]) == "954311"
def test_double_digit_numbers():
assert create_largest_number([10, 2]) == "210"
assert create_largest_number([20, 1]) == "201"
assert create_largest_number([9, 91, 9... | [
{
"docstring": null,
"function_declaration": "def compare(x, y):",
"function_name": "compare",
"parameter_list": "(x, y)"
},
{
"docstring": "Given a list of non-negative integers nums, arrange them such that they form the largest number.",
"function_declaration": "def create_largest_numb... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import cmp_to_key\n\ndef create_largest_number(nums):\n \"\"\"\n Returns the largest number that can be formed by concatenating\n the integers in the array.\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019482",
"row_id": 19482,
"seed_ids": "['Llama-3.3-70B-Instruct_49223']"
} | 0.717062 | Filter_19482 | I | [
"compare",
"create_largest_number"
] | 2 | [
[
"create_largest_number",
"compare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30d24696fcc9551ad61f3783cbbe38ef95151011 | 6620c9634f57a1976029b55eb0bc9b8a2462b0f1 | |||
v1.0 | instruct | Filter | Filter_19526_I | Here is a Python list of functions:
```python
def greet(name: str) -> str:
"""Return personalized greeting message."""
return f"Hello, {name}!"
def get_age() -> int:
"""Return the user's age."""
return 30
def get_phone_number() -> str:
"""Return the user's phone number."""
return "123-456-7890... | def greet(name: str) -> str:
"""Return personalized greeting message."""
return f"Hello, {name}!"
def get_age() -> int:
"""Return the user's age."""
return 30
def get_phone_number() -> str:
"""Return the user's phone number."""
return "123-456-7890"
def get_address() -> str:
"""Return the... | from solution import greet, get_age, get_phone_number, get_address, get_job, create_user
def test_greet():
assert greet("Alice") == "Hello, Alice!"
assert greet("Bob") == "Hello, Bob!"
def test_get_age():
assert get_age() == 30
def test_get_phone_number():
assert get_phone_number() == "123-456-7890"
... | [
{
"docstring": "Return personalized greeting message.",
"function_declaration": "def greet(name):",
"function_name": "greet",
"parameter_list": "(name)"
},
{
"docstring": "Return the user's age.",
"function_declaration": "def get_age():",
"function_name": "get_age",
"parameter_li... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greet(name: str) -> str:\n \"\"\"Return personalized greeting message.\"\"\"\n return f\"Hello, {name}!\"\n\ndef get_age() -> int:\n \"\"\"Return the user's age.\"\"\"\n return... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019526",
"row_id": 19526,
"seed_ids": "['Llama-3.3-70B-Instruct_49308']"
} | 0.640328 | Filter_19526 | I | [
"greet",
"get_age",
"get_phone_number",
"get_address",
"get_job",
"create_user"
] | 6 | [
[
"create_user",
"get_address"
],
[
"create_user",
"get_age"
],
[
"create_user",
"get_job"
],
[
"create_user",
"get_phone_number"
],
[
"create_user",
"greet"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 23a817ee3dc2043b988be6b4b02d9ac666b26da4 | 96e874eb8991a615c7934687d98e3a2bd5c3f20e | |||
v1.0 | instruct | Filter | Filter_19531_I | ### Question 1
Two-minute papers are often used at the end of classes to gauge student understanding. You want to sample a random subset of your students to determine their understanding of the course material. You have ten sections of a course, and each section has 30 students. Write a Python code snippet to generate ... | # Import necessary python modules
import random
# Define and initialize variables before they are used in the code
total_sections = 10
students_per_section = 30
# Calculate total number of students
total_students = total_sections * students_per_section
# Generate a list of student ids
student_ids = list(range(1, tot... | from solution import generate_student_sample, new_random_sample
def test_generate_student_sample_size():
sample = generate_student_sample(50)
assert len(sample) == 50
def test_generate_student_sample_uniqueness():
sample = generate_student_sample(50)
assert len(sample) == len(set(sample)), "Sample con... | [
{
"docstring": "Generates a random sample of student IDs.\n\nArgs:\nsample_size (int): The number of student IDs to sample.\n\nReturns:\nlist: A random sample of student IDs.",
"function_declaration": "def generate_student_sample(sample_size=50):",
"function_name": "generate_student_sample",
"parame... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_sample(total_sections, students_per_section, sample_size):\n \"\"\"\n Generate a random sample of student IDs.\n \n Parameters:\n total_sect... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019531",
"row_id": 19531,
"seed_ids": "['Llama-3.3-70B-Instruct_49317']"
} | 0.533032 | Filter_19531 | I | [
"generate_student_sample",
"new_random_sample"
] | 2 | [
[
"new_random_sample",
"generate_student_sample"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97c82d5a602c57f29db8d244e3329504cb7063c6 | 94862dfd181d477fa0de9c39d8fb5dcddb7b5d83 | |||
v1.0 | instruct | Filter | Filter_19590_I | I wrote a Python program to generate passwords. It takes a string as an input and produces a password with the same length as the number of characters in the string. The password will consist of letters from 'a' to 'z' and digits from 0 to 9.
My program, however, does not account for non-alphanumeric characters in a ... | import random
import string
def password_generator(length):
all_characters = string.ascii_lowercase + string.digits
return ''.join(random.choice(all_characters) for _ in range(length))
def password_from_string(input_string):
filtered_string = ''.join(char for char in input_string if char.isalnum())
le... | from solution import password_generator, password_from_string
def test_password_length():
assert len(password_from_string("example")) == len("example")
def test_password_with_non_alphanumeric():
input_string = "ex@mple!"
assert len(password_from_string(input_string)) == len("exmple")
def test_password_wi... | [
{
"docstring": null,
"function_declaration": "def password_generator(length):",
"function_name": "password_generator",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def password_from_string(input_string):",
"function_name": "password_from_string",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef password_generator(length):\n all_characters = string.ascii_lowercase + string.digits\n return ''.join(random.choice(all_characters) for _ in range(le... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019590",
"row_id": 19590,
"seed_ids": "['Llama-3.3-70B-Instruct_49445']"
} | 0.625609 | Filter_19590 | I | [
"password_generator",
"password_from_string"
] | 2 | [
[
"password_from_string",
"password_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e9f7a3011dc4f7dde0995e6531a73060bee39abd | 26d9768acd4d06c0223c2fab1124a2d3d074bd7f | |||
v1.0 | instruct | Filter | Filter_19615_I | Assume that we have a binary tree node:
```python
class Node:
def __init__(self, value):
self.val = value
self.right = None
self.left = None
```
And let's say we have a function that currently deletes a node from the tree. This function takes in the root node of the tree, the node that we wa... | class Node:
def __init__(self, value):
self.val = value
self.right = None
self.left = None
def delete_node(root, key):
"""
Deletes a node with the given key from the binary search tree rooted at 'root'.
"""
if not root:
return root
if key < root.val:
roo... | import pytest
from solution import Node, delete_node
def get_tree_values_inorder(root):
"""
Helper function to get the values of the tree in inorder traversal.
"""
if not root:
return []
return get_tree_values_inorder(root.left) + [root.val] + get_tree_values_inorder(root.right)
def test_d... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value):\n self.val = value\n self.right = None\n self.left = None\n\ndef delete_node(root, key):\n \"\"\"\n Deletes a node with t... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019615",
"row_id": 19615,
"seed_ids": "['Llama-3.3-70B-Instruct_49500']"
} | 0.510074 | Filter_19615 | I | [
"delete_node",
"get_min_value_node"
] | 2 | [
[
"delete_node",
"get_min_value_node"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 400932fc97440fda45cdce50d5a7fac2b9772b3c | 5dd6ed25c1ea5870212c13bb3aa9cc15c58183ef | |||
v1.0 | instruct | Filter | Filter_19635_I | I have a list of Python class instances and I want to use map() with a lambda function to call a method of each instance. However, the method to be called has parameters that also depend on the instance. How can I do this? | def method_with_parameters(instance):
"""
Calls a method on the instance where the parameters depend on the instance.
The instance method should be named 'method' and take parameters as instance variables.
"""
return instance.method(instance.param1, instance.param2)
def apply_method_with_map(instan... | class MockClass:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
def method(self, param1, param2):
return param1 + param2
def test_apply_method_with_map():
instance1 = MockClass(1, 2)
instance2 = MockClass(3, 4)
instances = [instance1, instance... | [
{
"docstring": "Calls a method on the instance where the parameters depend on the instance.\nThe instance method should be named 'method' and take parameters as instance variables.",
"function_declaration": "def method_with_parameters(instance):",
"function_name": "method_with_parameters",
"paramete... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def call_instance_method_with_params(instances, method_name):\n \"\"\"\n Calls the specified method with parameters that depend on each instance.\n \n :param instances: A list of c... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019635",
"row_id": 19635,
"seed_ids": "['Llama-3.3-70B-Instruct_49555']"
} | 0.452651 | Filter_19635 | I | [
"method_with_parameters",
"apply_method_with_map"
] | 2 | [
[
"apply_method_with_map",
"method_with_parameters"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | e9b9065544b3bdd347a64f85cbfac26e5d3a0777 | 1b4b7ea8e0e9019e61d970cad5ee87af4aec748c | |||
v1.0 | instruct | Filter | Filter_19664_I | I have an array that I'm trying to sort using merge sort, but the implementation seems incorrect. The array I'm passing to the function is `[4, 2, 7, 1, 3, 9, 6, 8, 5]`. However, I am getting an incorrect output which is `[1, 2, 4, 6, 7, 9]`. The numbers 3, 5, 8 are missing from the output.
Here is my code:
```python... | def merge_sort(arr):
# if the array has one or 0 elements, it's already sorted
if len(arr) <= 1:
return arr
mid = len(arr) // 2
# divide into two halves
left_half = arr[:mid]
right_half = arr[mid:] # Corrected the bug here
print("left_half:", left_half)
print("right_half:", r... | from solution import merge_sort
def test_sort():
assert merge_sort([4, 2, 7, 1, 3, 9, 6, 8, 5]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_empty_array():
assert merge_sort([]) == []
def test_single_element():
assert merge_sort([4]) == [4]
def test_sorted_array():
assert merge_sort([1, 2, 3, 4, 5, 6, 7,... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n # if the array has one or 0 elements, it's already sorted\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n\n # divide into two halves\n l... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019664",
"row_id": 19664,
"seed_ids": "['Llama-3.3-70B-Instruct_49629']"
} | 0.595914 | Filter_19664 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d87341051770f4658c8462de4d8e72d281a63748 | 84c6d35ea5eafe48e2be2eb34dfc2222f6abaa78 | |||
v1.0 | instruct | Filter | Filter_19671_I | Here is the Python code that Dijkstra's algorithm:
```python
import heapq
def dijkstra(graph, start):
queue = []
heapq.heappush(queue, (0, start))
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
while queue:
current_distance, current_node = heapq.heappop(qu... | import heapq
def has_negative_weight(graph):
"""
Check for presence of negative weight edges in the graph.
"""
for node in graph:
for neighbor in graph[node]:
if graph[node][neighbor] < 0:
return True
return False
def dijkstra(graph, start):
"""
Implemen... | import pytest
from solution import dijkstra, has_negative_weight
def test_dijkstra_positive_weights():
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
start = 'A'
assert dijkstra(graph, start) == {'A'... | [
{
"docstring": "Check for presence of negative weight edges in the graph.",
"function_declaration": "def has_negative_weight(graph):",
"function_name": "has_negative_weight",
"parameter_list": "(graph)"
},
{
"docstring": "Implementation of Dijkstra's algorithm for finding the shortest path.\... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(graph, start):\n \"\"\"\n Implementation of Dijkstra's algorithm for finding the shortest path.\n\n Args:\n graph (dict): A di... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019671",
"row_id": 19671,
"seed_ids": "['Llama-3.3-70B-Instruct_49650']"
} | 0.481505 | Filter_19671 | I | [
"has_negative_weight",
"dijkstra"
] | 2 | [
[
"dijkstra",
"has_negative_weight"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 22e620348cc9d1ec8815154a0e5b8e018ac9f5f2 | 92fb6d368c200babe96e2d74736d9fdf037569e2 | |||
v1.0 | instruct | Filter | Filter_19674_I | Based on the following Python code for a Hangman game, add features that require the user to play the game twice, and if they lose both times, the player is "executed" and the program terminates. | import random
def choose_word():
words = ['python', 'programming', 'hangman', 'challenge']
return random.choice(words)
def display_current_state(word, correct_guesses):
display = ''.join([letter if letter in correct_guesses else '_' for letter in word])
return display
def hangman_game():
word = c... | import pytest
from unittest.mock import patch, MagicMock
from io import StringIO
from solution import hangman_game, play_hangman
@pytest.fixture
def word_mock():
with patch('solution.choose_word', return_value='python'):
yield
def test_hangman_game_win(word_mock):
with patch('builtins.input', side_eff... | [
{
"docstring": null,
"function_declaration": "def choose_word():",
"function_name": "choose_word",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def display_current_state(word, correct_guesses):",
"function_name": "display_current_state",
"parameter_list... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_random_word(word_list):\n \"\"\"\n Get a random word from the given list of words.\n \"\"\"\n return random.choice(word_list)\n\ndef display_progress(word,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019674",
"row_id": 19674,
"seed_ids": "['Llama-3.3-70B-Instruct_49659']"
} | 0.433749 | Filter_19674 | I | [
"choose_word",
"display_current_state",
"hangman_game",
"play_hangman"
] | 4 | [
[
"hangman_game",
"choose_word"
],
[
"hangman_game",
"display_current_state"
],
[
"play_hangman",
"hangman_game"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 41780faf141f56352012697add0f7b3f9b893ac4 | 0f9778e1c3110cda4104aa1beb1fbc429ae58f12 | |||
v1.0 | instruct | Filter | Filter_19702_I | I have an algorithm that colors a matrix of nodes using Redis Pub/Sub. For each node in the matrix, the algorithm picks a color from a predefined list of colors. The algorithm has to ensure that no two adjacent nodes share the same color. | def is_safe(matrix, node, color, colors):
"""
Check if the current color assignment is safe for the node.
"""
# Check left neighbor
if node[1] > 0 and colors[node[0]][node[1] - 1] == color:
return False
# Check right neighbor
if node[1] < len(matrix[0]) - 1 and colors[node[0]][node[1... | from solution import color_matrix
def test_color_matrix_2x2():
matrix = [
[1, 1],
[1, 1]
]
color_list = [1, 2]
result = color_matrix(matrix, color_list)
assert result == [
[1, 2],
[2, 1]
] or result == [
[2, 1],
[1, 2]
]
def test_color_m... | [
{
"docstring": "Check if the current color assignment is safe for the node.",
"function_declaration": "def is_safe(matrix, node, color, colors):",
"function_name": "is_safe",
"parameter_list": "(matrix, node, color, colors)"
},
{
"docstring": "Solve the node coloring problem using backtracki... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_safe(node, color, matrix, colors, colored_nodes):\n n = len(matrix)\n for i in range(n):\n if matrix[node][i] == 1 and colored_nodes[i] == color:\n return False\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019702",
"row_id": 19702,
"seed_ids": "['Llama-3.3-70B-Instruct_49724']"
} | 0.549927 | Filter_19702 | I | [
"is_safe",
"solve_coloring",
"color_matrix"
] | 3 | [
[
"color_matrix",
"solve_coloring"
],
[
"solve_coloring",
"is_safe"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 08744ad4e7926b15d2efdf0ce80221da3fb7dde2 | da6611c35d2c73e37266d8ca1cf1ae4a6284b166 | |||
v1.0 | instruct | Filter | Filter_19708_I | Here is a mathematical concept I'd like you to implement: the Rock, Paper, Scissors game. Create a code that allows a user to play against the computer.
Here's a general outline of the steps I'd like the code to follow:
1. Ask the user for their name.
2. Generate a random choice (rock, paper, or scissors) for the c... | import random
def get_computer_choice():
"""Generate a random choice for the computer."""
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def get_user_choice(user_input):
"""Ask the user for their choice."""
user_choice = user_input.lower()
if user_choice in ['rock', 'pap... | from solution import get_computer_choice, get_user_choice, determine_winner
import pytest
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
assert get_computer_choice() in choices
def test_get_user_choice_valid():
assert get_user_choice('rock') == 'rock'
assert get_user_choice('p... | [
{
"docstring": "Generate a random choice for the computer.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Ask the user for their choice.",
"function_declaration": "def get_user_choice(user_input):"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_choice():\n \"\"\"Generate a random choice for the computer.\"\"\"\n choices = ['rock', 'paper', 'scissors']\n return random.choice(choices)\n\ndef g... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019708",
"row_id": 19708,
"seed_ids": "['Llama-3.3-70B-Instruct_49736']"
} | 0.57046 | Filter_19708 | I | [
"get_computer_choice",
"get_user_choice",
"determine_winner",
"play_game"
] | 4 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"get_computer_choice"
],
[
"play_game",
"get_user_choice"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7001d06178a6d05ca961dfb542daef44465bc0a6 | 316fa90295f91ab713c52436ea8641cd4d3b3df9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.