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_6188_I | I have been working on building a simple neural network from scratch. I'm interested in using gradient descent to update the weights and biases of my network, however I'm having some trouble understanding how to actually implement the gradient descent algorithm with respect to my network's parameters.
Could you provi... | import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(z):
return sigmoid(z) * (1 - sigmoid(z))
def compute_cost(Y, A):
m = Y.shape[1]
cost = -1/m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
return np.squeeze(cost)
class SimpleNeuralNetwork:
def __init__(... | from solution import SimpleNeuralNetwork
import numpy as np
def test_initialization_shapes():
nn = SimpleNeuralNetwork(input_size=2, hidden_size=3, output_size=1)
assert nn.W1.shape == (3, 2)
assert nn.b1.shape == (3, 1)
assert nn.W2.shape == (1, 3)
assert nn.b2.shape == (1, 1)
def test_forward_pr... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_parameters(layer_dims):\n \"\"\"\n Initialize the parameters of the neural network.\n \n Arguments:\n layer_dims -- python array (list) cont... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006188",
"row_id": 6188,
"seed_ids": "['Llama-3.3-70B-Instruct_18336']"
} | 0.272108 | Filter_6188 | I | [
"sigmoid",
"sigmoid_derivative",
"compute_cost"
] | 3 | [
[
"sigmoid_derivative",
"sigmoid"
]
] | 1 | [] | false | [
"SimpleNeuralNetwork"
] | true | pytest | true | [
"numpy"
] | false | ffcbaf52bfa48a641c16555325c39557964e0e14 | 3d1713572430f6143cd969a8c862d46a20cbd806 | |||
v1.0 | instruct | Filter | Filter_6210_I | I would like to create a game in Python where the player can play as either a human or a robot. If the player selects "human", they will be asked to input their name. If they select "robot", they will be given a random robot name. I would like to create a dictionary to store the player's information, including their na... | import random
ROBOT_NAMES = ['R2D2', 'C3PO', 'BB8', 'Wall-E', 'Terminator']
def get_player_name(character_type):
"""
Get the player's name based on their selected character type.
Args:
character_type (str): The type of character ('human' or 'robot').
Returns:
str: The player's name.
... | import pytest
from solution import create_player, get_player_name
def test_get_player_name_human(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: "John Doe")
assert get_player_name('human') == "John Doe"
def test_get_player_name_robot(monkeypatch):
monkeypatch.setattr(random, 'choice', lambda... | [
{
"docstring": "Get the player's name based on their selected character type.\n\nArgs:\ncharacter_type (str): The type of character ('human' or 'robot').\n\nReturns:\nstr: The player's name.",
"function_declaration": "def get_player_name(character_type):",
"function_name": "get_player_name",
"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 get_player_info(character_type, player_name=None):\n \"\"\"\n Returns a dictionary containing the player's character type and name.\n \n If character_type is '... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006210",
"row_id": 6210,
"seed_ids": "['Llama-3.3-70B-Instruct_18395']"
} | 0.508188 | Filter_6210 | I | [
"get_player_name",
"create_player"
] | 2 | [
[
"create_player",
"get_player_name"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a55f6d9c74320cc964de4cd51534d78768f45269 | d36aa4711fc3122fb4cbead38bb2f1100dd00140 | |||
v1.0 | instruct | Filter | Filter_6214_I | Here is a rough outline for a program to find the closest pair of points in a set of points in n-dimensional space.
- Take in a list of points where each point is a list of n coordinates
- Find the closest pair of points
- Output the closest pair and the distance between them
Here is the main function:
```python
def... | import numpy as np
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in n-dimensional space.
"""
return np.linalg.norm(np.array(point1) - np.array(point2))
def closest_pair(points):
"""
Find the closest pair of points and the distance between them.... | from solution import closest_pair
def test_closest_pair_3d():
points = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
closest, distance = closest_pair(points)
assert closest == ([1.0, 2.0, 3.0], [4.0, 5.0, 6.0])
assert np.isclose(distance, 5.196152422706632)
def test_closest_pair_2d():
points... | [
{
"docstring": "Calculate the Euclidean distance between two points in n-dimensional space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the closest pair of points and ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points in n-dimensional space.\n \"\"\"\n return np.linalg.nor... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006214",
"row_id": 6214,
"seed_ids": "['Llama-3.3-70B-Instruct_18405']"
} | 0.653584 | Filter_6214 | I | [
"euclidean_distance",
"closest_pair"
] | 2 | [
[
"closest_pair",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 985fb9ef72b5eb93f573f2a0c23f18a93a80ca17 | 3822aa20751460c1d0f3c410904fdd3b8739eb39 | |||
v1.0 | instruct | Filter | Filter_6235_I | I want to create a simple game where the user has to find a word hidden in a grid of letters. The game will have the following features:
* The grid will be 10x10
* The word can be placed horizontally, vertically, or diagonally in the grid
* The user will be given a hint about the word
* The user will have a limited num... | import random
grid = []
word = "test"
hint = "A common word"
max_attempts = 10
attempts = 0
# Initialize the grid with random letters
for i in range(10):
row = [chr(random.randint(97, 122)) for _ in range(10)]
grid.append(row)
# Function to print the grid
def print_grid():
for row in grid:
print(... | import pytest
from solution import check_word, grid, word
def test_check_word_horizontal():
# Place the word horizontally at (0,0)
for i in range(len(word)):
grid[0][i] = word[i]
assert check_word(0, 0, 0, 1, word) == True
assert check_word(0, 0, 0, 1, "wrong") == False
def test_check_word_ver... | [
{
"docstring": null,
"function_declaration": "def print_grid():",
"function_name": "print_grid",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def place_word_in_grid():",
"function_name": "place_word_in_grid",
"parameter_list": "()"
},
{
"docstri... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ngrid = []\nword = \"test\"\nhint = \"A common word\"\nmax_attempts = 10\nattempts = 0\n\n# Initialize the grid with random letters\nfor i in range(10):\n row = [chr(random.... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006235",
"row_id": 6235,
"seed_ids": "['Llama-3.3-70B-Instruct_18466']"
} | 0.533623 | Filter_6235 | I | [
"print_grid",
"place_word_in_grid",
"check_word",
"find_word"
] | 4 | [
[
"find_word",
"check_word"
],
[
"find_word",
"print_grid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7f774e987034a92d12f47fa479c87213565932ba | 9e59f92b5a0860bf6f9985e60cff3a0b97b21570 | |||
v1.0 | instruct | Filter | Filter_6249_I | I need a solution for a specific use case: I have to display a countdown timer that counts down from a specific time.
Here is an example:
Input: 02:15:00
Output: 02:14:59, 02:14:58, 02:14:57, ...
And it stops when it reaches 00:00:00.
Here is my attempt at a solution in Python:
```python
import time
def countdo... | import time
def countdown(t):
"""
Display a countdown timer from t seconds to 0.
Parameters:
- t (int): The total number of seconds for countdown.
"""
while t:
hrs, mins = divmod(t, 3600)
mins, secs = divmod(mins, 60)
print(f'{hrs:02}:{mins:02}:{secs:02}', end='\r')
... | from solution import countdown, countdown_from_string
import time
# monkey patch sleep to avoid waiting in tests
def mock_sleep(seconds):
time.sleep = lambda x: None
def test_countdown():
# Mocking the print function to capture prints
import builtins
original_print = builtins.print
printed_strings... | [
{
"docstring": "Display a countdown timer from t seconds to 0.\n\nParameters:\n- t (int): The total number of seconds for countdown.",
"function_declaration": "def countdown(t):",
"function_name": "countdown",
"parameter_list": "(t)"
},
{
"docstring": "Convert a time string in the format HH:... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom datetime import timedelta\n\ndef countdown(time_str):\n hours, minutes, seconds = map(int, time_str.split(':'))\n total_seconds = hours * 3600 + minutes * 60 + seconds\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006249",
"row_id": 6249,
"seed_ids": "['Llama-3.3-70B-Instruct_18486']"
} | 0.482248 | Filter_6249 | I | [
"countdown",
"countdown_from_string"
] | 2 | [
[
"countdown_from_string",
"countdown"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40e38859fc1cf8c2460c94ada151cbb34bd62ec8 | cd172d15e125ca4bd31a7a65e1a992a269b415ed | |||
v1.0 | instruct | Filter | Filter_6278_I | Here is the code for an open-source programming project:
```python
import numpy as np
def calculate(x, y):
result = x + y
return result
```
I want to add a new feature to the project. The feature should use the `calculate` function to perform some calculations, and then output the result in a human-readable fo... | import numpy as np
def calculate(x, y):
result = x + y
return result
def human_readable_calculate(x, y):
"""
Uses calculate function to add x and y and returns the result in a human-readable format.
Parameters:
x (int, float): The first number.
y (int, float): The second number.
... | from solution import calculate, human_readable_calculate
def test_calculate():
assert calculate(2, 3) == 5
assert calculate(0, 5) == 5
assert calculate(-1, -1) == -2
assert calculate(-1, 3) == 2
def test_human_readable_calculate():
assert human_readable_calculate(2, 3) == "The result of adding 2 a... | [
{
"docstring": null,
"function_declaration": "def calculate(x, y):",
"function_name": "calculate",
"parameter_list": "(x, y)"
},
{
"docstring": "Uses calculate function to add x and y and returns the result in a human-readable format.\n\nParameters:\nx (int, float): The first number.\ny (int... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def human_readable_calculate(x, y):\n \"\"\"\n Uses the `calculate` function to add x and y, then returns the result in a human-readable format.\n \"\"\"\n result = calculate(x, y)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006278",
"row_id": 6278,
"seed_ids": "['Llama-3.3-70B-Instruct_18555']"
} | 0.439489 | Filter_6278 | I | [
"calculate",
"human_readable_calculate"
] | 2 | [
[
"human_readable_calculate",
"calculate"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a41f23f65c5ef97ae99adb8c667ed125126b8cb5 | fe375e4f7449e9e63bbf4e9e378ba14236498921 | |||
v1.0 | instruct | Filter | Filter_6302_I | In this exercise, you will create a simple "Higher or Lower" card game. The game works as follows:
- The deck has 52 cards with 4 suits (hearts, diamonds, clubs and spades) and 13 values (Ace to King).
- The objective is to guess whether the next card drawn will be higher or lower in value than the current card.
- The... | import random
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __repr__(self):
return f"{self.value} of {self.suit}"
def get_value_index(self):
values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
... | from solution import Card, Deck, Player, check_guess
def test_card_initialization():
card = Card("Hearts", "Ace")
assert card.suit == "Hearts"
assert card.value == "Ace"
def test_card_representation():
card = Card("Hearts", "Ace")
assert repr(card) == "Ace of Hearts"
def test_card_value_index():
... | [] | [
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\nclass Card:\n def __init__(self, suit, value):\n self.suit = suit\n self.value = value\n\n def __repr__(self):\n return f\"{self.value} of {self.sui... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006302",
"row_id": 6302,
"seed_ids": "['Llama-3.3-70B-Instruct_18608']"
} | 0.585478 | Filter_6302 | I | [
"check_guess",
"play_game"
] | 2 | [
[
"play_game",
"check_guess"
]
] | 1 | [] | false | [
"Card",
"Deck",
"Player"
] | true | pytest | true | [] | true | 4e62cfdbc1576861ed5ea1cc019702da4e519957 | 30c2acb6ce7fee1f8dd2f8c5f931c000aa89e497 | |||
v1.0 | instruct | Filter | Filter_6312_I | I've got a large set of text data, and I'd like to create a simple web interface to explore the data. I'm thinking of using Flask, but I'm not sure where to start. Can you walk me through the process of building a basic Flask app?
### Expected Output
A simple web interface with two text boxes: one to input a search qu... | from flask import Flask, request, render_template_string
app = Flask(__name__)
# Sample text-based database
database = [
"Flask is a web framework.",
"Flask is simple and lightweight.",
"You can create web applications using Flask.",
"Exploring data with Flask can be easy."
]
# Basic search function
... | import pytest
from solution import search_database
def test_search_database_empty_query():
result = search_database("")
assert result == []
def test_search_database_no_results():
result = search_database("nonexistent")
assert result == []
def test_search_database_case_insensitive():
result = sear... | [
{
"docstring": null,
"function_declaration": "def search_database(query):",
"function_name": "search_database",
"parameter_list": "(query)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list": "()"
}
] | [
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, render_template_string\n\napp = Flask(__name__)\n\n# Sample text-based database\ndatabase = [\n \"Flask is a web framework.\",\n \"Flask is simple and l... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006312",
"row_id": 6312,
"seed_ids": "['Llama-3.3-70B-Instruct_18641']"
} | 0.419316 | Filter_6312 | I | [
"search_database",
"index"
] | 2 | [
[
"index",
"search_database"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | c5b0b0afe18637212406e776e40808487ee2a401 | b939498db4fefc3439fdf5b01624d20000be6ae1 | |||
v1.0 | instruct | Filter | Filter_6330_I | Create a functional program to find all possible combination of given array using backtracking
In this example, we will use array: [1, 2, 3]
For the above array, all possible combinations are
- 1
- 2
- 3
- 1, 2
- 1, 3
- 2, 3
- 1, 2, 3
Note: The above combinations are the power set of the given array
```python
def f... | def find_combinations(array):
"""
Returns all possible combinations of the given array using backtracking
"""
result = []
backtrack(result, [], array, 0)
return result
def backtrack(result, tempList, array, start):
result.append(tempList[:])
for i in range(start, len(array)):
te... | from solution import find_combinations
def test_find_combinations_empty_array():
assert find_combinations([]) == [[]]
def test_find_combinations_single_element_array():
assert find_combinations([1]) == [[], [1]]
def test_find_combinations_two_elements_array():
assert find_combinations([1, 2]) == [[], [1]... | [
{
"docstring": "Returns all possible combinations of the given array using backtracking",
"function_declaration": "def find_combinations(array):",
"function_name": "find_combinations",
"parameter_list": "(array)"
},
{
"docstring": null,
"function_declaration": "def backtrack(result, temp... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_combinations(array):\n result = []\n backtrack(result, [], array, 0)\n return result\n\ndef backtrack(result, tempList, nums, start):\n result.append(list(tempList)) # ma... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006330",
"row_id": 6330,
"seed_ids": "['Llama-3.3-70B-Instruct_18687']"
} | 0.649707 | Filter_6330 | I | [
"find_combinations",
"backtrack"
] | 2 | [
[
"find_combinations",
"backtrack"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fc96e8df00b940516eaef1d27cedc1d14ab5da17 | 7c82176b3de7eecff9b4359d6ecb54fb74876e7d | |||
v1.0 | instruct | Filter | Filter_6331_I | I have a list of integers in a file named "numbers.txt". Each integer is on a new line. I want to read this file, and for each integer, I want to check if it is a prime number. If it is a prime number, I want to write it to a new file named "prime_numbers.txt".
Can you provide me with a Python script that accomplishe... | def is_prime(number):
"""
Checks if a number is a prime number.
"""
if number <= 1:
return False
if number == 2:
return True
if number % 2 == 0:
return False
for i in range(3, int(number**0.5) + 1, 2):
if number % i == 0:
return False
return Tr... | import os
from solution import is_prime, write_prime_numbers
def test_is_prime():
# Testing prime numbers
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(11) == True
# Testing non-prime numbers
assert is_prime(1) == False
assert is_... | [
{
"docstring": "Checks if a number is a prime number.",
"function_declaration": "def is_prime(number):",
"function_name": "is_prime",
"parameter_list": "(number)"
},
{
"docstring": "Reads numbers from input_file, checks for prime numbers, and writes them to output_file.",
"function_decla... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(number):\n \"\"\"\n Checks if a number is a prime number.\n \"\"\"\n if number <= 1:\n return False\n if number == 2:\n return True\n if number % 2... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006331",
"row_id": 6331,
"seed_ids": "['Llama-3.3-70B-Instruct_18689']"
} | 0.569172 | Filter_6331 | I | [
"is_prime",
"write_prime_numbers"
] | 2 | [
[
"write_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee42bf826c38f1f83c0a1dd066b597f2f8d96bf9 | 0e88218fcdd3d19d6d4f927ababf248447f053f2 | |||
v1.0 | instruct | Filter | Filter_6347_I | I have a turtle graphics program and I need to help a turtle go from one random location to another random location. The turtle should move in a straight line.
Please provide the step by step process to accomplish this.
1. Generate two random points
2. Calculate the slope of the line connecting these two points
3.... | import turtle
import math
import random
def generate_random_point():
"""
Generates a random point within the screen coordinates.
Returns:
tuple: A tuple containing the (x, y) coordinates of the point.
"""
x = random.randint(-300, 300)
y = random.randint(-300, 300)
return (x, y)
def... | from solution import generate_random_point, calculate_slope, get_direction_and_distance
def test_generate_random_point():
x, y = generate_random_point()
assert -300 <= x <= 300
assert -300 <= y <= 300
def test_calculate_slope():
assert calculate_slope((0, 0), (1, 1)) == 1.0
assert calculate_slope(... | [
{
"docstring": "Generates a random point within the screen coordinates.\nReturns:\n tuple: A tuple containing the (x, y) coordinates of the point.",
"function_declaration": "def generate_random_point():",
"function_name": "generate_random_point",
"parameter_list": "()"
},
{
"docstring": "... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\nimport math\nimport random\n\ndef generate_random_point(x_range, y_range):\n \"\"\"\n Generate a random point within the specified x and y range.\n \"\"\"\n x = rand... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006347",
"row_id": 6347,
"seed_ids": "['Llama-3.3-70B-Instruct_18723']"
} | 0.607931 | Filter_6347 | I | [
"generate_random_point",
"calculate_slope",
"get_direction_and_distance",
"move_turtle",
"main"
] | 5 | [
[
"move_turtle",
"get_direction_and_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e31efb6fc91cb6fb3ea89f280fb93c358db21851 | 65e4c8d128fef4f274ad842440288cd6cccce4dd | |||
v1.0 | instruct | Filter | Filter_6353_I | ### The program is designed to be used to play a game of Charades.
### It should first prompt the user for the length of their acting time,
### then it should prompt the user to choose a category,
### then it should display a word from the chosen category,
### then it should start a countdown timer for the acting t... | import random
import time
# Define the categories and words
categories = {
"1": {"name": "Animals", "words": ["Lion", "Tiger", "Bear", "Wolf", "Elephant"]},
"2": {"name": "Countries", "words": ["USA", "Canada", "Mexico", "UK", "France"]},
"3": {"name": "Food", "words": ["Pizza", "Burger", "Tacos", "Sushi",... | def test_get_category_valid_input(monkeypatch):
from io import StringIO
monkeypatch.setattr('sys.stdin', StringIO('1\n'))
result = get_category()
assert result['name'] == 'Animals'
def test_get_category_invalid_then_valid_input(monkeypatch, capsys):
from io import StringIO
monkeypatch.setattr('... | [
{
"docstring": "Get the chosen category from the user",
"function_declaration": "def get_category():",
"function_name": "get_category",
"parameter_list": "()"
},
{
"docstring": "Get the acting time from the user",
"function_declaration": "def get_acting_time():",
"function_name": "ge... | [
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 time\n\n# Define the categories and words\ncategories = {\n \"1\": {\"name\": \"Animals\", \"words\": [\"Lion\", \"Tiger\", \"Bear\", \"Wolf\", \"Elephant\"]},\n \"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006353",
"row_id": 6353,
"seed_ids": "['Llama-3.3-70B-Instruct_18739']"
} | 0.584865 | Filter_6353 | I | [
"get_category",
"get_acting_time",
"play_round",
"main"
] | 4 | [
[
"play_round",
"get_acting_time"
],
[
"play_round",
"get_category"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 6bd7d0d07c59e96a5ae312ece46d1098a877532a | 58348413784252b758adb5abf416b3bf35ee8ff5 | |||
v1.0 | instruct | Filter | Filter_6360_I | ### Problem Statement
Create a simple chatbot that can understand basic commands and respond accordingly. The chatbot should be able to:
1. Greet the user
2. Tell the current time
3. Tell a joke
4. Provide information about itself
5. Exit the chat
### Code
```python
from datetime import datetime
def display_men... | from datetime import datetime
def display_menu():
"""Display the menu of available commands"""
return [
"Available commands:",
"1. Greet",
"2. Time",
"3. Joke",
"4. Info",
"5. Exit"
]
def greet(name):
"""Return a personalized greeting"""
return f"Hel... | from solution import display_menu, greet, get_current_time, tell_joke, get_info, exit_chat, chatbot
def test_display_menu():
result = display_menu()
assert "Available commands:" in result
assert "1. Greet" in result
assert "2. Time" in result
assert "3. Joke" in result
assert "4. Info" in resul... | [
{
"docstring": "Display the menu of available commands",
"function_declaration": "def display_menu():",
"function_name": "display_menu",
"parameter_list": "()"
},
{
"docstring": "Return a personalized greeting",
"function_declaration": "def greet(name):",
"function_name": "greet",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef display_menu():\n \"\"\"Display the menu of available commands\"\"\"\n return \"Available commands:\\n1. Greet\\n2. Time\\n3. Joke\\n4. Info\\n5. Exi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006360",
"row_id": 6360,
"seed_ids": "['Llama-3.3-70B-Instruct_18752']"
} | 0.4469 | Filter_6360 | I | [
"display_menu",
"greet",
"get_current_time",
"tell_joke",
"get_info",
"exit_chat",
"chatbot"
] | 7 | [
[
"chatbot",
"exit_chat"
],
[
"chatbot",
"get_current_time"
],
[
"chatbot",
"get_info"
],
[
"chatbot",
"greet"
],
[
"chatbot",
"tell_joke"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 8a69906bf582252ce3c6ea57fc91277c95a4221d | 2e7dd88cc81c4835837e740c0368807e315ac3f7 | |||
v1.0 | instruct | Filter | Filter_6374_I | ### Basic Python Problems
#### Problem 1: Basic Calculator
Create a basic calculator that can perform arithmetic operations like addition, subtraction, multiplication and division based on the users choice.
```python
# Sample Input:
# Enter your choice (1/2/3/4):
# 1
# Enter first number: 10
# Enter second number: 20
... | def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
if num2 == 0:
raise ValueError("Division by zero is not allowed")
return num1 / num2
def calculator(choice, num1, num2):
if choice... | from solution import add, subtract, multiply, divide, calculator
def test_add():
assert add(10, 20) == 30
assert add(-10, 5) == -5
assert add(10.5, 25.5) == 36
def test_subtract():
assert subtract(10, 20) == -10
assert subtract(20, 10) == 10
assert subtract(-10, -5) == -5
def test_multiply():... | [
{
"docstring": null,
"function_declaration": "def add(num1, num2):",
"function_name": "add",
"parameter_list": "(num1, num2)"
},
{
"docstring": null,
"function_declaration": "def subtract(num1, num2):",
"function_name": "subtract",
"parameter_list": "(num1, num2)"
},
{
"d... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006374",
"row_id": 6374,
"seed_ids": "['Llama-3.3-70B-Instruct_18775']"
} | 0.538093 | Filter_6374 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 2d062aec1b69f5f38cad0aa0d4030488163dd557 | f0e0ae7adfc63a73bdbd2189560739075a0f7b92 | |||
v1.0 | instruct | Filter | Filter_6405_I | I have a dataset with 3 columns: ID, Height, and Weight. The Height and Weight are in inches and pounds, respectively, and I want to convert them to centimeters and kilograms.
If I provide you the conversion rates, can you help me with writing a Python script to convert the Height and Weight columns of my dataset? | def convert_inches_to_cm(inches):
"""
Converts inches to centimeters.
1 inch = 2.54 cm
"""
return inches * 2.54
def convert_pounds_to_kg(pounds):
"""
Converts pounds to kilograms.
1 pound = 0.453592 kg
"""
return pounds * 0.453592
def convert_dataset(dataset):
"""
Conve... | import pytest
from solution import convert_inches_to_cm, convert_pounds_to_kg, convert_dataset
def test_convert_inches_to_cm():
assert convert_inches_to_cm(1) == 2.54
assert convert_inches_to_cm(0) == 0
assert convert_inches_to_cm(10) == 25.4
def test_convert_pounds_to_kg():
assert convert_pounds_to_... | [
{
"docstring": "Converts inches to centimeters.\n1 inch = 2.54 cm",
"function_declaration": "def convert_inches_to_cm(inches):",
"function_name": "convert_inches_to_cm",
"parameter_list": "(inches)"
},
{
"docstring": "Converts pounds to kilograms.\n1 pound = 0.453592 kg",
"function_decla... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def convert_to_metric(height_in_inches, weight_in_pounds):\n \"\"\"\n Converts height from inches to centimeters and weight from pounds to kilograms.\n \n Args:\n height_in_inch... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006405",
"row_id": 6405,
"seed_ids": "['Llama-3.3-70B-Instruct_18846']"
} | 0.507862 | Filter_6405 | I | [
"convert_inches_to_cm",
"convert_pounds_to_kg",
"convert_dataset"
] | 3 | [
[
"convert_dataset",
"convert_inches_to_cm"
],
[
"convert_dataset",
"convert_pounds_to_kg"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0b32c61357919b3057c67653ce93ed3dbf256364 | b5ac7c713bde745fc02b5e602b284f4efb34d8d9 | |||
v1.0 | instruct | Filter | Filter_6412_I | I've been tasked with writing a Python script to convert CSV files to JSON format. The script should be able to handle large CSV files and also be able to handle different data types in the CSV file (e.g., strings, integers, floats). | import csv
import json
import os
def csv_to_json(csv_filepath, json_filepath):
"""
Converts a CSV file to JSON format.
:param csv_filepath: Path to the input CSV file
:param json_filepath: Path to the output JSON file
"""
data = []
with open(csv_filepath, mode='r', encoding='utf-8') as cs... | import os
import json
from solution import csv_to_json, _convert_value
def setup_module(module):
with open('test.csv', mode='w', encoding='utf-8') as test_csv:
test_csv.write('Name,Age,Height,Is_Student\n')
test_csv.write('Alice,23,5.7,True\n')
test_csv.write('Bob,30,6.0,False\n')
def tear... | [
{
"docstring": "Converts a CSV file to JSON format.\n\n:param csv_filepath: Path to the input CSV file\n:param json_filepath: Path to the output JSON file",
"function_declaration": "def csv_to_json(csv_filepath, json_filepath):",
"function_name": "csv_to_json",
"parameter_list": "(csv_filepath, json... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport json\n\ndef csv_to_json(csv_file_path, json_file_path):\n \"\"\"\n Converts CSV file to JSON file.\n \n Args:\n csv_file_path (str): The path to the CSV file ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006412",
"row_id": 6412,
"seed_ids": "['Llama-3.3-70B-Instruct_18855']"
} | 0.719471 | Filter_6412 | I | [
"csv_to_json",
"_convert_value"
] | 2 | [
[
"csv_to_json",
"_convert_value"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 80494ee35424c23e39fdb011c6d9e159e54b1807 | e0e8a37c6e31da5867d436758e61694678c9851a | |||
v1.0 | instruct | Filter | Filter_6418_I | I have a matrix of size 5x5 and I want to fill it with random integers. How can I achieve this using Python? | import random
def generate_random_matrix(rows, cols, min_val=0, max_val=100):
"""
Generates a matrix of size rows x cols filled with random integers ranging from min_val to max_val.
Parameters:
- rows: Number of rows in the matrix.
- cols: Number of columns in the matrix.
- min_val: Minimu... | from solution import generate_5x5_random_matrix
def test_generate_5x5_random_matrix_size():
matrix = generate_5x5_random_matrix()
assert len(matrix) == 5
assert all(len(row) == 5 for row in matrix)
def test_generate_random_matrix_values_within_bounds():
min_val = 10
max_val = 20
matrix = gener... | [
{
"docstring": "Generates a matrix of size rows x cols filled with random integers ranging from min_val to max_val.\n\nParameters:\n- rows: Number of rows in the matrix.\n- cols: Number of columns in the matrix.\n- min_val: Minimum value of random integers (inclusive). Default is 0.\n- max_val: Maximum value of... | [
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 generate_random_matrix(seed=None):\n \"\"\"\n Generates a 5x5 matrix filled with random integers between 0 and 100.\n Optionally takes a seed for reproducibi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006418",
"row_id": 6418,
"seed_ids": "['Llama-3.3-70B-Instruct_18876']"
} | 0.617045 | Filter_6418 | I | [
"generate_random_matrix",
"generate_5x5_random_matrix"
] | 2 | [
[
"generate_5x5_random_matrix",
"generate_random_matrix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b95585d45bd81e5d6fa531927a69add29620dd5f | d4de8c840384fed1428fb325128376c3a1e1d605 | |||
v1.0 | instruct | Filter | Filter_6445_I | I have a dataset of 1000 images, each having a size of 28x28 pixels. I want to apply data augmentation to increase the size of my dataset. Specifically, I want to apply rotation, flipping, and adding noise to the images.
The following are the specifications:
* Rotation: Rotate the images by 90, 180, and 270 degrees... | import numpy as np
import cv2
import random
def rotate_image(image, angle):
"""
Rotates an image by the given angle.
"""
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
def flip... | import numpy as np
from solution import rotate_image, flip_image, add_gaussian_noise, augment_dataset
def generate_dummy_image():
"""
Generates a dummy 28x28 image with pixel values between 0 and 1.
"""
return np.random.rand(28, 28).astype(np.float32)
def test_rotate_image():
image = generate_dumm... | [
{
"docstring": "Rotates an image by the given angle.",
"function_declaration": "def rotate_image(image, angle):",
"function_name": "rotate_image",
"parameter_list": "(image, angle)"
},
{
"docstring": "Flips an image horizontally.",
"function_declaration": "def flip_image(image):",
"f... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport cv2\nfrom scipy.ndimage import rotate\n\ndef augment_image(image):\n \"\"\"\n Apply data augmentation to the input image.\n - Rotate by 90, 180, and 270 deg... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006445",
"row_id": 6445,
"seed_ids": "['Llama-3.3-70B-Instruct_18935']"
} | 0.415791 | Filter_6445 | I | [
"rotate_image",
"flip_image",
"add_gaussian_noise",
"augment_dataset"
] | 4 | [
[
"augment_dataset",
"add_gaussian_noise"
],
[
"augment_dataset",
"flip_image"
],
[
"augment_dataset",
"rotate_image"
]
] | 3 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 902394873a281971f65753c415f91e9f8b5f6448 | c2bff32916e07c4570fdb32c7457bfdaa9b5a62f | |||
v1.0 | instruct | Filter | Filter_6456_I | Below is a Python code for finding the GCD of two numbers using the Euclidean algorithm. How I can modify this code so that it calculates the GCD for more than two numbers? | def gcd(a, b):
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
def gcd_multiple(numbers):
"""
Returns the greatest common divisor of a list of numbers.
"""
if not numbers:
raise ValueError("The l... | from solution import gcd, gcd_multiple
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(100, 10) == 10
assert gcd(7, 1) == 1
assert gcd(0, 5) == 5
def test_gcd_multiple():
assert gcd_multiple([48, 18, 30]) == 6
assert gcd_multiple([100, 25, 40]) == 5
assert gcd_multiple([7, 1, 14]) == 1
... | [
{
"docstring": "Returns the greatest common divisor of a and b using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the greatest common divisor of a list of numbers.",
"function_declaratio... | [
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 GCD of a and b using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\ndef gcd_multiple(numbers):\n \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006456",
"row_id": 6456,
"seed_ids": "['Llama-3.3-70B-Instruct_18963']"
} | 0.740626 | Filter_6456 | I | [
"gcd",
"gcd_multiple"
] | 2 | [
[
"gcd_multiple",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eaaf58b99e7481397cbf8ad2878d097b838e79ed | 6b0f790b53455bc8ba0007dd4e550ded87b54b8d | |||
v1.0 | instruct | Filter | Filter_6465_I | I'm looking for a function that will return all combinations of a list of objects. I would like the function to be recursive and include a combination size of 1. | def get_combinations(lst):
"""
Returns all combinations of elements in lst, including combinations of size 1.
"""
if len(lst) == 0:
return [[]]
current_element = lst[0]
rest_combinations = get_combinations(lst[1:])
new_combinations = []
for combination in rest_combinations:
... | from solution import all_combinations
def test_empty_list():
assert all_combinations([]) == []
def test_single_element_list():
assert all_combinations([1]) == [[1]]
def test_two_element_list():
assert all_combinations([1, 2]) == [[2], [1], [1, 2]]
def test_three_element_list():
assert all_combinatio... | [
{
"docstring": "Returns all combinations of elements in lst, including combinations of size 1.",
"function_declaration": "def get_combinations(lst):",
"function_name": "get_combinations",
"parameter_list": "(lst)"
},
{
"docstring": "Filters out the empty combination and returns all non-empty... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def combinations(lst):\n \"\"\"\n Returns all combinations of the elements in the given list.\n The function is recursive and includes combinations of size 1.\n \"\"\"\n if len(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006465",
"row_id": 6465,
"seed_ids": "['Llama-3.3-70B-Instruct_18987']"
} | 0.7385 | Filter_6465 | I | [
"get_combinations",
"all_combinations"
] | 2 | [
[
"all_combinations",
"get_combinations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3bf9280a95e9ec2f89a4264427c31878164cfef2 | 4f10bd67bebf04b558b7190801e602215b46a887 | |||
v1.0 | instruct | Filter | Filter_6477_I | Can you write a code for a simple Rock, Paper, Scissors game in Python? | import random
def get_computer_choice():
"""
Randomly returns one of 'rock', 'paper', or 'scissors' which represents the computer's choice.
"""
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of a rock, paper, ... | from solution import get_computer_choice, determine_winner, play_rps
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
for _ in range(100):
choice = get_computer_choice()
assert choice in choices
def test_determine_winner_draw():
assert determine_winner('rock', 'rock'... | [
{
"docstring": "Randomly returns one of 'rock', 'paper', or 'scissors' which represents the computer's choice.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of a rock, paper, sci... | [
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 rock_paper_scissors(player_choice):\n \"\"\"\n Simulates a game of Rock, Paper, Scissors.\n \n Parameters:\n player_choice (str): The choice made by the pla... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006477",
"row_id": 6477,
"seed_ids": "['Llama-3.3-70B-Instruct_19006']"
} | 0.450472 | Filter_6477 | I | [
"get_computer_choice",
"determine_winner",
"play_rps"
] | 3 | [
[
"play_rps",
"determine_winner"
],
[
"play_rps",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 342f5076f8dec8afdd00038fb1e7608874205ab9 | 3d65594c0a1e50a5f404becc2cda5309b81f52ce | |||
v1.0 | instruct | Filter | Filter_6478_I | Can you help me implement a decorator function in Python that authenticates the user before running the decorated function? | from functools import wraps
def authenticate(user, password):
"""A simple authentication function."""
# This is a simplified example of an authentication function.
return user == "admin" and password == "1234"
def authentication_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
us... | import pytest
from solution import authentication_required, sensitive_function
def test_sensitive_function_authenticated():
result = sensitive_function(data="Top Secret", user="admin", password="1234")
assert result == "Sensitive data: Top Secret"
def test_sensitive_function_wrong_password():
with pytest.... | [
{
"docstring": "A simple authentication function.",
"function_declaration": "def authenticate(user, password):",
"function_name": "authenticate",
"parameter_list": "(user, password)"
},
{
"docstring": null,
"function_declaration": "def authentication_required(func):",
"function_name"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def authenticate(user, password, user_db):\n \"\"\"\n A simple authentication function that checks the user credentials\n :param user: The username\n :param password: The password\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006478",
"row_id": 6478,
"seed_ids": "['Llama-3.3-70B-Instruct_19007']"
} | 0.468787 | Filter_6478 | I | [
"authenticate",
"authentication_required",
"sensitive_function"
] | 3 | [
[
"authentication_required",
"authenticate"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71fa713d3bf3f91c607fd9fd5d1a930115e6c7a1 | 916966598999719ab88d65aad65aacc6ed1648f3 | |||
v1.0 | instruct | Filter | Filter_6491_I | Given a function `invert(x)` that takes an integer as input and returns its inverse (1/x), write a function that calculates the inverse of all elements in a given list of integers using the `invert(x)` function. | def invert(x):
"""
Returns the inverse of x.
"""
if x == 0:
raise ValueError("Cannot invert zero.")
return 1 / x
def invert_list(lst):
"""
Returns a list containing the inverse of each integer in the input list.
"""
return [invert(x) for x in lst] | from solution import invert, invert_list
import pytest
def test_invert_positive_number():
assert invert(2) == 0.5
def test_invert_negative_number():
assert invert(-4) == -0.25
def test_invert_zero():
with pytest.raises(ValueError):
invert(0)
def test_invert_list_all_positive():
assert invert... | [
{
"docstring": "Returns the inverse of x.",
"function_declaration": "def invert(x):",
"function_name": "invert",
"parameter_list": "(x)"
},
{
"docstring": "Returns a list containing the inverse of each integer in the input list.",
"function_declaration": "def invert_list(lst):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def invert(x):\n \"\"\"\n Returns the inverse of x if x is not zero.\n \"\"\"\n if x == 0:\n raise ValueError(\"Cannot invert 0\")\n return 1 / x\n\ndef invert_list(int_l... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006491",
"row_id": 6491,
"seed_ids": "['Llama-3.3-70B-Instruct_19044']"
} | 0.621265 | Filter_6491 | I | [
"invert",
"invert_list"
] | 2 | [
[
"invert_list",
"invert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a833947f498b6de6e1141d0d39733d60043092ab | 78141b644ebfc01dceebfce6987a8a9752c6c04a | |||
v1.0 | instruct | Filter | Filter_6510_I | I have a function that returns a list of values. I want to create a new list that contains the same values, but sorted.
Here is the sample code:
```
def my_function():
# some code here
return [4, 2, 9, 6, 5, 1, 8, 3, 7]
sorted_list = sorted(my_function())
print(sorted_list)
```
This works fine, but is there ... | def my_function():
"""
Returns an unsorted list of integers.
"""
return [4, 2, 9, 6, 5, 1, 8, 3, 7]
def get_sorted_list_comprehension():
"""
Returns a sorted list of integers using list comprehension from the output of my_function.
"""
# Using list comprehension to create a sorted list
... | from solution import my_function, get_sorted_list_comprehension
def test_my_function():
assert my_function() == [4, 2, 9, 6, 5, 1, 8, 3, 7]
def test_get_sorted_list_comprehension():
assert get_sorted_list_comprehension() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_sorted_list_is_sorted():
result = get_sorted... | [
{
"docstring": "Returns an unsorted list of integers.",
"function_declaration": "def my_function():",
"function_name": "my_function",
"parameter_list": "()"
},
{
"docstring": "Returns a sorted list of integers using list comprehension from the output of my_function.",
"function_declarati... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def my_function():\n \"\"\"\n Returns a list of unsorted values.\n \"\"\"\n return [4, 2, 9, 6, 5, 1, 8, 3, 7]\n\ndef sorted_list_comprehension():\n \"\"\"\n Returns the list... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006510",
"row_id": 6510,
"seed_ids": "['Llama-3.3-70B-Instruct_19086']"
} | 0.564783 | Filter_6510 | I | [
"my_function",
"get_sorted_list_comprehension"
] | 2 | [
[
"get_sorted_list_comprehension",
"my_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e903d42af3f0490e7f782a6462bd493e77910b96 | 82ab7fed6cb7980817fd6c26afdaceb9e40f441c | |||
v1.0 | instruct | Filter | Filter_6534_I | I have several big xml files and I want to create a JSON file from them. What are the best practices for achieving this?
To accomplish this, I will:
1. Parse the XML files.
2. Convert the parsed data to JSON.
3. Write the JSON data to a file.
What are the best practices for each of these steps, and what are some popu... | import xml.etree.ElementTree as ET
import json
import os
def parse_xml_to_dict(file_path):
"""
Converts an XML file to a dictionary.
"""
tree = ET.parse(file_path)
root = tree.getroot()
def _xml_to_dict(element):
"""
Recurse through the XML element to build a dictionary.
... | from solution import parse_xml_to_dict, write_json, convert_xml_to_json
import json
import os
def prepare_test_xml(file_path):
"""
Prepare test XML files for testing.
"""
xml_content = """<?xml version="1.0"?>
<root>
<child1>value1</child1>
<child2>value2</child2>
<child3>
... | [
{
"docstring": "Converts an XML file to a dictionary.",
"function_declaration": "def parse_xml_to_dict(file_path):",
"function_name": "parse_xml_to_dict",
"parameter_list": "(file_path)"
},
{
"docstring": "Writes a dictionary to a JSON file.",
"function_declaration": "def write_json(data... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\nimport json\nimport os\n\ndef parse_xml(file_path):\n \"\"\"\n Parses the XML file and returns the root element.\n \"\"\"\n tree = ET.parse(file... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006534",
"row_id": 6534,
"seed_ids": "['Llama-3.3-70B-Instruct_19128']"
} | 0.631019 | Filter_6534 | I | [
"parse_xml_to_dict",
"write_json",
"convert_xml_to_json"
] | 3 | [
[
"convert_xml_to_json",
"parse_xml_to_dict"
],
[
"convert_xml_to_json",
"write_json"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cd9536ed6d9200a2a401aa2c5b3e76d85b14d963 | 62960c25e660a6f52fd59f24d97bf6ef76b06c91 | |||
v1.0 | instruct | Filter | Filter_6548_I | I have a two-dimensional array of numbers. I'd like to find the largest sum of a subarray within this 2D array. The subarray can be any size, but it must be a rectangle (i.e., have the same number of rows and columns). I need a code that can efficiently find this largest sum.
### Solution Requirements
* It should h... | def max_subarray_sum(arr):
if not arr or not arr[0]:
return 0
rows, cols = len(arr), len(arr[0])
max_sum = float('-inf')
for top in range(rows):
temp = [0] * cols
for bottom in range(top, rows):
for i in range(cols):
temp[i] += arr[bottom][i]
... | from solution import max_subarray_sum
def test_max_subarray_sum_small_positive():
arr = [
[1, 2, -1, -4, -20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]
]
assert max_subarray_sum(arr) == 29
def test_max_subarray_sum_with_all_negative():
arr = [
[-1... | [
{
"docstring": null,
"function_declaration": "def max_subarray_sum(arr):",
"function_name": "max_subarray_sum",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def kadane(arr):",
"function_name": "kadane",
"parameter_list": "(arr)"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_subarray_sum(arr):\n if not arr or not arr[0]:\n return 0\n\n rows, cols = len(arr), len(arr[0])\n max_sum = float('-inf')\n\n for left in range(cols):\n temp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006548",
"row_id": 6548,
"seed_ids": "['Llama-3.3-70B-Instruct_19154']"
} | 0.639084 | Filter_6548 | I | [
"max_subarray_sum",
"kadane"
] | 2 | [
[
"max_subarray_sum",
"kadane"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee311c95750ba97cb6371c442c6940ab034ef035 | 4c4b84bcd7cace0979eb9d872cbd2d57c6726330 | |||
v1.0 | instruct | Filter | Filter_6554_I | I have a function foo that takes two parameters, x and y, and returns the sum of their squares. Please see below.
```python
def foo(x, y):
return x**2 + y**2
```
I would like to create a decorator that can be applied to this function to multiply the result by a certain value. Is there a way I can do this? | def multiply_result_by(factor):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result * factor
return wrapper
return decorator
@multiply_result_by(2)
def foo(x, y):
"""
Returns the sum of squares of x and y, and then mult... | from solution import foo, multiply_result_by
def test_foo_with_positive_numbers():
assert foo(2, 3) == 26 # (2^2 + 3^2) * 2 = 4 + 9 * 2 = 26
def test_foo_with_zero():
assert foo(0, 0) == 0 # (0^2 + 0^2) * 2 = 0
def test_foo_with_one_zero():
assert foo(0, 5) == 50 # (0^2 + 5^2) * 2 = 25 * 2 = 50
de... | [
{
"docstring": null,
"function_declaration": "def multiply_result_by(factor):",
"function_name": "multiply_result_by",
"parameter_list": "(factor)"
},
{
"docstring": "Returns the sum of squares of x and y, and then multiplies the result by 2 using the decorator.",
"function_declaration":... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply_decorator(factor):\n def decorator(func):\n def wrapper(x, y):\n original_result = func(x, y)\n modified_result = original_result * factor\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006554",
"row_id": 6554,
"seed_ids": "['Llama-3.3-70B-Instruct_19163']"
} | 0.526999 | Filter_6554 | I | [
"multiply_result_by",
"foo"
] | 2 | [
[
"foo",
"multiply_result_by"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7b82152fd077db256c8b9780f123fccc0acd2bd0 | 2b947391fd8d4353f20ba497880a5a3fdd6f0804 | |||
v1.0 | instruct | Filter | Filter_6587_I | I have an application where I need to find the distances between all pairs of points (in a given space) given their Cartesian coordinates. I have a function that calculates the Euclidean distance between two points, but I want to apply it to every pair of points in my list.
Example:
Input list of points:
```
[(0, 0),... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
Parameters:
point1 (tuple): The first point.
point2 (tuple): The second point.
Returns:
float: The Euclidean distance between the two points.
"""
return math.sqrt((... | from solution import euclidean_distance, distances_between_all_pairs
def test_euclidean_distance():
assert euclidean_distance((0, 0), (3, 4)) == 5.0
assert euclidean_distance((0, 0), (6, 8)) == 10.0
assert euclidean_distance((3, 4), (6, 8)) == 5.0
assert euclidean_distance((1, 1), (4, 5)) == 5.0
as... | [
{
"docstring": "Calculate the Euclidean distance between two points.\n\nParameters:\npoint1 (tuple): The first point.\npoint2 (tuple): The second point.\n\nReturns:\nfloat: The Euclidean distance between the two points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n\n Parameters:\n point1 (tuple): The first point.\n point... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006587",
"row_id": 6587,
"seed_ids": "['Llama-3.3-70B-Instruct_19241']"
} | 0.66704 | Filter_6587 | I | [
"euclidean_distance",
"distances_between_all_pairs"
] | 2 | [
[
"distances_between_all_pairs",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7780f1262a4b7fd7280eefad366b1a592c27becf | 90d33e46d34639da202485c6c2d8bd0235394a29 | |||
v1.0 | instruct | Filter | Filter_6600_I | I have two sets of SNPs of different sizes and I want to know which SNPs are identical between the two sets.
Set A is
1:101-2:C/G
1:102-2:T/A
1:103-2:C/T
1:104-2:G/C
1:105-2:A/T
1:106-2:C/G
1:107-2:G/A
1:108-2:C/T
1:109-2:G/A
1:110-2:A/T
Set B is
1:101-2:C/G
1:103-2:C/T
1:105-2:A/T
1:108-2:C/T
1:110-2:A/T
I want ... | def read_snps(file_path):
"""
Reads SNPs from a file and returns a set of SNPs.
:param file_path: Path to the file containing SNPs
:return: A set of SNPs
"""
with open(file_path, 'r') as file:
return {line.strip() for line in file}
def find_common_snps(file_path_A, file_path_B):
... | import tempfile
import os
from solution import find_common_snps
def create_temp_file(content):
fd, file_path = tempfile.mkstemp()
with os.fdopen(fd, 'w') as tmp:
tmp.write(content)
return file_path
def test_find_common_snps():
setA_content = """1:101-2:C/G
1:102-2:T/A
1:103-2:C/T
1:104-2:G/C
1... | [
{
"docstring": "Reads SNPs from a file and returns a set of SNPs.\n\n:param file_path: Path to the file containing SNPs\n:return: A set of SNPs",
"function_declaration": "def read_snps(file_path):",
"function_name": "read_snps",
"parameter_list": "(file_path)"
},
{
"docstring": "Finds common... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_common_snps(file_A, file_B):\n \"\"\"\n Finds and returns the set of common SNPs between two files containing SNP data.\n \"\"\"\n with open(file_A, 'r') as f_A, open(file... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006600",
"row_id": 6600,
"seed_ids": "['Llama-3.3-70B-Instruct_19265']"
} | 0.545069 | Filter_6600 | I | [
"read_snps",
"find_common_snps"
] | 2 | [
[
"find_common_snps",
"read_snps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c283c3f84848ac23aabbe12c713ebc029108d38 | 76c02b856073e2100de37cf6b1327dee3d2a0aff | |||
v1.0 | instruct | Filter | Filter_6628_I | I wrote a script that generates a random layout for a amateur radio contest. The script looks like this:
```python
import random
def generate_layout():
callsigns = ["K0BBC", "K1HP", "N0ARY", "W1AW", "N9NE", "K9EVT", "K9MOT", "W9RE", "K0KX", "W9XT"]
modes = ["SSB", "CW", "FM", "RTTY"]
bands = [20, 40, 80, ... | import random
import json
def generate_layout():
callsigns = ["K0BBC", "K1HP", "N0ARY", "W1AW", "N9NE", "K9EVT", "K9MOT", "W9RE", "K0KX", "W9XT"]
modes = ["SSB", "CW", "FM", "RTTY"]
bands = [20, 40, 80, 160]
operators = ["John", "Mike", "Emily", "David", "Sophia"]
layout = {
"callsign": ra... | import json
from solution import generate_layout, generate_multiple_layouts, save_layouts_to_json
def test_generate_layout():
layout = generate_layout()
assert "callsign" in layout
assert "mode" in layout
assert "band" in layout
assert "operator" in layout
def test_generate_multiple_layouts():
... | [
{
"docstring": null,
"function_declaration": "def generate_layout():",
"function_name": "generate_layout",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_multiple_layouts(n):",
"function_name": "generate_multiple_layouts",
"parameter_list": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport json\n\ndef generate_layout():\n callsigns = [\"K0BBC\", \"K1HP\", \"N0ARY\", \"W1AW\", \"N9NE\", \"K9EVT\", \"K9MOT\", \"W9RE\", \"K0KX\", \"W9XT\"]\n modes = [\"S... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006628",
"row_id": 6628,
"seed_ids": "['Llama-3.3-70B-Instruct_19325']"
} | 0.54055 | Filter_6628 | I | [
"generate_layout",
"generate_multiple_layouts",
"save_layouts_to_json",
"main"
] | 4 | [
[
"generate_multiple_layouts",
"generate_layout"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb3908cc57aa82aeca90e279e967d88edf40f97b | a26431034374ff48a61e79b15725cdc68fe30ddb | |||
v1.0 | instruct | Filter | Filter_6666_I | Here are two Python scripts. I want them to be combined into a single script with the same functionality.
**Script 1:**
```python
from datetime import datetime
import socket
def getServerTime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def getHostName():
return socket.gethostname()
def getServer... | from datetime import datetime
import socket
import os
import platform
import psutil
def getServerTime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def getHostName():
return socket.gethostname()
def getServerInfo():
return {
"time": getServerTime(),
"hostname": getHostName()
... | from solution import getServerTime, getHostName, getServerInfo, getDiskSpace, getOSInfo, getSystemInfo, getFullSystemInfo
import pytest
import datetime
import socket
import platform
import psutil
def test_getServerTime():
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
assert getServerTime... | [
{
"docstring": null,
"function_declaration": "def getServerTime():",
"function_name": "getServerTime",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def getHostName():",
"function_name": "getHostName",
"parameter_list": "()"
},
{
"docstring": nul... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\nimport socket\nimport os\nimport platform\nimport psutil\n\ndef getServerTime():\n return datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\ndef getHostName():... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006666",
"row_id": 6666,
"seed_ids": "['Llama-3.3-70B-Instruct_19408']"
} | 0.501827 | Filter_6666 | I | [
"getServerTime",
"getHostName",
"getServerInfo",
"getDiskSpace",
"getOSInfo",
"getSystemInfo",
"getFullSystemInfo"
] | 7 | [
[
"getFullSystemInfo",
"getServerInfo"
],
[
"getFullSystemInfo",
"getSystemInfo"
],
[
"getServerInfo",
"getHostName"
],
[
"getServerInfo",
"getServerTime"
],
[
"getSystemInfo",
"getDiskSpace"
],
[
"getSystemInfo",
"getOSInfo"
]
] | 6 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | 6f0b6ce87c8f1dfd96942b5d3b6a8a8ab84fa254 | 44b75eaad09ff2a953a87f8037add742f0f6bdbf | |||
v1.0 | instruct | Filter | Filter_6692_I | An industrial robot consists of two robotic arms that can extend or retract to handle objects of different sizes. Each arm can extend from 1 to 10 feet in length. The robot is designed to handle objects ranging from 2 to 20 feet in diameter. Write a Python program to simulate the extension and retraction of the robotic... | def calculate_arm_lengths(diameter):
"""
Calculate the length of each robotic arm to handle the object.
Args:
diameter (float): The diameter of the object.
Returns:
tuple: A tuple containing the length of each arm.
"""
if diameter < 2 or diameter > 20:
return "Object is too lar... | from solution import calculate_arm_lengths, total_arm_length
def test_calculate_arm_lengths_small_diameter():
assert calculate_arm_lengths(2) == (1, 1)
def test_calculate_arm_lengths_large_diameter():
assert calculate_arm_lengths(20) == (10, 10)
def test_calculate_arm_lengths_too_small():
assert calc... | [
{
"docstring": "Calculate the length of each robotic arm to handle the object.\n\nArgs:\ndiameter (float): The diameter of the object.\n\nReturns:\ntuple: A tuple containing the length of each arm.",
"function_declaration": "def calculate_arm_lengths(diameter):",
"function_name": "calculate_arm_lengths"... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_arm_lengths(diameter):\n \"\"\"\n Calculate the length of each robotic arm to handle the object.\n\n Args:\n diameter (float): The diameter of the object.\n\n Retu... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006692",
"row_id": 6692,
"seed_ids": "['Llama-3.3-70B-Instruct_19467']"
} | 0.384844 | Filter_6692 | I | [
"calculate_arm_lengths",
"total_arm_length"
] | 2 | [
[
"total_arm_length",
"calculate_arm_lengths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67010e3b4a3a33650d4a0206285024a60b291d37 | 7acad22e212902642c952ddfeb6119792cbabcc5 | |||
v1.0 | instruct | Filter | Filter_6694_I | Here is my code for the "rock, paper, scissors" game.
How do I add more options like "lizard" and "spock" to make it a "rock, paper, scissors, lizard, spock" game? | import random
def determine_winner(player_choice, computer_choice):
"""
Determines the winner of the game based on player and computer choices.
Parameters:
player_choice (str): The player's choice in the game.
computer_choice (str): The computer's choice in the game.
Returns:
str:... | from solution import determine_winner, play_game
def test_determine_winner():
assert determine_winner('rock', 'scissors') == "You win!"
assert determine_winner('rock', 'lizard') == "You win!"
assert determine_winner('rock', 'paper') == "You lose!"
assert determine_winner('rock', 'spock') == "You lose!"... | [
{
"docstring": "Determines the winner of the game based on player and computer choices.\n\nParameters:\nplayer_choice (str): The player's choice in the game.\ncomputer_choice (str): The computer's choice in the game.\n\nReturns:\nstr: The result of the game, indicating whether the player wins, loses, or ties.",... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef play_rpsls(player_choice):\n \"\"\"\n Play Rock, Paper, Scissors, Lizard, Spock.\n Args:\n player_choice (str): Player's choice, which must be one of \"rock\",... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006694",
"row_id": 6694,
"seed_ids": "['Llama-3.3-70B-Instruct_19471']"
} | 0.415407 | Filter_6694 | I | [
"determine_winner",
"play_game"
] | 2 | [
[
"play_game",
"determine_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 18e68d0824f2306157f26502513a8518c8a9a17f | b38c66f38e105fbaa2c4270922b601e51bb3da8c | |||
v1.0 | instruct | Filter | Filter_6697_I | I have two functions `gross_to_net(gross)` and `net_to_gross(net)` that convert between gross and net salaries. I want to create a new function `gross_to_net_with_tax_deductions(gross)` that uses these functions to calculate the net salary after tax deduction, based on a given tax rate. The tax rate is not fixed and wi... | def gross_to_net(gross: float) -> float:
"""
Dummy implementation for conversion from gross to net salary.
"""
# For the purpose of the problem, we assume a dummy conversion rate
return gross * 0.8
def net_to_gross(net: float) -> float:
"""
Dummy implementation for conversion from net to gr... | from solution import gross_to_net, net_to_gross, gross_to_net_with_tax_deductions
def test_gross_to_net():
assert abs(gross_to_net(1000) - 800) < 1e-5
def test_net_to_gross():
assert abs(net_to_gross(800) - 1000) < 1e-5
def test_gross_to_net_with_tax_deductions():
assert abs(gross_to_net_with_tax_deducti... | [
{
"docstring": "Dummy implementation for conversion from gross to net salary.",
"function_declaration": "def gross_to_net(gross):",
"function_name": "gross_to_net",
"parameter_list": "(gross)"
},
{
"docstring": "Dummy implementation for conversion from net to gross salary.",
"function_de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gross_to_net(gross: float) -> float:\n \"\"\"\n Returns the net salary from the gross salary.\n This is a placeholder function. Actual implementation is not shown.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006697",
"row_id": 6697,
"seed_ids": "['Llama-3.3-70B-Instruct_19479']"
} | 0.412357 | Filter_6697 | I | [
"gross_to_net",
"net_to_gross",
"gross_to_net_with_tax_deductions"
] | 3 | [
[
"gross_to_net_with_tax_deductions",
"gross_to_net"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d870550bd6d6bd7064d6d9ce0d3e0301f7d6bad8 | 87886f6ff6101d663dfdd1d0ddd0e6bc34a6964d | |||
v1.0 | instruct | Filter | Filter_6703_I | I have a .csv file which contains data that includes the lease expiration dates for a set of properties. I need to write a script that will calculate the number of days until the lease expires for each property.
The .csv file has the following columns: Property ID, Lease Expiration Date, and Address. The Lease Expirat... | import csv
import datetime
import logging
# Set up logging
logging.basicConfig(
filename='lease_expiration.log',
level=logging.ERROR,
format='%(asctime)s,%(levelname)s,%(message)s'
)
# Define a function to calculate the number of days until the lease expires
def calculate_days_until_expiration(expiration... | import datetime
import csv
import os
import pytest
from solution import calculate_days_until_expiration, process_lease_data, write_results_to_csv
def test_calculate_days_until_expiration_future_date():
future_date = (datetime.date.today() + datetime.timedelta(days=10)).strftime('%Y-%m-%d')
assert calculate_da... | [
{
"docstring": null,
"function_declaration": "def calculate_days_until_expiration(expiration_date):",
"function_name": "calculate_days_until_expiration",
"parameter_list": "(expiration_date)"
},
{
"docstring": null,
"function_declaration": "def process_lease_data(csv_file):",
"functi... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport datetime\nimport logging\n\n# Set up logging\nlogging.basicConfig(filename='lease_expiration.log', level=logging.ERROR,\n format='%(asctime)s,%(levelname)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006703",
"row_id": 6703,
"seed_ids": "['Llama-3.3-70B-Instruct_19491']"
} | 0.603981 | Filter_6703 | I | [
"calculate_days_until_expiration",
"process_lease_data",
"write_results_to_csv",
"main"
] | 4 | [
[
"process_lease_data",
"calculate_days_until_expiration"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fc27299046ec6e836667bfc86149b1ab03361a73 | 55dd782c12049a3b68cbe7598c5be5eaa519eef5 | |||
v1.0 | instruct | Filter | Filter_6711_I | Here is the code for a lesson plan on Introduction to Vectors:
```
import numpy as np
# Define vectors
vector_a = np.array([3, 4])
vector_b = np.array([2, 1])
# Define a function to add two vectors
def add_vectors(vector1, vector2):
return np.add(vector1, vector2)
# Define a function to multiply a vector by a sc... | import numpy as np
# Define vectors
vector_a = np.array([3, 4])
vector_b = np.array([2, 1])
# Define a function to add two vectors
def add_vectors(vector1, vector2):
return np.add(vector1, vector2)
# Define a function to multiply a vector by a scalar
def multiply_vector_by_scalar(vector, scalar):
return np.m... | from solution import (add_vectors, multiply_vector_by_scalar, calculate_magnitude,
calculate_dot_product, calculate_unit_vector, calculate_angle_between_vectors)
import numpy as np
def test_add_vectors():
assert np.array_equal(add_vectors(np.array([1, 2]), np.array([3, 4])), np.array([4, 6])... | [
{
"docstring": null,
"function_declaration": "def add_vectors(vector1, vector2):",
"function_name": "add_vectors",
"parameter_list": "(vector1, vector2)"
},
{
"docstring": null,
"function_declaration": "def multiply_vector_by_scalar(vector, scalar):",
"function_name": "multiply_vecto... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\n# Define vectors\nvector_a = np.array([3, 4])\nvector_b = np.array([2, 1])\n\n# Define a function to add two vectors\ndef add_vectors(vector1, vector2):\n return np.ad... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006711",
"row_id": 6711,
"seed_ids": "['Llama-3.3-70B-Instruct_19501']"
} | 0.474612 | Filter_6711 | I | [
"add_vectors",
"multiply_vector_by_scalar",
"calculate_magnitude",
"calculate_dot_product",
"calculate_unit_vector",
"calculate_angle_between_vectors",
"main"
] | 7 | [
[
"calculate_angle_between_vectors",
"calculate_dot_product"
],
[
"calculate_angle_between_vectors",
"calculate_magnitude"
],
[
"calculate_unit_vector",
"calculate_magnitude"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 08417810dd74045ad216a06616a6fbf727222033 | db8775adb36a32ec52ca6f552f862b656cc7aad6 | |||
v1.0 | instruct | Filter | Filter_6755_I | I'm a budding programmer trying to learn more about data structures and algorithms. I'm having trouble understanding how to properly implement the "Knuth-Morris-Pratt" algorithm for string searching. Can you provide an guidance on the implementation of this algorithm? | def kmp_search(text, pattern):
"""
Searches for occurrences of the pattern in the text using the
Knuth-Morris-Pratt algorithm.
Parameters:
text (str): The main text within which the pattern is to be searched.
pattern (str): The pattern to be searched within the text.
Returns:
l... | from solution import kmp_search
def test_kmp_search_basic():
assert kmp_search("ababcabcabababd", "ababd") == [10]
assert kmp_search("ababcabcabababd", "abc") == [2, 5]
def test_kmp_search_no_match():
assert kmp_search("hello world", "bye") == []
def test_kmp_search_multiple_matches():
assert kmp_sea... | [
{
"docstring": "Searches for occurrences of the pattern in the text using the\nKnuth-Morris-Pratt algorithm.\n\nParameters:\ntext (str): The main text within which the pattern is to be searched.\npattern (str): The pattern to be searched within the text.\n\nReturns:\nlist: A list of starting indices where patte... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def kmp_search(text, pattern):\n \"\"\"\n Searches for occurrences of the pattern in the text using the\n Knuth-Morris-Pratt algorithm.\n \n Parameters:\n text (str): The mai... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006755",
"row_id": 6755,
"seed_ids": "['Llama-3.3-70B-Instruct_19622']"
} | 0.450829 | Filter_6755 | I | [
"kmp_search",
"build_lps_array"
] | 2 | [
[
"kmp_search",
"build_lps_array"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1b0341bf8637248e80fbb6874f196a11f9ae78a3 | b0cfc23238fa4e80475ea4ef0119174044fbc88e | |||
v1.0 | instruct | Filter | Filter_6776_I | I am looking for a way to create a program that can add, subtract, multiply, and divide the numbers in two separate lists of numbers and then output the resulting lists for each operation.
Here you is the add_list function as a starting point:
```python
def add_list(list1, list2):
result = []
for i in range(l... | def add_list(list1, list2):
return [x + y for x, y in zip(list1, list2)]
def sub_list(list1, list2):
return [x - y for x, y in zip(list1, list2)]
def mult_list(list1, list2):
return [x * y for x, y in zip(list1, list2)]
def div_list(list1, list2):
return [x / y if y != 0 else "undefined" for x, y in ... | from solution import add_list, sub_list, mult_list, div_list
def test_add_list():
assert add_list([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
assert add_list([0, 0], [0, 0]) == [0, 0]
assert add_list([-1, 2], [1, -2]) == [0, 0]
def test_sub_list():
assert sub_list([1, 2, 3], [4, 5, 6]) == [-3, -3, -3]
asse... | [
{
"docstring": null,
"function_declaration": "def add_list(list1, list2):",
"function_name": "add_list",
"parameter_list": "(list1, list2)"
},
{
"docstring": null,
"function_declaration": "def sub_list(list1, list2):",
"function_name": "sub_list",
"parameter_list": "(list1, list2... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_list(list1, list2):\n return [a + b for a, b in zip(list1, list2)]\n\ndef sub_list(list1, list2):\n return [a - b for a, b in zip(list1, list2)]\n\ndef mult_list(list1, list2):\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006776",
"row_id": 6776,
"seed_ids": "['Llama-3.3-70B-Instruct_19684']"
} | 0.68505 | Filter_6776 | I | [
"add_list",
"sub_list",
"mult_list",
"div_list",
"perform_operations"
] | 5 | [
[
"perform_operations",
"add_list"
],
[
"perform_operations",
"div_list"
],
[
"perform_operations",
"mult_list"
],
[
"perform_operations",
"sub_list"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | bec7a2ef6f452c5a1568b1f7e5781926c0afebb6 | c94407364ad232c81f5593fc1d1b56e24eff9154 | |||
v1.0 | instruct | Filter | Filter_6807_I | I've just been asked to implement a chat system for a small to medium-sized team. I've decided to use Python and WebSockets for this, but I'm not sure how to get started. What are the components I should consider, what are some potential pitfalls, and are there any frameworks or libraries that can help?
# Step-by-step... | import asyncio
import websockets
connected_clients = set()
async def handle_connection(websocket, path):
# Register new client
connected_clients.add(websocket)
try:
async for message in websocket:
# Broadcast the message to all connected clients
await broadcast(message)
... | import asyncio
import websockets
import pytest
async def test_broadcast():
# Mimic client connections
async def mock_client(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("Hello World!")
response = await websocket.recv()
assert response ... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport websockets\n\nconnected_clients = set()\n\nasync def handle_connection(websocket, path):\n # Register client\n connected_clients.add(websocket)\n try:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006807",
"row_id": 6807,
"seed_ids": "['Llama-3.3-70B-Instruct_19757']"
} | 0.450573 | Filter_6807 | I | [
"handle_connection",
"broadcast",
"main"
] | 3 | [
[
"handle_connection",
"broadcast"
]
] | 1 | [] | false | [] | false | pytest | false | [
"websockets"
] | false | f10628544323e044d65204389f33ae4fd0774771 | 9e114fa7a77f8e72254aecc4c65f0b2b5692ffbe | |||
v1.0 | instruct | Filter | Filter_6823_I | Here is the Python code that I have written so far. I'm trying to create a Rock, Paper, Scissors game.
```python
import random
def get_computer_choice():
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def get_user_choice():
while True:
user_choice = input("Enter your choic... | import random
def get_computer_choice():
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def get_user_choice():
while True:
user_choice = input("Enter your choice (rock, paper, or scissors): ")
user_choice = user_choice.lower()
if user_choice in ['rock', 'pape... | from solution import get_computer_choice, determine_winner
def test_get_computer_choice():
choices = ['rock', 'paper', 'scissors']
for _ in range(100):
choice = get_computer_choice()
assert choice in choices
def test_determine_winner():
assert determine_winner('rock', 'scissors') == "win"
... | [
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_user_choice():",
"function_name": "get_user_choice",
"parameter_list": "()"
},
{
... | [
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 choices = ['rock', 'paper', 'scissors']\n return random.choice(choices)\n\ndef get_user_choice():\n while True:\n user_choice = in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006823",
"row_id": 6823,
"seed_ids": "['Llama-3.3-70B-Instruct_19799']"
} | 0.535078 | Filter_6823 | 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 | 32ecd550f5ba2ad879d195297e78195cfe4766d4 | 6907b2e67ade2b065abbbecc425fa67c80fb048c | |||
v1.0 | instruct | Filter | Filter_6859_I | I have a large number of text files that contain JSON objects, one JSON object per line. I'd like to parse these JSON objects and extract a specific field from each one. To make this more efficient, I'd like to parallelize the process. How can I accomplish this in Python? | import json
import os
from concurrent.futures import ProcessPoolExecutor
def extract_field_from_json_line(json_line, field):
try:
json_object = json.loads(json_line)
return json_object[field]
except (json.JSONDecodeError, KeyError):
return None
def process_file(file_path, field):
r... | import os
import pytest
from solution import extract_field_from_json_line, process_file, process_files_in_parallel
# Helper functions to create and remove test files
def create_test_file(file_path, lines):
with open(file_path, 'w') as f:
for line in lines:
f.write(line + '\n')
def remove_test_... | [
{
"docstring": null,
"function_declaration": "def extract_field_from_json_line(json_line, field):",
"function_name": "extract_field_from_json_line",
"parameter_list": "(json_line, field)"
},
{
"docstring": null,
"function_declaration": "def process_file(file_path, field):",
"function... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport os\nfrom concurrent.futures import ProcessPoolExecutor\n\ndef extract_field_from_json_line(json_line, field):\n try:\n json_object = json.loads(json_line)\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006859",
"row_id": 6859,
"seed_ids": "['Llama-3.3-70B-Instruct_19877']"
} | 0.605983 | Filter_6859 | I | [
"extract_field_from_json_line",
"process_file",
"process_files_in_parallel"
] | 3 | [
[
"process_file",
"extract_field_from_json_line"
],
[
"process_files_in_parallel",
"process_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3a020a506a743870e32df3df3d38bc9c84e42924 | 7f7dcad2bb98d14a8e8ea995b547e812fc425c20 | |||
v1.0 | instruct | Filter | Filter_6953_I | ### Overview
The goal of this project is to create a simple game of Tic Tac Toe for 2 players.
#### Rules of the Game
- The game is played on a 3x3 grid.
- Player 1 is X and Player 2 is O.
- The first player to get three in a row (horizontally, vertically or diagonally) wins the game.
- If all squares are filled and no... | def initialize_game_board():
"""Initialize the game board with a 3x3 grid."""
board = [[' ' for _ in range(3)] for _ in range(3)]
return board
def print_game_board(board):
"""Print the current state of the game board."""
for row in board:
print(' | '.join(row))
print('---------')
d... | from solution import initialize_game_board, handle_player_move, check_for_win, check_for_draw
def test_initialize_game_board():
board = initialize_game_board()
assert board == [[' ' for _ in range(3)] for _ in range(3)], "The initialized board should be empty."
def test_handle_player_move_valid():
board =... | [
{
"docstring": "Initialize the game board with a 3x3 grid.",
"function_declaration": "def initialize_game_board():",
"function_name": "initialize_game_board",
"parameter_list": "()"
},
{
"docstring": "Print the current state of the game board.",
"function_declaration": "def print_game_bo... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def initialize_game_board():\n \"\"\"Initialize the game board with a 3x3 grid.\"\"\"\n board = [[' ' for _ in range(3)] for _ in range(3)]\n return board\n\ndef print_game_board(boar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006953",
"row_id": 6953,
"seed_ids": "['Llama-3.3-70B-Instruct_20087']"
} | 0.58209 | Filter_6953 | I | [
"initialize_game_board",
"print_game_board",
"handle_player_move",
"check_for_win",
"check_for_draw",
"play_game"
] | 6 | [
[
"play_game",
"check_for_draw"
],
[
"play_game",
"check_for_win"
],
[
"play_game",
"handle_player_move"
],
[
"play_game",
"initialize_game_board"
],
[
"play_game",
"print_game_board"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | e3553b7d1bcdd5194a4e731434871af03b338706 | 81a780bfecd95e71959c5501a0d4d1c0d535698e | |||
v1.0 | instruct | Filter | Filter_6957_I | I have a task to process a large number of XML files stored in a directory and its subdirectories. The task involves parsing each XML file, extracting certain information, and then saving that information to a single CSV file. How can I achieve this using Python? | import os
import csv
import xml.etree.ElementTree as ET
def extract_info_from_xml(file_path):
"""
Parses the given XML file, extracts certain information, and returns it.
"""
try:
tree = ET.parse(file_path)
root = tree.getroot()
# Assuming we need to extract 'name' and 'value' ... | import pytest
import os
import shutil
from solution import extract_from_xml_directory
@pytest.fixture
def setup_test_directory():
"""
Sets up a temporary test directory with XML files for testing.
"""
test_dir = 'test_xml_files'
os.makedirs(test_dir, exist_ok=True)
xml_content_1 = """<?xml ver... | [
{
"docstring": "Parses the given XML file, extracts certain information, and returns it.",
"function_declaration": "def extract_info_from_xml(file_path):",
"function_name": "extract_info_from_xml",
"parameter_list": "(file_path)"
},
{
"docstring": "Processes XML files in a directory (and its... | [
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 csv\nimport xml.etree.ElementTree as ET\n\ndef extract_info_from_xml(file_path):\n \"\"\"\n Parses the given XML file, extracts certain information, and returns it.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00006957",
"row_id": 6957,
"seed_ids": "['Llama-3.3-70B-Instruct_20093']"
} | 0.709074 | Filter_6957 | I | [
"extract_info_from_xml",
"extract_from_xml_directory"
] | 2 | [
[
"extract_from_xml_directory",
"extract_info_from_xml"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ab5eddf8fa3abad5f8d6635720efd3258d7c0cd | bcf5db832ab50c2c33bba120304adc4d2b86af7d | |||
v1.0 | instruct | Filter | Filter_6982_I | ### Description of the Problem
The credit card company is launching a new premium credit card, and the benefits are determined by a points-based system. The company wants to determine how many points a cardholder should receive for each type of transaction.
The points system has the following rules:
* For every dollar... | class Transaction:
"""Represents a transaction with an amount and type."""
def __init__(self, amount, type):
"""
Initializes a Transaction object.
Args:
amount (float): The amount of the transaction.
type (str): The type of the transaction (e.g., 'groceries', 'ga... | from solution import Transaction, calculate_points, total_points
def test_calculate_points_groceries():
transaction = Transaction(100, 'groceries')
assert calculate_points(transaction) == 300
def test_calculate_points_gas():
transaction = Transaction(50, 'gas')
assert calculate_points(transaction) == ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Transaction:\n \"\"\"Represents a transaction with an amount and type.\"\"\"\n def __init__(self, amount, type):\n \"\"\"\n Initializes a Transaction object.\n\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00006982",
"row_id": 6982,
"seed_ids": "['Llama-3.3-70B-Instruct_20139']"
} | 0.571353 | Filter_6982 | I | [
"calculate_points",
"total_points"
] | 2 | [
[
"total_points",
"calculate_points"
]
] | 1 | [] | false | [
"Transaction"
] | true | pytest | true | [] | true | 3f4fb9a281ee3aa42340a2d248339ad8ee8df258 | db206432d211e3ae1cb708edaf1234cfa1c5a2ef | |||
v1.0 | instruct | Filter | Filter_6993_I | Can you write a code that can sort a list of integers using merge sort algorithm?
Here's a sample list of integers to test it out:
[64, 34, 25, 12, 22, 11, 90]
Let's use Python as our programming language for this exercise.
Also, let's assume that this list can grow up to 1000 integers.
### Requirements
* The cod... | def merge_sort(arr):
if not arr:
raise ValueError("Input list must not be empty")
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
return merge(merge_sort(left_half), merge_sort(right_half))
def merge(left, right):
merged = []
... | import pytest
from solution import merge_sort
def test_empty_list():
with pytest.raises(ValueError, match="Input list must not be empty"):
merge_sort([])
def test_single_element_list():
assert merge_sort([5]) == [5]
def test_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
de... | [
{
"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": "class EmptyArrayError(ValueError):\n pass\n\ndef merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n \"\"\"\n if not arr:\n raise Emp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00006993",
"row_id": 6993,
"seed_ids": "['Llama-3.3-70B-Instruct_20163']"
} | 0.617337 | Filter_6993 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 92ae724c7b5c45ffccead1bd1f248a6a59c8679c | 177daafb194aa9efb9e992a81302bb25291e998e | |||
v1.0 | instruct | Filter | Filter_7028_I | I want to write a program that can solve a Rubik's Cube. I want to to be able to solve it in the least moves possible. In order to do so, I need a way to determine the shortest path.
One possible way to solve this problem is to use a breadth-first search (BFS) algorithm. However, implementing BFS on a Rubik's Cube is... | def get_all_possible_moves(cube_state):
"""
Generates all possible moves for a given state of the Rubik's Cube.
Args:
cube_state (list of str): The current state of the Rubik's Cube as a list of strings,
where each string represents the stickers on one face.
... | from solution import get_all_possible_moves, apply_move
def test_apply_move():
initial_state = ["WWWWWWWWW", "OOOOOOOOO", "GGGGGGGGG", "RRRRRRRRR", "BBBBBBBBB", "YYYYYYYYY"]
move = "U"
new_state = apply_move(initial_state, move)
assert new_state == initial_state, "Dummy implementation should return the... | [
{
"docstring": "Generates all possible moves for a given state of the Rubik's Cube.\n\nArgs:\ncube_state (list of str): The current state of the Rubik's Cube as a list of strings, \n where each string represents the stickers on one face.\n \nReturns:\nlist of li... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\nclass RubiksCube:\n def __init__(self, state):\n \"\"\"\n Initializes the cube with a given state.\n \"\"\"\n self.state = state... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007028",
"row_id": 7028,
"seed_ids": "['Llama-3.3-70B-Instruct_20243']"
} | 0.35466 | Filter_7028 | I | [
"get_all_possible_moves",
"apply_move"
] | 2 | [
[
"get_all_possible_moves",
"apply_move"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a0d0267355aca97c943dda1b07c971da435174d3 | f1082e3e966375619c94d69816fd2ee019cce914 | |||
v1.0 | instruct | Filter | Filter_7031_I | ### Writing a Python Program to Read and Display High Scores
#### Problem Statement
Write a program that reads high scores from a file named `high_scores.txt` and displays them in order from highest to lowest. If the file does not exist, create it and initialize it with a default score. The program should also allow us... | import os
FILE_PATH = 'high_scores.txt'
DEFAULT_SCORES = [100, 90, 80]
def initialize_file():
if not os.path.exists(FILE_PATH):
with open(FILE_PATH, 'w') as file:
file.write('\n'.join(map(str, DEFAULT_SCORES)))
def read_scores():
with open(FILE_PATH, 'r') as file:
scores = file.re... | import os
import pytest
from solution import initialize_file, read_scores, add_score, display_scores, add_new_score_and_display, FILE_PATH
def setup_function(function):
if os.path.exists(FILE_PATH):
os.remove(FILE_PATH)
initialize_file()
def test_initialize_file():
initialize_file()
assert os.... | [
{
"docstring": null,
"function_declaration": "def initialize_file():",
"function_name": "initialize_file",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def read_scores():",
"function_name": "read_scores",
"parameter_list": "()"
},
{
"docstring":... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\nFILE_PATH = 'high_scores.txt'\nDEFAULT_SCORES = [100, 90, 80]\n\ndef initialize_file():\n if not os.path.exists(FILE_PATH):\n with open(FILE_PATH, 'w') as file:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007031",
"row_id": 7031,
"seed_ids": "['Llama-3.3-70B-Instruct_20256']"
} | 0.584058 | Filter_7031 | I | [
"initialize_file",
"read_scores",
"add_score",
"display_scores",
"add_new_score_and_display"
] | 5 | [
[
"add_new_score_and_display",
"add_score"
],
[
"add_new_score_and_display",
"display_scores"
],
[
"add_score",
"read_scores"
],
[
"display_scores",
"read_scores"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 4da6f5f3ab7ed55ffe5dc35eba514b87ca281947 | 35f09d5668acfc2d91d4293b653bd9ea4c70d128 | |||
v1.0 | instruct | Filter | Filter_7073_I | I have been learning about machine learning and this is my first project to classify a dataset using k-NN algorithm. I'd like to ask for help in implementing it.
Here is the code I have:
```python
import numpy as np
def euclidean_distance(x, y):
return np.sqrt(np.sum((x - y) ** 2))
def k_nearest_neighbors(train... | import numpy as np
def euclidean_distance(x, y):
return np.sqrt(np.sum((x - y) ** 2))
def k_nearest_neighbors(train_data, train_labels, test_data, k):
predictions = []
for test_example in test_data:
# Find distances between test example and all train examples
distances = [euclidean_distanc... | import numpy as np
from solution import euclidean_distance, k_nearest_neighbors
def test_euclidean_distance():
assert euclidean_distance(np.array([1, 2]), np.array([1, 2])) == 0
assert euclidean_distance(np.array([1, 2]), np.array([4, 6])) == 5
assert np.isclose(euclidean_distance(np.array([1, 2]), np.arra... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(x, y):",
"function_name": "euclidean_distance",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def k_nearest_neighbors(train_data, train_labels, test_data, k):",
"function_name": "k_near... | [
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 euclidean_distance(x, y):\n return np.sqrt(np.sum((x - y) ** 2))\n\ndef k_nearest_neighbors(train_data, train_labels, test_data, k):\n predictions = []\n for... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007073",
"row_id": 7073,
"seed_ids": "['Llama-3.3-70B-Instruct_20358']"
} | 0.61912 | Filter_7073 | I | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 7dd5bc89a538fca8141ad275e206584474b261bc | f56e0fc6d6943991b36c09bb260a07c482fbc260 | |||
v1.0 | instruct | Filter | Filter_7077_I | In the first example, the tool is helping to find the closest pair of points, and in the second example, the tool is helping to find the closest pair of points in a set of points, with the additional restriction that the points must be from different clusters. So the restriction is not just about the points being in a ... | from math import sqrt
from itertools import product
def euclidean_distance(point1, point2):
"""
Calculates the Euclidean distance between two points in 2D space.
"""
return sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def closest_pair_between_clusters(cluster1, cluster2):
"""
... | from solution import euclidean_distance, closest_pair_between_clusters
def test_euclidean_distance_same_points():
assert euclidean_distance((0, 0), (0, 0)) == 0
def test_euclidean_distance_different_points():
assert euclidean_distance((0, 0), (3, 4)) == 5
def test_closest_pair_between_clusters_basic():
c... | [
{
"docstring": "Calculates 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": "Finds the closest pair of points between two c... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import sqrt\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n Points are represented as tuples (x, y).\n \"\"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007077",
"row_id": 7077,
"seed_ids": "['Llama-3.3-70B-Instruct_20366']"
} | 0.496015 | Filter_7077 | I | [
"euclidean_distance",
"closest_pair_between_clusters"
] | 2 | [
[
"closest_pair_between_clusters",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac84e337915660c177fa96f5415d692c5ce7f4e1 | fa6f96b0dcfcde74ac897d4e54618dadb7285544 | |||
v1.0 | instruct | Filter | Filter_7091_I | I have a long list of students in a CSV file. I need to iterate through the file, calculate the student's age, and output the student's age to a new CSV file.
Here is what my CSV file looks like:
```
"firstName","lastName","dateOfBirth"
"Alice","Johnson","1995-02-12"
"Billy","Smith","1993-07-25"
"Charlie","Brown","1... | import csv
from datetime import datetime
def calculate_age(birthdate):
"""
Calculate the age of a person given their birthdate.
:param birthdate: A string representing the birthdate in YYYY-MM-DD format.
:return: Integer age.
"""
birthdate = datetime.strptime(birthdate, '%Y-%m-%d')
today = ... | import csv
import os
from solution import calculate_age, process_students
def test_calculate_age():
assert calculate_age('2000-01-01') == datetime.today().year - 2000
assert calculate_age('2010-12-31') == datetime.today().year - 2011
assert calculate_age('1995-01-01') == datetime.today().year - 1995
def t... | [
{
"docstring": "Calculate the age of a person given their birthdate.\n:param birthdate: A string representing the birthdate in YYYY-MM-DD format.\n:return: Integer age.",
"function_declaration": "def calculate_age(birthdate):",
"function_name": "calculate_age",
"parameter_list": "(birthdate)"
},
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nfrom datetime import datetime\n\ndef calculate_age(birth_date):\n \"\"\"\n Calculate the age of a person given their birth date.\n :param birth_date: A string representing... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007091",
"row_id": 7091,
"seed_ids": "['Llama-3.3-70B-Instruct_20390']"
} | 0.579139 | Filter_7091 | I | [
"calculate_age",
"process_students"
] | 2 | [
[
"process_students",
"calculate_age"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b6588ce74d78d576a9bb254cc0c1494685c6b00c | a1413b55ae6edbc694b7a771951bd12b4e3765e8 | |||
v1.0 | instruct | Filter | Filter_7092_I | Here is code in python that uses the k-means algorithm to find clusters of data points, but it doesn't work correctly.
```python
import numpy as np
def initialize_centroids(data, K):
indices = np.random.choice(data.shape[0], K, replace=False)
centroids = data[indices]
return centroids
def assign_cluster... | import numpy as np
def initialize_centroids(data, K):
indices = np.random.choice(data.shape[0], K, replace=False)
centroids = data[indices]
return centroids
def assign_clusters(data, centroids):
distances = np.sqrt(np.sum((data[:, np.newaxis] - centroids) ** 2, axis=2))
cluster_assignments = np.ar... | import numpy as np
from solution import initialize_centroids, assign_clusters, update_centroids, kmeans
def test_initialize_centroids():
data = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
K = 2
centroids = initialize_centroids(data, K)
assert centroids.shape == (K, data.shape[1])
def... | [
{
"docstring": null,
"function_declaration": "def initialize_centroids(data, K):",
"function_name": "initialize_centroids",
"parameter_list": "(data, K)"
},
{
"docstring": null,
"function_declaration": "def assign_clusters(data, centroids):",
"function_name": "assign_clusters",
"... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_centroids(data, K):\n indices = np.random.choice(data.shape[0], K, replace=False)\n centroids = data[indices]\n return centroids\n\ndef assign_clu... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007092",
"row_id": 7092,
"seed_ids": "['Llama-3.3-70B-Instruct_20392']"
} | 0.780849 | Filter_7092 | I | [
"initialize_centroids",
"assign_clusters",
"update_centroids",
"kmeans"
] | 4 | [
[
"kmeans",
"assign_clusters"
],
[
"kmeans",
"initialize_centroids"
],
[
"kmeans",
"update_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 6526471e1ef5f8ede6372392dfd3a38ca6954dad | 08e3a3df35b072b24e0c3b1981be9edee591a491 | |||
v1.0 | instruct | Filter | Filter_7107_I | I wrote a program that counts the number of inversions in a list of integers. The code is as follows:
```python
def count_inversions(lst):
if len(lst) <= 1:
return lst, 0
else:
mid = len(lst) // 2
left, inv_left = count_inversions(lst[:mid])
right, inv_right = count_inversions(l... | def count_inversions(lst):
"""
Counts the number of inversions in the given list of integers.
An inversion is a pair (i, j) such that i < j and lst[i] > lst[j].
Parameters:
lst (list of int): The list of integers.
Returns:
tuple: A tuple (sorted_list, number_of_inversions)
... | from solution import count_inversions, merge_and_count
def test_sorted_array():
assert count_inversions([1, 2, 3, 4, 5]) == ([1, 2, 3, 4, 5], 0)
def test_reverse_sorted_array():
assert count_inversions([5, 4, 3, 2, 1]) == ([1, 2, 3, 4, 5], 10)
def test_random_array():
assert count_inversions([2, 4, 1, 3,... | [
{
"docstring": "Counts the number of inversions in the given list of integers.\n\nAn inversion is a pair (i, j) such that i < j and lst[i] > lst[j].\n\nParameters:\nlst (list of int): The list of integers.\n\nReturns:\ntuple: A tuple (sorted_list, number_of_inversions)",
"function_declaration": "def count_i... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_inversions(lst):\n \"\"\"\n Returns a sorted version of the list and the count of inversions found in the list.\n \"\"\"\n if len(lst) <= 1:\n return lst, 0\n e... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007107",
"row_id": 7107,
"seed_ids": "['Llama-3.3-70B-Instruct_20418']"
} | 0.724841 | Filter_7107 | I | [
"count_inversions",
"merge_and_count"
] | 2 | [
[
"count_inversions",
"merge_and_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f1bdbec1c6015761c63719339fb500ed5ab56206 | b317abd8ab0425349a4da8ad0ea908c51e9e52f7 | |||
v1.0 | instruct | Filter | Filter_7111_I | You need to write a code for a rock, paper, scissors game in python. The game will have the following rules:
- The game will be played between two players.
- The game will be played for a best of three rounds.
- The player who wins two rounds first wins the game.
- The players will input their moves via the console.
H... | def determine_winner(move1, move2):
"""Determine the winner of a round"""
if move1 == move2:
return "tie"
if (move1 == "rock" and move2 == "scissors") or \
(move1 == "paper" and move2 == "rock") or \
(move1 == "scissors" and move2 == "paper"):
return "player1"
return "playe... | from solution import determine_winner, is_valid_move
def test_determine_winner():
assert determine_winner("rock", "scissors") == "player1"
assert determine_winner("paper", "rock") == "player1"
assert determine_winner("scissors", "paper") == "player1"
assert determine_winner("rock", "paper") == "player2... | [
{
"docstring": "Determine the winner of a round",
"function_declaration": "def determine_winner(move1, move2):",
"function_name": "determine_winner",
"parameter_list": "(move1, move2)"
},
{
"docstring": "Check if the move is valid",
"function_declaration": "def is_valid_move(move):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def determine_winner(move1, move2):\n \"\"\"Determine the winner of a round\"\"\"\n if move1 == move2:\n return \"tie\"\n if (move1 == \"rock\" and move2 == \"scissors\") or \\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007111",
"row_id": 7111,
"seed_ids": "['Llama-3.3-70B-Instruct_20430']"
} | 0.54385 | Filter_7111 | I | [
"determine_winner",
"is_valid_move",
"game"
] | 3 | [
[
"game",
"determine_winner"
],
[
"game",
"is_valid_move"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3402abf4d17b80fe5ec61f57a52d7ca938f62dd9 | 02da4c50fedd69807cb21ca4c9f58068499e0b39 | |||
v1.0 | instruct | Filter | Filter_7123_I | Here's what I have so far:
```python
import math
def calculate_distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def calculate_area_of_triangle(point1, point2, point3):
a = calculate_distance(point1, point2)
b = calculate_distance(point2, point... | import math
def calculate_distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def calculate_area_of_triangle(point1, point2, point3):
a = calculate_distance(point1, point2)
b = calculate_distance(point2, point3)
c = calculate_distance(point3,... | from solution import calculate_distance, calculate_area_of_triangle
def test_calculate_distance():
assert calculate_distance((0, 0), (3, 4)) == 5
assert calculate_distance((0, 0), (0, 0)) == 0
assert calculate_distance((-1, -1), (-4, -5)) == 5
def test_calculate_area_of_triangle():
assert calculate_ar... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def calculate_area_of_triangle(point1, point2, point3):",
"function_nam... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef calculate_distance(point1, point2):\n x1, y1 = point1\n x2, y2 = point2\n return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\n\ndef calculate_area_of_triangle(point1, po... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007123",
"row_id": 7123,
"seed_ids": "['Llama-3.3-70B-Instruct_20466']"
} | 0.610857 | Filter_7123 | I | [
"calculate_distance",
"calculate_area_of_triangle",
"main"
] | 3 | [
[
"calculate_area_of_triangle",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae55e101ee8b43ad04fd7900a66ce2eb8212a6e4 | 1fe9997056b4171d5572885595dc059eb26a5fa5 | |||
v1.0 | instruct | Filter | Filter_7142_I | I'm trying to write a lisp-like language and I could see that the 'eval' function in lisp is implemented in a way that treats lists and atoms as a basic data-type, how does a typical lisp reader or parser know how to treat a string of characters as either a symbol, string, integer, or list, without having a separate le... | def parse_lisp_expr(expr):
"""
Parses a Lisp expression and returns tuple of (type, value).
- 'symbol': for symbols like 'x', 'foo'
- 'integer': for integers like '123', '-456'
- 'string': for strings like '"hello"'
- 'list': for lists like '(1 2 3)', '(foo (bar))'
"""
expr = expr.strip(... | from solution import parse_lisp_expr
def test_parse_symbol():
assert parse_lisp_expr('x') == ('symbol', 'x')
assert parse_lisp_expr('foo') == ('symbol', 'foo')
def test_parse_integer():
assert parse_lisp_expr('123') == ('integer', 123)
assert parse_lisp_expr('-456') == ('integer', -456)
def test_pars... | [
{
"docstring": "Parses a Lisp expression and returns tuple of (type, value).\n- 'symbol': for symbols like 'x', 'foo'\n- 'integer': for integers like '123', '-456'\n- 'string': for strings like '\"hello\"'\n- 'list': for lists like '(1 2 3)', '(foo (bar))'",
"function_declaration": "def parse_lisp_expr(expr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def parse_lisp_expr(expr):\n \"\"\"\n Parses a Lisp expression and returns tuple of (type, value).\n - 'symbol': for symbols like 'x', 'foo'\n - 'integer': for integers like '123',... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007142",
"row_id": 7142,
"seed_ids": "['Llama-3.3-70B-Instruct_20506']"
} | 0.386834 | Filter_7142 | I | [
"parse_lisp_expr",
"parse_list"
] | 2 | [
[
"parse_lisp_expr",
"parse_list"
],
[
"parse_list",
"parse_lisp_expr"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 113bf76cd033797de5c4b8b776462099029a3ad4 | e1fe6c3bedb213ca6b91a89dd0d3017a06847083 | |||
v1.0 | instruct | Filter | Filter_7151_I | I have a list of words and I need to find all pairs of words that have the same number of vowels. I'm not using this for any production code but just for learning purposes.
Here's a list of words for example:
dog, cat, house, bird, elephant, car, boat
I want to get all pairs of words with the same number of vowels.... | def count_vowels(word):
"""
Returns the number of vowels in the given word.
"""
return sum(1 for char in word.lower() if char in 'aeiou')
def find_pairs_with_same_vowels(words):
"""
Returns all pairs of words that have the same number of vowels.
Parameters:
words (list): List of wo... | from solution import count_vowels, find_pairs_with_same_vowels
def test_count_vowels():
assert count_vowels('dog') == 1
assert count_vowels('cat') == 1
assert count_vowels('house') == 3
assert count_vowels('bird') == 1
assert count_vowels('car') == 1
assert count_vowels('boat') == 2
assert ... | [
{
"docstring": "Returns the number of vowels in the given word.",
"function_declaration": "def count_vowels(word):",
"function_name": "count_vowels",
"parameter_list": "(word)"
},
{
"docstring": "Returns all pairs of words that have the same number of vowels.\n\nParameters:\nwords (list): Li... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_vowels(word):\n \"\"\"\n Returns the number of vowels in a given word.\n \"\"\"\n return sum(1 for char in word.lower() if char in 'aeiou')\n\ndef find_pairs_same_vowels(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007151",
"row_id": 7151,
"seed_ids": "['Llama-3.3-70B-Instruct_20537']"
} | 0.664696 | Filter_7151 | I | [
"count_vowels",
"find_pairs_with_same_vowels"
] | 2 | [
[
"find_pairs_with_same_vowels",
"count_vowels"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 083891b1a2a117571c5c41c7f103f08e5e9d5e55 | f469898afac38dad9ee13cc0d93de659b3be7258 | |||
v1.0 | instruct | Filter | Filter_7163_I | I'm looking to create a simple chat application using a client-server model. The server should be able to handle multiple clients and be able to send messages to all connected clients. | import socket
import threading
# Global list to keep track of connected clients
clients = []
def broadcast_message(message, exclude_client=None):
"""
Send a message to all connected clients.
"""
for client in clients:
if client != exclude_client:
client.send(message)
def handle_cl... | import socket
from threading import Thread
import time
from solution import start_server, broadcast_message, clients
# Auxiliary function to simulate a client
def simulate_client(host, port, messages, responses):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, po... | [
{
"docstring": "Send a message to all connected clients.",
"function_declaration": "def broadcast_message(message, exclude_client=None):",
"function_name": "broadcast_message",
"parameter_list": "(message, exclude_client=None)"
},
{
"docstring": "Handle communication with a connected client.... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport threading\n\n# Global list to keep track of connected clients\nclients = []\n\ndef broadcast_message(message, exclude_client=None):\n \"\"\"\n Send a message to all... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007163",
"row_id": 7163,
"seed_ids": "['Llama-3.3-70B-Instruct_20558']"
} | 0.388433 | Filter_7163 | I | [
"broadcast_message",
"handle_client",
"start_server"
] | 3 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 062987229d9df304872cfad49c3b7e7692c8c4ca | 19b0f0505959aeb2178af2ab55e03b42fd2674cf | |||
v1.0 | instruct | Filter | Filter_7196_I | I see that you have an understanding of the Python language. I'm having some trouble with understanding and implementing the Radix Sort algorithm. Would you be able to explain it in a way that makes sense and provide a Python implementation? | def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
... | from solution import radix_sort
def test_radix_sort():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
radix_sort(arr)
assert arr == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_with_duplicates():
arr = [3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0]
radix_sort(arr)
assert arr == [0, 0, 0, 1, 1, 2, 3... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n \n output = [0] * n\n count = [0] * 10\n \n for i in range(n):\n index = arr[i] // exp\n count[index % 10] += 1\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007196",
"row_id": 7196,
"seed_ids": "['Llama-3.3-70B-Instruct_20634']"
} | 0.585127 | Filter_7196 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 097bf20e82350ab792ca59884078d253e6598cab | 52a205220f48a9f0fe25882b107d7f41573191e7 | |||
v1.0 | instruct | Filter | Filter_7208_I | I have been developing a algorithm and I want to convert it to a GUI application. I'd like your help with this.
What are the best practices for converting command line application to GUI application?
Also, some part of my algorithm will be computationally expensive. How can I use multi-threading/multi-processing fo... | import tkinter as tk
from tkinter import messagebox
from threading import Thread
import numpy as np
def find_max(array):
return np.max(array)
# Function to be run in a separate thread
def compute_max_value(array, result_label):
max_val = find_max(array)
result_label.config(text=f"Max Value: {max_val}")
... | from solution import find_max
def test_find_max():
assert find_max(np.array([1, 2, 3, 4, 5])) == 5
assert find_max(np.array([-10, -5, 0, 5, 10])) == 10
assert find_max(np.array([100, 200, 300])) == 300
assert find_max(np.array([1])) == 1
def test_find_max_with_negative_numbers():
assert find_max(n... | [
{
"docstring": null,
"function_declaration": "def find_max(array):",
"function_name": "find_max",
"parameter_list": "(array)"
},
{
"docstring": null,
"function_declaration": "def compute_max_value(array, result_label):",
"function_name": "compute_max_value",
"parameter_list": "(a... | [
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 tkinter as tk\nfrom tkinter import messagebox\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef find_max(array):\n return np.max(array)\n\ndef on_find_max... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007208",
"row_id": 7208,
"seed_ids": "['Llama-3.3-70B-Instruct_20652']"
} | 0.326511 | Filter_7208 | I | [
"find_max",
"compute_max_value",
"start_computation",
"create_gui"
] | 4 | [
[
"compute_max_value",
"find_max"
],
[
"create_gui",
"start_computation"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 4c2da49184254eedb7184bd446a9242bf933c17d | ec870309596371c3fcdf73984f16329100093507 | |||
v1.0 | instruct | Filter | Filter_7219_I | Can you write a code snippet that prints all the prime numbers in a given range using Python? | def is_prime(n):
"""
Check if a number is a prime number.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def primes_in_range(start, end):
"""
Returns a list of all prime numbers in the given range [star... | from solution import is_prime, primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(0) == False
assert is_prime(1) == False
assert is_prime(13) == True
assert is_prime(15) == Fal... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers in the given range [start, end].",
"function_declaration": "def primes_in_range(s... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True # 2 and 3 are pr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007219",
"row_id": 7219,
"seed_ids": "['Llama-3.3-70B-Instruct_20687']"
} | 0.691568 | Filter_7219 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c5cb769bc51bbd4b54601561b2c8e1f6461aa3ae | c113cb97a7f9648db337cca246af1ade23ddd572 | |||
v1.0 | instruct | Filter | Filter_7221_I | I've been given a task to write a program in Python that can encrypt and decrypt messages using a Caesar cipher. The Caesar cipher is one of the earliest known and simplest encryption techniques. It is a type of substitution cipher where each letter in the plaintext is 'shifted' a certain number of places down the alph... | def caesar_cipher_encrypt(text, shift):
"""
Encrypts the given text using Caesar cipher with the specified shift.
"""
encrypted_text = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
if char.islower():
start = ord('a')
els... | from solution import caesar_cipher_encrypt, caesar_cipher_decrypt
def test_caesar_cipher_encrypt():
assert caesar_cipher_encrypt("abc", 1) == "bcd"
assert caesar_cipher_encrypt("xyz", 3) == "abc"
assert caesar_cipher_encrypt("Abc", 1) == "Bcd"
assert caesar_cipher_encrypt("abc XYZ", 1) == "bcd YZA"
... | [
{
"docstring": "Encrypts the given text using Caesar cipher with the specified shift.",
"function_declaration": "def caesar_cipher_encrypt(text, shift):",
"function_name": "caesar_cipher_encrypt",
"parameter_list": "(text, shift)"
},
{
"docstring": "Decrypts the given text using Caesar ciphe... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def caesar_cipher_encrypt(message, shift):\n \"\"\"\n Encrypts the input message using the Caesar cipher technique.\n \n :param message: The message to encrypt (a string).\n :pa... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007221",
"row_id": 7221,
"seed_ids": "['Llama-3.3-70B-Instruct_20689']"
} | 0.654296 | Filter_7221 | I | [
"caesar_cipher_encrypt",
"caesar_cipher_decrypt"
] | 2 | [
[
"caesar_cipher_decrypt",
"caesar_cipher_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 044239fc98abc2e19126a82cc9f4f94129b8f9c3 | 07bd0438beac219c12503e39011f33e813430542 | |||
v1.0 | instruct | Filter | Filter_7236_I | I am trying to write a function that will find all the prime numbers within a certain range and return them. I was thinking about using recursion but I am not sure if it is the best way to solve this problem.
I can use the following functions:
- `is_prime(n)` which checks if a number is prime
- `range(a, b)` which r... | def is_prime(n):
"""
Checks if the number n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import is_prime, find_primes_in_range
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert not is_prime(0)
assert not is_prime(-1)
assert is_prime(29) # prime number
assert not is_prime(30) ... | [
{
"docstring": "Checks if the number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers in the range from a to b (not inclusive).",
"function_declaration": "def fin... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007236",
"row_id": 7236,
"seed_ids": "['Llama-3.3-70B-Instruct_20730']"
} | 0.568675 | Filter_7236 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31e11b63c95fc757cd9c79810011d6e78ac5b3ec | aa33a96d5dc35c80122ef7c73e2c0adb5eb1bf39 | |||
v1.0 | instruct | Filter | Filter_7263_I | Based on the following code, write a new function that takes a dictionary as input and returns the average of its values.
```python
def get_sum_of_values(dictionary):
total = 0
for key, value in dictionary.items():
total += value
return total
def get_average_of_values(dictionary):
total = get_s... | def get_sum_of_values(dictionary):
total = 0
for key, value in dictionary.items():
total += value
return total
def get_average_of_values(dictionary):
total = get_sum_of_values(dictionary)
count = len(dictionary)
average = total / count if count > 0 else 0
return average | import pytest
from solution import get_sum_of_values, get_average_of_values
def test_get_sum_of_values():
assert get_sum_of_values({'a': 1, 'b': 2, 'c': 3}) == 6
assert get_sum_of_values({'a': -1, 'b': -2, 'c': -3}) == -6
assert get_sum_of_values({'a': 0, 'b': 0, 'c': 0}) == 0
assert get_sum_of_values(... | [
{
"docstring": null,
"function_declaration": "def get_sum_of_values(dictionary):",
"function_name": "get_sum_of_values",
"parameter_list": "(dictionary)"
},
{
"docstring": null,
"function_declaration": "def get_average_of_values(dictionary):",
"function_name": "get_average_of_values"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_sum_of_values(dictionary):\n total = 0\n for key, value in dictionary.items():\n total += value\n return total\n\ndef get_average_of_values(dictionary):\n total = ge... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007263",
"row_id": 7263,
"seed_ids": "['Llama-3.3-70B-Instruct_20790']"
} | 0.57655 | Filter_7263 | I | [
"get_sum_of_values",
"get_average_of_values"
] | 2 | [
[
"get_average_of_values",
"get_sum_of_values"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e71da5bf4d03df3c3a772488b9f6eec1ab00710 | 1c0b4b78a8ff871025089ddf67dfb8161843cb94 | |||
v1.0 | instruct | Filter | Filter_7268_I | Create a code that simulates a rock, paper, scissors game between two players. The players can choose one of rock, paper, or scissors each round. The game will continue until one player reaches a score of 3. | import random
def play_round(player1_choice, player2_choice):
"""
Simulates a round of rock, paper, scissors between two players.
Returns:
1 if player1 wins,
2 if player2 wins,
0 if it's a tie
"""
outcomes = {
('rock', 'scissors'): 1,
('scissors', 'paper'): 1... | from solution import play_round, rock_paper_scissors
def test_play_round_tie():
assert play_round('rock', 'rock') == 0
assert play_round('paper', 'paper') == 0
assert play_round('scissors', 'scissors') == 0
def test_play_round_win():
assert play_round('rock', 'scissors') == 1
assert play_round('sc... | [
{
"docstring": "Simulates a round of rock, paper, scissors between two players.\nReturns:\n 1 if player1 wins,\n 2 if player2 wins,\n 0 if it's a tie",
"function_declaration": "def play_round(player1_choice, player2_choice):",
"function_name": "play_round",
"parameter_list": "(player1_choic... | [
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 rock_paper_scissors(player1_choice, player2_choice):\n \"\"\"\n Simulates a single round of rock, paper, scissors.\n Returns the result of the round as 'Player 1 ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007268",
"row_id": 7268,
"seed_ids": "['Llama-3.3-70B-Instruct_20803']"
} | 0.545385 | Filter_7268 | I | [
"play_round",
"rock_paper_scissors"
] | 2 | [
[
"rock_paper_scissors",
"play_round"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2f74aba15e78ba5864fbd77d40ee273d3b0a2134 | 973c6ee25c5ffbc5bd67f7d1828873e6122cf505 | |||
v1.0 | instruct | Filter | Filter_7281_I | I have an algorithm that generates an approximate solution to a given optimization problem. However, the algorithm is sensitive to the initial conditions. Therefore, I want to run the algorithm multiple times with different initial conditions and keep track of the best solution found so far.
I am using Python. How wo... | import random
def algorithm(initial_condition):
"""
This function represents the algorithm which generates an approximate solution
to an optimization problem based on the provided initial condition.
For the sake of this example, let's assume it simply returns a computed value.
"""
random.... | from solution import algorithm, run_multiple_times
def test_algorithm_returns_value():
# Check if the algorithm returns a float value within a specified range
value = algorithm(10)
assert isinstance(value, float)
assert 0 <= value <= 100
def test_run_multiple_times_best_solution():
# Test with kno... | [
{
"docstring": "This function represents the algorithm which generates an approximate solution \nto an optimization problem based on the provided initial condition.\n\nFor the sake of this example, let's assume it simply returns a computed value.",
"function_declaration": "def algorithm(initial_condition):"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef optimization_algorithm(initial_condition):\n \"\"\"\n Example optimization algorithm which takes an initial condition \n and returns a pseudo-random \"optimized\"... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007281",
"row_id": 7281,
"seed_ids": "['Llama-3.3-70B-Instruct_20829']"
} | 0.397452 | Filter_7281 | I | [
"algorithm",
"run_multiple_times"
] | 2 | [
[
"run_multiple_times",
"algorithm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f9b2dc053f3b60f05853bbc90b5dc8194ba93a98 | 2840a53faa0d88fcacd442f367ed52792be9ed22 | |||
v1.0 | instruct | Filter | Filter_7304_I | I have a Python script that simulates a simplified version of the popular game Hangman. The current implementation allows the user to guess a letter, and if the letter is in the word, it gets revealed, otherwise the hangman figure gets drawn. However, I'm struggling to implement a scoring system. My goal is to award th... | import random
HANGMAN_PICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O ... | from solution import calculateScore
def test_calculateScore_no_misses():
assert calculateScore(0, 5) == 50
def test_calculateScore_some_misses():
assert calculateScore(3, 6) == 54
def test_calculateScore_many_misses():
assert calculateScore(10, 8) == 60
def test_calculateScore_score_not_negative():
... | [
{
"docstring": null,
"function_declaration": "def getRandomWord(wordList):",
"function_name": "getRandomWord",
"parameter_list": "(wordList)"
},
{
"docstring": null,
"function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):",
"function_name":... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007304",
"row_id": 7304,
"seed_ids": "['Llama-3.3-70B-Instruct_20876']"
} | 0.594702 | Filter_7304 | I | [
"getRandomWord",
"displayBoard",
"getGuess",
"playAgain",
"calculateScore",
"runHangman"
] | 6 | [
[
"runHangman",
"calculateScore"
],
[
"runHangman",
"displayBoard"
],
[
"runHangman",
"getGuess"
],
[
"runHangman",
"getRandomWord"
],
[
"runHangman",
"playAgain"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 544cae801d7720bb5e5feadb65f6614828b2c809 | cd98862589d3ebc2edfbfb4086772b066de5152b | |||
v1.0 | instruct | Filter | Filter_7339_I | I have a list of researchers in a field, and I'd like to make a web scraping script in Python to collect the publication data (e.g., title, authors, publication date, journal) for each researcher from Google Scholar.
My goal is to get an output that looks like this:
```
{
"researcher1": [
{"title": "Paper... | import requests
from bs4 import BeautifulSoup
import re
def get_publication_data(researcher_name):
search_url = f"https://scholar.google.com/scholar?hl=en&q={'+'.join(researcher_name.split())}"
response = requests.get(search_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'htm... | from solution import get_publication_data, scrape_researchers_publications
def test_get_publication_data():
# This is a hypothetical test since actual web scraping results may vary every time.
researcher_name = "John Doe"
publications = get_publication_data(researcher_name)
assert isinstance(publicati... | [
{
"docstring": null,
"function_declaration": "def get_publication_data(researcher_name):",
"function_name": "get_publication_data",
"parameter_list": "(researcher_name)"
},
{
"docstring": null,
"function_declaration": "def process_authors_journal(authors_journal_text):",
"function_na... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom bs4 import BeautifulSoup\nimport time\n\ndef fetch_publications_for_researcher(researcher_name):\n \"\"\"\n Fetch publications data for a given researcher from Goog... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007339",
"row_id": 7339,
"seed_ids": "['Llama-3.3-70B-Instruct_20956']"
} | 0.536922 | Filter_7339 | I | [
"get_publication_data",
"process_authors_journal",
"scrape_researchers_publications"
] | 3 | [
[
"get_publication_data",
"process_authors_journal"
],
[
"scrape_researchers_publications",
"get_publication_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | f80ee7344493a271a303fc8fbe3a51ed70294ef0 | 43978b89fbc4340d998431d948319f97d5bd9a65 | |||
v1.0 | instruct | Filter | Filter_7342_I | Create a code snippet that calculates the dot product of two vectors. This code should have the following properties:
- The vectors should have the same length.
- The vectors should only contain integers.
- The error checking should be done by a separate function.
The code should be a function named `calculate_dot_pro... | def error_check(vector1, vector2):
"""
Check if both vectors have the same length and contain only integers.
"""
if len(vector1) != len(vector2):
return False
for v in vector1 + vector2:
if not isinstance(v, int):
return False
return True
def calculate_dot_prod... | from solution import calculate_dot_product, error_check
def test_error_check_valid_input():
assert error_check([1, 2, 3], [4, 5, 6]) == True
def test_error_check_different_lengths():
assert error_check([1, 2], [1, 2, 3]) == False
def test_error_check_non_integer_elements():
assert error_check([1, 2, 'a']... | [
{
"docstring": "Check if both vectors have the same length and contain only integers.",
"function_declaration": "def error_check(vector1, vector2):",
"function_name": "error_check",
"parameter_list": "(vector1, vector2)"
},
{
"docstring": "Calculate the dot product of two vectors.",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def error_check(vector1, vector2):\n \"\"\"\n Checks if the input vectors are valid for dot product calculation.\n Vectors must:\n - Be of the same length\n - Contain only integ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007342",
"row_id": 7342,
"seed_ids": "['Llama-3.3-70B-Instruct_20960']"
} | 0.53052 | Filter_7342 | I | [
"error_check",
"calculate_dot_product"
] | 2 | [
[
"calculate_dot_product",
"error_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 96ccec0656f3163310e023f05116c80add177780 | 7147a12dabc0c631ff5776421ddc65643abcd7c1 | |||
v1.0 | instruct | Filter | Filter_7378_I | I have created a simple board game where players take turns rolling a dice and moving their piece around the board. The first player to reach the end of the board wins. If a player lands on a space that has already been occupied by another player, the player who landed on the space is sent back to the start.
I need t... | import random
def roll_dice():
return random.randint(1, 6)
def move_player(player, positions, board_size):
positions[player] += roll_dice()
if positions[player] >= board_size:
positions[player] = board_size
return True
return False
def check_collision(positions, current_player):
f... | from solution import roll_dice, move_player, check_collision, game_loop
def test_roll_dice():
outcomes = [roll_dice() for _ in range(100)]
for outcome in outcomes:
assert 1 <= outcome <= 6
def test_move_player():
positions = {1: 0, 2: 0}
random.seed(0) # Setting the seed for deterministic beh... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def move_player(player, positions, board_size):",
"function_name": "move_player",
"parameter_list": "(player, pos... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n return random.randint(1, 6)\n\ndef move_player(player_position, roll, board_length):\n new_position = player_position + roll\n if new_position >= b... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007378",
"row_id": 7378,
"seed_ids": "['Llama-3.3-70B-Instruct_21038']"
} | 0.409981 | Filter_7378 | I | [
"roll_dice",
"move_player",
"check_collision",
"game_loop"
] | 4 | [
[
"game_loop",
"check_collision"
],
[
"game_loop",
"move_player"
],
[
"move_player",
"roll_dice"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | eba320762054e260e0cd1224f827ea6f5f5e0cbd | 7dd816cc8c011cfb1174f25583ec595cee2183ff | |||
v1.0 | instruct | Filter | Filter_7395_I | ### Overview of Project
This project involves developing a simple web application using the Flask web framework. The web application will take a string input from the user and output the number of vowels in the given string.
### Tasks
1. **Develop the web application**: Create a basic web application using Flask that ... | from flask import Flask, request, render_template_string
app = Flask(__name__)
def count_vowels(s):
"""
Returns the number of vowels in the input string s.
"""
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)
@app.route('/', methods=['GET', 'POST'])
def index():
vowel_count... | from solution import count_vowels
def test_count_vowels_all_vowels():
assert count_vowels("aeiou") == 5
assert count_vowels("AEIOU") == 5
def test_count_vowels_mixed_chars():
assert count_vowels("hello world") == 3
assert count_vowels("Python Programming") == 4
def test_count_vowels_no_vowels():
... | [
{
"docstring": "Returns the number of vowels in the input string s.",
"function_declaration": "def count_vowels(s):",
"function_name": "count_vowels",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list... | [
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, render_template_string\n\napp = Flask(__name__)\n\ndef count_vowels(s):\n \"\"\"\n Returns the number of vowels in the input string s.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007395",
"row_id": 7395,
"seed_ids": "['Llama-3.3-70B-Instruct_21075']"
} | 0.743767 | Filter_7395 | I | [
"count_vowels",
"index"
] | 2 | [
[
"index",
"count_vowels"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 22ebdeb59ccaf8f90407633391a759ed7f269b64 | ea06c3cad53772b8d20b03ba66654429226f38df | |||
v1.0 | instruct | Filter | Filter_7419_I | Consider the matrix A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], find the sum of the elements in the main diagonal.
Here is the code to calculate the sum:
```
def get_diagonal_sum(A):
n = len(A)
sum = 0
for i in range(n):
sum += A[i][i]
return sum
```
However the code does not handle the case when th... | def is_square_matrix(A):
n = len(A)
for row in A:
if len(row) != n:
return False
return True
def get_diagonal_sum(A):
if not is_square_matrix(A):
raise ValueError("Input is not a square matrix")
n = len(A)
diagonal_sum = 0
for i in range(n):
diagonal_sum ... | from solution import get_diagonal_sum, is_square_matrix
def test_is_square_matrix():
assert is_square_matrix([[1, 2], [3, 4]]) == True
assert is_square_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == True
assert is_square_matrix([[1, 2], [3, 4, 5]]) == False
assert is_square_matrix([[1, 2, 3], [4, 5, 6]])... | [
{
"docstring": null,
"function_declaration": "def is_square_matrix(A):",
"function_name": "is_square_matrix",
"parameter_list": "(A)"
},
{
"docstring": null,
"function_declaration": "def get_diagonal_sum(A):",
"function_name": "get_diagonal_sum",
"parameter_list": "(A)"
}
] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_square_matrix(A):\n n = len(A)\n for row in A:\n if len(row) != n:\n return False\n return True\n\ndef get_diagonal_sum(A):\n if not is_square_matrix(A):\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007419",
"row_id": 7419,
"seed_ids": "['Llama-3.3-70B-Instruct_21133']"
} | 0.560801 | Filter_7419 | I | [
"is_square_matrix",
"get_diagonal_sum"
] | 2 | [
[
"get_diagonal_sum",
"is_square_matrix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7ec0ecd84b16886b947c8e55ef98b26de5e46ec4 | 01d24d60ff87d7fccff59eb24d41582c332ace74 | |||
v1.0 | instruct | Filter | Filter_7420_I | I've been given two functions in Python:
```python
def function1(a, b):
return a + b
def function2(x, y):
return x * y
```
I want to apply these functions to two separate lists of numbers. How can I use the `map()` function to do this? | def function1(a, b):
return a + b
def function2(x, y):
return x * y
def apply_function1_to_lists(list1, list2):
"""
Applies function1 to elements of list1 and list2.
"""
return list(map(function1, list1, list2))
def apply_function2_to_lists(list1, list2):
"""
Applies function2 to elem... | from solution import function1, function2, apply_function1_to_lists, apply_function2_to_lists
def test_apply_function1_to_lists():
list1 = [1, 2, 3]
list2 = [4, 5, 6]
expected = [5, 7, 9]
assert apply_function1_to_lists(list1, list2) == expected
list1 = [0, 5, -3]
list2 = [0, 5, 3]
expecte... | [
{
"docstring": null,
"function_declaration": "def function1(a, b):",
"function_name": "function1",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def function2(x, y):",
"function_name": "function2",
"parameter_list": "(x, y)"
},
{
"docstring":... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def apply_function1_to_lists(list1, list2):\n \"\"\"\n Applies function1 to each pair of elements from list1 and list2 using map().\n \"\"\"\n return list(map(function1, list1, lis... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007420",
"row_id": 7420,
"seed_ids": "['Llama-3.3-70B-Instruct_21135']"
} | 0.558534 | Filter_7420 | I | [
"function1",
"function2",
"apply_function1_to_lists",
"apply_function2_to_lists"
] | 4 | [
[
"apply_function1_to_lists",
"function1"
],
[
"apply_function2_to_lists",
"function2"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 050cc835ae8a400b2632083c6d989b70f1d095df | a1858de2298d6a5c278f2f754b17cb61b2d99708 | |||
v1.0 | instruct | Filter | Filter_7425_I | I'm trying to create a simple, text-based Rock, Paper, Scissors game. In this game, user will be able to play against the computer. Here's what I've done so far:
```python
import random
def game():
while True:
user_choice = input("Enter a choice (rock, paper, scissors): ").lower()
while user_choic... | import random
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "tie"
elif user_choice == "rock":
return "win" if computer_choice == "scissors" else "lose"
elif user_choice == "paper":
return "win" if computer_choice == "rock" else "lose"
... | from solution import determine_winner
def test_determine_winner():
assert determine_winner("rock", "rock") == "tie"
assert determine_winner("rock", "scissors") == "win"
assert determine_winner("rock", "paper") == "lose"
assert determine_winner("paper", "paper") == "tie"
assert determine_winner("pa... | [
{
"docstring": null,
"function_declaration": "def determine_winner(user_choice, computer_choice):",
"function_name": "determine_winner",
"parameter_list": "(user_choice, computer_choice)"
},
{
"docstring": null,
"function_declaration": "def game():",
"function_name": "game",
"par... | [
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_computer_choice():\n possible_choices = [\"rock\", \"paper\", \"scissors\"]\n return random.choice(possible_choices)\n\ndef determine_winner(user_choice, compute... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007425",
"row_id": 7425,
"seed_ids": "['Llama-3.3-70B-Instruct_21141']"
} | 0.570614 | Filter_7425 | I | [
"determine_winner",
"game"
] | 2 | [
[
"game",
"determine_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 82169bc11920bd794d1f812658c482464a504999 | a8a2d67eddee66b0afa82b8e15dc0b3a30147260 | |||
v1.0 | instruct | Filter | Filter_7463_I | It seems like jupyter notebook relies on idleshell and idlesyntax. Do you think we can make a jupyter notebook-like application by using idleshell and idlesyntax, but without using ipython? | import tkinter as tk
from tkinter import scrolledtext
def execute_code(code, output_widget):
try:
exec(code, globals())
output_widget.insert(tk.END, '\nExecution succeeded.\n')
except Exception as e:
output_widget.insert(tk.END, f'\nError: {e}\n')
def create_notebook_app():
root = ... | from unittest.mock import Mock, patch
import tkinter as tk
import sys
@patch('tkinter.scrolledtext.ScrolledText')
@patch('tkinter.Button')
@patch('tkinter.Frame')
@patch('tkinter.Tk')
def test_create_notebook_app(mock_tk, mock_frame, mock_button, mock_scrolledtext):
# Setup mock objects
mock_root = Mock()
... | [
{
"docstring": null,
"function_declaration": "def execute_code(code, output_widget):",
"function_name": "execute_code",
"parameter_list": "(code, output_widget)"
},
{
"docstring": null,
"function_declaration": "def create_notebook_app():",
"function_name": "create_notebook_app",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\nfrom tkinter import scrolledtext\n\ndef execute_code(code, output_widget):\n try:\n exec(code, globals())\n output_widget.insert(tk.END, '\\nExecution su... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007463",
"row_id": 7463,
"seed_ids": "['Llama-3.3-70B-Instruct_21241']"
} | 0.324776 | Filter_7463 | I | [
"execute_code",
"create_notebook_app"
] | 2 | [
[
"create_notebook_app",
"execute_code"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5acbd3de45fc7d6d7ed4aacadf67fe80b24f5444 | c9517f3ffe61abe29ed44dbde3ac30555d05be9c | |||
v1.0 | instruct | Filter | Filter_7474_I | I have two input files:
file1:
0.01 0.01
0.01 0.1
0.01 0.5
0.01 1
0.1 0.01
0.1 0.1
0.1 0.5
0.1 1
0.5 0.01
0.5 0.1
0.5 0.5
0.5 1
1 0.01
1 0.1
1 0.5
1 1
file2:
0.01 1
0.1 1
0.5 1
1 1
I want to compare each line from file2 with all lines in file1 and calculate the Euclidean distance between the corresponding x and y coo... | import math
def calculate_distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def compare_files(file1_path, file2_path):
results = []
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
file1_lines = file1.readlines()
file2_lines = file2.readli... | import pytest
from solution import calculate_distance, compare_files
def test_calculate_distance():
assert calculate_distance(0, 0, 3, 4) == 5.0
assert calculate_distance(1, 1, 4, 5) == 5.0
assert calculate_distance(0, 0, 0, 0) == 0.0
assert calculate_distance(-1, -1, 1, 1) == math.sqrt(8)
def test_co... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(x1, y1, x2, y2):",
"function_name": "calculate_distance",
"parameter_list": "(x1, y1, x2, y2)"
},
{
"docstring": null,
"function_declaration": "def compare_files(file1_path, file2_path):",
"function_name": "compare_... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef calculate_distance(x1, y1, x2, y2):\n return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n\ndef compare_files(file1_path, file2_path):\n results = []\n \n with op... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007474",
"row_id": 7474,
"seed_ids": "['Llama-3.3-70B-Instruct_21262']"
} | 0.601329 | Filter_7474 | I | [
"calculate_distance",
"compare_files"
] | 2 | [
[
"compare_files",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 07837b8b763ef88f84a816592e6049dcde278337 | 99c1216699a5443ef48aca38206a3aae4f9d321b | |||
v1.0 | instruct | Filter | Filter_7478_I | I want to create a program that generates a random word from a list of words, and checks if a user's input matches the word.
Here's a basic implementation in Python:
```python
import random
def get_random_word(word_list):
return random.choice(word_list)
def check_match(random_word, user_input):
if random_wo... | import random
from typing import List
def get_random_word(word_list: List[str]) -> str:
"""
Returns a random word from the provided word list.
Args:
word_list (List[str]): The list of words to choose from.
Returns:
str: A randomly chosen word from the list.
"""
return random.c... | import pytest
from solution import get_random_word, check_match, game
def test_get_random_word():
word_list = ["apple", "banana", "cherry"]
random_word = get_random_word(word_list)
assert random_word in word_list
def test_check_match():
assert check_match("apple", "apple") == True
assert check_mat... | [
{
"docstring": "Returns a random word from the provided word list.\n\nArgs:\nword_list (List[str]): The list of words to choose from.\n\nReturns:\nstr: A randomly chosen word from the list.",
"function_declaration": "def get_random_word(word_list):",
"function_name": "get_random_word",
"parameter_li... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_random_word(word_list):\n \"\"\"\n Returns a random word from the word_list.\n \"\"\"\n if not word_list:\n raise ValueError(\"The word list cannot ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007478",
"row_id": 7478,
"seed_ids": "['Llama-3.3-70B-Instruct_21272']"
} | 0.714786 | Filter_7478 | I | [
"get_random_word",
"check_match",
"game",
"main"
] | 4 | [
[
"game",
"check_match"
],
[
"game",
"get_random_word"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3e1bedc5abd339f7469aa22ee3906532a61b5851 | ae75e8e513ab8c28991e9b6f67e50d13cd7c62f8 | |||
v1.0 | instruct | Filter | Filter_7483_I | ### Overview
This is a simple implementation of a Rock, Paper, Scissors game. The game allows two players to play against each other.
The game can also be played with one player and the computer.
#### Rules
The rules are standard:
- Rock beats Scissors
- Scissors beats Paper
- Paper beats Rock
### Implementation
```p... | import random
class Player:
def __init__(self, name):
self.name = name
def get_move(self):
while True:
move = input(f"{self.name}, please enter your move (rock, paper, or scissors): ")
if move.lower() in ["rock", "paper", "scissors"]:
return move.lower()... | from solution import Player, ComputerPlayer, determine_winner
def test_determine_winner_same_move():
assert determine_winner("rock", "rock") == None
assert determine_winner("scissors", "scissors") == None
assert determine_winner("paper", "paper") == None
def test_determine_winner_rock_beats_scissors():
... | [] | [
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 random\n\nclass Player:\n def __init__(self, name):\n self.name = name\n\n def get_move(self):\n while True:\n move = input(f\"{s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007483",
"row_id": 7483,
"seed_ids": "['Llama-3.3-70B-Instruct_21280']"
} | 0.602867 | Filter_7483 | I | [
"determine_winner",
"play_game"
] | 2 | [
[
"play_game",
"determine_winner"
]
] | 1 | [] | false | [
"Player",
"ComputerPlayer"
] | true | pytest | true | [] | true | 758de4985f7e132390ed58f74960e799c9fc43b1 | f2c62b589e190b315bc449b923ae62e28fa43c17 | |||
v1.0 | instruct | Filter | Filter_7527_I | This is what I know about the problem:
- The problem is about finding the number of connected components in a graph.
- The graph is represented as an adjacency list.
- The graph is general, i.e., it can be undirected or directed, and can contain self-loops and multiple edges between the same pair of vertices.
- I need ... | def dfs(node, visited, graph):
"""
Helper function that performs a depth-first search (DFS) on the graph.
Args:
- node (Any): The starting node for DFS.
- visited (set): A set to keep track of visited nodes.
- graph (dict): The adjacency list representation of the graph.
"""
visited.add... | from solution import count_connected_components
def test_empty_graph():
graph = {}
assert count_connected_components(graph) == 0
def test_single_node_graph():
graph = {1: []}
assert count_connected_components(graph) == 1
def test_disconnected_graph():
graph = {1: [], 2: [], 3: []}
assert coun... | [
{
"docstring": "Helper function that performs a depth-first search (DFS) on the graph.\n\nArgs:\n- node (Any): The starting node for DFS.\n- visited (set): A set to keep track of visited nodes.\n- graph (dict): The adjacency list representation of the graph.",
"function_declaration": "def dfs(node, visited,... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_connected_components(graph):\n \"\"\"\n This function counts the number of connected components in a graph.\n\n Args:\n graph (dict): The input graph represented as an ad... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007527",
"row_id": 7527,
"seed_ids": "['Llama-3.3-70B-Instruct_21376']"
} | 0.552291 | Filter_7527 | I | [
"dfs",
"count_connected_components"
] | 2 | [
[
"count_connected_components",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c86a86f10b43576aacc1311e3e7fe7a72349451 | 63e083399e5e5e784dc7fb1a249fe5d0551d699b | |||
v1.0 | instruct | Filter | Filter_7530_I | I have a function that accepts the name of a file and returns the first line of the file. I want to call this function with a lot of different file names. I want to write a function that will call my existing function and save the results for all the files I'm interested in.
Here since are my requirements:
1. The fu... | def get_first_lines(filenames):
"""
Accepts a list of file names and returns a dictionary with the file names as keys
and the first lines as values.
"""
result = {}
for filename in filenames:
result[filename] = first_line(filename)
return result
def first_line(filename):
"""
... | import os
import pytest
from solution import get_first_lines, first_line
def create_test_file(filename, content):
with open(filename, 'w') as f:
f.write(content)
def test_get_first_lines():
# Create test files
create_test_file('test_file1.txt', 'First line of file 1\nSecond line of file 1')
cr... | [
{
"docstring": "Accepts a list of file names and returns a dictionary with the file names as keys\nand the first lines as values.",
"function_declaration": "def get_first_lines(filenames):",
"function_name": "get_first_lines",
"parameter_list": "(filenames)"
},
{
"docstring": "Returns the fi... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_first_lines(filenames):\n \"\"\"\n Accepts a list of file names, calls `first_line` for each file,\n and returns a dictionary with the file names as keys and the first lines a... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007530",
"row_id": 7530,
"seed_ids": "['Llama-3.3-70B-Instruct_21384']"
} | 0.572507 | Filter_7530 | I | [
"get_first_lines",
"first_line"
] | 2 | [
[
"get_first_lines",
"first_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7224c730e09e5d778dbabf9b65b49ff64de31b3d | 44f7efca5c7bf3c5b089207c4c19f996cd159caa | |||
v1.0 | instruct | Filter | Filter_7555_I | I have two functions, `get_item` and `set_item`. These functions retrieve and set items from a list, respectively. They are defined as follows:
```
def get_item(my_list, index):
return my_list[index]
def set_item(my_list, index, item):
my_list[index] = item
```
Now, I want to create a new function `update_item... | def get_item(my_list, index):
return my_list[index]
def set_item(my_list, index, item):
my_list[index] = item
def update_item(my_list, index, new_item):
if index < 0 or index >= len(my_list):
raise IndexError("Index out of bounds")
set_item(my_list, index, new_item) | import pytest
from solution import get_item, set_item, update_item
def test_get_item():
my_list = [1, 2, 3]
assert get_item(my_list, 1) == 2
assert get_item(my_list, 0) == 1
def test_set_item():
my_list = [1, 2, 3]
set_item(my_list, 1, 4)
assert my_list == [1, 4, 3]
set_item(my_list, 0, 7)... | [
{
"docstring": null,
"function_declaration": "def get_item(my_list, index):",
"function_name": "get_item",
"parameter_list": "(my_list, index)"
},
{
"docstring": null,
"function_declaration": "def set_item(my_list, index, item):",
"function_name": "set_item",
"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_item(my_list, index):\n return my_list[index]\n\ndef set_item(my_list, index, item):\n my_list[index] = item\n\ndef update_item(my_list, index, new_item):\n if index < 0 or in... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007555",
"row_id": 7555,
"seed_ids": "['Llama-3.3-70B-Instruct_21445']"
} | 0.366245 | Filter_7555 | I | [
"get_item",
"set_item",
"update_item"
] | 3 | [
[
"update_item",
"set_item"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bab3cf98e05fb0afb9917054e3c0759afee70d28 | f8ff99a95cd92db84cddcf3293d7d29872407b69 | |||
v1.0 | instruct | Filter | Filter_7584_I | I have a function `mergesort(arr)` which sorts an array in ascending order using merge sort algorithm. The function works well for all test cases.
However, I want to create a new function called `mergesort_modified(arr, comparator)`. This new function should sort the array in the order specified by the `comparator` f... | def mergesort_modified(arr, comparator):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = mergesort_modified(arr[:mid], comparator)
right = mergesort_modified(arr[mid:], comparator)
return merge_modified(left, right, comparator)
def merge_modified(left, right, comparator):
resu... | from solution import mergesort_modified
def comparator_ascending(a, b):
return a < b
def comparator_descending(a, b):
return a > b
def test_mergesort_modified_ascending():
assert mergesort_modified([4, 1, 3, 2], comparator_ascending) == [1, 2, 3, 4]
assert mergesort_modified([1, 2, 3, 4], comparator_... | [
{
"docstring": null,
"function_declaration": "def mergesort_modified(arr, comparator):",
"function_name": "mergesort_modified",
"parameter_list": "(arr, comparator)"
},
{
"docstring": null,
"function_declaration": "def merge_modified(left, right, comparator):",
"function_name": "merg... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def mergesort_modified(arr, comparator):\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left = mergesort_modified(arr[:mid], comparator)\n right = mergesort_modi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007584",
"row_id": 7584,
"seed_ids": "['Llama-3.3-70B-Instruct_21503']"
} | 0.578777 | Filter_7584 | I | [
"mergesort_modified",
"merge_modified"
] | 2 | [
[
"mergesort_modified",
"merge_modified"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a75e33832ad31a88dbf7cc10d67e5faf0115043c | e18b820755544aa612ad0c4636e68e26a8f09274 | |||
v1.0 | instruct | Filter | Filter_7586_I | This is a simple text-based rock-paper-scissors game played between two players. The game continues until one player chooses to quit.
Here is the code:
```python
import random
def get_computer_move():
"""Returns the computer's move."""
return random.choice(['rock', 'paper', 'scissors'])
def get_user_move():
... | import random
def get_computer_move():
"""Returns the computer's move."""
return random.choice(['rock', 'paper', 'scissors'])
def get_user_move(player_name):
"""Returns the user's move."""
while True:
move = input(f"{player_name}, enter your move (rock/paper/scissors) or 'q' to quit: ")
... | from solution import determine_winner # Importing only the function that can be tested programmatically.
def test_tie_cases():
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!"... | [
{
"docstring": "Returns the computer's move.",
"function_declaration": "def get_computer_move():",
"function_name": "get_computer_move",
"parameter_list": "()"
},
{
"docstring": "Returns the user's move.",
"function_declaration": "def get_user_move(player_name):",
"function_name": "g... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_computer_move():\n \"\"\"Returns the computer's move.\"\"\"\n return random.choice(['rock', 'paper', 'scissors'])\n\ndef get_user_move(player_name):\n \"\"\"R... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007586",
"row_id": 7586,
"seed_ids": "['Llama-3.3-70B-Instruct_21506']"
} | 0.575528 | Filter_7586 | I | [
"get_computer_move",
"get_user_move",
"determine_winner",
"play_game"
] | 4 | [
[
"play_game",
"determine_winner"
],
[
"play_game",
"get_computer_move"
],
[
"play_game",
"get_user_move"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | c1e4e8a0b2038880eef959c57e495cc3dc79ea25 | f38426778766b31b59684a02fe99d1f0595decd0 | |||
v1.0 | instruct | Filter | Filter_7646_I | I've got a binary search tree and I need to find the second largest node.
Here are the rules for the second largest node in a binary search tree:
- The second largest node is the node with the second largest value in the tree.
- If the tree has less than two nodes, there is no second largest node.
- If the tree has ... | class BinaryNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def find_largest(node):
"""
Helper function to find the largest node in a subtree.
"""
current = node
while current.right:
current = current... | import pytest
from solution import BinaryNode, second_largest_node
def test_single_node():
root = BinaryNode(10)
assert second_largest_node(root) == None
def test_two_nodes():
root = BinaryNode(10, BinaryNode(5))
assert second_largest_node(root) == 5
def test_find_second_largest():
root = BinaryN... | [] | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class BinaryNode:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef find_largest(node):\n \"\"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007646",
"row_id": 7646,
"seed_ids": "['Llama-3.3-70B-Instruct_21626']"
} | 0.497324 | Filter_7646 | I | [
"find_largest",
"second_largest_node"
] | 2 | [
[
"second_largest_node",
"find_largest"
]
] | 1 | [] | false | [
"BinaryNode"
] | true | pytest | true | [] | true | ecf64e83a7fda199b0873bec2e8df5867dd4c357 | 359b4d9a20055095ac55eb8e797e5b7a48be13dd | |||
v1.0 | instruct | Filter | Filter_7664_I | I'm trying to create an algorithm for a ride-hailing service. The algorithm should be able to efficiently match drivers with riders. Here are some details about the system:
* Riders can request a ride by specifying their current location and desired destination.
* Drivers have a current location and a vehicle capa... | from math import sqrt
class Rider:
def __init__(self, id, current_location, destination):
"""
Initialize a Rider object.
Args:
id (int): Unique identifier for the rider.
current_location (tuple): Current location of the rider in the format (x, y).
destination (tuple... | from solution import Rider, Driver, match_rider_to_driver
def test_calculate_distance():
from solution import calculate_distance
assert calculate_distance((0, 0), (3, 4)) == 5.0
assert calculate_distance((1, 2), (1, 2)) == 0.0
assert calculate_distance((0, 0), (0, 0)) == 0.0
def test_match_rider_to_dr... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import sqrt\n\nclass Rider:\n def __init__(self, id, current_location, destination):\n \"\"\"\n Initialize a Rider object.\n\n Args:\n id (int): Unique... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007664",
"row_id": 7664,
"seed_ids": "['Llama-3.3-70B-Instruct_21665']"
} | 0.520137 | Filter_7664 | I | [
"calculate_distance",
"match_rider_to_driver"
] | 2 | [
[
"match_rider_to_driver",
"calculate_distance"
]
] | 1 | [] | false | [
"Rider",
"Driver"
] | true | pytest | true | [] | true | 8c54bcddea5ec5683056ca3cb009c83c5e794bb0 | dcc59c821f8b0c5dc49bee05a568155995dbbaf4 | |||
v1.0 | instruct | Filter | Filter_7674_I | ### Overview
The goal of this project is to create a simple chatbot using sockets for network communication. The chatbot should be able to receive and process messages from clients, and then respond accordingly.
### Tasks
1. Define the structure of the chatbot's responses.
2. Create a socket server that can handle mul... | import socket
import threading
# Dictionary to store predefined responses
RESPONSES = {
"hello": "Hello! How can I assist you today?",
"how are you": "I'm just a bot, but I'm working just fine!",
"bye": "Goodbye! Have a great day!",
}
ERROR_RESPONSE = "I'm sorry, I don't understand that."
# Function to h... | import socket
import threading
import time
import pytest
from solution import start_server, get_response, handle_client
# Unit tests for get_response function
def test_get_response_hello():
assert get_response("hello") == "Hello! How can I assist you today?"
def test_get_response_how_are_you():
assert get_re... | [
{
"docstring": null,
"function_declaration": "def handle_client(client_socket):",
"function_name": "handle_client",
"parameter_list": "(client_socket)"
},
{
"docstring": null,
"function_declaration": "def get_response(message):",
"function_name": "get_response",
"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 socket\nimport threading\n\n# Dictionary to store predefined responses\nRESPONSES = {\n \"hello\": \"Hello! How can I assist you today?\",\n \"how are you\": \"I'm just a bot, but... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007674",
"row_id": 7674,
"seed_ids": "['Llama-3.3-70B-Instruct_21697']"
} | 0.480729 | Filter_7674 | I | [
"handle_client",
"get_response",
"start_server"
] | 3 | [
[
"handle_client",
"get_response"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 14f831b4ac5a713c0dae57b9a165873b8ec59b77 | 419264e048a5f997feaae3b3fcc8eb923c32dfcd | |||
v1.0 | instruct | Filter | Filter_7686_I | I want to create a simple dice game that uses a random number generator to simulate the roll of a dice. The game will be played between the user and the computer and the player with the highest score at the end of 5 rounds wins.
Here is a sample of what the game should look like:
```
Welcome to the Dice Game!
You wil... | import random
def roll_dice():
return random.randint(1, 6)
def play_round():
user_roll = roll_dice()
computer_roll = roll_dice()
return user_roll, computer_roll
def game():
print("Welcome to the Dice Game!")
print("You will play 5 rounds against the computer.")
print("To win, you must hav... | import pytest
from solution import roll_dice, play_round
def test_roll_dice():
for _ in range(100):
roll = roll_dice()
assert 1 <= roll <= 6
def test_play_round():
for _ in range(100):
user_roll, computer_roll = play_round()
assert 1 <= user_roll <= 6
assert 1 <= comput... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def play_round():",
"function_name": "play_round",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"\n Simulate rolling a six-sided dice and return the result (an integer between 1 and 6).\n \"\"\"\n return random.randint(1, 6)\n\ndef pla... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007686",
"row_id": 7686,
"seed_ids": "['Llama-3.3-70B-Instruct_21728']"
} | 0.538205 | Filter_7686 | I | [
"roll_dice",
"play_round",
"game"
] | 3 | [
[
"game",
"play_round"
],
[
"play_round",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 40dfe7c2d3d1399a310d16975d149b97482139fd | 8b88bf0407d072cad68181323df258f292e6e015 | |||
v1.0 | instruct | Filter | Filter_7703_I | I'm trying to model the population growth of a particular species in a given area. I'd like to use the logistic growth model, which is defined as follows:
dP/dt = r * P * (1 - P / K)
where:
- P is the population size at time t
- r is the intrinsic growth rate
- K is the carrying capacity
I'd like to solve this diffe... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def logistic_growth(P, t, r, K):
"""
Logistic growth model differential equation.
Parameters:
- P: Population size at time t
- t: Time
- r: Intrinsic growth rate
- K: Carrying capacity
Return... | import numpy as np
import pytest
from solution import logistic_growth, solve_logistic_growth
def test_logistic_growth_initial():
# Basic test for the differential equation at initial conditions.
P0 = 10
t = 0
r = 0.2
K = 100
dPdt = logistic_growth(P0, t, r, K)
expected_dPdt = 0.2 * 10 * (1 ... | [
{
"docstring": "Logistic growth model differential equation.\n\nParameters:\n- P: Population size at time t\n- t: Time\n- r: Intrinsic growth rate\n- K: Carrying capacity\n\nReturns:\n- dP/dt: Rate of population change",
"function_declaration": "def logistic_growth(P, t, r, K):",
"function_name": "logis... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\n\ndef logistic_growth(P, t, r, K):\n \"\"\"\n Logistic growth differential equation.\n dP/dt = r * P * (1 - P / K)\n\n Param... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007703",
"row_id": 7703,
"seed_ids": "['Llama-3.3-70B-Instruct_21772']"
} | 0.320491 | Filter_7703 | I | [
"logistic_growth",
"solve_logistic_growth"
] | 2 | [
[
"solve_logistic_growth",
"logistic_growth"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 493444ad3de1b336dab0647c3487ad32e61e3be6 | a3cac57e28f4ba564c22a12f2425b348571dc2dd | |||
v1.0 | instruct | Filter | Filter_7707_I | Here is the Python code to perform a merge sort:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
return merge(merge_sort(left_half), merge_sort(right_half))
def merge(left, right):
merged = []
left_index ... | def merge_sort(arr):
"""
Perform merge sort on the provided array and return the sorted array.
Parameters:
arr (list): The array to be sorted.
Returns:
list: The sorted array.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_... | from solution import merge_sort, merge
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_array():
as... | [
{
"docstring": "Perform merge sort on the provided array and return the sorted array.\n\nParameters:\narr (list): The array to be sorted.\n\nReturns:\nlist: The sorted array.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docs... | [
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 len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n\n return merge(merge_sort(left_half), mer... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007707",
"row_id": 7707,
"seed_ids": "['Llama-3.3-70B-Instruct_21779']"
} | 0.584916 | Filter_7707 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 43aea2f8bc3fff51767d5d86c1afac9dcbfc197e | 1c7c9bd7e8056160e16d037de8d169114650454f | |||
v1.0 | instruct | Filter | Filter_7713_I | In this problem, you will implement a simple version of the popular game Hangman. The game will be played on the command line. Words to be guessed will be chosen randomly from a predefined list. The user will have to guess the word by suggesting letters. For each letter that is not in the word, the hangman's gallows wi... | import random
HANGMAN_PICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O ... | from solution import getUniqueRandomWord, words
def test_getUniqueRandomWord_no_used_words():
usedWords = []
word = getUniqueRandomWord(words, usedWords)
assert word in words
usedWords.append(word)
def test_getUniqueRandomWord_some_used_words():
usedWords = ['ant', 'bat', 'cat']
word = getUniq... | [
{
"docstring": null,
"function_declaration": "def getUniqueRandomWord(wordList, usedWords):",
"function_name": "getUniqueRandomWord",
"parameter_list": "(wordList, usedWords)"
},
{
"docstring": null,
"function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, s... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007713",
"row_id": 7713,
"seed_ids": "['Llama-3.3-70B-Instruct_21794']"
} | 0.539448 | Filter_7713 | I | [
"getUniqueRandomWord",
"displayBoard",
"getGuess",
"playAgain",
"hangman"
] | 5 | [
[
"hangman",
"displayBoard"
],
[
"hangman",
"getGuess"
],
[
"hangman",
"getUniqueRandomWord"
],
[
"hangman",
"playAgain"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | d51b17c487a1a5fdf4a84ee8a737c180db55c8f7 | b60d19bf40c9ee07e28a04f9682c9edf7532be83 | |||
v1.0 | instruct | Filter | Filter_7728_I | Here is a simple question that will help me understand the concept of recursion better: how would you implement a recursive function that prints all possible strings of length 3 using only lowercase English letters ('a' to 'z')? | def generate_strings(prefix, length):
"""
Generates all possible strings of a given length using lowercase English letters.
Arguments:
prefix : str - Current prefix of the string being generated
length : int - The total length of strings to generate
"""
if length == 0:
print(pre... | from solution import generate_strings, print_all_strings_of_length_3
def test_generate_strings():
results = []
def custom_print(s):
results.append(s)
import builtins
original_print = builtins.print
builtins.print = custom_print
try:
generate_strings("", 2)
... | [
{
"docstring": "Generates all possible strings of a given length using lowercase English letters.\n\nArguments:\nprefix : str - Current prefix of the string being generated\nlength : int - The total length of strings to generate",
"function_declaration": "def generate_strings(prefix, length):",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_strings(prefix, length):\n \"\"\"\n Generates all possible strings of given length using only lowercase English letters.\n Prints each possible string.\n \n :param ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007728",
"row_id": 7728,
"seed_ids": "['Llama-3.3-70B-Instruct_21825']"
} | 0.511687 | Filter_7728 | I | [
"generate_strings",
"print_all_strings_of_length_3"
] | 2 | [
[
"print_all_strings_of_length_3",
"generate_strings"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0e730aa5ad759473b0be41756ec313de61ead102 | aaba8dc0f6cb81eaf4bd82aae8212047e2487f09 | |||
v1.0 | instruct | Filter | Filter_7738_I | I have an email that contains a list of names and email addresses in the following format:
Name <email@example.com>
Name2 <email2@example.com>
Name3 <email3@example.com>
I would like to extract the names and email addresses from this email and put them in a spreadsheet. What is the best way to do this?
Additionall... | import re
import csv
import socket
def parse_contacts(input_file, output_file):
"""
Parses a text file containing contacts in the format 'Name <email@example.com>'
and writes the parsed data to a CSV file.
:param input_file: Path to the input text file.
:param output_file: Path to the output C... | import pytest
from solution import parse_contacts, is_valid_domain, filter_invalid_emails
import os
def test_parse_contacts(tmp_path):
input_file = tmp_path / "contacts.txt"
output_file = tmp_path / "contacts.csv"
contacts_data = """Name1 <email1@example.com>
Name2 <email2@example.com>
Name3 <email3@e... | [
{
"docstring": "Parses a text file containing contacts in the format 'Name <email@example.com>'\nand writes the parsed data to a CSV file.\n\n:param input_file: Path to the input text file.\n:param output_file: Path to the output CSV file.",
"function_declaration": "def parse_contacts(input_file, output_fil... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nimport csv\n\ndef parse_contacts(text):\n \"\"\"\n Parses a text that contains names and emails in the format 'Name <email>'.\n Returns a list of tuples with (name, email).... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007738",
"row_id": 7738,
"seed_ids": "['Llama-3.3-70B-Instruct_21850']"
} | 0.645729 | Filter_7738 | I | [
"parse_contacts",
"is_valid_domain",
"filter_invalid_emails"
] | 3 | [
[
"filter_invalid_emails",
"is_valid_domain"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 232aa751275a8b616a585211a1a02ec9c9456ef3 | 778844e9f762c00ece42670ede23c0fcde2cab06 | |||
v1.0 | instruct | Filter | Filter_7744_I | ### Task
Create a simple game using a card deck in which the player has to guess whether the next card drawn will be higher or lower than the previous one. The game should continue until the player makes a mistake.
### Requirements
- The game should start with a shuffled deck of 52 cards.
- The game should draw the fi... | import random
# Define suits and ranks
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
# Define a class for the Card
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.r... | from solution import Deck, Card, game_turn
def fixed_input_generator(inputs):
"""
Creates a fake input function that returns predefined values.
"""
def inner(prompt):
return inputs.pop(0)
return inner
def test_deck_draw():
deck = Deck()
drawn_cards = [deck.draw() for _ in range(52)... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Define suits and ranks\nsuits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\nranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']\n\n# Define... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007744",
"row_id": 7744,
"seed_ids": "['Llama-3.3-70B-Instruct_21864']"
} | 0.635572 | Filter_7744 | I | [
"game_turn",
"play_game"
] | 2 | [
[
"play_game",
"game_turn"
]
] | 1 | [] | false | [
"Card",
"Deck"
] | true | pytest | true | [] | true | 0617cea44b4d9b3b6d8aaa66aabeb27198dd06fe | 48b1908e0435aaffedfc4fe1e746dccf2150e552 | |||
v1.0 | instruct | Filter | Filter_7757_I | You've been tasked with writing a program that implements a specific algorithm to find the closest pair of points in a set of points in n-dimensional space. The algorithm should use a brute force approach to calculate the distance between each pair of points and keep track of the pair with the minimum distance.
Here ... | import math
from itertools import combinations
def euclidean_distance(point1, point2):
"""
Calculate Euclidean distance between two points in n-dimensional space.
"""
return math.sqrt(sum((p1 - p2) ** 2 for p1, p2 in zip(point1, point2)))
def closest_pair_brute_force(points):
"""
Find the clos... | from solution import euclidean_distance, closest_pair_brute_force
def test_euclidean_distance():
assert math.isclose(euclidean_distance([1, 2, 3], [4, 5, 6]), 5.196152422706632)
assert math.isclose(euclidean_distance([0, 0], [3, 4]), 5.0)
assert math.isclose(euclidean_distance([1], [1]), 0.0)
def test_clo... | [
{
"docstring": "Calculate Euclidean distance between two points in n-dimensional space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the closest pair of points in n-dim... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import sqrt\nfrom itertools import combinations\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points in n-dimensional space... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007757",
"row_id": 7757,
"seed_ids": "['Llama-3.3-70B-Instruct_21890']"
} | 0.635409 | Filter_7757 | I | [
"euclidean_distance",
"closest_pair_brute_force"
] | 2 | [
[
"closest_pair_brute_force",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c198eb5ad6691c5fa62e64780227b94bdba4a709 | 3cd0be21e0c656289ed0b9d6e88c4249fad3d03c | |||
v1.0 | instruct | Filter | Filter_7758_I | I have to create a program that takes in a user input of 2 numbers and calculates the LCM of those two numbers using the GCD method.
This is the code I've come up with so far:
```python
def calculate_gcd(num1, num2):
while num2:
num1, num2 = num2, num1 % num2
return num1
def calculate_lcm(num1, num2)... | def calculate_gcd(num1, num2):
while num2:
num1, num2 = num2, num1 % num2
return num1
def calculate_lcm(num1, num2):
return (num1 * num2) // calculate_gcd(num1, num2)
def main():
user_num1 = int(input("Enter the first number: "))
user_num2 = int(input("Enter the second number: "))
... | from solution import calculate_lcm, calculate_gcd
def test_calculate_gcd():
assert calculate_gcd(8, 12) == 4
assert calculate_gcd(54, 24) == 6
assert calculate_gcd(48, 180) == 12
assert calculate_gcd(101, 103) == 1 # prime numbers case
def test_calculate_lcm():
assert calculate_lcm(8, 12) == 24
... | [
{
"docstring": null,
"function_declaration": "def calculate_gcd(num1, num2):",
"function_name": "calculate_gcd",
"parameter_list": "(num1, num2)"
},
{
"docstring": null,
"function_declaration": "def calculate_lcm(num1, num2):",
"function_name": "calculate_lcm",
"parameter_list": ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_gcd(num1, num2):\n while num2:\n num1, num2 = num2, num1 % num2\n return num1\n\ndef calculate_lcm(num1, num2):\n return (num1 * num2) // calculate_gcd(num1, num2... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007758",
"row_id": 7758,
"seed_ids": "['Llama-3.3-70B-Instruct_21891']"
} | 0.70806 | Filter_7758 | I | [
"calculate_gcd",
"calculate_lcm",
"main"
] | 3 | [
[
"calculate_lcm",
"calculate_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 25b208d2ba2620d766fc6e7eba0707a938834a46 | 876c38ff21070149040fc4417cdfc79ef832410c | |||
v1.0 | instruct | Filter | Filter_7767_I | Here is the code:
```
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):
merged = []
left_index = 0
right_index = 0
while left_index < len(left) a... | def merge_sort(arr):
"""
Recursively sorts an array using the merge sort algorithm.
Parameters:
arr (list of int): The array to be sorted.
Returns:
list of int: The sorted array.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([5]) == [5]
def test_merge_sort_already_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_... | [
{
"docstring": "Recursively sorts an array using the merge sort algorithm.\n\nParameters:\n arr (list of int): The array to be sorted.\n\nReturns:\n list of int: The sorted array.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Recursively sorts an array using the merge sort algorithm.\n \n Parameters:\n arr (list of int): The array to be sorted.\n \n Returns:\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007767",
"row_id": 7767,
"seed_ids": "['Llama-3.3-70B-Instruct_21906']"
} | 0.61204 | Filter_7767 | I | [
"merge_sort",
"merge",
"main"
] | 3 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 06c31cadab1cb5b2aec2bd25a9dab7286ba341e9 | 1b4656373cc04bfd69e65b50ed2799bfe1e86fc2 | |||
v1.0 | instruct | Filter | Filter_7807_I | I have a Python function that adds two numbers together. Can I extend this function to also subtract, multiply, and divide the numbers (without using the built-in operators +, -, *, /)? | def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def subtract(a, b):
"""
Returns the result of a minus b.
"""
return add(a, -b)
def multiply(a, b):
"""
Returns the product of a and b using repeated addition.
"""
result = 0
for _ in range(abs(b)):
... | from solution import add, subtract, multiply, divide
def test_add():
assert add(10, 5) == 15
assert add(-10, 5) == -5
assert add(10, -5) == 5
assert add(0, 0) == 0
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(-10, 5) == -15
assert subtract(10, -5) == 15
assert subtr... | [
{
"docstring": "Returns the sum of a and b.",
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the result of a minus b.",
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b using bitwise operations.\n \"\"\"\n while b != 0:\n carry = a & b\n a = a ^ b\n b = carry << 1\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00007807",
"row_id": 7807,
"seed_ids": "['Llama-3.3-70B-Instruct_22001']"
} | 0.610512 | Filter_7807 | I | [
"add",
"subtract",
"multiply",
"divide"
] | 4 | [
[
"divide",
"add"
],
[
"divide",
"subtract"
],
[
"multiply",
"add"
],
[
"multiply",
"subtract"
],
[
"subtract",
"add"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 59ce5153a128847ab5332e34c9d3695019f634d2 | 3e38a2e620cc1b80d9f6142d7729e55105cee56a | |||
v1.0 | instruct | Filter | Filter_7810_I | I have a list of tuples, where each tuple represents a job with its duration and deadline. For example: [(1, 2), (2, 3), (3, 1)]. I want to schedule these jobs to minimize the maximum latency, which is the maximum difference between the deadline and the finish time of any job.
Here, finish time is the time at which t... | from itertools import permutations
def calculate_max_latency(jobs):
finish_time = 0
max_latency = float('-inf')
for duration, deadline in jobs:
finish_time += duration
latency = finish_time - deadline
max_latency = max(max_latency, latency)
return max_latency
def find... | from solution import find_minimum_max_latency
def test_find_minimum_max_latency_simple():
jobs = [(1, 2), (2, 3), (3, 1)]
assert find_minimum_max_latency(jobs) == 3
def test_find_minimum_max_latency_identical_deadlines():
jobs = [(2, 5), (1, 5), (3, 5)]
assert find_minimum_max_latency(jobs) == 1
def ... | [
{
"docstring": null,
"function_declaration": "def calculate_max_latency(jobs):",
"function_name": "calculate_max_latency",
"parameter_list": "(jobs)"
},
{
"docstring": null,
"function_declaration": "def find_minimum_max_latency(jobs):",
"function_name": "find_minimum_max_latency",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef calculate_max_latency(jobs):\n finish_time = 0\n max_latency = float('-inf')\n \n for duration, deadline in jobs:\n finish_time += ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007810",
"row_id": 7810,
"seed_ids": "['Llama-3.3-70B-Instruct_22004']"
} | 0.55333 | Filter_7810 | I | [
"calculate_max_latency",
"find_minimum_max_latency"
] | 2 | [
[
"find_minimum_max_latency",
"calculate_max_latency"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b8a181d741e0bb1554a72284cc2be897f47292e | 8adc1e6fed381acab1d8c312b32bfdc1aa980053 | |||
v1.0 | instruct | Filter | Filter_7825_I | I have a large collection of files. I want to iterate over them and perform pre-processing steps such as converting all files to a uniform size, resizing images, and so on. What is the best way to achieve this in Python? | import os
from PIL import Image
from multiprocessing import Pool
def resize_image(image_path, output_size=(128, 128)):
"""
Resize an image to the specified output_size.
Parameters:
image_path (str): Path to the image file.
output_size (tuple): Desired output size (width, height).
"""
w... | import os
from PIL import Image
from solution import resize_image, process_images
def create_test_image(file_path, size=(256, 256), color=(255, 0, 0)):
with Image.new('RGB', size, color) as img:
img.save(file_path)
def test_resize_image():
# arrange
test_dir = 'test_images'
os.makedirs(test_di... | [
{
"docstring": "Resize an image to the specified output_size.\n\nParameters:\nimage_path (str): Path to the image file.\noutput_size (tuple): Desired output size (width, height).",
"function_declaration": "def resize_image(image_path, output_size=(128, 128)):",
"function_name": "resize_image",
"para... | [
0,
1,
0
] | 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 preprocess_images(input_dir, output_dir, target_size=(256, 256)):\n \"\"\"\n Converts all images in input_dir to a uniform size and saves them in ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00007825",
"row_id": 7825,
"seed_ids": "['Llama-3.3-70B-Instruct_22036']"
} | 0.467068 | Filter_7825 | I | [
"resize_image",
"process_images"
] | 2 | [
[
"process_images",
"resize_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | e749a771b446b24a7da8df5727c14aa9b8fc755b | 634f91fea550b2f907ef2d28175e1aa6c7774a64 | |||
v1.0 | instruct | Filter | Filter_7850_I | Can you explain how to create a Python decorator to implement the retry mechanism for a function? | import time
def retry(retries=3, delay=1):
"""
A decorator to retry the execution of a function upon failure.
:param retries: Number of retry attempts
:param delay: Delay in seconds between retries
"""
def decorator(func):
def wrapper(*args, **kwargs):
attempt = 0
... | import pytest
from solution import retry
import random
# To test the decorator, we define a function that will fail multiple times.
@retry(retries=3, delay=1)
def always_fail():
raise ValueError("This function always fails!")
@retry(retries=3, delay=1)
def fail_then_succeed():
if fail_then_succeed.counter < ... | [
{
"docstring": "A decorator to retry the execution of a function upon failure.\n\n:param retries: Number of retry attempts\n:param delay: Delay in seconds between retries",
"function_declaration": "def retry(retries=3, delay=1):",
"function_name": "retry",
"parameter_list": "(retries=3, delay=1)"
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef retry(retries=3, delay=1):\n \"\"\"\n A decorator to retry the execution of a function upon failure.\n \n :param retries: Number of retry attempts\n :param de... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007850",
"row_id": 7850,
"seed_ids": "['Llama-3.3-70B-Instruct_22105']"
} | 0.418311 | Filter_7850 | I | [
"retry",
"risky_function"
] | 2 | [
[
"risky_function",
"retry"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9eba106f8e5561b9d154dce4764fa1a3c14b1da8 | f16a78747a6bcd924d7f74ed2f41069a2f08788b | |||
v1.0 | instruct | Filter | Filter_7856_I | I'm trying to write a Python script that will keep track of the number of visitors to a website. I want to store the number of visitors in a file, and then be able to retrieve that information when I need it.
My script should have two main functions:
1. A function to increment the visitor count by 1.
2. A function t... | def get_visitor_count():
try:
with open('visitor_count.txt', 'r') as file:
visitor_count = int(file.read())
return visitor_count
except FileNotFoundError:
return 0
def increment_visitor_count():
current_count = get_visitor_count()
current_count += 1
with open('vi... | import os
import pytest
from solution import get_visitor_count, increment_visitor_count
def test_get_visitor_count_initial():
# Assure the file does not exist before
if os.path.exists('visitor_count.txt'):
os.remove('visitor_count.txt')
assert get_visitor_count() == 0
def test_increment_visit... | [
{
"docstring": null,
"function_declaration": "def get_visitor_count():",
"function_name": "get_visitor_count",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def increment_visitor_count():",
"function_name": "increment_visitor_count",
"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_visitor_count():\n try:\n with open('visitor_count.txt', 'r') as file:\n visitor_count = int(file.read())\n return visitor_count\n except FileNotFoundErr... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00007856",
"row_id": 7856,
"seed_ids": "['Llama-3.3-70B-Instruct_22122']"
} | 0.454342 | Filter_7856 | I | [
"get_visitor_count",
"increment_visitor_count",
"main"
] | 3 | [
[
"increment_visitor_count",
"get_visitor_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc824eb26d11852f33fc294cf7fde6f4b660293b | 7db367d626e71f163f9edef65b3f29b1fdec84ec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.