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_10346_I
I have a function `f(x)` that takes in a list of integers and returns the maximum sum of a contiguous subarray within the list. The function uses Kadane's algorithm. However, I'm struggling to implement the same function but for a 2D list (or matrix) of integers. Here is my current implementation for a 1D list: ```py...
def max_submatrix_sum(matrix): """ This function calculates the maximum sum of a contiguous subarray within a given 2D list (matrix) of integers, using an adaptation of Kadane's algorithm for 2D arrays. Parameters: matrix (list of list of int): A 2D list (matrix) of integers. Returns: ...
from solution import max_submatrix_sum, max_subarray_sum def test_max_submatrix_sum_basic(): matrix = [ [1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6] ] assert max_submatrix_sum(matrix) == 29 def test_max_submatrix_sum_single_element(): mat...
[ { "docstring": "This function calculates the maximum sum of a contiguous subarray within a given 2D list (matrix) of integers,\nusing an adaptation of Kadane's algorithm for 2D arrays.\n\nParameters:\nmatrix (list of list of int): A 2D list (matrix) of integers.\n\nReturns:\nint: The maximum sum of a contiguous...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_submatrix_sum(matrix):\n \"\"\"\n This function calculates the maximum sum of a contiguous submatrix within the given 2D list.\n \n Parameters:\n matrix (list of lists):...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00010346", "row_id": 10346, "seed_ids": "['Llama-3.3-70B-Instruct_27800']" }
0.551359
Filter_10346
I
[ "max_submatrix_sum", "max_subarray_sum" ]
2
[ [ "max_submatrix_sum", "max_subarray_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
846d6f27338472a4ae213c342cccab5017d55e2b
034f4ac2e83ed8675fe2a34dcd2bf2b940c7ca38
v1.0
instruct
Filter
Filter_10483_I
Here is a problem I am having. I have a grid of squares, each with a color. Each square is either red, blue or green. I want to know the shortest path between two points in this grid, where you can only move in the four cardinal directions (up, down, left, right) and you can move between squares of the same color. ...
from collections import deque def neighbors(grid, x, y): """ This function returns the neighbors of a cell in the grid. Args: grid (list of lists): A 2D list representing the grid, where each element is a color. x (int): The x-coordinate of the cell. y (int): The y-coordinate of the cell. ...
from solution import shortest_path def test_shortest_path_example_case(): grid = [ ['R', 'G', 'R'], ['R', 'R', 'G'], ['R', 'R', 'R'] ] start = (0, 0) end = (2, 2) assert shortest_path(grid, start, end) == 4 def test_no_path_due_to_different_colors(): grid = [ ['...
[ { "docstring": "This function returns the neighbors of a cell in the grid.\n\nArgs:\ngrid (list of lists): A 2D list representing the grid, where each element is a color.\nx (int): The x-coordinate of the cell.\ny (int): The y-coordinate of the cell.\n\nReturns:\nlist: A list of tuples representing the coordina...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef shortest_path(grid, start, end):\n \"\"\"\n This function finds the shortest path between two points in a grid, \n where you can only move between...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00010483", "row_id": 10483, "seed_ids": "['Llama-3.3-70B-Instruct_28127']" }
0.680355
Filter_10483
I
[ "neighbors", "shortest_path" ]
2
[ [ "shortest_path", "neighbors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5704be39ee8ee134271fc23ae55ab54f8c580370
0c3ed59821ab01b40c68e80ab4153a85e85b3a64
v1.0
instruct
Filter
Filter_10529_I
### Description This is the game of Tic Tac Toe. Player 1 is X and Player 2 is O. ### Game Board 1 | 2 | 3 --------- 4 | 5 | 6 --------- 7 | 8 | 9 ### Objective The objective of the game is to get three in a row, either horizontally, vertically, or diagonally. ### How to Play 1. The game starts with an em...
def generate_win_conditions(size): """ Generate all possible win conditions for a Tic Tac Toe board of given size. """ win_conditions = [] # Rows for i in range(size): win_conditions.append([(i * size) + j for j in range(size)]) # Columns for i in range(size): win_c...
from solution import check_winner def test_small_board(): assert check_winner(['X', 'X', 'X', '', '', '', '', '', '']) == 'X' assert check_winner(['O', 'O', 'O', '', '', '', '', '', '']) == 'O' def test_medium_board(): assert check_winner(['X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X']) == 'X' assert ch...
[ { "docstring": "Generate all possible win conditions for a Tic Tac Toe board of given size.", "function_declaration": "def generate_win_conditions(size):", "function_name": "generate_win_conditions", "parameter_list": "(size)" }, { "docstring": "Determines the winner of the Tic Tac Toe game ...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_winner(board):\n \"\"\"\n Check the winner of a Tic Tac Toe game of any board size.\n :param board: List of strings representing the board.\n :return: 'X' (Player 1 wins)...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00010529", "row_id": 10529, "seed_ids": "['Llama-3.3-70B-Instruct_28237']" }
0.615386
Filter_10529
I
[ "generate_win_conditions", "check_winner" ]
2
[ [ "check_winner", "generate_win_conditions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a34ba2904675b1f594adf5396800c9fda0d4f46c
c79c2635efb28c4db95d77d1ddb653e6778f9763
v1.0
instruct
Filter
Filter_10560_I
Greetings! I'm trying to implement a script to automate the process of creating users on my system. As a first step, I'd like to create a function that accepts a username and password, then checks if the username already exists. My system uses a Unix-based operating system, and I have `pam-python` installed to intera...
import os import pwd def user_exists(username): """ Check if a user exists in the system. :param username: The username to check. :return: True if the user exists, False otherwise. """ try: pwd.getpwnam(username) return True except KeyError: return False def cr...
import pytest from solution import user_exists, create_user import os def test_user_exists_existing_user(monkeypatch): def mock_getpwnam(username): return None monkeypatch.setattr(pwd, 'getpwnam', mock_getpwnam) assert user_exists("existing_user") == True def test_user_exists_nonexistent_user(monk...
[ { "docstring": "Check if a user exists in the system.\n\n:param username: The username to check.\n:return: True if the user exists, False otherwise.", "function_declaration": "def user_exists(username):", "function_name": "user_exists", "parameter_list": "(username)" }, { "docstring": "Creat...
[ 0, 0, 0, 0, 1, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport pwd\nimport subprocess\n\ndef user_exists(username):\n \"\"\"\n Check if a user exists on the Unix-based system.\n \"\"\"\n try:\n pwd.getpwnam(username)\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00010560", "row_id": 10560, "seed_ids": "['Llama-3.3-70B-Instruct_28302']" }
0.407656
Filter_10560
I
[ "user_exists", "create_user" ]
2
[ [ "create_user", "user_exists" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6ae2e622f270b906b87167ac1faa94ce93cf0da1
0b1c696e51cdefcab15018a80ff6d8031416244c
v1.0
instruct
Filter
Filter_10709_I
I have a 10x10 matrix and I want to create a function that checks all eight possible directions (up, down, left, right, and 4 diagonals) from each cell. Is there a way to implement this in Python? ### Example Use Case: Given a matrix: ```python [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 1...
def get_directions(matrix, row, col): """ Get the values in all eight possible directions from the given cell (row, col). Returns a dictionary with the direction names as keys and the corresponding cells as values. """ directions = { "up": (row-1, col), "down": (row+1, col), ...
from solution import get_directions, check_directions def test_get_directions(): matrix = [ [1, 2], [3, 4] ] assert get_directions(matrix, 0, 0) == { "up": None, "down": 3, "left": None, "right": 2, "up_left": None, "up_right": None, "...
[ { "docstring": "Get the values in all eight possible directions from the given cell (row, col).\nReturns a dictionary with the direction names as keys and the corresponding cells as values.", "function_declaration": "def get_directions(matrix, row, col):", "function_name": "get_directions", "paramet...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_directions(matrix):\n \"\"\"\n Given a 10x10 matrix, return the values in all eight possible directions from each cell,\n taking care of the matrix boundaries.\n \"\"\"\n...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00010709", "row_id": 10709, "seed_ids": "['Llama-3.3-70B-Instruct_28645']" }
0.518821
Filter_10709
I
[ "get_directions", "check_directions" ]
2
[ [ "check_directions", "get_directions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6c1fac3b622707f94d299e9657b55ea7d8a7ca58
519054384f1a66af31d2036298ed50015d7a247e
v1.0
instruct
Filter
Filter_10838_I
The problem states that we have a list of numbers and we need to find the longest increasing subsequence in that list. However, there is a catch. The list is not given explicitly but it is represented as a tree where each node represents a number and the children of a node represent the possible next numbers in the l...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def find_lis_from_node(node, prev_val, memo): if not node: return [] if (node, prev_val) in memo: return memo[(node, prev_val)] lis_from...
from solution import TreeNode, longest_increasing_subsequence def test_example_tree(): # Constructing the example tree root = TreeNode(3) root.left = TreeNode(2) root.right = TreeNode(5) root.left.left = TreeNode(1) root.left.right = TreeNode(4) root.right.right = TreeNode(6) lis =...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef longest_increasing_subsequence(root)...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00010838", "row_id": 10838, "seed_ids": "['Llama-3.3-70B-Instruct_28953']" }
0.633719
Filter_10838
I
[ "find_lis_from_node", "longest_increasing_subsequence" ]
2
[ [ "longest_increasing_subsequence", "find_lis_from_node" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
41dcf78928cd3a3eca8d4836ce30853fcccfec8e
f5c2e8cc4aa25b399a6b8ea4b4fd9890ff068925
v1.0
instruct
Filter
Filter_11020_I
I want to create a simple text-based game. The game is a puzzle game where the player has to solve a series of puzzles to progress through the game. The game starts with the player being presented with a menu that allows them to select which puzzle type they want to play. Here is my initial attempt at implementing the...
def main_menu(): """ Displays the main menu and navigates to the chosen puzzle type. """ print("Welcome to the puzzle game!") print("Please select a puzzle type:") print("1. Word Scramble") print("2. Math") print("3. Logic") choice = input("Enter your choice (1/2/3): ") if choic...
def test_word_scramble(): scrambled_word, word = word_scramble() assert sorted(scrambled_word) == sorted(word) assert scrambled_word != word def test_math_puzzle(): equation, result = math_puzzle() assert eval(equation.replace('/', '//')) == result if '/' in equation else eval(equation) == result ...
[ { "docstring": "Displays the main menu and navigates to the chosen puzzle type.", "function_declaration": "def main_menu():", "function_name": "main_menu", "parameter_list": "()" }, { "docstring": "Word scramble puzzle where player has to unscramble a randomly chosen word.", "function_de...
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def main_menu():\n print(\"Welcome to the puzzle game!\")\n print(\"Please select a puzzle type:\")\n print(\"1. Word Scramble\")\n print(\"2. Math\")\n print(\"3. Logic\")\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00011020", "row_id": 11020, "seed_ids": "['Llama-3.3-70B-Instruct_29356']" }
0.520113
Filter_11020
I
[ "main_menu", "word_scramble", "math_puzzle", "logic_puzzle" ]
4
[ [ "main_menu", "logic_puzzle" ], [ "main_menu", "math_puzzle" ], [ "main_menu", "word_scramble" ] ]
3
[]
false
[]
false
pytest
false
[]
true
555412e9ae66e27ace9e7f422437bed2569be4ec
e33a377ddc3fde10ccd69dd31723c298aa0aedc3
v1.0
instruct
Filter
Filter_11330_I
I have a file with 40,000 rows and want to write a script in python to pre-process the file by replacing some special characters and trimming the text. I am using a csv file and I am using the pandas library. Here's an example of the file content: <table> <tr> <th>id</th> <th>text</th> </tr> <tr> <...
import pandas as pd import re def preprocess_text(text): """ Preprocess the text by replacing special characters and trimming the text. """ # Replace special characters with spaces using regex cleaned_text = re.sub(r'[^\w\s]', ' ', text) # Trim extra spaces cleaned_text = ' '.join(cleaned_t...
from solution import preprocess_text import pandas as pd def test_preprocess_text_removes_special_characters(): input_text = "This is a sample text @ # with some $ special % characters !" expected_output = "This is a sample text with some special characters" assert preprocess_text(input_text) == expected_o...
[ { "docstring": "Preprocess the text by replacing special characters and trimming the text.", "function_declaration": "def preprocess_text(text):", "function_name": "preprocess_text", "parameter_list": "(text)" }, { "docstring": "Preprocess the csv file by applying the preprocess_text functio...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport re\n\ndef preprocess_file(file_path):\n \"\"\"\n Pre-processes the CSV file by replacing special characters and trimming whitespace.\n \n :param file_pa...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00011330", "row_id": 11330, "seed_ids": "['Llama-3.3-70B-Instruct_30065']" }
0.620555
Filter_11330
I
[ "preprocess_text", "preprocess_csv" ]
2
[ [ "preprocess_csv", "preprocess_text" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
d68f4fcebb04614d26ff0c420721cd3eb8d6bdaf
235589f80739ce38f2bef81def89b990c653cf89
v1.0
instruct
Filter
Filter_11372_I
### Hangman Game # No Arguements # Allows the user to play multiple rounds # Keep track of the number of wins and losses # Allows the user to guess a letter or the entire word # Hangman """ ______ | | | | | | """ HANGMAN_PICS = [''' +---+ | | | | | | =========''', ''' +---+ | | ...
import random HANGMAN_PICS = [''' +---+ | | | | | | =========''',''' +---+ | | O | | | | =========''',''' +---+ | | O | | | | | =========''',''' +---+ | | O | /| | | | =========''',''' +---+ | | O | ...
import pytest from unittest.mock import patch, MagicMock from solution import getRandomWord, playAgain def test_getRandomWord(): words = ['ant', 'baboon', 'badger'] random.seed(0) assert getRandomWord(words) == 'baboon' @patch('builtins.input', MagicMock(return_value='yes')) def test_playAgain_yes(): ...
[ { "docstring": null, "function_declaration": "def getRandomWord(wordList):", "function_name": "getRandomWord", "parameter_list": "(wordList)" }, { "docstring": null, "function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):", "function_name":...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00011372", "row_id": 11372, "seed_ids": "['Llama-3.3-70B-Instruct_30158']" }
0.537863
Filter_11372
I
[ "getRandomWord", "displayBoard", "getGuess", "playAgain", "hangmanGame" ]
5
[ [ "hangmanGame", "displayBoard" ], [ "hangmanGame", "getGuess" ], [ "hangmanGame", "getRandomWord" ], [ "hangmanGame", "playAgain" ] ]
4
[]
false
[]
false
pytest
true
[]
true
5c0f2a74150ea68a0b28ac8b96f48ad6aba75fda
b7164aa4234edb6c70842cc0d5fe75c49a86aaf3
v1.0
instruct
Filter
Filter_11487_I
I have a dataset of images of various objects, and I want to use a convolutional neural network (CNN) to classify these images into different categories. I am using the PyTorch library to implement the CNN. However, I am having trouble finding the optimal hyperparameters for my model. Can you provide some guidance on t...
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, Dataset from itertools import product class SimpleCNN(nn.Module): def __init__(self, num_classes=10): super(SimpleCNN, self).__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padd...
from solution import SimpleCNN, train_model, evaluate_model, hyperparameter_tuning import torch from torch.utils.data import DataLoader, TensorDataset def test_SimpleCNN_structure(): model = SimpleCNN(num_classes=10) assert isinstance(model, nn.Module) assert hasattr(model, 'conv1') assert hasattr(mode...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, random_split\nfrom torchvision import datasets, transforms\nimport itertools\n\ndef i...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00011487", "row_id": 11487, "seed_ids": "['Llama-3.3-70B-Instruct_30414']" }
0.293114
Filter_11487
I
[ "train_model", "evaluate_model", "hyperparameter_tuning" ]
3
[ [ "hyperparameter_tuning", "evaluate_model" ], [ "hyperparameter_tuning", "train_model" ] ]
2
[]
false
[ "SimpleCNN" ]
true
pytest
true
[ "torch" ]
false
7aa69e60df4720dcb534b7104f416dda18347343
c35f967f194a0d072ad7311831cc7000ade6e773
v1.0
instruct
Filter
Filter_11524_I
Here is the code: ``` class SensorData: def __init__(self, sensor_name, data): self.sensor_name = sensor_name self.data = data def __str__(self): return f"{self.sensor_name}: {self.data}" class SensorManager: def __init__(self): self.sensors = [] def add_sensor(self, s...
class SensorData: def __init__(self, sensor_name, data): self.sensor_name = sensor_name self.data = data def __str__(self): return f"{self.sensor_name}: {self.data}" class SensorManager: def __init__(self): self.sensors = [] def add_sensor(self, sensor): self.s...
from solution import SensorData, SensorManager, find_sensors_with_name, extract_sensor_data, get_sensor_data def test_find_sensors_with_name(): manager = SensorManager() manager.add_sensor(SensorData("TempSensor", 25)) manager.add_sensor(SensorData("PressureSensor", 1013)) manager.add_sensor(SensorData...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class SensorData:\n def __init__(self, sensor_name, data):\n self.sensor_name = sensor_name\n self.data = data\n\n def __str__(self):\n return f\"{self.sensor_name}:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00011524", "row_id": 11524, "seed_ids": "['Llama-3.3-70B-Instruct_30516']" }
0.529302
Filter_11524
I
[ "find_sensors_with_name", "extract_sensor_data", "get_sensor_data" ]
3
[ [ "get_sensor_data", "extract_sensor_data" ], [ "get_sensor_data", "find_sensors_with_name" ] ]
2
[]
false
[ "SensorData", "SensorManager" ]
true
pytest
true
[]
true
360e4260ff3aa757ab38786f556080cb94461f0d
388f23ede8824f51d312b7733eaf6e2fcd56cd73
v1.0
instruct
Filter
Filter_11534_I
I have a list of 2000+ terms that are a mix of abbreviations and full words. I'd like to expand the abbreviations into their full words. I want to write code that can achieve this. The approach I'll take is to create a dictionary that maps the abbreviations to full words, then use this dictionary to replace the abbre...
import re from typing import List, Dict from difflib import get_close_matches # Example mapping dictionary for abbreviations to full words abbreviation_dict = { "BP": "Blood Pressure", "HR": "Heart Rate", "ECG": "Electrocardiogram", # Add more abbreviations and their full forms here } def expand_abbre...
import pytest from solution import expand_abbreviation, expand_medical_terms, abbreviation_dict def test_expand_abbreviation(): assert expand_abbreviation("BP", abbreviation_dict) == "Blood Pressure" assert expand_abbreviation("HR", abbreviation_dict) == "Heart Rate" assert expand_abbreviation("Unknown", a...
[ { "docstring": "Expands a given term if it is an abbreviation.\nUses a dictionary to find the full form.", "function_declaration": "def expand_abbreviation(term, abbreviation_dict):", "function_name": "expand_abbreviation", "parameter_list": "(term, abbreviation_dict)" }, { "docstring": "Exp...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from fuzzywuzzy import process\nimport re\n\ndef expand_abbreviations(term_list, abbreviation_dict, threshold=90):\n \"\"\"\n This function expands abbreviations in the input list of ter...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00011534", "row_id": 11534, "seed_ids": "['Llama-3.3-70B-Instruct_30540']" }
0.580084
Filter_11534
I
[ "expand_abbreviation", "expand_medical_terms" ]
2
[ [ "expand_medical_terms", "expand_abbreviation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
75be21d2d26355e0d633cf18e6b6eb675c863f00
1fd4ec3ad332638eb118bf022f6794848789785f
v1.0
instruct
Filter
Filter_11636_I
I wrote a simple web scraper that can scrape some basic information from a website. However, I am looking for a way to scrape more advanced information such as tables or other data formats. Here's an example of my current code: ``` import requests from bs4 import BeautifulSoup def scrape(url): page = requests.ge...
import requests from bs4 import BeautifulSoup def scrape(url): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') return soup def scrape_table(url, table_id): soup = scrape(url) table = soup.find('table', id=table_id) if not table: return None headers =...
from solution import scrape_table, scrape_list from unittest.mock import Mock, patch def test_scrape_table_valid(): url = "https://www.example.com" table_id = "main-table" mock_html = ''' <table id="main-table"> <tr> <th>Header 1</th><th>Header 2</th> </tr> <tr> ...
[ { "docstring": null, "function_declaration": "def scrape(url):", "function_name": "scrape", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def scrape_table(url, table_id):", "function_name": "scrape_table", "parameter_list": "(url, table_id)" }, { ...
[ 0, 0, 0, 0, 1, 1, 1, 0, 0 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\n\ndef scrape(url):\n \"\"\"\n Scrapes the entire HTML content of the given URL.\n \"\"\"\n page = requests.get(url)\n soup = Beau...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00011636", "row_id": 11636, "seed_ids": "['Llama-3.3-70B-Instruct_30789']" }
0.659871
Filter_11636
I
[ "scrape", "scrape_table", "scrape_list" ]
3
[ [ "scrape_list", "scrape" ], [ "scrape_table", "scrape" ] ]
2
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
ecfce0b86cbaffae0f0d3d3d4e844b802d01f27e
96090b6bd73017202d7e757c0677653f2da19a01
v1.0
instruct
Filter
Filter_11771_I
I've built a robot and I'm looking for some information about how to program it. The robot has a left and right motor, each with a forward and reverse direction and a sensor that can detect obstacles in front of it ( returning a boolean value). What would be a good approach for programming the robot to avoid obstacle...
import time def avoid_obstacles(): left_motor_speed = 50 right_motor_speed = 50 reverse_speed = -20 while True: sensor_reading = get_sensor_reading() if sensor_reading: # stop the robot set_motor(0, 'left') set_motor(0, 'right') # back ...
from solution import set_motor, get_sensor_reading def test_set_motor(): # Test that set_motor function accepts the correct parameters without errors try: set_motor(50, 'left') set_motor(-50, 'right') except Exception as e: assert False, f"set_motor raised an exception: {e}" ass...
[ { "docstring": null, "function_declaration": "def avoid_obstacles():", "function_name": "avoid_obstacles", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def set_motor(speed, motor):", "function_name": "set_motor", "parameter_list": "(speed, motor)" }, ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef avoid_obstacles():\n left_motor_speed = 50\n right_motor_speed = 50\n reverse_speed = -20\n\n while True:\n sensor_reading = get_sensor_reading()\n\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00011771", "row_id": 11771, "seed_ids": "['Llama-3.3-70B-Instruct_31089']" }
0.402262
Filter_11771
I
[ "avoid_obstacles", "set_motor", "get_sensor_reading" ]
3
[ [ "avoid_obstacles", "get_sensor_reading" ], [ "avoid_obstacles", "set_motor" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f22b0ac00ee7b49114989e4bd77eb5ebe67777f5
30e22724be145ffe0609449443236001edb144a9
v1.0
instruct
Filter
Filter_11811_I
Consider the following Python code: ```python import math from itertools import product def get_neighbours(x, y, grid): neighbours = [] for i in range(-1, 2): for j in range(-1, 2): if (i, j) == (0, 0): continue nx, ny = x+i, y+j if 0 <= nx < len(grid...
import math from itertools import product def get_neighbours(x, y, grid): neighbours = [] for i in range(-1, 2): for j in range(-1, 2): if (i, j) == (0, 0): continue nx, ny = x+i, y+j if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]): ...
import pytest from solution import get_neighbours, is_low_point, solve_day9_part1 def test_get_neighbours(): grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] assert get_neighbours(1, 1, grid) == [1, 2, 3, 4, 6, 7, 8, 9] assert get_neighbours(0, 0, grid) == [2, 4, 5] def test_is_low_p...
[ { "docstring": null, "function_declaration": "def get_neighbours(x, y, grid):", "function_name": "get_neighbours", "parameter_list": "(x, y, grid)" }, { "docstring": null, "function_declaration": "def is_low_point(x, y, grid):", "function_name": "is_low_point", "parameter_list": ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def main(input_file):\n with open(input_file, 'r') as file:\n grid = [list(map(int, line.strip())) for line in file.readlines()]\n\n result = solve_day9_part1(grid)\n print(res...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00011811", "row_id": 11811, "seed_ids": "['Llama-3.3-70B-Instruct_31172']" }
0.530426
Filter_11811
I
[ "get_neighbours", "is_low_point", "solve_day9_part1", "main" ]
4
[ [ "is_low_point", "get_neighbours" ], [ "solve_day9_part1", "is_low_point" ] ]
2
[]
false
[]
false
pytest
true
[]
true
412d97be51128b5d79b3cdc9de2910251403b29e
df63883309dd864d589f2bd286e2c7acd1474f7c
v1.0
instruct
Filter
Filter_11967_I
I have a list of companies and their respective websites. I want to write a script that will go through this list, visit each website, and extract the name of the company from the website's HTML content. This script should be able to handle broken links and exceptions. How do I write such a script?
import requests from bs4 import BeautifulSoup def extract_company_name(url): """ Extract the company name from the given website URL. This function handles exceptions for broken links and other errors. """ headers = {'User-Agent': 'Mozilla/5.0'} try: response = requests.get(url, headers...
import pytest from solution import extract_company_name, extract_company_names def test_extract_company_name_valid_url(monkeypatch): class MockResponse: @staticmethod def raise_for_status(): pass def __init__(self, content): self.content = content ...
[ { "docstring": "Extract the company name from the given website URL.\nThis function handles exceptions for broken links and other errors.", "function_declaration": "def extract_company_name(url):", "function_name": "extract_company_name", "parameter_list": "(url)" }, { "docstring": "Goes thr...
[ 0, 0, 0, 1, 1, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\n\ndef extract_company_name_from_website(url):\n \"\"\"\n Extracts the company name from the HTML content of the given URL.\n \"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00011967", "row_id": 11967, "seed_ids": "['Llama-3.3-70B-Instruct_31514']" }
0.636689
Filter_11967
I
[ "extract_company_name", "extract_company_names" ]
2
[ [ "extract_company_names", "extract_company_name" ] ]
1
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
83e608e5854c39a948d97ad01123d664b525a769
b364c31b35aaead24452c244a556b34e9a29fb9e
v1.0
instruct
Filter
Filter_12023_I
I would like to know how to create a basic simulation using Python. I want to create a simulation of a roller coaster. Here's what I'm thinking: the roller coaster will consist of hills and a flat track. Hills will be modeled as a parabola, and the flat track will be modeled as a straight line. I can calculate the ...
import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation def parabola(x, a=1, h=0, k=0): """ Returns the y value of a parabola. y = a*(x-h)^2 + k """ return a * (x - h)**2 + k def flat_track(x, k=0): """ Returns the y value of a flat track. y = k ...
from solution import parabola, flat_track, generate_roller_coaster_path import numpy as np def test_parabola(): assert parabola(0) == 0 assert parabola(1, 1, 0, 0) == 1 assert parabola(2, 0.5, 0, 0) == 2 def test_flat_track(): x = np.array([0, 1, 2]) np.testing.assert_array_equal(flat_track(x, k=5...
[ { "docstring": "Returns the y value of a parabola.\ny = a*(x-h)^2 + k", "function_declaration": "def parabola(x, a=1, h=0, k=0):", "function_name": "parabola", "parameter_list": "(x, a=1, h=0, k=0)" }, { "docstring": "Returns the y value of a flat track.\ny = k", "function_declaration": ...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n# Define the time array\ntime = np.linspace(0, 10, 500)\n\n# Define the parabola for the ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00012023", "row_id": 12023, "seed_ids": "['Llama-3.3-70B-Instruct_31652']" }
0.439559
Filter_12023
I
[ "parabola", "flat_track", "generate_roller_coaster_path", "animate_roller_coaster" ]
4
[ [ "generate_roller_coaster_path", "flat_track" ], [ "generate_roller_coaster_path", "parabola" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
0bf763f1edbf82a16b6e2685958f32227b57f00e
e37dcf5145072056e65038ce5cf6cbe0e3294c42
v1.0
instruct
Filter
Filter_12054_I
Here is a code that can be used for the Caesar Cipher: ```python def caesar_cipher(text, shift): """ Encrypts or decrypts a message using the Caesar Cipher. Parameters: text (str): The input message to be encrypted or decrypted. shift (int): The shift value for the Caesar Cipher. Returns: ...
import tkinter as tk from tkinter import ttk def caesar_cipher(text, shift): """ Encrypts or decrypts a message using the Caesar Cipher. Parameters: text (str): The input message to be encrypted or decrypted. shift (int): The shift value for the Caesar Cipher. Returns: str: The encrypted ...
from solution import caesar_cipher def test_caesar_cipher_encrypt(): assert caesar_cipher("ABC", 1) == "BCD" assert caesar_cipher("XYZ", 3) == "ABC" assert caesar_cipher("Hello, World!", 3) == "Khoor, Zruog!" def test_caesar_cipher_decrypt(): assert caesar_cipher("BCD", -1) == "ABC" assert caesar_...
[ { "docstring": "Encrypts or decrypts a message using the Caesar Cipher.\n\nParameters:\ntext (str): The input message to be encrypted or decrypted.\nshift (int): The shift value for the Caesar Cipher.\n\nReturns:\nstr: The encrypted or decrypted message.", "function_declaration": "def caesar_cipher(text, sh...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\nfrom tkinter import messagebox\n\ndef caesar_cipher(text, shift):\n \"\"\"\n Encrypts or decrypts a message using the Caesar Cipher.\n\n Parameters:\n text (s...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00012054", "row_id": 12054, "seed_ids": "['Llama-3.3-70B-Instruct_31713']" }
0.502715
Filter_12054
I
[ "caesar_cipher", "on_submit", "main" ]
3
[ [ "on_submit", "caesar_cipher" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e98b8e5dd96e2cf1ca4b637583266af28535627
881de758f1369089b6895b9c3ab17d282f472cc1
v1.0
instruct
Filter
Filter_12189_I
I've been looking at questions on your site and I'd like to know how to implement efficient basic algorithms, specifically the Knuth-Morris-Pratt algorithm for string searching.
def compute_lps(pattern): """ Compute the longest proper prefix which is also a suffix (lps) array for the pattern. """ lps = [0] * len(pattern) length = 0 i = 1 while i < len(pattern): if pattern[i] == pattern[length]: length += 1 lps[i] = length ...
from solution import kmp_search def test_kmp_search_no_match(): assert kmp_search("abcde", "fgh") == [] def test_kmp_search_single_match(): assert kmp_search("abcde", "bcd") == [1] def test_kmp_search_multiple_matches(): assert kmp_search("abababab", "ab") == [0, 2, 4, 6] def test_kmp_search_pattern_ent...
[ { "docstring": "Compute the longest proper prefix which is also a suffix (lps) array for the pattern.", "function_declaration": "def compute_lps(pattern):", "function_name": "compute_lps", "parameter_list": "(pattern)" }, { "docstring": "Searches the pattern in the given text using the KMP a...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def kmp_search(pattern, text):\n \"\"\"\n Implementation of the Knuth-Morris-Pratt (KMP) string searching algorithm.\n Returns the starting indices of occurrences of the pattern in th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00012189", "row_id": 12189, "seed_ids": "['Llama-3.3-70B-Instruct_32022']" }
0.344532
Filter_12189
I
[ "compute_lps", "kmp_search" ]
2
[ [ "kmp_search", "compute_lps" ] ]
1
[]
false
[]
false
pytest
true
[]
true
630484f977bab214f56b2b0647b5fffea072f562
bbe96017b29ae59d6809e8d8478530e71a62a0fe
v1.0
instruct
Filter
Filter_12229_I
Here is my algorithm for finding the maximum sum of a submatrix within a given matrix: ``` def max_submatrix_sum(matrix): rows = len(matrix) cols = len(matrix[0]) max_sum = float('-inf') for left in range(cols): for right in range(left, cols): temp = [0] * rows for i in...
def max_submatrix_sum(matrix): rows = len(matrix) cols = len(matrix[0]) max_sum = float('-inf') for left in range(cols): for right in range(left, cols): temp = [0] * rows for i in range(rows): for j in range(left, right + 1): temp[i] +...
from solution import max_submatrix_sum, max_subarray_sum def test_max_submatrix_sum_basic(): matrix = [ [1, -2, 1], [-3, 4, 1], [1, -1, 3] ] assert max_submatrix_sum(matrix) == 7 # Expected max sum submatrix is [[4, 1], [-1, 3]] def test_max_submatrix_sum_all_negative(): matri...
[ { "docstring": null, "function_declaration": "def max_submatrix_sum(matrix):", "function_name": "max_submatrix_sum", "parameter_list": "(matrix)" }, { "docstring": null, "function_declaration": "def max_subarray_sum(arr):", "function_name": "max_subarray_sum", "parameter_list": "...
[ 0, 0, 0, 1, 1, 0, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_submatrix_sum(matrix):\n \"\"\"\n Returns the maximum sum of a submatrix within the given 2D matrix.\n \"\"\"\n rows = len(matrix)\n cols = len(matrix[0])\n max_sum =...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00012229", "row_id": 12229, "seed_ids": "['Llama-3.3-70B-Instruct_32130']" }
0.561333
Filter_12229
I
[ "max_submatrix_sum", "max_subarray_sum" ]
2
[ [ "max_submatrix_sum", "max_subarray_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
619db2650220bcb0cf0c2f9fa97799d3afd9e0ea
de0d053db415d911f234f19e084727999fe33113
v1.0
instruct
Filter
Filter_12494_I
You have been tasked with the job of creating a program that will take a list of numbers as input, find the most frequent number, and then delete all occurrences of that number from the list. Please create such a program using Python. Please include comments to explain how it works. ```python # Import the required...
# Import the required libraries import collections def delete_most_frequent(lst): """ Deletes all occurrences of the most frequent number in a list. Args: lst (list): A list of numbers. Returns: list: The list with all occurrences of the most frequent number removed. """ ...
from solution import delete_most_frequent, process_multiple_lists def test_delete_most_frequent_empty_list(): assert delete_most_frequent([]) == [] def test_delete_most_frequent_single_element_list(): assert delete_most_frequent([1]) == [] def test_delete_most_frequent_all_same_elements(): assert delete_...
[ { "docstring": "Deletes all occurrences of the most frequent number in a list.\n\nArgs:\n lst (list): A list of numbers.\n\nReturns:\n list: The list with all occurrences of the most frequent number removed.", "function_declaration": "def delete_most_frequent(lst):", "function_name": "delete_most_...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import collections\n\ndef delete_most_frequent(lst):\n \"\"\"\n Deletes all occurrences of the most frequent number in a list.\n \n Args:\n lst (list): A list of numbers.\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00012494", "row_id": 12494, "seed_ids": "['Llama-3.3-70B-Instruct_32706']" }
0.623976
Filter_12494
I
[ "delete_most_frequent", "process_multiple_lists", "get_user_input" ]
3
[ [ "process_multiple_lists", "delete_most_frequent" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4530be01d713aa623cdb079cda12cfc2285f524e
2730926bc9e6108a985ca36cf58c4be6e1360d25
v1.0
instruct
Filter
Filter_12579_I
I have written a simple ray tracing algorithm that can render 3D scenes. I am trying to implement a feature to support rendering reflective surfaces. The problem is, I am not sure how to handle recursive ray tracing where the recursive depth limit is reached and the ray hits a reflective surface. Here are the main fun...
import numpy as np MAX_DEPTH = 5 def intersect(ray, scene): closest_object = None closest_distance = float('inf') for obj in scene.objects: distance = obj.intersect(ray) if distance is not None and distance < closest_distance: closest_object = obj closest_distance =...
import pytest import numpy as np from solution import intersect, calculate_color, Ray, Material, base_color class MockObject: def __init__(self, color, reflective, distance): self.material = Material(color, reflective) self.color = color self._distance = distance def intersect(self, ra...
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\nMAX_DEPTH = 5\n\ndef intersect(ray, scene):\n closest_object = None\n closest_distance = float('inf')\n for obj in scene.objects:\n distance = obj.interse...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00012579", "row_id": 12579, "seed_ids": "['Llama-3.3-70B-Instruct_32888']" }
0.293223
Filter_12579
I
[ "intersect", "calculate_color", "base_color" ]
3
[ [ "base_color", "intersect" ], [ "calculate_color", "base_color" ], [ "calculate_color", "intersect" ] ]
3
[]
false
[ "Ray", "Material" ]
true
pytest
true
[ "numpy" ]
false
b8046a2e1029ec48d6bbfda913d94c2dc567935a
50a18f30e9da6bb50c4ae33b0a4e1050b637e58a
v1.0
instruct
Filter
Filter_12675_I
### Overview The project is a Python script that uses a genetic algorithm to evolve a population of candidate solutions for a given problem. The goal is to find the optimal solution by iteratively selecting, breeding, and mutating individuals. ### Genetic Algorithm Requirements - The problem to be solved is to find th...
import numpy as np def generate_initial_population(size, min_x, max_x): """ Generate an initial population of random floating-point numbers. Args: size (int): The size of the population. min_x (float): The minimum value for the random numbers. max_x (float): The maximum value for the random nu...
import pytest from solution import generate_initial_population, calculate_fitness, tournament_selection, uniform_crossover, gaussian_mutation def test_generate_initial_population(): population = generate_initial_population(100, -10, 10) assert len(population) == 100 assert all(-10 <= x <= 10 for x in popul...
[ { "docstring": "Generate an initial population of random floating-point numbers.\n\nArgs:\nsize (int): The size of the population.\nmin_x (float): The minimum value for the random numbers.\nmax_x (float): The maximum value for the random numbers.\n\nReturns:\nlist: A list of floating-point numbers representing ...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef generate_initial_population(size, min_x, max_x):\n \"\"\"\n Generate an initial population of random floating-point numbers.\n\n Args:\n size (int): The s...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00012675", "row_id": 12675, "seed_ids": "['Llama-3.3-70B-Instruct_33095']" }
0.484053
Filter_12675
I
[ "generate_initial_population", "calculate_fitness", "tournament_selection", "uniform_crossover", "gaussian_mutation", "genetic_algorithm" ]
6
[ [ "genetic_algorithm", "calculate_fitness" ], [ "genetic_algorithm", "gaussian_mutation" ], [ "genetic_algorithm", "generate_initial_population" ], [ "genetic_algorithm", "tournament_selection" ], [ "genetic_algorithm", "uniform_crossover" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy" ]
false
b4d2d47b97a934d35d6f05526845e43a5439f889
6ab3b77d75addede456929202701fb3af8ef78a4
v1.0
instruct
Filter
Filter_13016_I
I have a simple neural network and I want to know how to predict the output with the given input for the network. I have the following network architecture: * Input layer with 2 neurons * Hidden layer with 2 neurons and sigmoid activation * Output layer with 1 neuron and sigmoid activation Let's assume that the w...
import numpy as np def sigmoid(x): """ Sigmoid activation function. """ return 1 / (1 + np.exp(-x)) def predict(inputs): """ Predict the output of the network given the input. """ # Define weights and biases weights_input_to_hidden = np.array([[0.1, 0.2], [0.3, 0.4]]) bias_hidd...
from solution import predict def test_predict(): # Testing with input [0.5, 0.6] inputs = np.array([0.5, 0.6]) expected_output = sigmoid(np.dot(sigmoid(np.dot(inputs, np.array([[0.1, 0.2], [0.3, 0.4]])) + np.array([0.5, 0.6])), np.array([[0.7], [0.8]])) + np.array([0.9])) output = predict(inputs) ...
[ { "docstring": "Sigmoid activation function.", "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": "Predict the output of the network given the input.", "function_declaration": "def predict(inputs):", "function_name": "pred...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Sigmoid activation function.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef predict(input_data):\n \"\"\"\n Predict the output...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00013016", "row_id": 13016, "seed_ids": "['Llama-3.3-70B-Instruct_33826']" }
0.467523
Filter_13016
I
[ "sigmoid", "predict" ]
2
[ [ "predict", "sigmoid" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
5b933c321cff5ffaeb1bf05a1640375ea589a57f
48a96110dcf63585054615449afe54bff7ad84ff
v1.0
instruct
Filter
Filter_13029_I
Here's a simple function that will print values to the console. The function will take in a string of input and print out the values of each word as a sum of the position of each letter in the alphabet. For example, the word "cat" would have a value of 3 + 1 + 20 = 24. Here's the code: ```python def word_value(wor...
def word_value(word): """ Calculate the value of a word as the sum of the position of each letter in the alphabet. Args: word (str): The word to calculate the value for. Returns: int: The calculated value of the word. """ value = 0 for char in word: if char.isalpha(): ...
from solution import word_value, print_word_values def test_word_value_single_word(): assert word_value("cat") == 24 assert word_value("zoo") == 26 + 15 + 15 assert word_value("a") == 1 def test_word_value_with_uppercase(): assert word_value("Cat") == 24 assert word_value("ZOO") == 26 + 15 + 15 d...
[ { "docstring": "Calculate the value of a word as the sum of the position of each letter in the alphabet.\n\nArgs:\nword (str): The word to calculate the value for.\n\nReturns:\nint: The calculated value of the word.", "function_declaration": "def word_value(word):", "function_name": "word_value", "p...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def word_value(word):\n \"\"\"\n Calculate the value of a word as the sum of the position of each letter in the alphabet.\n\n Parameters:\n word (str): The word to calculate the va...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00013029", "row_id": 13029, "seed_ids": "['Llama-3.3-70B-Instruct_33854']" }
0.543733
Filter_13029
I
[ "word_value", "print_word_values", "main" ]
3
[ [ "print_word_values", "word_value" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e720592390ba1e3a9976938c4deef54063c7aa09
a4d27bf8700159f98630d6068e052f34ce09ed51
v1.0
instruct
Filter
Filter_13083_I
I am looking to build a custom AI chatbot using Python. I'm interested in using natural language processing (NLP) techniques to analyze user input and respond accordingly. Can you guide me through the process of building a simple chatbot? ### Prerequisites * Python 3.8 or later * Basic understanding of Python programm...
import re responses = { "hello": "Hello! How can I help you today?", "bye": "Goodbye! Have a great day!", "how are you": "I'm just a bot, but I'm doing great!", "default": "I'm sorry, I don't understand that." } def preprocess_input(user_input): """ Preprocesses the user input by converting it...
from solution import preprocess_input, get_response def test_preprocess_input(): assert preprocess_input("Hello, World!") == "hello world" assert preprocess_input("How are you?") == "how are you" assert preprocess_input("I'm fine, thank you.") == "im fine thank you" def test_get_response_hello(): asse...
[ { "docstring": "Preprocesses the user input by converting it to lowercase and removing punctuation.", "function_declaration": "def preprocess_input(user_input):", "function_name": "preprocess_input", "parameter_list": "(user_input)" }, { "docstring": "Returns an appropriate response based on...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import nltk\nfrom nltk.chat.util import Chat, reflections\n\n# Ensure NLTK data packages are downloaded\nnltk.download('punkt')\n\ndef chatbot():\n patterns = [\n (r'hi|hello', ['Hel...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00013083", "row_id": 13083, "seed_ids": "['Llama-3.3-70B-Instruct_33979']" }
0.345496
Filter_13083
I
[ "preprocess_input", "get_response", "chatbot" ]
3
[ [ "chatbot", "get_response" ], [ "get_response", "preprocess_input" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3b397dce1720b9cef575cad46d7fc16eb61e22ab
d5b37845b44c0f63f371a332bcb1725c0ce45e68
v1.0
instruct
Filter
Filter_13160_I
I have a series of words and I want to see how many of them can be combined into valid English words by adding, removing or replacing letters. Example: input: ["cat", "hat", "car", "bar"] output: ["cat", "hat", "car", "bar", "bat", "cart"] Here is what I've done so far, but I'm not sure how to generate all possible...
import string def find_related_words(words): dictionary = {"cat", "hat", "car", "bar", "bat", "cart"} related_words = set(words) for word in words: # Adding a character for char in string.ascii_lowercase: for i in range(len(word) + 1): new_word = word[:i] + ...
from solution import find_related_words def test_find_related_words_basic_case(): words = ["cat", "hat", "car", "bar"] related_words = find_related_words(words) expected_output = {"cat", "hat", "car", "bar", "bat", "cart"} assert related_words == expected_output def test_find_related_words_empty_input...
[ { "docstring": null, "function_declaration": "def find_related_words(words):", "function_name": "find_related_words", "parameter_list": "(words)" }, { "docstring": null, "function_declaration": "def is_valid_word(word, dictionary):", "function_name": "is_valid_word", "parameter_l...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "import string\n\ndef generate_related_words(word, word_set):\n related_words = set()\n\n # Add letters\n for i in range(len(word) + 1):\n for letter in...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00013160", "row_id": 13160, "seed_ids": "['Llama-3.3-70B-Instruct_34159']" }
0.683346
Filter_13160
I
[ "find_related_words", "is_valid_word" ]
2
[ [ "find_related_words", "is_valid_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8503ce59478647b511189a3a8545b67bff284bcc
1111d85cd7deb926dee8caa33c353aedfc6530d9
v1.0
instruct
Filter
Filter_13180_I
I've been given a task to classify the sentiment of text using Natural Language Processing (NLP) techniques. I'm required to implement a sentiment analysis model using a supervised learning approach. I've decided to use Python and its relevant libraries to perform this task. However, I would like to know more about t...
import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score, classification_report def load_data(): # For this example, we assume a dataset with 'review'...
import pytest from solution import load_data, preprocess_data, vectorize_data, train_model, evaluate_model def test_load_data(): df = load_data() assert 'review' in df.columns assert 'sentiment' in df.columns def test_preprocess_data(): df = load_data() processed_df = preprocess_data(df) asser...
[ { "docstring": null, "function_declaration": "def load_data():", "function_name": "load_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def preprocess_data(df):", "function_name": "preprocess_data", "parameter_list": "(df)" }, { "docstring":...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom skle...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00013180", "row_id": 13180, "seed_ids": "['Llama-3.3-70B-Instruct_34199']" }
0.55366
Filter_13180
I
[ "load_data", "preprocess_data", "vectorize_data", "train_model", "evaluate_model", "sentiment_analysis" ]
6
[ [ "sentiment_analysis", "evaluate_model" ], [ "sentiment_analysis", "load_data" ], [ "sentiment_analysis", "preprocess_data" ], [ "sentiment_analysis", "train_model" ], [ "sentiment_analysis", "vectorize_data" ] ]
5
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
be88cb295f6a518ca6cab539b450ed86f5a70f35
aa333301d4be7f72cd1381ed0eceb1e4a776733a
v1.0
instruct
Filter
Filter_13209_I
I have a dynamic function, with 2 parameters, that needs to be registered to an on-screen button. On button click, I want to pass 2 arguments to this function. Is this possible in Python?
import tkinter as tk def dynamic_function(arg1, arg2): """ A dynamic function that takes two arguments and returns their concatenation. """ return f"Arguments received: {arg1} and {arg2}" def on_button_click(arg1, arg2): result = dynamic_function(arg1, arg2) print(result) return result # ...
from solution import dynamic_function, on_button_click def test_dynamic_function(): result = dynamic_function("Hello", "World") assert result == "Arguments received: Hello and World" def test_on_button_click(): result = on_button_click("Hello", "World") assert result == "Arguments received: Hello and ...
[ { "docstring": "A dynamic function that takes two arguments and returns their concatenation.", "function_declaration": "def dynamic_function(arg1, arg2):", "function_name": "dynamic_function", "parameter_list": "(arg1, arg2)" }, { "docstring": null, "function_declaration": "def on_button...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\n\ndef dynamic_function(a, b):\n \"\"\"\n Returns the product of a and b.\n \"\"\"\n return a * b\n\ndef on_button_click():\n # Example arguments to pass\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00013209", "row_id": 13209, "seed_ids": "['Llama-3.3-70B-Instruct_34265']" }
0.385362
Filter_13209
I
[ "dynamic_function", "on_button_click", "create_gui" ]
3
[ [ "create_gui", "on_button_click" ], [ "on_button_click", "dynamic_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
69545a61ca090def46df695ba6e4b13ee1358a01
2741b9cea1307ccdd0857d3abaea44d65c15c41b
v1.0
instruct
Filter
Filter_13317_I
Based on the following code, I want to create a new function `get_sorted_documents` that will sort the documents by last modification date in descending order and return a list of dictionaries where each dictionary represents a document and has three keys: 'name', 'modified', 'size'. Here is the existing code: ```pyt...
import os def get_documents(directory): documents = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(('.txt', '.doc', '.docx', '.pdf')): file_path = os.path.join(root, file) file_modified = os.path.getmtime(file_path) ...
import os import pytest from unittest.mock import patch, mock_open from solution import get_documents, get_sorted_documents def test_get_documents(): directory = '/mock/directory' documents = [ ('document1.txt', 1643723400.0, 1024), ('document2.pdf', 1643723390.0, 2048), ('document3.doc...
[ { "docstring": null, "function_declaration": "def get_documents(directory):", "function_name": "get_documents", "parameter_list": "(directory)" }, { "docstring": null, "function_declaration": "def get_sorted_documents(directory):", "function_name": "get_sorted_documents", "parame...
[ 0, 0, 0, 1, 1, 1, 0, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef get_documents(directory):\n documents = []\n for root, dirs, files in os.walk(directory):\n for file in files:\n if file.endswith(('.txt', '.doc', '.do...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00013317", "row_id": 13317, "seed_ids": "['Llama-3.3-70B-Instruct_34548']" }
0.671321
Filter_13317
I
[ "get_documents", "get_sorted_documents" ]
2
[ [ "get_sorted_documents", "get_documents" ] ]
1
[]
false
[]
false
pytest
true
[]
true
091a19cf2b56ec0e8656a099e39cb4e4fce65a33
2696db2cf810ea104f87b271ad60c7eb27564e39
v1.0
instruct
Filter
Filter_13620_I
Your task is to create a simple Python script that can process a pair of files: 1) a data file with several rows and ‘n’ number of columns, and 2) a template file with a header row. The script will find the file names from the command line arguments, read the data file and the template file, and use the data from the d...
import sys import csv def read_file(file_path): """ Reads a CSV file and returns its content as a list of rows. """ with open(file_path, mode='r', newline='') as file: reader = csv.reader(file) return list(reader) def write_file(file_path, content): """ Writes content to a CSV ...
import os import csv import pytest from solution import read_file, write_file, process_files TEST_DATA_FILE = 'test_data.csv' TEST_TEMPLATE_FILE = 'test_template.csv' TEST_OUTPUT_FILE = 'test_output.csv' def create_csv(file_path, content): with open(file_path, mode='w', newline='') as file: writer = csv.w...
[ { "docstring": "Reads a CSV file and returns its content as a list of rows.", "function_declaration": "def read_file(file_path):", "function_name": "read_file", "parameter_list": "(file_path)" }, { "docstring": "Writes content to a CSV file.", "function_declaration": "def write_file(file...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport csv\n\ndef process_files(data_file, template_file):\n # Read the template file\n with open(template_file, 'r') as tmpl_file:\n template = tmpl_file.readline().s...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00013620", "row_id": 13620, "seed_ids": "['Llama-3.3-70B-Instruct_35283']" }
0.572633
Filter_13620
I
[ "read_file", "write_file", "process_files" ]
3
[ [ "process_files", "read_file" ], [ "process_files", "write_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
777d55ebee63f647465f3b120755418282121926
05a342c190f94521f294a6d5a98a914822a649a7
v1.0
instruct
Filter
Filter_13649_I
Let's develop a simple real-time chat application in Python. We'll need to create a server that can handle multiple clients. Our chat server will have the following features: - Allow multiple clients to connect to the server - Broadcast messages from one client to all other connected clients - Handle client disconnect...
import socket import threading clients = [] def broadcast(message, client_socket): """ Sends the message to all clients except the sender. """ for client in clients: if client != client_socket: try: client.send(message) except: # In case ...
import socket import threading import time def test_start_server(): """ Test to start the server and check connections. """ server_thread = threading.Thread(target=start_server) server_thread.daemon = True server_thread.start() time.sleep(1) # Wait a bit for the server to start # Conn...
[ { "docstring": "Sends the message to all clients except the sender.", "function_declaration": "def broadcast(message, client_socket):", "function_name": "broadcast", "parameter_list": "(message, client_socket)" }, { "docstring": "Handles the client's messages and broadcasts them to other cli...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import socket\nimport threading\n\nclients = []\n\ndef broadcast(message, client_socket):\n for client in clients:\n if client != client_socket:\n try:\n cl...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00013649", "row_id": 13649, "seed_ids": "['Llama-3.3-70B-Instruct_35356']" }
0.68799
Filter_13649
I
[ "broadcast", "handle_client", "remove_client", "start_server" ]
4
[ [ "broadcast", "remove_client" ], [ "handle_client", "broadcast" ], [ "handle_client", "remove_client" ] ]
3
[]
false
[]
false
pytest
false
[]
true
c6492777364f87c55f655c127e5688127dd289b2
8ef61d4c50caba1852f3bddd13a068e9b86dd655
v1.0
instruct
Filter
Filter_13697_I
I have an assignment where I'm required to build a hangman game. The word to be guessed is randomly selected from a predefined list of words. I need help with generating a list of words for the game and implementing the game logic. Here are the requirements: - The game should allow the user to guess the word by sugge...
import random # List of words to guess from word_list = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew'] # Function to run the hangman game def hangman(): word_to_guess = random.choice(word_list) word_length = len(word_to_guess) display = ['_'] * word_length guessed...
from solution import hangman, display_hangman def test_display_initial_stage(): assert display_hangman(6) == """ -------- | | | | | | - """ ...
[ { "docstring": null, "function_declaration": "def hangman():", "function_name": "hangman", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def display_hangman(tries):", "function_name": "display_hangman", "parameter_list": "(tries)" } ]
[ 0, 0, 0, 1, 0, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nword_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n\nclass HangmanGame:\n def __init__(self, word_list):\n self.word_list = word_list\n self.sco...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00013697", "row_id": 13697, "seed_ids": "['Llama-3.3-70B-Instruct_35474']" }
0.56031
Filter_13697
I
[ "hangman", "display_hangman" ]
2
[ [ "hangman", "display_hangman" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cfdc3d9f93112c38ec3aa963dd5a30d3595f772e
abe77f1556e867ea1f2395e4ffb6c19e7e65896f
v1.0
instruct
Filter
Filter_13767_I
Given the following Python code: ``` def check_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True def find_decompositions(N): primes = [i for i in range(2, N+1) if check_prime(i)] result = set() for prime in primes: ...
def check_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def find_decompositions(N): primes = [i for i in range(2, N+1) if check_prime(i)] result = set() def generate_products(i, product): if pro...
from solution import check_prime, find_decompositions def test_check_prime(): assert check_prime(2) == True assert check_prime(3) == True assert check_prime(4) == False assert check_prime(17) == True assert check_prime(20) == False def test_find_decompositions(): assert find_decompositions(10)...
[ { "docstring": null, "function_declaration": "def check_prime(n):", "function_name": "check_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_decompositions(N):", "function_name": "find_decompositions", "parameter_list": "(N)" }, { ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef find_prime_powers(N...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00013767", "row_id": 13767, "seed_ids": "['Llama-3.3-70B-Instruct_35656']" }
0.63404
Filter_13767
I
[ "check_prime", "find_decompositions" ]
2
[ [ "find_decompositions", "check_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
444e12c88a6dde1c2535538bf95a459de21970fc
38b19fe4827200c1053439f267970a70bc3ca5f0
v1.0
instruct
Filter
Filter_13888_I
This is a reference solution for simple chess move generation. The code provided here is to generate legal moves for the pieces on the board. The structure of the code here may seem complex, but the system can easily be expanded to check for checkmates, or generate a minimax algorithm for making decisions. This is jus...
import itertools # Define the piece types PIECE_TYPES = { 'K': 'King', 'Q': 'Queen', 'R': 'Rook', 'B': 'Bishop', 'N': 'Knight', 'P': 'Pawn' } # Define the possible moves for each piece type PIECE_MOVES = { 'K': [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)], 'Q'...
from solution import generate_moves, piece_color def test_king_moves(): board = [[0]*8 for _ in range(8)] board[4][4] = 'K' expected_moves = [(5, 4), (3, 4), (4, 5), (4, 3), (5, 5), (3, 3), (5, 3), (3, 5)] generated_moves = generate_moves(board, 'K', 4, 4) assert sorted(generated_moves) == sorted(e...
[ { "docstring": null, "function_declaration": "def piece_color(piece):", "function_name": "piece_color", "parameter_list": "(piece)" }, { "docstring": "Restrict moves, handle knight blocking, pawn details, and multiple pieces.\nDeal with castling, en-passant.\n(simplifying - not all features ...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\n# Define the piece types\nPIECE_TYPES = {\n 'K': 'King',\n 'Q': 'Queen',\n 'R': 'Rook',\n 'B': 'Bishop',\n 'N': 'Knight',\n 'P': 'Pawn'\n}\n\n# Define the...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00013888", "row_id": 13888, "seed_ids": "['Llama-3.3-70B-Instruct_35902']" }
0.570244
Filter_13888
I
[ "piece_color", "generate_moves", "print_board", "main" ]
4
[ [ "generate_moves", "piece_color" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e0eac8691dca67d50a9790d2ec68b5fc4061efe
f6900e4d0b02150cdaf828f3344469045e1dc073
v1.0
instruct
Filter
Filter_13938_I
### Programming Challenge: Hangman Game ===================================== ## Game Overview The game of Hangman is a guessing game where one player thinks of a word, and the other player tries to guess the word by suggesting letters. For each incorrect guess, a part of a hangman's gallows is drawn. The game continu...
import random def get_word(): words = ['hangman', 'python', 'java', 'programming', 'algorithm'] return random.choice(words).upper() def display_board(hidden_word, correct_guesses, incorrect_guesses): display = '' for letter in hidden_word: if letter in correct_guesses: display += l...
def test_get_word_length(): word = get_word() assert len(word) > 0 def test_display_board_initial(): hidden_word = "PYTHON" correct_guesses = set() incorrect_guesses = set() display, incorrect_display = display_board(hidden_word, correct_guesses, incorrect_guesses) assert display == "______...
[ { "docstring": null, "function_declaration": "def get_word():", "function_name": "get_word", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def display_board(hidden_word, correct_guesses, incorrect_guesses):", "function_name": "display_board", "parameter_...
[ 0, 0, 0, 0, 1, 1, 0, 0, 1 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nclass HangmanGame:\n def __init__(self, words):\n self.words = words\n self.reset_game()\n \n def reset_game(self):\n self.word = random.choi...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00013938", "row_id": 13938, "seed_ids": "['Llama-3.3-70B-Instruct_36024']" }
0.485011
Filter_13938
I
[ "get_word", "display_board", "hangman_gallows", "hangman_game" ]
4
[ [ "hangman_game", "display_board" ], [ "hangman_game", "get_word" ], [ "hangman_game", "hangman_gallows" ] ]
3
[]
false
[]
false
pytest
false
[]
true
04bf792404453d21d9ce9e18173e13af71fba8ec
fb3f8fd9230086d3ed8694cae86dc875f0c5cb84
v1.0
instruct
Filter
Filter_14068_I
### Overview A university is offering a new class on computer vision and image processing. The class is designed to teach students how to analyze and understand visual data from images and videos. The class will cover various techniques and tools used in the field, including deep learning models and traditional compute...
import cv2 import numpy as np def read_output(output_file): """ Reads the output of the student's code from a file. Supported types: .jpg, .png, .mp4 Parameters: output_file (str): The file path to the output to be read. Returns: output: The image in a form of numpy array or video capture...
import pytest from solution import read_output, compare_output, calculate_grade, auto_grade import numpy as np import cv2 def test_read_output_image(): img = np.ones((100, 100, 3), dtype=np.uint8) * 255 cv2.imwrite('temp_output.jpg', img) output = read_output('temp_output.jpg') assert output.shape == i...
[ { "docstring": "Reads the output of the student's code from a file.\nSupported types: .jpg, .png, .mp4\n\nParameters:\noutput_file (str): The file path to the output to be read.\n\nReturns:\noutput: The image in a form of numpy array or video capture object.", "function_declaration": "def read_output(output...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\nimport numpy as np\n\ndef read_output(output_file):\n \"\"\"\n Reads the output file of the student's code.\n \n Parameters:\n output_file (str): Path to the output ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00014068", "row_id": 14068, "seed_ids": "['Llama-3.3-70B-Instruct_36328']" }
0.527099
Filter_14068
I
[ "read_output", "compare_output", "calculate_grade", "auto_grade" ]
4
[ [ "auto_grade", "calculate_grade" ], [ "auto_grade", "compare_output" ], [ "auto_grade", "read_output" ] ]
3
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
a506a2f933231af497ee73442be832b8a927c459
1802e781596d9f268f7af0023d87f7966b2f00d7
v1.0
instruct
Filter
Filter_14118_I
I wrote a solution to the "Find Integer Inversion Count" problem, where the problem asks to find the number of inversions in a list of integers. An inversion is a pair of elements in the wrong order, i.e., a larger element appearing before a smaller element in the list. This is my code: ```python def find_inversions(...
def merge_sort(arr): if len(arr) <= 1: return arr, 0 mid = len(arr) // 2 left, left_inv = merge_sort(arr[:mid]) right, right_inv = merge_sort(arr[mid:]) merged, merge_inv = merge(left, right) return merged, left_inv + right_inv + merge_inv def merge(left, right): result = [] inv...
def test_find_inversions(): from solution import find_inversions def test_single_element_array(): assert find_inversions([1]) == 0 def test_sorted_array(): assert find_inversions([1, 2, 3, 4, 5]) == 0 def test_reverse_sorted_array(): assert find_inversions([5, 4, 3, 2,...
[ { "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)" }, { "docst...
[ 0, 0, 0, 0, 1, 1, 0, 0, 1, 1 ]
4
medium
0.4
{ "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, 0\n mid = len(arr) // 2\n left, left_inv = merge_sort(arr[:mid])\n right, right_inv = merge_sort(arr[mid:])\n merge...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00014118", "row_id": 14118, "seed_ids": "['Llama-3.3-70B-Instruct_36482']" }
0.666303
Filter_14118
I
[ "merge_sort", "merge", "find_inversions" ]
3
[ [ "find_inversions", "merge_sort" ], [ "merge_sort", "merge" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a71ad32eef7e18850ef2be594acf9251123beaa9
c27ca68c83f6ae8cf7236a8262c8ced47d99b5e7
v1.0
instruct
Filter
Filter_14243_I
I have a large whitespace-separated file containing digits (up to 50 digits long), and I would like to write a Python program that can convert these numbers from base 16 to base 10. However, I will need to modify it to handle longer than 50 digit numbers. In this point, I can make use of the built-in int() function ...
def hex_to_decimal(hex_number): """ Converts a hexadecimal number to a decimal number. Handles numbers longer than 50 digits. """ return int(hex_number, 16) def process_hex_file(file_path): """ Processes a file containing hexadecimal numbers and prints their decimal equivalents. """ ...
from solution import hex_to_decimal, process_hex_file import tempfile def test_hex_to_decimal(): assert hex_to_decimal('1') == 1 assert hex_to_decimal('A') == 10 assert hex_to_decimal('10') == 16 assert hex_to_decimal('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') == int('FFFFFFFFF...
[ { "docstring": "Converts a hexadecimal number to a decimal number.\nHandles numbers longer than 50 digits.", "function_declaration": "def hex_to_decimal(hex_number):", "function_name": "hex_to_decimal", "parameter_list": "(hex_number)" }, { "docstring": "Processes a file containing hexadecim...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def hex_to_decimal(hex_string):\n \"\"\"\n Convert a hexadecimal string to a decimal number.\n \"\"\"\n return int(hex_string, 16)\n\ndef process_hex_file(file_path):\n \"\"\"\n...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00014243", "row_id": 14243, "seed_ids": "['Llama-3.3-70B-Instruct_36772']" }
0.586068
Filter_14243
I
[ "hex_to_decimal", "process_hex_file" ]
2
[ [ "process_hex_file", "hex_to_decimal" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3e303cb8cbd16f6809a8741bdba20c8de293d515
6f84107694d4b1d6d3c6aa71eff207e7376b2773
v1.0
instruct
Filter
Filter_14258_I
### Convex Hull Given a set of points in the plane, find their convex hull using the Graham's scan algorithm. #### Problem Statement Implement the Graham's scan algorithm to find the convex hull of a set of given points. #### Code ```python import math import matplotlib.pyplot as plt def orientation(p, q, r): ""...
import math import matplotlib.pyplot as plt def orientation(p, q, r): """Find the orientation of an ordered triplet (p, q, r) of points.""" val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) if val == 0: return 0 # Collinear elif val > 0: return 1 # Clockwise else...
from solution import orientation, convex_hull def test_orientation(): assert orientation((0, 0), (1, 1), (2, 2)) == 0 # Collinear assert orientation((0, 0), (1, 1), (2, 0)) == 1 # Clockwise assert orientation((0, 0), (1, 1), (0, 2)) == 2 # Counterclockwise def test_convex_hull_with_collinear_points(): ...
[ { "docstring": "Find the orientation of an ordered triplet (p, q, r) of points.", "function_declaration": "def orientation(p, q, r):", "function_name": "orientation", "parameter_list": "(p, q, r)" }, { "docstring": "Compute the convex hull of a set of points.", "function_declaration": "d...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef orientation(p, q, r):\n \"\"\"Find the orientation of an ordered triplet (p, q, r) of points.\"\"\"\n val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00014258", "row_id": 14258, "seed_ids": "['Llama-3.3-70B-Instruct_36807']" }
0.50599
Filter_14258
I
[ "orientation", "convex_hull", "plot_convex_hull" ]
3
[ [ "convex_hull", "orientation" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib" ]
false
4405167336a5e3594eaaeff9d77726cce39b7896
049af31b191b3bd92ebb4f24fddf4f04f8e3ff02
v1.0
instruct
Filter
Filter_14385_I
I am having trouble with an algorithm and I am looking for some guidance on how to create a correct implementation. Here is my algorithm: 1. Start with 4 "starting" nodes (A, B, C, D) that each consist of 2 sub-nodes (1 and 2). 2. Set the "starting" node's sub-nodes as active. 3. Iterate through the sub-nodes, st...
class Node: def __init__(self, name): self.name = name self.sub_nodes = [SubNode(1), SubNode(2)] self.is_active = True class SubNode: def __init__(self, name): self.name = name self.is_active = True def __repr__(self): return f"SubNode({self.name}, is_active...
from solution import create_starting_nodes, algorithm, Node def test_algorithm(): nodes = create_starting_nodes() result = algorithm(nodes) # As per the algorithm, we should be left with one starting node assert isinstance(result, Node) assert result.name in ["A", "B", "C", "D"] assert len...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Node:\n def __init__(self, name):\n self.name = name\n self.sub_nodes = [SubNode(\"1\"), SubNode(\"2\")]\n\n def active_sub_nodes_count(self):\n return sum(sub...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00014385", "row_id": 14385, "seed_ids": "['Llama-3.3-70B-Instruct_37083']" }
0.538397
Filter_14385
I
[ "count_active_subnodes", "algorithm", "create_starting_nodes" ]
3
[ [ "algorithm", "count_active_subnodes" ] ]
1
[]
false
[ "Node", "SubNode" ]
true
pytest
true
[]
true
65ab833962c14a7bee0753f0e094d64a425e8e0a
115c85fe5d341bf7f640ff498b8cf96af2a7fc46
v1.0
instruct
Filter
Filter_14485_I
Here is a script that converts infix to postfix: ```python def isoperator(char): """Check if a character is an operator.""" if char in ["+", "-", "*", "/"]: return True else: return False def precedence(operator): """Define the precedence of operators.""" precedence_dict = {"+": 1, ...
def isoperator(char): """Check if a character is an operator.""" if char in ["+", "-", "*", "/"]: return True else: return False def precedence(operator): """Define the precedence of operators.""" precedence_dict = {"+": 1, "-": 1, "*": 2, "/": 2} return precedence_dict.get(oper...
from solution import convert_infix_to_postfix def test_basic_expression(): assert convert_infix_to_postfix("2+3") == "2 3 +" def test_multiple_operators(): assert convert_infix_to_postfix("2+3*4") == "2 3 4 * +" def test_expression_with_parentheses(): assert convert_infix_to_postfix("(2+3)*4") == "2 ...
[ { "docstring": "Check if a character is an operator.", "function_declaration": "def isoperator(char):", "function_name": "isoperator", "parameter_list": "(char)" }, { "docstring": "Define the precedence of operators.", "function_declaration": "def precedence(operator):", "function_na...
[ 0, 0, 0, 0, 0, 1, 1, 0, 1 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def isoperator(char):\n \"\"\"Check if a character is an operator.\"\"\"\n if char in [\"+\", \"-\", \"*\", \"/\"]:\n return True\n else:\n return False\n\ndef precedenc...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00014485", "row_id": 14485, "seed_ids": "['Llama-3.3-70B-Instruct_37321']" }
0.451831
Filter_14485
I
[ "isoperator", "precedence", "convert_infix_to_postfix" ]
3
[ [ "convert_infix_to_postfix", "isoperator" ], [ "convert_infix_to_postfix", "precedence" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b244f57417d6b8bcbfb48ff2d3ecaa4234fefe45
420ec9a751ae8596380f5d9f0804614a225e13aa
v1.0
instruct
Filter
Filter_14560_I
Here is a small Python program that plays a game of Hangman. ```python def get_word(): return "hangman" def guess_letter(): letter = input("Guess a letter: ") return letter.lower() def draw_hangman(tries): stages = [ # final state: head, torso, both arms, and both legs # initial sta...
import random words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'] def get_word(): """ Function to get a random word from the predefined list. """ return random.choice(words) def guess_letter(): """ Function to get a guessed letter from the user. """ letter = in...
import pytest from solution import get_word, draw_hangman def test_get_word(): words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'] assert get_word() in words def test_draw_hangman(): stages = [ ''' -------- | | | | ...
[ { "docstring": "Function to get a random word from the predefined list.", "function_declaration": "def get_word():", "function_name": "get_word", "parameter_list": "()" }, { "docstring": "Function to get a guessed letter from the user.", "function_declaration": "def guess_letter():", ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nwords = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\n\ndef get_word():\n return random.choice(words)\n\ndef guess_letter():\n letter = input(\"Gu...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00014560", "row_id": 14560, "seed_ids": "['Llama-3.3-70B-Instruct_37504']" }
0.49289
Filter_14560
I
[ "get_word", "guess_letter", "draw_hangman", "play_game" ]
4
[ [ "play_game", "draw_hangman" ], [ "play_game", "get_word" ], [ "play_game", "guess_letter" ] ]
3
[]
false
[]
false
pytest
true
[]
true
785736bb275439dad00ba434273839e3a65ea420
b2c4e6fee011e66ac2ee6633b8f8677a6dbc0a26
v1.0
instruct
Filter
Filter_14606_I
I have written a code in python to solve this problem: You are given a 2D grid consisting of '1's (representing empty spaces) and '0's (representing obstacles). You need to find the shortest path from the top-left cell to the bottom-right cell while avoiding obstacles. Here is my code: ``` from collections import deq...
from collections import deque def is_valid_move(grid, visited, row, col): return (0 <= row < len(grid)) and (0 <= col < len(grid[0])) and grid[row][col] == '1' and not visited[row][col] def shortest_path(grid): if not grid or not grid[0]: return -1 directions = [(0, 1), (0, -1), (1, 0), (-1, ...
from solution import is_valid_move, shortest_path def test_is_valid_move(): grid = [ ['1', '0'], ['0', '1'] ] visited = [ [False, False], [False, False] ] assert is_valid_move(grid, visited, 0, 0) == True assert is_valid_move(grid, visited, 0, 1) == False ass...
[ { "docstring": null, "function_declaration": "def is_valid_move(grid, visited, row, col):", "function_name": "is_valid_move", "parameter_list": "(grid, visited, row, col)" }, { "docstring": null, "function_declaration": "def shortest_path(grid):", "function_name": "shortest_path", ...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef is_valid_move(grid, visited, row, col):\n return (0 <= row < len(grid)) and (0 <= col < len(grid[0])) and grid[row][col] == '1' and not visited[row][col...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00014606", "row_id": 14606, "seed_ids": "['Llama-3.3-70B-Instruct_37618']" }
0.70716
Filter_14606
I
[ "is_valid_move", "shortest_path" ]
2
[ [ "shortest_path", "is_valid_move" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4fc01ecde00751abfa851686a9262af8ff2856b9
f9a8ee828729b0ebfd3ed3adc3e97b89ee1cf0d2
v1.0
instruct
Filter
Filter_14647_I
I have a customer request to make an image analysis software that can detect if a product is in a sealed condition or not. I'm looking for a simple approach to get started with this. I prefer a Python solution. Can you help me get started on how to approach this problem and what methods I could use? **Requirements...
import cv2 import numpy as np def preprocess_image(image_path): """ Preprocesses the image by converting it to grayscale and applying thresholding. """ # Load the image image = cv2.imread(image_path) # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply...
from solution import preprocess_image, extract_features, predict_sealed_condition, analyze_seal import numpy as np import cv2 def test_preprocess_image(): # Create a dummy image image = np.zeros((100, 100, 3), dtype=np.uint8) cv2.rectangle(image, (30, 30), (70, 70), (255, 255, 255), -1) cv2.imwrite("du...
[ { "docstring": "Preprocesses the image by converting it to grayscale and applying thresholding.", "function_declaration": "def preprocess_image(image_path):", "function_name": "preprocess_image", "parameter_list": "(image_path)" }, { "docstring": "Extracts features from the binary image. For...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cv2\nimport numpy as np\nfrom skimage.feature import hog\nfrom sklearn.svm import LinearSVC\n\ndef preprocess_image(image_path):\n \"\"\"\n Preprocess the image for analysis: load...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00014647", "row_id": 14647, "seed_ids": "['Llama-3.3-70B-Instruct_37707']" }
0.336869
Filter_14647
I
[ "preprocess_image", "extract_features", "predict_sealed_condition", "analyze_seal" ]
4
[ [ "analyze_seal", "extract_features" ], [ "analyze_seal", "predict_sealed_condition" ], [ "analyze_seal", "preprocess_image" ] ]
3
[]
false
[]
false
pytest
true
[ "cv2", "numpy" ]
false
76d91ea7038c15c0befcb25b704af631fb70e4e3
e3be3be44c11b9caa1b14490d22a375e1d60f226
v1.0
instruct
Filter
Filter_14660_I
I have a large number of files in a directory, and I need to calculate the total size of all files within it, taking into account both the size of the files and the size of the directory's metadata (e.g. file names, timestamps, etc.). However, I'm using a custom file system, so I need to replicate the process that th...
import os def get_file_size(file_path): return os.path.getsize(file_path) def get_metadata_size(dir_path): """ Placeholder function to get the size of directory metadata such as file names, timestamps, etc. Here, we assume a fixed size for the metadata. """ # This is an example implementat...
import os from solution import get_file_size, get_metadata_size, get_dir_size import tempfile def test_get_file_size_with_zero_byte_file(): with tempfile.NamedTemporaryFile() as tmp_file: assert get_file_size(tmp_file.name) == 0 def test_get_file_size_with_non_zero_byte_file(): with tempfile.NamedTemp...
[ { "docstring": null, "function_declaration": "def get_file_size(file_path):", "function_name": "get_file_size", "parameter_list": "(file_path)" }, { "docstring": "Placeholder function to get the size of directory metadata\nsuch as file names, timestamps, etc. Here, we assume a fixed\nsize fo...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef get_file_size(file_path):\n \"\"\"\n Returns the size of the file at the given path.\n \"\"\"\n return os.path.getsize(file_path)\n\ndef get_metadata_size(file_pat...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00014660", "row_id": 14660, "seed_ids": "['Llama-3.3-70B-Instruct_37742']" }
0.609081
Filter_14660
I
[ "get_file_size", "get_metadata_size", "get_dir_size" ]
3
[ [ "get_dir_size", "get_file_size" ], [ "get_dir_size", "get_metadata_size" ] ]
2
[]
false
[]
false
pytest
true
[]
true
61dc73ac580dc7339c7be36c4b3e9adc7b094c4d
1fea60a15affa66c7696d3849998b353f55f7719
v1.0
instruct
Filter
Filter_14697_I
### Objective The objective of this task is to create a simple console-based quiz game. The game should have the following features: * The game should ask the user 5 multiple-choice questions. * Each question should have 4 possible answers. * The user's answers should be case-insensitive and space-insensitive. * ...
def format_answer(answer): """ Formats the user's answer to be case-insensitive and space-insensitive. """ return answer.strip().lower() def check_answer(user_answer, correct_answer): """ Compares the user's answer with the correct answer. """ return format_answer(user_answer) == format...
def test_format_answer(): assert format_answer("Paris ") == "paris" assert format_answer(" paris ") == "paris" assert format_answer(" PARIS") == "paris" assert format_answer(" pArIs ") == "paris" def test_check_answer(): assert check_answer("a", "A") assert check_answer(" B ", "b") asse...
[ { "docstring": "Formats the user's answer to be case-insensitive and space-insensitive.", "function_declaration": "def format_answer(answer):", "function_name": "format_answer", "parameter_list": "(answer)" }, { "docstring": "Compares the user's answer with the correct answer.", "functio...
[ 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def normalize_answer(answer):\n \"\"\"\n Normalizes the input answer to be lowercased and stripped of whitespace.\n \"\"\"\n return answer.lower().strip()\n\ndef check_answer(user_...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00014697", "row_id": 14697, "seed_ids": "['Llama-3.3-70B-Instruct_37805']" }
0.45391
Filter_14697
I
[ "format_answer", "check_answer", "quiz_game" ]
3
[ [ "check_answer", "format_answer" ], [ "quiz_game", "check_answer" ] ]
2
[ "format_answer" ]
false
[]
false
pytest
false
[]
true
b83dc7cb5fed747ba61ef268047cd6e2e32ca3e9
96c1328748c885400e49636e50f2ae9958cfecf2
v1.0
instruct
Filter
Filter_14842_I
### Creating a Game: Guess My Number **Objective:** Create a program that lets a user play a number guessing game. The computer will think of a number between 1 and 100, and the user will try to guess it. After each guess, the computer will tell the user if their guess was higher or lower than the number it's thinking...
import random def get_user_guess(): """Gets and validates the user's guess.""" while True: try: user_guess = int(input("Guess a number between 1 and 100: ")) if 1 <= user_guess <= 100: return user_guess else: print("Please enter a numb...
import pytest from unittest.mock import patch from solution import get_user_guess, play_game def test_get_user_guess_valid_input(): with patch('builtins.input', return_value='50'): assert get_user_guess() == 50 def test_get_user_guess_invalid_then_valid_input(): with patch('builtins.input', side_effec...
[ { "docstring": "Gets and validates the user's guess.", "function_declaration": "def get_user_guess():", "function_name": "get_user_guess", "parameter_list": "()" }, { "docstring": "Plays the number guessing game.", "function_declaration": "def play_game():", "function_name": "play_ga...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_user_guess():\n \"\"\"Gets and validates the user's guess.\"\"\"\n while True:\n try:\n user_guess = int(input(\"Guess a number between 1 and 1...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00014842", "row_id": 14842, "seed_ids": "['Llama-3.3-70B-Instruct_38112']" }
0.635607
Filter_14842
I
[ "get_user_guess", "play_game", "main" ]
3
[ [ "play_game", "get_user_guess" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1e8f3e53945cfaf3fdce0781c2201ae272470c61
70d85c59c6e8144ea0e143240ddf34b9aa025e38
v1.0
instruct
Filter
Filter_14930_I
### Programming Challenge: Hangman #### Objective Implement a version of the classic game Hangman. #### Overview The game will select a random word from a predefined list of words. The player will have to guess the word by suggesting letters. For each incorrect guess, a part of a hangman's gallows will appear. The gam...
import random HANGMAN_PICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O ...
import pytest from solution import getRandomWord, displayBoard def test_getRandomWord_not_empty(): assert getRandomWord(WORDS) in WORDS def test_displayBoard_basic(): missedLetters = "" correctLetters = "" secretWord = "ant" displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord)...
[ { "docstring": null, "function_declaration": "def getRandomWord(wordList):", "function_name": "getRandomWord", "parameter_list": "(wordList)" }, { "docstring": null, "function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):", "function_name":...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nHANGMAN_PICS = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00014930", "row_id": 14930, "seed_ids": "['Llama-3.3-70B-Instruct_38341']" }
0.467839
Filter_14930
I
[ "getRandomWord", "displayBoard", "getGuess", "playAgain", "hangman" ]
5
[ [ "hangman", "displayBoard" ], [ "hangman", "getGuess" ], [ "hangman", "getRandomWord" ], [ "hangman", "playAgain" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ead1bf735b67cfb32d61a87affe2935f55973b1e
e2692151b545ae89e0babfb8e9b291a8535ede2f
v1.0
instruct
Filter
Filter_15036_I
I have a task to generate 100,000 new unique email addresses. I need them to have the following rules: - Be in the format of local-part@domain - Local-part can contain letters (both uppercase and lowercase), numbers, and the special characters ".","-", and "_". - Domain can contain letters (both uppercase and lowercase...
import random import string def generate_random_email(): characters = string.ascii_letters + string.digits + ".-_" local_part_length = random.randint(2, 32) local_part = ''.join(random.choices(characters, k=local_part_length)) domain_characters = string.ascii_letters + string.digits domain_length ...
from solution import generate_random_email, generate_unique_emails def test_generate_random_email_format(): email = generate_random_email() assert "@" in email local_part, domain = email.split("@") assert 2 <= len(local_part) <= 32 assert 2 <= len(domain) <= 32 for char in local_part: a...
[ { "docstring": null, "function_declaration": "def generate_random_email():", "function_name": "generate_random_email", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def generate_unique_emails(n):", "function_name": "generate_unique_emails", "parameter_li...
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport string\nimport itertools\nfrom tqdm import tqdm\n\ndef generate_email_addresses(n):\n \"\"\"\n Generates n unique email addresses following the specified rules.\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00015036", "row_id": 15036, "seed_ids": "['Llama-3.3-70B-Instruct_38575']" }
0.561652
Filter_15036
I
[ "generate_random_email", "generate_unique_emails" ]
2
[ [ "generate_unique_emails", "generate_random_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4c7060dad296889335506923396450a40c35cd47
689309e5fa5de7b81ae4ebbb573119f817a22f29
v1.0
instruct
Filter
Filter_15041_I
Given a string of digits and a dictionary, count the total number of occurrences of all the words in the dictionary that can be formed using the digits of the string. Note: - Each digit in the string can be used at most once in a word. - The order of digits in the word must match the order of digits in the string. - T...
def is_subsequence(string, word): """ Check if 'word' is a subsequence of 'string'. """ it = iter(string) return all(char in it for char in word) def count_occurrences(string, dictionary): """ Given a string of digits and a list of words (dictionary), count the total number of occurrenc...
from solution import count_occurrences def test_count_occurrences_example(): string = "123" dictionary = ["12", "23", "123", "234", "345"] assert count_occurrences(string, dictionary) == 3 def test_count_occurrences_empty_string(): string = "" dictionary = ["12", "23", "123"] assert count_occu...
[ { "docstring": "Check if 'word' is a subsequence of 'string'.", "function_declaration": "def is_subsequence(string, word):", "function_name": "is_subsequence", "parameter_list": "(string, word)" }, { "docstring": "Given a string of digits and a list of words (dictionary), count the total\nnu...
[ 0, 0, 0, 1, 1, 1, 1, 1 ]
5
medium
0.625
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "def count_occurrences(string, dictionary):\n \"\"\"\n Counts the total number of occurrences of all the words in the dictionary\n that can be formed using the...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00015041", "row_id": 15041, "seed_ids": "['Llama-3.3-70B-Instruct_38584']" }
0.665852
Filter_15041
I
[ "is_subsequence", "count_occurrences" ]
2
[ [ "count_occurrences", "is_subsequence" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e46d265dcfc08ad15038049285157640bd75e77f
972acf76a233c83a4ce514f4d9f8b81f1bd6df6f
v1.0
instruct
Filter
Filter_15078_I
I will provide a list of words with their corresponding frequencies and I want you to implement a Huffman coding algorithm to encode the given words using variable-length binary prefixes.
import heapq from collections import defaultdict class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None # Defining comparison operators for priority queue def __lt__(self, other): return self.freq < ot...
from solution import huffman_encoding def test_huffman_encoding_basic(): words_freq = [('a', 5), ('b', 9), ('c', 12), ('d', 13), ('e', 16), ('f', 45)] codes = huffman_encoding(words_freq) # Checks if all characters are present in the code dictionary assert all(char in codes for char, freq in words_freq...
[]
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict, Counter\n\nclass Node:\n def __init__(self, freq, char=None, left=None, right=None):\n self.freq = freq\n self.char = char\n...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00015078", "row_id": 15078, "seed_ids": "['Llama-3.3-70B-Instruct_38674']" }
0.539401
Filter_15078
I
[ "build_huffman_tree", "generate_huffman_codes", "huffman_encoding" ]
3
[ [ "huffman_encoding", "build_huffman_tree" ], [ "huffman_encoding", "generate_huffman_codes" ] ]
2
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
89d8fe9121bd4dc50d04e24ae3fd9b11c8370572
8b35386ca6249f8ff9399e42e4a55305ff8d724d
v1.0
instruct
Filter
Filter_15162_I
### You Don't Understand the Assignment #### Your Task You are given some guidelines to generate the code for the following problem: * Given a set of `n` points on the plane (defined by their Cartesian coordinates `x` and `y`), determine if a set of three points form an equilateral triangle. * Implement a function ...
import math def distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2) def is_equilateral(point1, point2, point3): """ Determine if a set of three points form an equilateral triangle. ...
from solution import is_equilateral import math def test_equilateral_triangle(): # An equilateral triangle with side length 1 point1 = (0, 0) point2 = (1, 0) point3 = (0.5, math.sqrt(3)/2) assert is_equilateral(point1, point2, point3) == True def test_not_equilateral_triangle(): # Not an equil...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def distance(point1, point2):", "function_name": "distance", "parameter_list": "(point1, point2)" }, { "docstring": "Determine if a set of three points form an equilateral triangle.\n\nArgs:\npoin...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n\n Args:\n point1 (tuple): The first point as (x1, y1).\n point2 (t...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00015162", "row_id": 15162, "seed_ids": "['Llama-3.3-70B-Instruct_38855']" }
0.706682
Filter_15162
I
[ "distance", "is_equilateral" ]
2
[ [ "is_equilateral", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3cd7f05e44720bde1c791e9d45629f6d14a6ff00
e9ac7343c0f499243828dc0c6efd7b29e7ded963
v1.0
instruct
Filter
Filter_15202_I
I have two text files (`file1.txt`, `file2.txt`) in the same directory as my Python script. I want a Python script to read the two files, compare their contents, and print the differences. Specifically, I want to run the following comparison tasks: 1. Check to see if there are any lines that are in `file1.txt` but no...
def read_file(filename): """ reads a file and returns its contents as a list of lines """ try: with open(filename, 'r') as file: lines = file.readlines() # Removing the newline character from the end of each line lines = [line.strip() for line in lines] re...
import os from solution import read_file, compare_files def setup_module(module): with open('file1.txt', 'w') as f: f.write("line1\nline2\nline3\nline4_changed\n") with open('file2.txt', 'w') as f: f.write("line1\nline2\nline3_changed\nline4\nline5_new\n") def teardown_module(module): os....
[ { "docstring": "reads a file and returns its contents as a list of lines ", "function_declaration": "def read_file(filename):", "function_name": "read_file", "parameter_list": "(filename)" }, { "docstring": "compares two files and prints the differences ", "function_declaration": "def co...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def read_file(filename):\n \"\"\" reads a file and returns its contents as a list of lines \"\"\"\n try:\n with open(filename, 'r') as file:\n lines = file.readlines()\...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00015202", "row_id": 15202, "seed_ids": "['Llama-3.3-70B-Instruct_38934']" }
0.661381
Filter_15202
I
[ "read_file", "compare_files", "main" ]
3
[ [ "compare_files", "read_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fc1fb7c6f2bec5e90e34ff3c7a565f5a2aff3e83
9b1ce4503aa580c9a7609124be161457115bc1e6
v1.0
instruct
Filter
Filter_15257_I
I have a Python code that decrypts messages using a columnar transposition cipher. The code works correctly when the input is a string of letters, but it has issues when the input contains spaces or punctuation. I want to modify the code to remove spaces and punctuation, and also ignore the case of the input message. ...
import string def normalize_message(message): """ Removes spaces and punctuation from the message, and converts it to lowercase. """ return ''.join(char.lower() for char in message if char.isalnum()) def decryptMessage(message): """ Decrypts a given message using a columnar transposition ciphe...
from solution import decryptMessage, normalize_message def test_decrypt_message_with_spaces(): assert decryptMessage("BTyeo hugs reoea ao lsel!") == "btyeohugsreoeaaolsel" def test_decrypt_message_with_punctuation(): assert decryptMessage("bTyEo hUgS reOdE?") == "btyeohugsreode" def test_decrypt_message_...
[ { "docstring": "Removes spaces and punctuation from the message, and converts it to lowercase.", "function_declaration": "def normalize_message(message):", "function_name": "normalize_message", "parameter_list": "(message)" }, { "docstring": "Decrypts a given message using a columnar transpo...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import string\n\ndef decryptMessage(message):\n \"\"\"\n This function decrypts a message that has been encoded using a columnar transposition cipher.\n It removes spaces, punctuation...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00015257", "row_id": 15257, "seed_ids": "['Llama-3.3-70B-Instruct_39062']" }
0.519821
Filter_15257
I
[ "normalize_message", "decryptMessage" ]
2
[ [ "decryptMessage", "normalize_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9671f2c4b61bb368c42d802a746efb90b56172f4
c87acc1a06be2c8153fb876c2e0752afca068dc2
v1.0
instruct
Filter
Filter_15359_I
I've been trying to write a script in Python to remind me to drink water throughout the day. The idea of the script is that it reminds me to drink water every 60 minutes. What I want the script to do is: - Take the current time and convert it to minutes - Create a variable to hold the current time in minutes - Create ...
import time from datetime import datetime def get_current_time_in_minutes(): now = datetime.now() current_time_in_minutes = now.hour * 60 + now.minute return current_time_in_minutes def set_target_time(current_time_in_minutes, interval=60): target_time_in_minutes = current_time_in_minutes + interval ...
from solution import get_current_time_in_minutes, set_target_time def test_get_current_time_in_minutes(): # Getting current time in minutes now = datetime.now() expected_minutes = now.hour * 60 + now.minute assert get_current_time_in_minutes() == expected_minutes def test_set_target_time(): # Sett...
[ { "docstring": null, "function_declaration": "def get_current_time_in_minutes():", "function_name": "get_current_time_in_minutes", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def set_target_time(current_time_in_minutes, interval=60):", "function_name": "se...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nfrom datetime import datetime, timedelta\n\ndef get_current_time_in_minutes():\n now = datetime.now()\n return now.hour * 60 + now.minute\n\ndef water_reminder():\n curre...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00015359", "row_id": 15359, "seed_ids": "['Llama-3.3-70B-Instruct_39301']" }
0.49803
Filter_15359
I
[ "get_current_time_in_minutes", "set_target_time", "water_reminder" ]
3
[ [ "water_reminder", "get_current_time_in_minutes" ], [ "water_reminder", "set_target_time" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c2010b158c286a62f370641bd12f0400cde283b7
f5ac55051e80236e6c529a860fdd05db4a860be0
v1.0
instruct
Filter
Filter_15435_I
Here are some Python methods that I'm trying to use to solve a Hamiltonian path problem. ```python from itertools import permutations from math import factorial def all_permutations(n): """Generate all permutations of n distinct objects""" return permutations(range(n)) def is_hamiltonian_path(graph, path): ...
from itertools import permutations def all_permutations(n): """Generate all permutations of n distinct objects""" return permutations(range(n)) def is_hamiltonian_path(graph, path): """Check if the path given forms a hamiltonian path on the graph""" # Ensure the path visits every vertex exactly once ...
from solution import all_permutations, is_hamiltonian_path, is_valid_graph, print_all_hamiltonian_paths import pytest def test_is_hamiltonian_path_valid(): graph = [ [0, 1, 1, 0], [1, 0, 1, 0], [1, 1, 0, 1], [0, 0, 1, 0], ] path = [0, 1, 2, 3] assert is_hamiltonian_path(...
[ { "docstring": "Generate all permutations of n distinct objects", "function_declaration": "def all_permutations(n):", "function_name": "all_permutations", "parameter_list": "(n)" }, { "docstring": "Check if the path given forms a hamiltonian path on the graph", "function_declaration": "d...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef all_permutations(n):\n \"\"\"\n Generate all permutations of n distinct objects.\n \"\"\"\n return permutations(range(n))\n\ndef is_hamilt...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00015435", "row_id": 15435, "seed_ids": "['Llama-3.3-70B-Instruct_39482']" }
0.487974
Filter_15435
I
[ "all_permutations", "is_hamiltonian_path", "is_valid_graph", "print_all_hamiltonian_paths" ]
4
[ [ "print_all_hamiltonian_paths", "all_permutations" ], [ "print_all_hamiltonian_paths", "is_hamiltonian_path" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f9382350130e1265d7b4cad384a454aea945e685
bb905616f32ac86b09cb236e3065ee75c2b6b041
v1.0
instruct
Filter
Filter_15503_I
Here is the information from the program that I am currently using: "Host: myhost Port: 1234 Output: output567" The above information will be used for the following instructions. 1. Create a file named "output.txt" and write the "Output" value into it. 2. Send a message to the host using the host and port informatio...
import socket import hashlib def write_output_to_file(output_value): with open("output.txt", "w") as file: file.write(f"Output:{output_value}\n") def send_message_to_host(host, port, message): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((host, port))...
import os import hashlib def test_write_output_to_file(): from solution import write_output_to_file output_value = "test_output" write_output_to_file(output_value) assert os.path.exists("output.txt") with open("output.txt", "r") as file: content = file.read().strip() assert content...
[ { "docstring": null, "function_declaration": "def write_output_to_file(output_value):", "function_name": "write_output_to_file", "parameter_list": "(output_value)" }, { "docstring": null, "function_declaration": "def send_message_to_host(host, port, message):", "function_name": "send...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import socket\nimport hashlib\n\ndef write_to_file(filename, content):\n with open(filename, 'a') as f:\n f.write(content + '\\n')\n\ndef send_message_to_host(host, port, message):\n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00015503", "row_id": 15503, "seed_ids": "['Llama-3.3-70B-Instruct_39620']" }
0.673287
Filter_15503
I
[ "write_output_to_file", "send_message_to_host", "write_hash_to_file", "execute_instructions" ]
4
[ [ "execute_instructions", "send_message_to_host" ], [ "execute_instructions", "write_hash_to_file" ], [ "execute_instructions", "write_output_to_file" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5971a1ae60648675da32fefffae4bb20a11dff36
2500a9b9b5970031fed21775e5ed5c53ec76984f
v1.0
instruct
Filter
Filter_15679_I
Can you write a code which would solve a simple text-based maze and find an exit? Let's say we have the following maze: ``` ########## #S# # # # ##### # # # # ##### # #E# # ########## ``` Here's a brief explanation of what each symbol represents: - `#` represents a wall - `S` represents the starting point ...
from collections import deque def find_start(maze): """ Find the starting point 'S' in the maze. """ for y, row in enumerate(maze): for x, cell in enumerate(row): if cell == 'S': return (x, y) return None def find_exit(maze): """ Find the exit point 'E' ...
from solution import solve_maze, find_start, find_exit, is_valid_move def test_find_start(): maze = [ "#####", "#S#E#", "#####" ] assert find_start(maze) == (1, 1) def test_find_exit(): maze = [ "#####", "#S#E#", "#####" ] assert find_exit(maze) ...
[ { "docstring": "Find the starting point 'S' in the maze.", "function_declaration": "def find_start(maze):", "function_name": "find_start", "parameter_list": "(maze)" }, { "docstring": "Find the exit point 'E' in the maze.", "function_declaration": "def find_exit(maze):", "function_na...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def solve_maze(maze):\n from collections import deque\n \n # Define possible movements (right, down, left, up)\n movements = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n # Find th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00015679", "row_id": 15679, "seed_ids": "['Llama-3.3-70B-Instruct_40026']" }
0.60736
Filter_15679
I
[ "find_start", "find_exit", "is_valid_move", "solve_maze" ]
4
[ [ "solve_maze", "find_exit" ], [ "solve_maze", "find_start" ], [ "solve_maze", "is_valid_move" ] ]
3
[]
false
[]
false
pytest
true
[]
true
604c5320da2ff3076e660ad675f0e4de6401b884
1c1a313da71fada37547277f2c64b06904014843
v1.0
instruct
Filter
Filter_15830_I
You have been tasked with creating an authentication system that needs to perform a brute-force attack on a password. The password is a number, and the attacker has a range of numbers to guess from. You should write a function called `crack_password` which should take two parameters, `min_value` and `max_value`, repre...
def is_prime(n): """ Return True if n is a prime number, else False. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i ...
from solution import crack_password def test_crack_password_found(): # This range includes 2, 3, 5 ... assert crack_password(1, 10) in [2, 3, 5, 7] def test_crack_password_not_found(): # Large range without enough guesses max_guesses = 1 assert crack_password(4, 10, max_guesses) is None def test...
[ { "docstring": "Return True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Tries to find a prime number password within the given range [min_value, max_value].\nReturns the password if ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else False.\n \"\"\"\n if n < 2:\n return False\n if n == 2:\n return True\n if ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00015830", "row_id": 15830, "seed_ids": "['Llama-3.3-70B-Instruct_40359']" }
0.589629
Filter_15830
I
[ "is_prime", "crack_password" ]
2
[ [ "crack_password", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8b87db11c709e02063b2b24b13c6b57753bacb6e
9a35f575352e72dceec84842757f485dd029f776
v1.0
instruct
Filter
Filter_15916_I
Here is a program that tests whether a number is prime or not: ```python def is_prime(n): if n < 2: return False for d in range(2, int(n**0.5) + 1): if n % d == 0: return False return True n = int(input("Enter a number: ")) if is_prime(n): print(f"{n} is prime") else: pr...
def is_prime(n): if n < 2: return False for d in range(2, int(n**0.5) + 1): if n % d == 0: return False return True def largest_prime_factor(n): if is_prime(n): return n largest_prime = -1 for d in range(2, int(n**0.5) + 1): while n % d == 0: ...
from solution import is_prime, largest_prime_factor def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(17) == True assert is_prime(19) == True assert is_prime(20) == False def test_largest_prime_factor(): assert largest_pr...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def largest_prime_factor(n):", "function_name": "largest_prime_factor", "parameter_list": "(n)" } ]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else returns False.\n \"\"\"\n if n < 2:\n return False\n for d in range(2, int(n**0.5) + 1):\n if...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00015916", "row_id": 15916, "seed_ids": "['Llama-3.3-70B-Instruct_40571']" }
0.80888
Filter_15916
I
[ "is_prime", "largest_prime_factor" ]
2
[ [ "largest_prime_factor", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ba0da14833768d3e711090671ab6314732201c2
c659d9243ef5610b858fde25c5bf7ebcc0790413
v1.0
instruct
Filter
Filter_16106_I
Here is a version of a Hamiltonian Cycle problem, but with a twist. Let's call this the "Hamiltonian Cycle with a Twist" problem. The problem is stated as follows: **Problem Statement:** Given a weighted undirected graph `G = (V, E)` with `n` vertices and `m` edges, find a Hamiltonian cycle in `G` such that the total ...
import random import numpy as np def calculate_cycle_length(cycle, graph, costs): length = 0 for i in range(len(cycle)): u, v = cycle[i], cycle[(i + 1) % len(cycle)] length += costs[u] for j, w in graph[u]: if j == v: length += w break ret...
def test_calculate_cycle_length(): graph = [[(1, 10), (2, 15)], [(0, 10), (2, 10)], [(0, 15), (1, 10)]] costs = [1, 2, 3] cycle = [0, 1, 2] length = calculate_cycle_length(cycle, graph, costs) assert length == 1 + 2 + 3 + 10 + 10 + 15 def test_create_initial_population(): graph = [[(1, 10)...
[ { "docstring": null, "function_declaration": "def calculate_cycle_length(cycle, graph, costs):", "function_name": "calculate_cycle_length", "parameter_list": "(cycle, graph, costs)" }, { "docstring": null, "function_declaration": "def create_initial_population(graph, population_size):", ...
[ 0, 0, 0, 0, 1, 1, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport numpy as np\n\ndef fitness(route, graph, costs):\n total_cost = 0\n for i in range(len(route)):\n u = route[i]\n v = route[(i + 1) % len(route)] # En...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00016106", "row_id": 16106, "seed_ids": "['Llama-3.3-70B-Instruct_40995']" }
0.524108
Filter_16106
I
[ "calculate_cycle_length", "create_initial_population", "select_best_population", "crossover", "mutate", "genetic_algorithm" ]
6
[ [ "genetic_algorithm", "calculate_cycle_length" ], [ "genetic_algorithm", "create_initial_population" ], [ "genetic_algorithm", "crossover" ], [ "genetic_algorithm", "mutate" ], [ "genetic_algorithm", "select_best_population" ], [ "select_best_populati...
6
[]
false
[]
false
pytest
false
[ "numpy" ]
false
bc5818c7853386fb36b8ed38ba6614dcd75be900
9303cfae98a164a05653042a79c1d9468f37e6f7
v1.0
instruct
Filter
Filter_16135_I
I think I may need help addressing some complications with my app. It's a 3D graphics engine, and I'm having some trouble with triangle geometry. I have an STL file that defines an object in terms of triangles, where each triangle is defined by three 3D vertices (so, for each triangle, I have nine values: three x, y, ...
import numpy as np def is_degenerate(triangle): """ Check if a triangle is degenerate. A triangle is degenerate if its area is zero, i.e., the vertices are collinear or same. """ v0 = triangle[0:3] v1 = triangle[3:6] v2 = triangle[6:9] # Calculate vectors vec1 = np.subtract(v1, ...
import numpy as np from solution import filter_degenerate_triangles, is_degenerate def test_is_degenerate(): degenerate_triangle1 = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0]) degenerate_triangle2 = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) non_degenerate_triangle = np.array([0.0,...
[ { "docstring": "Check if a triangle is degenerate. A triangle is degenerate if its area is zero, \ni.e., the vertices are collinear or same.", "function_declaration": "def is_degenerate(triangle):", "function_name": "is_degenerate", "parameter_list": "(triangle)" }, { "docstring": "Filters o...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef remove_degenerate_triangles(triangles):\n \"\"\"\n Removes degenerate triangles from a given list of triangles represented as a 2D NumPy array.\n :param tria...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00016135", "row_id": 16135, "seed_ids": "['Llama-3.3-70B-Instruct_41078']" }
0.521544
Filter_16135
I
[ "is_degenerate", "filter_degenerate_triangles" ]
2
[ [ "filter_degenerate_triangles", "is_degenerate" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
39c66202330ba7f70e9917bc8f12786194b8884b
9d13ab142a22f04bab451c4380da662bd506340f
v1.0
instruct
Filter
Filter_16164_I
Here is a Python program that can solve the 8-Puzzle using A* search algorithm and heuristics. ```python import heapq # Define the goal state GOAL_STATE = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] # Define the possible moves MOVES = [(0, 1), (0, -1), (1, 0), (-1, 0)] def get_neighbors(state): """Get all possible neigh...
import heapq # Define the goal state GOAL_STATE = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] # Define the possible moves MOVES = [(0, 1), (0, -1), (1, 0), (-1, 0)] def get_neighbors(state): """Get all possible neighbors of the current state""" neighbors = [] x, y = next((i, j) for i in range(3) for j in range(3) ...
import pytest from solution import a_star_search def test_already_solved(): initial_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] solution = a_star_search(initial_state) assert solution == [[[1, 2, 3], [4, 5, 6], [7, 8, 0]]] def test_one_move_away(): initial_state = [[1, 2, 3], [4, 5, 6], [7, 0, 8]] s...
[ { "docstring": "Get all possible neighbors of the current state", "function_declaration": "def get_neighbors(state):", "function_name": "get_neighbors", "parameter_list": "(state)" }, { "docstring": "Calculate the Manhattan distance heuristic", "function_declaration": "def manhattan_dist...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\n# Define the goal state\nGOAL_STATE = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]\n\n# Define the possible moves\nMOVES = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\ndef get_neighbors(state):\...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00016164", "row_id": 16164, "seed_ids": "['Llama-3.3-70B-Instruct_41165']" }
0.607001
Filter_16164
I
[ "get_neighbors", "manhattan_distance", "a_star_search", "print_state", "main" ]
5
[ [ "a_star_search", "get_neighbors" ], [ "a_star_search", "manhattan_distance" ] ]
2
[]
false
[]
false
pytest
true
[]
true
63ca16cdd54c0e6cd660df1e5299285b319976b2
df9434b0c202ae637f4ea55dba11db4042ed85f3
v1.0
instruct
Filter
Filter_16227_I
Here is a problem that I want to solve: I have a large number of levels in a platforming game, and I want to make sure that each level is unique and diverse. To do this, I want to write a script that generates a random level for me. Here are the details about the levels: * The levels are all the same width (100 units...
import random def generate_random_height(): """ Generate a random level height between 50 and 200 units. """ return random.randint(50, 200) def generate_random_tunnel_height(): """ Generate a random tunnel height between 1 and 5 chunks (each chunk is 10 units high). """ return random.r...
from solution import generate_level, print_level def test_generate_level_dimensions(): level = generate_level() assert len(level) >= 5 # Minimum height in chunks (50 units) assert len(level) <= 20 # Maximum height in chunks (200 units) assert len(level[0]) == 10 # Width in chunks def test_generate_...
[ { "docstring": "Generate a random level height between 50 and 200 units.", "function_declaration": "def generate_random_height():", "function_name": "generate_random_height", "parameter_list": "()" }, { "docstring": "Generate a random tunnel height between 1 and 5 chunks (each chunk is 10 un...
[ 0, 0, 0, 0, 0, 1, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\n# Define the probabilities for platform, gap, and tunnel\nPLATFORM_PROB = 0.5\nGAP_PROB = 0.2\nTUNNEL_PROB = 0.1\n\ndef generate_level(width=10, height=None):\n if height i...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00016227", "row_id": 16227, "seed_ids": "['Llama-3.3-70B-Instruct_41312']" }
0.491114
Filter_16227
I
[ "generate_random_height", "generate_random_tunnel_height", "generate_level", "print_level" ]
4
[ [ "generate_level", "generate_random_height" ], [ "generate_level", "generate_random_tunnel_height" ] ]
2
[]
false
[]
false
pytest
true
[]
true
43595d52f5c27f267cf5feea2805d6ee6d8b1285
7435c112a527bc5c2357d23f7e8f6122158f672d
v1.0
instruct
Filter
Filter_16255_I
I'm working on a service that allows users to receive a list of daily motivational quotes from a predefined list of quotes. I want to create a simple program that randomly selects a quote from the list and sends it to the user daily. I can implement this functionality using a scheduler like Apache Airflow or AWS Lamb...
import random import time from datetime import datetime, timedelta quotes = [ "Believe you can and you're halfway there. - Theodore Roosevelt", "It does not matter how slowly you go as long as you do not stop. - Confucius", "Success is not final, failure is not fatal: It is the courage to continue that cou...
from solution import get_quote def test_get_quote(): quote = get_quote() assert quote in [ "Believe you can and you're halfway there. - Theodore Roosevelt", "It does not matter how slowly you go as long as you do not stop. - Confucius", "Success is not final, failure is not fatal: It is...
[ { "docstring": "Return a random quote from the predefined list of quotes.", "function_declaration": "def get_quote():", "function_name": "get_quote", "parameter_list": "()" }, { "docstring": "Prints a random quote from the predefined list at the specified time daily (default is 8:00 AM).", ...
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport random\nfrom datetime import datetime, timedelta\n\nquotes = [\n \"Believe you can and you're halfway there. - Theodore Roosevelt\",\n \"It does not matter how slowly...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00016255", "row_id": 16255, "seed_ids": "['Llama-3.3-70B-Instruct_41379']" }
0.492405
Filter_16255
I
[ "get_quote", "print_daily_quote" ]
2
[ [ "print_daily_quote", "get_quote" ] ]
1
[]
false
[]
false
pytest
true
[]
true
02a31eb093295451995dc9b8c0c4262e606dca9e
17a9b2c764385e1671b40fe87e9e1c083f9ca650
v1.0
instruct
Filter
Filter_16379_I
This program should take an input from the user in the form of a string and output the longest palindrome that is a substring of the input string. It should use Breadth-First Search (BFS) to find all substrings and then determine if they are a palindrome. It should use Python as the programming language.
def is_palindrome(s): """ Returns True if s is a palindrome, otherwise False. """ return s == s[::-1] def longest_palindrome_bfs(s): """ Given a string s, returns the longest palindromic substring using BFS. """ if not s: return "" n = len(s) queue = [] longest_pali...
from solution import is_palindrome, longest_palindrome_bfs def test_is_palindrome(): assert is_palindrome("racecar") assert not is_palindrome("hello") assert is_palindrome("madam") assert is_palindrome("a") assert is_palindrome("") def test_longest_palindrome_empty_string(): assert longest_pal...
[ { "docstring": "Returns True if s is a palindrome, otherwise False.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Given a string s, returns the longest palindromic substring using BFS.", "function_declarati...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import deque\n\ndef is_palindrome(s):\n return s == s[::-1]\n\ndef longest_palindrome_bfs(s):\n if not s:\n return \"\"\n\n n = len(s)\n longest_palindrome ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016379", "row_id": 16379, "seed_ids": "['Llama-3.3-70B-Instruct_41707']" }
0.803599
Filter_16379
I
[ "is_palindrome", "longest_palindrome_bfs" ]
2
[ [ "longest_palindrome_bfs", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f7cbad9eac1a11d043b18e92f202b8409e91c12c
5e3aea65dc7115d72af20e68841238beba332828
v1.0
instruct
Filter
Filter_16423_I
I am trying to write a Python script that downloads images from a list of URLs and provides the option of converting them to grayscale and/or resizing them. I can provide the list of URLs and the desired dimensions for resizing. Can you give me a helpful example of how to accomplish this task?
import requests from PIL import Image from io import BytesIO import os def download_image(url): """ Downloads an image from a URL. :param url: URL of the image to download. :return: PIL Image object. """ response = requests.get(url) response.raise_for_status() # Raise HTTPError for ba...
import pytest from PIL import Image from io import BytesIO from unittest.mock import patch, Mock from solution import download_image, process_image # Mock URL response @pytest.fixture def mock_image_url(): image = Image.new('RGB', (100, 100)) byte_arr = BytesIO() image.save(byte_arr, format='JPEG') by...
[ { "docstring": "Downloads an image from a URL.\n\n:param url: URL of the image to download.\n:return: PIL Image object.", "function_declaration": "def download_image(url):", "function_name": "download_image", "parameter_list": "(url)" }, { "docstring": "Saves a PIL Image object to a file.\n\...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom PIL import Image\nfrom io import BytesIO\n\ndef download_image(url):\n \"\"\"\n Downloads an image from a URL and returns it as a PIL image.\n \"\"\"\n respon...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00016423", "row_id": 16423, "seed_ids": "['Llama-3.3-70B-Instruct_41823']" }
0.540366
Filter_16423
I
[ "download_image", "save_image", "process_image", "download_and_process_images" ]
4
[ [ "download_and_process_images", "download_image" ], [ "download_and_process_images", "process_image" ], [ "download_and_process_images", "save_image" ] ]
3
[]
false
[]
false
pytest
true
[ "PIL", "requests" ]
false
e658b9cbdf6aab07a916178b5081c7f153c5027f
af6bd545099d98cd74d09b5c1cffb652aaf4277f
v1.0
instruct
Filter
Filter_16445_I
Here is a simple problem to check your understanding of Python code: The filename is primes.py. This script will calculate the prime numbers between two user-given integers x and y. The script will ask the user to input two numbers. It should check that the inputs are positive integers, raise an error if the first numb...
def is_prime(n): """ Checks whether a given 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 ...
from solution import is_prime, find_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(1) == False assert is_prime(11) == True assert is_prime(25) == False def test_find_primes(): ass...
[ { "docstring": "Checks whether a given number n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Finds and returns a list of prime numbers between two given numbers x and y (exclusive).", "function_de...
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016445", "row_id": 16445, "seed_ids": "['Llama-3.3-70B-Instruct_41877']" }
0.674725
Filter_16445
I
[ "is_prime", "find_primes" ]
2
[ [ "find_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a8a80853a312d9f55164d3e3d010c3ac0cbd02d9
8b63fc98785bcc7419649d0f2d4ffbb8bd6782d8
v1.0
instruct
Filter
Filter_16461_I
Write a code to find the GCD of two numbers using recursion ```python def gcd(a, b): # base case: if b is zero, the GCD is a if b == 0: return a # recursive case: call the function with b and the remainder of a divided by b else: return gcd(b, a % b) # test the function print(gcd(48, 1...
def gcd(a, b): """ Returns the Greatest Common Divisor (GCD) of a and b using recursion. """ # base case: if b is zero, the GCD is a if b == 0: return a # recursive case: call the function with b and the remainder of a divided by b else: return gcd(b, a % b) def lcm(a, b): ...
from solution import gcd, lcm def test_gcd(): assert gcd(48, 18) == 6 assert gcd(101, 10) == 1 assert gcd(54, 24) == 6 assert gcd(56, 42) == 14 assert gcd(12, 15) == 3 def test_lcm(): assert lcm(48, 18) == 144 assert lcm(101, 10) == 1010 assert lcm(54, 24) == 216 assert lcm(56, 42)...
[ { "docstring": "Returns the Greatest Common Divisor (GCD) of a and b using recursion.", "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": "Returns the Least Common Multiple (LCM) of a and b using the GCD function.", "function_d...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "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 recursion.\n \"\"\"\n if b == 0:\n return a\n else:\n return gcd(b, a % b)\n \ndef lcm(a, b):\n \"...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00016461", "row_id": 16461, "seed_ids": "['Llama-3.3-70B-Instruct_41921']" }
0.663909
Filter_16461
I
[ "gcd", "lcm" ]
2
[ [ "lcm", "gcd" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a5e03c033d18bfe2219a4f2fbcee82185faa5330
6169e934b312702d0e36dc663da94cbc7faa2437
v1.0
instruct
Filter
Filter_16608_I
Here is a Python code for finding roots of an equation using Newton's method. But the equation is given as an array of coefficients. For example for the equation $x^3 + 2x^2 - 3x + 4 = 0$ the array should be $[1, 2, -3, 4]$. Also the initial guess value should be provided. My maximum allowed error and the maximum numbe...
def evaluate_polynomial(coefficients, x): """ Evaluate the polynomial for a given x. """ n = len(coefficients) result = 0 for i in range(n): result += coefficients[i] * (x ** (n - i - 1)) return result def evaluate_polynomial_derivative(derivative_coeffs, x): """ Evaluate th...
from solution import evaluate_polynomial, evaluate_polynomial_derivative, find_root_newton_method import pytest def test_evaluate_polynomial(): assert evaluate_polynomial([1, 0, -1], 1) == 0 # x^2 - 1 at x = 1 assert evaluate_polynomial([1, 0, -1], -1) == 0 # x^2 - 1 at x = -1 assert evaluate_polynomial(...
[ { "docstring": "Evaluate the polynomial for a given x.", "function_declaration": "def evaluate_polynomial(coefficients, x):", "function_name": "evaluate_polynomial", "parameter_list": "(coefficients, x)" }, { "docstring": "Evaluate the derivative of the polynomial for a given x.", "funct...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def evaluate_polynomial(coefficients, x):\n \"\"\"\n Evaluates a polynomial with the given coefficients at x.\n \"\"\"\n n = len(coefficients)\n result = 0\n for i in range(n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00016608", "row_id": 16608, "seed_ids": "['Llama-3.3-70B-Instruct_42286']" }
0.540647
Filter_16608
I
[ "evaluate_polynomial", "evaluate_polynomial_derivative", "find_root_newton_method" ]
3
[ [ "find_root_newton_method", "evaluate_polynomial" ], [ "find_root_newton_method", "evaluate_polynomial_derivative" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3ecb30c01c2c643f3f2ab7e541a8e73079c6dad1
51e9ee1fadae457736e965e3a23350e4b2eca50e
v1.0
instruct
Filter
Filter_16774_I
Here is the programming challenge: Write a program that accepts as input a sequence of decimal numbers. The output should be a sequence of numbers where each number is the sum of unique prime factors of the corresponding number in the input sequence. For example, given the sequence 24, 18, 12 the output should be 5,...
def sum_unique_prime_factors(n): """ Calculate the sum of unique prime factors of a number. Parameters: n (int): The input number. Returns: int: The sum of unique prime factors. """ def get_prime_factors(n): """ Get the prime factors of a number. ...
from solution import sum_unique_prime_factors, process_sequence def test_sum_unique_prime_factors(): assert sum_unique_prime_factors(24) == 5 # Prime factors are 2, 2, 2, 3 -> unique are 2, 3 -> sum is 5 assert sum_unique_prime_factors(18) == 5 # Prime factors are 2, 3, 3 -> unique are 2, 3 -> sum is 5 a...
[ { "docstring": "Calculate the sum of unique prime factors of a number.\n\nParameters:\nn (int): The input number.\n\nReturns:\nint: The sum of unique prime factors.", "function_declaration": "def sum_unique_prime_factors(n):", "function_name": "sum_unique_prime_factors", "parameter_list": "(n)" },...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sum_unique_prime_factors(n):\n \"\"\"\n Calculate the sum of unique prime factors of a number.\n \n Parameters:\n n (int): The input number.\n \n Returns:\n int: Th...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016774", "row_id": 16774, "seed_ids": "['Llama-3.3-70B-Instruct_42675']" }
0.647519
Filter_16774
I
[ "sum_unique_prime_factors", "process_sequence" ]
2
[ [ "process_sequence", "sum_unique_prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
edfa5a58a557c6b0a37a54ebca2378f397bcb037
7779d1c2d6063d120c5f2d1535de36698aac6ae4
v1.0
instruct
Filter
Filter_16884_I
Create a new version of the classic Hangman game, called "Word Builder." In this version, the word to be guessed is not fixed, but instead, the player gets to choose a category and the computer generates a random word from that category. The player has 6 chances to guess a letter, and if they guess the word correctly b...
import random def get_random_word(category_words): return random.choice(category_words) def display_word(word, guessed_letters): return ' '.join([letter if letter in guessed_letters else '_' for letter in word]) def play_word_builder(category, categories): word = get_random_word(categories[category]) ...
import pytest from solution import get_random_word, display_word # Mock categories for testing categories = { "fruits": ["apple", "banana", "cherry"], "animals": ["cat", "dog", "elephant"] } def test_get_random_word(): assert get_random_word(categories["fruits"]) in categories["fruits"] assert get_ran...
[ { "docstring": null, "function_declaration": "def get_random_word(category_words):", "function_name": "get_random_word", "parameter_list": "(category_words)" }, { "docstring": null, "function_declaration": "def display_word(word, guessed_letters):", "function_name": "display_word", ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef get_categories():\n \"\"\"\n Returns a dictionary of categories with their corresponding word lists.\n \"\"\"\n return {\n \"Fruits\": [\"apple\", \"ban...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016884", "row_id": 16884, "seed_ids": "['Llama-3.3-70B-Instruct_42974']" }
0.525638
Filter_16884
I
[ "get_random_word", "display_word", "play_word_builder", "main" ]
4
[ [ "play_word_builder", "display_word" ], [ "play_word_builder", "get_random_word" ] ]
2
[]
false
[]
false
pytest
true
[]
true
40c21af9c5491d97371a8c00807eab80df72b957
10d52dab63050e111e0b76ed18a8d9bc5d3f229f
v1.0
instruct
Filter
Filter_16935_I
I have a list of URLs that I'd like to validate and then check if they are actually active, by sending a GET request and verifying the response code. I'll be using Python for this task. Here's a sample of the list: - https://www.google.com - https://www.bing.com - https://www.duckduckgo.com - https://www.indeed.com ...
import re import requests def is_valid_url(url): """ Check if a given URL is properly formatted and valid. """ regex = re.compile( r'^(?:http|https)://' # http:// or https:// r'(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|' # domain... r'(?:%[0-9a-fA-F][0-9a-fA-F]))+$') return ...
from solution import is_valid_url, check_url_status def test_is_valid_url(): assert is_valid_url("https://www.google.com") assert is_valid_url("https://www.bing.com") assert is_valid_url("https://www.duckduckgo.com") assert not is_valid_url("htp://www.invalidurl.com") assert not is_valid_url("https...
[ { "docstring": "Check if a given URL is properly formatted and valid.", "function_declaration": "def is_valid_url(url):", "function_name": "is_valid_url", "parameter_list": "(url)" }, { "docstring": "Send a GET request to the given URL and verify the response code is between 200-400.", "...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nimport requests\n\ndef validate_and_check_urls(urls):\n \"\"\"\n Validates the list of URLs and checks if they are active.\n \n Parameters:\n urls (list of str): List...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00016935", "row_id": 16935, "seed_ids": "['Llama-3.3-70B-Instruct_43096']" }
0.698047
Filter_16935
I
[ "is_valid_url", "check_url_status" ]
2
[ [ "check_url_status", "is_valid_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
d897dd90b24f70ba9321586546502bf41d084c47
de8e24284a215fed0e3beb8902d13327e9b2cb4b
v1.0
instruct
Filter
Filter_16942_I
I have a folder containing a mix of files and subfolders. I'd like to sort the files in this folder into subfolders based on their extensions. For example, if I have the following files in my folder: - dog.jpg - cat.jpg - bird.mp3 - car.docx - bike.mp3 - house.pdf I'd like to have them sorted into the following str...
import os import shutil def get_folder_name(extension): image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'] audio_extensions = ['.mp3', '.wav', '.aac', '.flac'] document_extensions = ['.doc', '.docx', '.pdf', '.txt', '.xlsx'] if extension in image_extensions: return 'images' e...
import os import pytest from solution import get_folder_name, sort_files_by_extension def test_get_folder_name(): assert get_folder_name('.jpg') == 'images' assert get_folder_name('.mp3') == 'audio' assert get_folder_name('.docx') == 'documents' assert get_folder_name('.pdf') == 'documents' assert ...
[ { "docstring": null, "function_declaration": "def get_folder_name(extension):", "function_name": "get_folder_name", "parameter_list": "(extension)" }, { "docstring": null, "function_declaration": "def sort_files_by_extension(folder_path):", "function_name": "sort_files_by_extension",...
[ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport shutil\n\ndef sort_files_by_extension(directory):\n \"\"\"\n Sorts files in the given directory into subfolders based on their extensions.\n \"\"\"\n # Dictionary...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00016942", "row_id": 16942, "seed_ids": "['Llama-3.3-70B-Instruct_43119']" }
0.720488
Filter_16942
I
[ "get_folder_name", "sort_files_by_extension" ]
2
[ [ "sort_files_by_extension", "get_folder_name" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bf34f08d9ced0f9a8ee59958620ba2ecc9eba1e6
ca4e84eb60afb60d7b8e13d0afa69493b5656bbb
v1.0
instruct
Filter
Filter_17168_I
### Distributed File System #### Overview Our company is planning to build a distributed file system. The system will have multiple nodes, and each node will store a portion of the overall data. We want to ensure that the system is fault-tolerant and can recover from node failures. #### Requirements * The system shoul...
import hashlib import bisect def hash_fn(key): """ Hashes a key using SHA-256 and returns an integer. """ return int(hashlib.sha256(key.encode()).hexdigest(), 16) def get_nodes_for_file(file_name, nodes, replication_factor): """ Get the nodes that store the chunks of a file. Args: fil...
from solution import get_nodes_for_file, hash_fn def test_get_nodes_for_file(): nodes = ["node1", "node2", "node3", "node4", "node5"] file_name = "example.txt" replication_factor = 3 selected_nodes = get_nodes_for_file(file_name, nodes, replication_factor) assert len(selected_nodes) == re...
[ { "docstring": "Hashes a key using SHA-256 and returns an integer.", "function_declaration": "def hash_fn(key):", "function_name": "hash_fn", "parameter_list": "(key)" }, { "docstring": "Get the nodes that store the chunks of a file.\n\nArgs:\nfile_name (str): The name of the file.\nnodes (l...
[ 0, 0, 0, 1, 1, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nfrom bisect import bisect_right\n\ndef hash_value(value):\n \"\"\"\n Returns the SHA-256 hash of the given value.\n \"\"\"\n return int(hashlib.sha256(value.encode(...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00017168", "row_id": 17168, "seed_ids": "['Llama-3.3-70B-Instruct_43681']" }
0.385656
Filter_17168
I
[ "hash_fn", "get_nodes_for_file" ]
2
[ [ "get_nodes_for_file", "hash_fn" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11eabd6efbcef721a70b7c5ecba2995be07b0fa3
1338fb15377c38707bc44e228fbd25e098c3fa04
v1.0
instruct
Filter
Filter_17219_I
I have a List Of Movie Titles. The titles are mostly in English, but there are some in other languages. I want to detect the language of each title. I can use the following things to determine the language: - a list of common English words - a list of common words in other languages - the script (alphabet) used Here ...
def detect_script(title): # This function is a placeholder for the script detection algorithm # For now, it just returns 'Latin' for any title return 'Latin' def detect_language(title, common_words, script_to_languages): detected_script = detect_script(title) possible_languages = script_to_language...
from solution import detect_language, detect_script common_words = { 'English': ['the', 'and', 'a', 'of', 'to'], 'French': ['le', 'la', 'les', 'de', 'du'], 'Spanish': ['el', 'la', 'los', 'de', 'del'], 'Finnish': ['ja', 'kuin', 'on', 'se', 'että'] } script_to_languages = { 'Latin': ['English', 'Fre...
[ { "docstring": null, "function_declaration": "def detect_script(title):", "function_name": "detect_script", "parameter_list": "(title)" }, { "docstring": null, "function_declaration": "def detect_language(title, common_words, script_to_languages):", "function_name": "detect_language"...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import string\n\ndef detect_script(title):\n # This function is a placeholder for the script detection algorithm\n # For now, it just returns 'Latin' for any title\n return 'Latin'\n\...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00017219", "row_id": 17219, "seed_ids": "['Llama-3.3-70B-Instruct_43794']" }
0.429866
Filter_17219
I
[ "detect_script", "detect_language" ]
2
[ [ "detect_language", "detect_script" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5fc3142ccce371d38c1cee9f19960b7d30fda653
e03ddb1846f8f768e603742110687456c042ced0
v1.0
instruct
Filter
Filter_17329_I
Please provide a step-by-step guide to creating a simple fractal tree in Python using the turtle library.
import turtle def draw_branch(branch_length, t): if branch_length > 5: t.forward(branch_length) t.right(20) draw_branch(branch_length - 15, t) t.left(40) draw_branch(branch_length - 15, t) t.right(20) t.backward(branch_length) def draw_frac...
# It's difficult to test graphical output with unit tests as you would with numerical or textual output. # However, we can implement some basic assertions about the function calls and their structure. # Asserting the core functionalities: from solution import draw_branch def test_draw_branch(): # Mock turtle obj...
[ { "docstring": null, "function_declaration": "def draw_branch(branch_length, t):", "function_name": "draw_branch", "parameter_list": "(branch_length, t)" }, { "docstring": null, "function_declaration": "def draw_fractal_tree():", "function_name": "draw_fractal_tree", "parameter_l...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\n\ndef draw_branch(branch_length, t):\n \"\"\"\n Draws a fractal tree branch.\n :param branch_length: The length of the branch\n :param t: Turtle object\n \"\"\"\n...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00017329", "row_id": 17329, "seed_ids": "['Llama-3.3-70B-Instruct_44036']" }
0.44855
Filter_17329
I
[ "draw_branch", "draw_fractal_tree" ]
2
[ [ "draw_fractal_tree", "draw_branch" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8bda121a49fd9808cb152761942b05a8720e7511
920eae43157304468cd6f54df5679463e24810c1
v1.0
instruct
Filter
Filter_17343_I
Create an advanced program for h-index calculation, that has the following features: 1. The input can be a list of integers, or a list of lists of integers. 2. The h-index will be calculated separately for each list (or for the whole list, if it is flat). 3. The program should keep track of and print the maximum h-inde...
def calculate_h_index(citations): """ Calculate the h-index for a list of citations. """ citations.sort(reverse=True) h_index = 0 for i, c in enumerate(citations): if c >= i + 1: h_index = i + 1 else: break return h_index def stats_on_h_index(citation...
from solution import calculate_h_index, stats_on_h_index, process_citations def test_calculate_h_index(): assert calculate_h_index([6, 5, 3, 1, 0]) == 3 assert calculate_h_index([10, 8, 5, 4, 3]) == 4 assert calculate_h_index([25, 8, 5, 3, 3]) == 3 assert calculate_h_index([0, 0, 0]) == 0 assert ca...
[ { "docstring": "Calculate the h-index for a list of citations.", "function_declaration": "def calculate_h_index(citations):", "function_name": "calculate_h_index", "parameter_list": "(citations)" }, { "docstring": "Given a nested list of citations, calculates and prints:\n1. H-index for each...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def calculate_h_index(citations):\n citations.sort(reverse=True)\n h_index = 0\n for i, c in enumerate(citations):\n if i + 1 <= c:\n h_index = i + 1\n else:\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00017343", "row_id": 17343, "seed_ids": "['Llama-3.3-70B-Instruct_44068']" }
0.416227
Filter_17343
I
[ "calculate_h_index", "stats_on_h_index", "process_citations" ]
3
[ [ "process_citations", "stats_on_h_index" ], [ "stats_on_h_index", "calculate_h_index" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f3e1490c5450e7d596d0a7b585b2e91b7b894ef8
1a50354f5a5c334c6c1ae026cca6161f7d7ed8d1
v1.0
instruct
Filter
Filter_17435_I
I was given the task to get all possible 5-letter words from a list of letters Using permutations I can get all possible 5-letter words but how can I filter the list to get only valid words. To solve this I plan to use a dictionary file , containing one word per line. Using python , how can I read the dictionary file ...
import itertools def load_dictionary(file_path): """ Loads a dictionary file. Returns a set of valid words. """ with open(file_path, 'r') as file: valid_words = set(word.strip() for word in file if len(word.strip()) == 5) return valid_words def get_valid_words(letters, dictionary_path)...
from solution import load_dictionary, get_valid_words import tempfile # Helper function to create a temporary dictionary file for testing def create_temp_dictionary(word_list): temp_file = tempfile.NamedTemporaryFile(delete=False) with open(temp_file.name, 'w') as file: for word in word_list: ...
[ { "docstring": "Loads a dictionary file.\nReturns a set of valid words.", "function_declaration": "def load_dictionary(file_path):", "function_name": "load_dictionary", "parameter_list": "(file_path)" }, { "docstring": "Returns a list of valid 5-letter words that can be made from the given l...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef get_valid_words(letters, dictionary_file_path):\n \"\"\"\n Returns a set of valid 5-letter words from permutations of given letters using the specified dictionary...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00017435", "row_id": 17435, "seed_ids": "['Llama-3.3-70B-Instruct_44271']" }
0.561039
Filter_17435
I
[ "load_dictionary", "get_valid_words" ]
2
[ [ "get_valid_words", "load_dictionary" ] ]
1
[]
false
[]
false
pytest
true
[]
true
52b45c68787811e5be71e3138a63715c9ef8e5c8
0d2d58fe1245006f63f820038dc4dd77d9bfd836
v1.0
instruct
Filter
Filter_17440_I
I see. So my plan for the PyTorch model is to use pre-trained BERT base model. I will fine-tune it for sentiment analysis on my custom dataset. Can you help me explain how I can approach this with PyTorch?
import torch from torch.utils.data import DataLoader, Dataset from transformers import BertTokenizer, BertForSequenceClassification, AdamW class CustomDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_len): self.texts = texts self.labels = labels self.tokenizer = tokenizer ...
def test_create_data_loader(): texts = ["This is a positive example!", "This is a negative example."] labels = [1, 0] max_len = 32 batch_size = 2 tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') data_loader = create_data_loader(texts, labels, tokenizer, max_len, batch_size) ...
[]
[ 0, 0, 0, 1, 1, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from transformers import BertTokenizer, BertForSequenceClassification\nfrom torch.utils.data import DataLoader, Dataset\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# 1...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00017440", "row_id": 17440, "seed_ids": "['Llama-3.3-70B-Instruct_44285']" }
0.37956
Filter_17440
I
[ "create_data_loader", "train_epoch", "eval_model", "train_model" ]
4
[ [ "train_model", "create_data_loader" ], [ "train_model", "eval_model" ], [ "train_model", "train_epoch" ] ]
3
[]
false
[ "CustomDataset" ]
true
pytest
false
[ "torch", "transformers" ]
false
cece46354db8dbc620a2edb47ba941de75f7c9f3
16d1845783571abae5de9aaca09b6f7ad5b81346
v1.0
instruct
Filter
Filter_17457_I
This is the third in a series of problems leading you through the creation of a game of Hangman. This is the final part of the problem. In this part, we will complete the game. In the previous problem, you have the code to create a hangman game. However, you must have realized that it can only be used to guess a singl...
import random HANGMAN_PICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O ...
def test_get_random_word(): word = getRandomWord(WORDS) assert word in WORDS assert isinstance(word, str) def test_play_again_yes(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: 'yes') assert playAgain() == True def test_play_again_no(monkeypatch): monkeypatch.setattr('builtins.i...
[ { "docstring": null, "function_declaration": "def getRandomWord(wordList):", "function_name": "getRandomWord", "parameter_list": "(wordList)" }, { "docstring": null, "function_declaration": "def displayBoard(HANGMAN_PICS, missedLetters, correctLetters, secretWord):", "function_name":...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "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 | |\n O |\n |\n |\n |\n=========''', '''\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00017457", "row_id": 17457, "seed_ids": "['Llama-3.3-70B-Instruct_44327']" }
0.493867
Filter_17457
I
[ "getRandomWord", "displayBoard", "getGuess", "playAgain", "hangman" ]
5
[ [ "hangman", "displayBoard" ], [ "hangman", "getGuess" ], [ "hangman", "getRandomWord" ], [ "hangman", "playAgain" ] ]
4
[]
false
[]
false
pytest
false
[]
true
7bcaf4f591f1027120c41233b44649b1ab7ff8c0
4d095c40eae56fc70186c5cf917969ebcb2acba7
v1.0
instruct
Filter
Filter_17465_I
I have a 2D grid, and I want to perform the following operation on it: - Select a cell at random - Place a "stone" on the cell - If there is a stone on a neighboring cell (horizontally, vertically, or diagonally), flip all the stones in the respective direction (like Othello/Reversi) - Iterate this process How can I i...
import numpy as np import random def initialize_grid(rows, cols): """ Initialize a 2D grid of given size with zeros. """ return np.zeros((rows, cols), dtype=int) def get_neighbors(row, col, rows, cols): """ Get the neighboring cells of the given cell (row, col). """ neighbors = [] ...
from solution import initialize_grid, get_neighbors, flip_in_direction, place_stone import numpy as np def test_initialize_grid(): grid = initialize_grid(3, 3) assert grid.shape == (3, 3) assert np.all(grid == 0) def test_get_neighbors(): neighbors = get_neighbors(1, 1, 3, 3) expected_neighbors = ...
[ { "docstring": "Initialize a 2D grid of given size with zeros.", "function_declaration": "def initialize_grid(rows, cols):", "function_name": "initialize_grid", "parameter_list": "(rows, cols)" }, { "docstring": "Get the neighboring cells of the given cell (row, col).", "function_declara...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport random\n\ndef place_and_flip(grid):\n \"\"\"\n Function to place a stone on a randomly selected cell of the grid and\n flip the stones in all 8 directions i...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00017465", "row_id": 17465, "seed_ids": "['Llama-3.3-70B-Instruct_44343']" }
0.506652
Filter_17465
I
[ "initialize_grid", "get_neighbors", "flip_in_direction", "place_stone" ]
4
[ [ "place_stone", "flip_in_direction" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
725f3731cf6c13f01bd348b3271c8b61f04953b6
10dc37cf650d5930cc40ec4b217cb773c4098447
v1.0
instruct
Filter
Filter_17471_I
I have an NFA (Nondeterministic Finite Automaton) M with 5 states: {q0, q1, q2, q3, q4} and the following transitions: - δ(q0, a) = {q0, q1} - δ(q0, b) = {q2} - δ(q1, a) = {q1, q3} - δ(q1, b) = {q4} - δ(q2, a) = {q2} - δ(q2, b) = {q1, q2} - δ(q3, a) = {q3} - δ(q3, b) = {q1, q4} - δ(q4, a) = {q4} - δ(q4, b) = ∅ We are g...
# NFA definition TRANSITIONS = { 'q0': {'a': {'q0', 'q1'}, 'b': {'q2'}}, 'q1': {'a': {'q1', 'q3'}, 'b': {'q4'}}, 'q2': {'a': {'q2'}, 'b': {'q1', 'q2'}}, 'q3': {'a': {'q3'}, 'b': {'q1', 'q4'}}, 'q4': {'a': {'q4'}, 'b': set()} } def transition(states, char): """ Given a set of states and an i...
from solution import accepts def test_accept_string_aab(): assert accepts('q0', 'aab') == True def test_accept_string_ab(): assert accepts('q0', 'ab') == True def test_reject_string_aa(): assert accepts('q0', 'aa') == False def test_accept_string_abb(): assert accepts('q0', 'abb') == False # It shou...
[ { "docstring": "Given a set of states and an input character,\nreturns the set of states reached after transition.", "function_declaration": "def transition(states, char):", "function_name": "transition", "parameter_list": "(states, char)" }, { "docstring": "Check if the NFA accepts the give...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def epsilon_transition(state):\n \"\"\"\n Returns the set of states that can be reached from `state` using only ε-transitions.\n Since there are no ε-transitions, this function return...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00017471", "row_id": 17471, "seed_ids": "['Llama-3.3-70B-Instruct_44351']" }
0.447437
Filter_17471
I
[ "transition", "accepts" ]
2
[ [ "accepts", "transition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d8e476086f8d3d5cb14d9274029571275b087221
5563195643a184f5f4438b3e68a60f19e714c41c
v1.0
instruct
Filter
Filter_17531_I
Below we write Python code which allows us to plot the solution of a differential equation, allows us to input a function, and allows us to input initial conditions. We essentially want to add the ability to see a 3D representation of the differential equation's solutions given different initial conditions. Here is t...
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # function that returns dy/dt def model(y, t, func_str): # We use the sympy library to convert the string func_str into a SymPy expression from sympy import symbols, sympify y1, y2,...
from solution import model, solve_and_plot_3d def test_model_simple_linear(): func_str = "y1 + y2" t = 0 y = [1, 1] result = model(y, t, func_str) assert result == [2, 2], f"Expected [2, 2], got {result}" def test_model_zero_initial(): func_str = "y1 - y2" t = 0 y = [0, 0] result =...
[ { "docstring": null, "function_declaration": "def model(y, t, func_str):", "function_name": "model", "parameter_list": "(y, t, func_str)" }, { "docstring": null, "function_declaration": "def solve_and_plot_3d(func_str, initial_conditions, t):", "function_name": "solve_and_plot_3d", ...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef model(y, t, func_str):\n from sympy import symbols, s...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00017531", "row_id": 17531, "seed_ids": "['Llama-3.3-70B-Instruct_44505']" }
0.451696
Filter_17531
I
[ "model", "solve_and_plot_3d" ]
2
[ [ "solve_and_plot_3d", "model" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "mpl_toolkits", "numpy", "scipy", "sympy" ]
false
205cbf6014b19b7b513946bc48b9acc6d935c146
5a7d11490bf84698c2e5d4319e7c5e4ca9fcc455
v1.0
instruct
Filter
Filter_17581_I
I have a 2D numpy array of size (n, m). Each element in the array is either a 0 or 1, representing a block or empty space. I want to find all the connected components (of blocks) in the array. Here's a basic idea of how to solve the problem: 1. Create a copy of the input array. 2. Iterate through the copy array, and ...
import numpy as np def find_connected_components(arr): """ Finds all connected components of blocks in a given 2D array. Parameters: arr (2D numpy array): A 2D array where each element is either 0 (empty space) or 1 (block). Returns: list: A list of connected components, where each component ...
import numpy as np from solution import find_connected_components def test_find_connected_components_single_component(): arr = np.array([ [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [1, 1, 1, 1] ]) components = find_connected_components(arr) assert len(components) == 1 ...
[ { "docstring": "Finds all connected components of blocks in a given 2D array.\n\nParameters:\narr (2D numpy array): A 2D array where each element is either 0 (empty space) or 1 (block).\n\nReturns:\nlist: A list of connected components, where each component is represented as a list of coordinates.", "functi...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef find_connected_components(arr):\n \"\"\"\n Finds all connected components of blocks in a given 2D array.\n\n Parameters:\n arr (2D numpy array): A 2D arra...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00017581", "row_id": 17581, "seed_ids": "['Llama-3.3-70B-Instruct_44624']" }
0.443101
Filter_17581
I
[ "find_connected_components", "dfs" ]
2
[ [ "find_connected_components", "dfs" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
e00b4d8da62afc37f6bcc6423cad5f9461fafcf8
4042d73cd83e7f6d7b4bcdb67b23c1316edf3837
v1.0
instruct
Filter
Filter_17623_I
You can assume that the following functions have been defined and work as specified: - `insert`: inserts an element into a sorted list while maintaining sorted order. - `delete`: removes the first occurrence of an element from a list. - `find`: returns the index of the first occurrence of an element in a sorted list, o...
def replace(element1, element2, sorted_list): """ Replaces all occurrences of element1 in sorted_list with element2. Parameters: - element1: Element to be replaced. - element2: Element to replace with. - sorted_list: A sorted list of elements. Returns: A new list with all occur...
from solution import replace, sort_list, insert, delete, find def test_replace_no_match(): assert replace(6, 10, [1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_replace_single_occurrence(): assert replace(2, 10, [1, 2, 3, 2, 4]) == [1, 3, 4, 10, 10] def test_replace_multiple_occurrences(): assert replace(2,...
[ { "docstring": "Replaces all occurrences of element1 in sorted_list with element2.\n\nParameters:\n- element1: Element to be replaced.\n- element2: Element to replace with.\n- sorted_list: A sorted list of elements.\n\nReturns:\nA new list with all occurrences of element1 replaced by element2.", "function_d...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def replace(element1, element2, sorted_list):\n # Create a copy of the list to avoid modifying the original list\n new_list = sorted_list[:]\n \n # Find and replace all occurrences...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00017623", "row_id": 17623, "seed_ids": "['Llama-3.3-70B-Instruct_44724']" }
0.657824
Filter_17623
I
[ "replace", "sort_list", "insert", "delete", "find" ]
5
[ [ "replace", "delete" ], [ "replace", "find" ], [ "replace", "insert" ], [ "replace", "sort_list" ] ]
4
[]
false
[]
false
pytest
true
[]
true
9fef695348fa2dcd8ed25f041ce64419d1b398c0
ba2285aaec40a425e04ed9ca91b1b59ab23d0768
v1.0
instruct
Filter
Filter_17666_I
### Programming Language Theory ## Overview Programming language theory is a branch of computer science that explores the design, description, analysis, and implementation of programming languages. It provides a framework for understanding the properties, behavior, and limitations of programming languages, as well as t...
def tokenize(source_code): """ Tokenizes the source code into a list of tokens. """ tokens = source_code.split() # Simplistic tokenizer based on whitespace return tokens def parse(tokens): """ Parses the list of tokens to generate an Abstract Syntax Tree (AST). """ ast = {"type": "...
import pytest from solution import tokenize, parse, generate_bytecode, compile_source def test_tokenize(): source_code = "x = 42" assert tokenize(source_code) == ["x", "=", "42"] def test_parse(): tokens = ["x", "=", "42"] assert parse(tokens) == {"type": "Program", "body": ["x", "=", "42"]} def test...
[ { "docstring": "Tokenizes the source code into a list of tokens.", "function_declaration": "def tokenize(source_code):", "function_name": "tokenize", "parameter_list": "(source_code)" }, { "docstring": "Parses the list of tokens to generate an Abstract Syntax Tree (AST).", "function_decl...
[ 0, 0, 0, 1, 1, 1, 0, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Step-by-Step Guide to Writing a Basic Compiler\n\n## 1. Lexical Analysis\nThe first step in writing a compiler is to perform lexical analysis. This involves breaking the source code into tok...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00017666", "row_id": 17666, "seed_ids": "['Llama-3.3-70B-Instruct_44830']" }
0.353284
Filter_17666
I
[ "tokenize", "parse", "generate_bytecode", "compile_source" ]
4
[ [ "compile_source", "generate_bytecode" ], [ "compile_source", "parse" ], [ "compile_source", "tokenize" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2ed3bc3b079c4e9b47aef5cca0bd4d8f5278669a
0a608db53e23fb64987367edaa9a57db33c0bc07
v1.0
instruct
Filter
Filter_17803_I
I have a Python project that I need help with. I am making a program that will take a user's input and put it through a Markov chain process to generate text based on the input. I will want to generate multiple chains from the same corpus but with different parameters such as order and size of the output. I have th...
import random import re from collections import defaultdict, namedtuple Chain = namedtuple('Chain', ['order', 'chain']) def clean_text(text): """Clean the input text""" text = text.lower() text = re.sub(r'[^\w\s]', '', text) return text def generate_chain(text, order): """Generate a Markov chain ...
from solution import clean_text, generate_chain, generate_text, generate_multiple_chains def test_clean_text(): assert clean_text("Hello, World!") == "hello world" assert clean_text("It's a beautiful day.") == "its a beautiful day" def test_generate_chain(): text = "one fish two fish red fish blue fish" ...
[ { "docstring": "Clean the input text", "function_declaration": "def clean_text(text):", "function_name": "clean_text", "parameter_list": "(text)" }, { "docstring": "Generate a Markov chain from the input text", "function_declaration": "def generate_chain(text, order):", "function_nam...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport re\nfrom collections import defaultdict\n\ndef clean_text(text):\n \"\"\"Clean the input text\"\"\"\n text = text.lower()\n text = re.sub(r'[^\\w\\s]', '', text)...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00017803", "row_id": 17803, "seed_ids": "['Llama-3.3-70B-Instruct_45154']" }
0.555981
Filter_17803
I
[ "clean_text", "generate_chain", "generate_text", "generate_multiple_chains" ]
4
[ [ "generate_multiple_chains", "clean_text" ], [ "generate_multiple_chains", "generate_chain" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2e26b3efb3526baa8b5dae5bb5d9822efb6a7911
fd9f502842a844206c475ede7ac82b17c3e259be
v1.0
instruct
Filter
Filter_17855_I
I have a 4D array where each 3D sub-array has shape (256, 256, 3) representing a color image. I'm trying to convert these images from RGB to YCrCb color space. How do I accomplish this in python with numpy?
import numpy as np def rgb_to_ycrcb(rgb_image): """ Convert a single RGB image to YCrCb color space. Parameters: rgb_image (numpy.ndarray): A 3D numpy array with shape (256, 256, 3) representing an RGB image. Returns: numpy.ndarray: A 3D numpy array with shape (256, 256, 3) representing the Y...
import numpy as np from solution import rgb_to_ycrcb, convert_4d_rgb_to_ycrcb def test_rgb_to_ycrcb_single_image(): rgb_image = np.ones((256, 256, 3)) * 255 # White image ycrcb_image = rgb_to_ycrcb(rgb_image) assert ycrcb_image.shape == (256, 256, 3) # Check some values to verify correctness asser...
[ { "docstring": "Convert a single RGB image to YCrCb color space.\n\nParameters:\nrgb_image (numpy.ndarray): A 3D numpy array with shape (256, 256, 3) representing an RGB image.\n\nReturns:\nnumpy.ndarray: A 3D numpy array with shape (256, 256, 3) representing the YCrCb image.", "function_declaration": "def ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef rgb_to_ycrcb(rgb_image):\n \"\"\"\n Converts an RGB image to YCrCb color space.\n\n Parameters:\n rgb_image (numpy.ndarray): 3D numpy array with shape (25...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00017855", "row_id": 17855, "seed_ids": "['Llama-3.3-70B-Instruct_45264']" }
0.445039
Filter_17855
I
[ "rgb_to_ycrcb", "convert_4d_rgb_to_ycrcb" ]
2
[ [ "convert_4d_rgb_to_ycrcb", "rgb_to_ycrcb" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
70f58dc85b7855b08e5a737263f2d8311b73312d
5ae3dd5a01cfeca0c3d9e357e3a23f53705b618d
v1.0
instruct
Filter
Filter_17874_I
You've been tasked with determining the longest prefix of a given string that is a palindrome. A palindrome is a sequence of characters that reads the same backward as forward. Given the string "racecar", write a code snippet that will return the longest palindromic prefix. For example, given the string "racecar", the...
def is_palindrome(s): """ Helper function to check if a given string s is a palindrome. """ return s == s[::-1] def longest_palindromic_prefix(s): """ This function finds the longest prefix of a given string that is a palindrome. Parameters: s (str): The input string. Retu...
from solution import is_palindrome, longest_palindromic_prefix def test_is_palindrome(): assert is_palindrome("racecar") == True assert is_palindrome("hello") == False assert is_palindrome("madam") == True assert is_palindrome("") == True assert is_palindrome("a") == True def test_longest_palindro...
[ { "docstring": "Helper function to check if a given string s is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "This function finds the longest prefix of a given string that is a palindrome.\n\nPara...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(s):\n \"\"\"\n Check if string s is equal to its reverse.\n \n Parameters:\n s (str): The input string.\n \n Returns:\n bool: True if the string is a ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00017874", "row_id": 17874, "seed_ids": "['Llama-3.3-70B-Instruct_45310']" }
0.756893
Filter_17874
I
[ "is_palindrome", "longest_palindromic_prefix" ]
2
[ [ "longest_palindromic_prefix", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
51c7f5930fe6ee926cb3e54e9263ca4746d7b6b2
f14995f725fd70934c81dee7f8b9cf64150f0402
v1.0
instruct
Filter
Filter_17884_I
I've been trying to write a program that can take in a folder and find all instances of a certain pattern in all files in that folder. So far, I've been able to write code that can find the pattern in a single file. Now I need to extend it to multiple files. Here's the code I have so far: ```python import re def find...
import re import os def find_pattern(file_path, pattern): try: with open(file_path, 'r') as file: for num, line in enumerate(file, 1): if re.search(pattern, line): print(f"Pattern '{pattern}' found at line {num} in file {file_path}") except FileNotFoundEr...
import os import re from solution import find_pattern_in_folder def setup_files(): os.makedirs("test_folder", exist_ok=True) with open("test_folder/file1.txt", "w") as f: f.write("hello world\nthis is a test\n") with open("test_folder/file2.txt", "w") as f: f.write("another test file\nstill...
[ { "docstring": null, "function_declaration": "def find_pattern(file_path, pattern):", "function_name": "find_pattern", "parameter_list": "(file_path, pattern)" }, { "docstring": null, "function_declaration": "def find_pattern_in_folder(folder_path, pattern):", "function_name": "find_...
[ 0, 0, 0, 1, 0, 1, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nimport os\n\ndef find_pattern_in_file(file_path, pattern):\n \"\"\"\n Finds and prints the lines containing the pattern\n in a given file.\n \"\"\"\n try:\n wi...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00017884", "row_id": 17884, "seed_ids": "['Llama-3.3-70B-Instruct_45332']" }
0.650491
Filter_17884
I
[ "find_pattern", "find_pattern_in_folder", "main" ]
3
[ [ "find_pattern_in_folder", "find_pattern" ] ]
1
[]
false
[]
false
pytest
true
[]
true
54f4a422651e326564c7a936a667697226dde6b5
3ec8bd8ed35c37a49082434c7246a69c0bd16512
v1.0
instruct
Filter
Filter_17947_I
I have a list of strings, and I want to count the number of unique substrings in each string. Is it possible to solve it using Python?
def count_unique_substrings(s): """ Returns the number of unique substrings in a single string s. """ unique_substrings = set() length = len(s) for i in range(length): for j in range(i + 1, length + 1): unique_substrings.add(s[i:j]) return len(unique_substrings)...
from solution import count_unique_substrings, count_unique_substrings_in_list def test_count_unique_substrings(): assert count_unique_substrings("abc") == 6 # 'a', 'b', 'c', 'ab', 'bc', 'abc' assert count_unique_substrings("aaa") == 3 # 'a', 'aa', 'aaa' assert count_unique_substrings("") == 0 # No su...
[ { "docstring": "Returns the number of unique substrings in a single string s.", "function_declaration": "def count_unique_substrings(s):", "function_name": "count_unique_substrings", "parameter_list": "(s)" }, { "docstring": "Given a list of strings, returns a list with the count of unique s...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def count_unique_substrings(s):\n \"\"\"\n Given a string s, return the number of unique substrings.\n \"\"\"\n substrings = set()\n length = len(s)\n \n for i in range(le...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00017947", "row_id": 17947, "seed_ids": "['Llama-3.3-70B-Instruct_45486']" }
0.78501
Filter_17947
I
[ "count_unique_substrings", "count_unique_substrings_in_list" ]
2
[ [ "count_unique_substrings_in_list", "count_unique_substrings" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0257454e1c564fed4ed889caf1817da975730b77
4d4d09ea96f57dedb62a3d409b65867daf096a10
v1.0
instruct
Filter
Filter_18028_I
In this problem, we are asked to build a triangle given a set of points. But the catch is that all the sides of the triangle should have the same length. Given an array of points where points[i] = [xi, yi] represents a point on a 2D plane, find all equilateral triangles. For example: Input: points = [[0,0],[1,0],[1...
import math import itertools def validEquilateralTriangle(p1, p2, p3): """ Returns True if the triangle formed by points p1, p2, and p3 is equilateral. """ def distance(q1, q2): return math.sqrt((q1[0] - q2[0])**2 + (q1[1] - q2[1])**2) d1 = distance(p1, p2) d2 = distance(p2, p3) d3...
from solution import find_equilateral_triangles def test_no_points(): assert find_equilateral_triangles([]) == [] def test_one_point(): assert find_equilateral_triangles([[0, 0]]) == [] def test_two_points(): assert find_equilateral_triangles([[0, 0], [1, 1]]) == [] def test_three_non_collinear_points()...
[ { "docstring": "Returns True if the triangle formed by points p1, p2, and p3 is equilateral.", "function_declaration": "def validEquilateralTriangle(p1, p2, p3):", "function_name": "validEquilateralTriangle", "parameter_list": "(p1, p2, p3)" }, { "docstring": "Finds all equilateral triangles...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nimport itertools\n\ndef distance(p1, p2):\n \"\"\"\n Returns the Euclidean distance between two points in a 2D plane.\n \"\"\"\n return math.sqrt((p1[0] - p2[0])**2 + ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00018028", "row_id": 18028, "seed_ids": "['Llama-3.3-70B-Instruct_45706']" }
0.57809
Filter_18028
I
[ "validEquilateralTriangle", "find_equilateral_triangles" ]
2
[ [ "find_equilateral_triangles", "validEquilateralTriangle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
508f11afd51a0e367da36be2a02d488b9075581d
3de177f2a92e0d4e32ba644516978b9beea2f6c1
v1.0
instruct
Filter
Filter_18057_I
### Writing a Small TCP Client and Server using HMAC Integrity Protection
import hmac import hashlib import socket SECRET_KEY = b'supersecretkey' def create_hmac(message: bytes) -> bytes: return hmac.new(SECRET_KEY, message, hashlib.sha256).hexdigest().encode() def verify_hmac(message: bytes, received_hmac: bytes) -> bool: calculated_hmac = create_hmac(message) return hmac.com...
import threading from solution import start_server, start_client import time def start_server_in_thread(): thread = threading.Thread(target=start_server) thread.daemon = True thread.start() time.sleep(1) # Give server time to start return thread def test_server_response(): server_thread = sta...
[ { "docstring": null, "function_declaration": "def create_hmac(message):", "function_name": "create_hmac", "parameter_list": "(message)" }, { "docstring": null, "function_declaration": "def verify_hmac(message, received_hmac):", "function_name": "verify_hmac", "parameter_list": "(...
[ 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.286
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import socket\nimport hmac\nimport hashlib\n\nSECRET_KEY = b'secret_key_here'\n\ndef create_hmac(message):\n return hmac.new(SECRET_KEY, message, hashlib.sha256).hexdigest()\n\ndef start_se...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00018057", "row_id": 18057, "seed_ids": "['Llama-3.3-70B-Instruct_45771']" }
0.46333
Filter_18057
I
[ "create_hmac", "verify_hmac", "start_server", "start_client" ]
4
[ [ "start_client", "verify_hmac" ], [ "start_server", "create_hmac" ], [ "verify_hmac", "create_hmac" ] ]
3
[]
false
[]
false
pytest
true
[]
true
77b09ee6e97b23ad4844262ef7c383bee4a989e2
009e1192cbdf7c30c32de66807a7b3826e1edefd
v1.0
instruct
Filter
Filter_18104_I
### Objective: Convert Input stream into lower case and remove duplicate characters Below is the input stream apple banana dog elephant fish goat horse I need a output stream with the following features 1. All characters should be in lower case 2. No duplicate characters should be present Here is a code temp...
def remove_duplicates(word): """ Removes duplicate characters from a word, preserving the order of their first appearances. """ seen = set() result = [] for char in word: if char not in seen: seen.add(char) result.append(char) return ''.join(result) def proce...
from solution import process_stream def test_process_stream_with_given_input(): input_stream = ["apple", "banana", "dog", "elephant", "horse"] expected_output = ["aple", "ban", "dog", "elphant", "horse"] assert process_stream(input_stream) == expected_output def test_process_stream_all_unique_characters()...
[ { "docstring": "Removes duplicate characters from a word, preserving the order of their first appearances.", "function_declaration": "def remove_duplicates(word):", "function_name": "remove_duplicates", "parameter_list": "(word)" }, { "docstring": "Processes the input stream to convert each ...
[ 0, 0, 0, 0, 0, 1, 1, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def process_stream(input_stream):\n all_chars = ''.join(input_stream).lower()\n seen = set()\n unique_chars = []\n for char in all_chars:\n if char not in seen:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00018104", "row_id": 18104, "seed_ids": "['Llama-3.3-70B-Instruct_45882']" }
0.526481
Filter_18104
I
[ "remove_duplicates", "process_stream" ]
2
[ [ "process_stream", "remove_duplicates" ] ]
1
[]
false
[]
false
pytest
true
[]
true
84c2843f0ab2b4bda12bf894ed8c95531411e462
9e3af0379b164f6ea5b6e23a484b64a545d4e252
v1.0
instruct
Filter
Filter_18148_I
I understand You can form a number using digits which appear at the same position in the same base when converted from decimal to binary. For example, in base 5 to binary is 101, you can form a number 1*5^2 + 1*5^0 = 26 (in decimal). The task is to write a program that takes in a number and its base, converts it to b...
def decimal_to_binary(n): """ Converts a decimal number to its binary representation. """ return bin(n)[2:] def new_number_from_binary(n, base): """ Converts a decimal number `n` to its equivalent in the given `base` using the digits that appear in the binary representation of `n` at t...
import pytest from solution import decimal_to_binary, new_number_from_binary def test_decimal_to_binary(): assert decimal_to_binary(5) == '101' assert decimal_to_binary(26) == '11010' assert decimal_to_binary(0) == '0' assert decimal_to_binary(1) == '1' def test_new_number_from_binary(): # Binary ...
[ { "docstring": "Converts a decimal number to its binary representation.", "function_declaration": "def decimal_to_binary(n):", "function_name": "decimal_to_binary", "parameter_list": "(n)" }, { "docstring": "Converts a decimal number `n` to its equivalent in the given `base`\nusing the digit...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def decimal_to_binary(n):\n \"\"\"\n Convert decimal number to binary string.\n \"\"\"\n if n == 0:\n return \"0\"\n result = \"\"\n while n > 0:\n result = str...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00018148", "row_id": 18148, "seed_ids": "['Llama-3.3-70B-Instruct_45990']" }
0.744776
Filter_18148
I
[ "decimal_to_binary", "new_number_from_binary" ]
2
[ [ "new_number_from_binary", "decimal_to_binary" ] ]
1
[]
false
[]
false
pytest
true
[]
true
970da5c872a07dc3e38e1a5bdd1d3b10a7c4a3a0
5f4d65e5643a483b320eecc638c6756a42e0da02
v1.0
instruct
Filter
Filter_18226_I
I'm trying to write some code that extracts a specific substring from each line of a text file. The line can contain multiple substrings. The substring is defined as: - It starts with the word "WARNING" (case-insensitive) - It ends with a colon followed by a space This means that the substring can be part of a sent...
import re def extract_warnings(text): """ Extracts all substrings from the input text that start with 'WARNING' (case-insensitive) and end with a colon followed by a space. """ pattern = re.compile(r'WARNING:.*?(?=WARNING:|$|: )', re.IGNORECASE) matches = pattern.findall(text) return [matc...
from solution import extract_warnings_from_file def test_single_warning(): content = "This is a line with WARNING: something bad: happened" expected = ["WARNING: something bad"] assert extract_warnings_from_file(content) == expected def test_multiple_warnings_in_line(): content = "This line has multip...
[ { "docstring": "Extracts all substrings from the input text that start with 'WARNING' (case-insensitive) \nand end with a colon followed by a space.", "function_declaration": "def extract_warnings(text):", "function_name": "extract_warnings", "parameter_list": "(text)" }, { "docstring": "Ext...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef extract_warnings(text):\n \"\"\"\n Extracts substrings that start with \"WARNING\" (case-insensitive)\n and end with a colon followed by a space, from each line of th...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00018226", "row_id": 18226, "seed_ids": "['Llama-3.3-70B-Instruct_46199']" }
0.492149
Filter_18226
I
[ "extract_warnings", "extract_warnings_from_file" ]
2
[ [ "extract_warnings_from_file", "extract_warnings" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9d3ed0f7f4f02c2112d20243bc3cc4d4afc1d083
bbd6c04e17835f987a3188d5df506bb55aab57ea
v1.0
instruct
Filter
Filter_18233_I
Write a Python solution for Project Euler problem 14. The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using this rule, and starting at 13, for example, we generate the sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 Which contains 10 ter...
collatz_cache = {} def collatz_length(n): if n in collatz_cache: return collatz_cache[n] if n == 1: return 1 elif n % 2 == 0: result = 1 + collatz_length(n // 2) else: result = 1 + collatz_length(3 * n + 1) collatz_cache[n] = result return result def find_longes...
import pytest from solution import collatz_length, find_longest_chain def test_collatz_length(): assert collatz_length(1) == 1 assert collatz_length(2) == 2 assert collatz_length(13) == 10 assert collatz_length(10) == 7 assert collatz_length(27) == 112 # Known long sequence for 27 def test_find_l...
[ { "docstring": null, "function_declaration": "def collatz_length(n):", "function_name": "collatz_length", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_longest_chain(limit=1000000):", "function_name": "find_longest_chain", "parameter_list": "(l...
[ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def collatz_length(n, known_lengths):\n \"\"\"\n Calculates the length of the Collatz sequence for a given n using memoization.\n \"\"\"\n original_n = n\n length = 0\n \n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00018233", "row_id": 18233, "seed_ids": "['Llama-3.3-70B-Instruct_46212']" }
0.615963
Filter_18233
I
[ "collatz_length", "find_longest_chain" ]
2
[ [ "find_longest_chain", "collatz_length" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c39eed5372c1c2d1b8972c97467aa8ca306d5341
7e63d999100b2d076adf230f1d0daedf9f5475c5
v1.0
instruct
Filter
Filter_18285_I
I've always been curious about generating fractals using programming. What are the basic steps for getting started with generating fractals in code? I'm not really sure where to start, but I have some experience with Python, which I'd like to utilize to generate the images. Could you guide me through the process, p...
def generate_mandelbrot(width, height, x_min, x_max, y_min, y_max, max_iter): mandelbrot_set = [[0] * width for _ in range(height)] for px in range(width): for py in range(height): x0 = x_min + (px / width) * (x_max - x_min) y0 = y_min + (py / height) * (y_max - y_min) ...
from solution import generate_mandelbrot, render_image, generate_and_show_mandelbrot def test_generate_mandelbrot(): data = generate_mandelbrot(10, 10, -2, 2, -2, 2, 10) assert len(data) == 10 assert len(data[0]) == 10 assert all(isinstance(i, int) for row in data for i in row) def test_render_image()...
[ { "docstring": null, "function_declaration": "def generate_mandelbrot(width, height, x_min, x_max, y_min, y_max, max_iter):", "function_name": "generate_mandelbrot", "parameter_list": "(width, height, x_min, x_max, y_min, y_max, max_iter)" }, { "docstring": null, "function_declaration": ...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1 ]
3
medium
0.333
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(c, max_iter):\n \"\"\"\n Calculate the Mandelbrot value for a given complex number `c`.\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00018285", "row_id": 18285, "seed_ids": "['Llama-3.3-70B-Instruct_46337']" }
0.358776
Filter_18285
I
[ "generate_mandelbrot", "render_image", "generate_and_show_mandelbrot" ]
3
[ [ "generate_and_show_mandelbrot", "generate_mandelbrot" ], [ "generate_and_show_mandelbrot", "render_image" ] ]
2
[]
false
[]
false
pytest
true
[ "PIL" ]
false
591fa713a41f0b8e5d132f966a0297922947743f
21c9f2588289d1e196d9ee6cf5dec6e31119d58e