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_22644_I | Here's a Python code that can be used to import a CSV file:
```python
import pandas as pd
df = pd.read_csv('file.csv')
```
However, I can't find my file and I need to get all the filenames with specific extension that are located on my computer.
Here's a specific path where the file may be located: `/Users/username/D... | import os
import pandas as pd
def get_csv_files(directory):
"""
Returns a list of CSV filenames in the specified directory.
"""
if not os.path.isdir(directory):
raise FileNotFoundError(f"The directory {directory} does not exist.")
csv_files = [file for file in os.listdir(directory) if ... | import os
import pytest
from solution import get_csv_files, read_csv_file, get_and_read_csv_files
def test_get_csv_files(tmpdir):
# Creating temporary files for testing
test_dir = tmpdir.mkdir("MyFolder")
test_file1 = test_dir.join("test1.csv")
test_file2 = test_dir.join("test2.csv")
test_file3 = t... | [
{
"docstring": "Returns a list of CSV filenames in the specified directory.",
"function_declaration": "def get_csv_files(directory):",
"function_name": "get_csv_files",
"parameter_list": "(directory)"
},
{
"docstring": "Reads a CSV file from the specified directory.",
"function_declarati... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport pandas as pd\n\ndef get_csv_filenames(directory):\n \"\"\"\n Returns a list of all CSV filenames in the specified directory.\n \"\"\"\n if not os.path.exists(dire... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022644",
"row_id": 22644,
"seed_ids": "['Llama-3.3-70B-Instruct_56690']"
} | 0.680111 | Filter_22644 | I | [
"get_csv_files",
"read_csv_file",
"get_and_read_csv_files"
] | 3 | [
[
"get_and_read_csv_files",
"get_csv_files"
],
[
"get_and_read_csv_files",
"read_csv_file"
]
] | 2 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 836f9bf7c70ab7db7bbfff331e072c1fffcba113 | d6930665acdf0ece291a19e6756e16d442bb6724 | |||
v1.0 | instruct | Filter | Filter_22679_I | ### Game Outline
The game is called **Bubble Blast**. It is a puzzle game where players are presented with a grid of colored bubbles. When a player taps on a bubble, its color and that of the adjacent bubbles (horizontally and vertically) changes. The goal of the game is to change all the bubbles in the grid to the sam... | import random
class Bubble:
def __init__(self, color):
self.color = color
def __str__(self):
return self.color
def generate_grid(size):
colors = ['R', 'G', 'B']
grid = [[Bubble(random.choice(colors)) for _ in range(size)] for _ in range(size)]
return grid
def print_grid(grid):
... | import pytest
from solution import Bubble, generate_grid, print_grid, handle_move, is_game_won
def test_generate_grid():
size = 5
grid = generate_grid(size)
assert len(grid) == size and len(grid[0]) == size
assert all(isinstance(bubble, Bubble) for row in grid for bubble in row)
def test_handle_move()... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass Bubble:\n def __init__(self, color):\n self.color = color\n\n def __str__(self):\n return self.color\n\ndef generate_grid(size):\n colors = ['R', ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022679",
"row_id": 22679,
"seed_ids": "['Llama-3.3-70B-Instruct_56775']"
} | 0.556454 | Filter_22679 | I | [
"generate_grid",
"print_grid",
"is_valid_move",
"handle_move",
"is_game_won",
"play_game"
] | 6 | [
[
"handle_move",
"is_valid_move"
],
[
"play_game",
"generate_grid"
],
[
"play_game",
"handle_move"
],
[
"play_game",
"is_game_won"
],
[
"play_game",
"print_grid"
]
] | 5 | [] | false | [
"Bubble"
] | true | pytest | true | [] | true | 576586d42dc92b02707ae604c8cb3e9be87687a9 | a8c750c52201e2befaeb92974e21292537633646 | |||
v1.0 | instruct | Filter | Filter_22714_I | I have a list of hash values (in hexadecimal format) in a yaml file. I want to convert them into a binary format (without a 0b prefix) just by reading the yaml file and printing them in the console.
Example input (in input.yaml):
```yml
hash_values:
- 12345678
- ABCDEF12
- F2A345D7
```
Example output:
```
01010... | import yaml
def convert_hex_to_bin(hex_values):
"""
Converts a list of hexadecimal values to their binary string representation without '0b' prefix.
"""
bin_values = [bin(int(x, 16))[2:] for x in hex_values]
return bin_values
def read_and_convert_yaml(file_path):
"""
Reads a YAML file, par... | from solution import convert_hex_to_bin
def test_convert_hex_to_bin():
hex_values = ['12345678', 'ABCDEF12', 'F2A345D7']
bin_values = convert_hex_to_bin(hex_values)
assert bin_values == [
'10010001101000101011001111000',
'10101011110011011110111100010010',
'11110010101000110100... | [
{
"docstring": "Converts a list of hexadecimal values to their binary string representation without '0b' prefix.",
"function_declaration": "def convert_hex_to_bin(hex_values):",
"function_name": "convert_hex_to_bin",
"parameter_list": "(hex_values)"
},
{
"docstring": "Reads a YAML file, pars... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import yaml\n\ndef read_yaml(file_path):\n \"\"\"\n Reads yaml file from a given file_path.\n \"\"\"\n with open(file_path, 'r') as file:\n data = yaml.safe_load(file)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022714",
"row_id": 22714,
"seed_ids": "['Llama-3.3-70B-Instruct_56847']"
} | 0.460485 | Filter_22714 | I | [
"convert_hex_to_bin",
"read_and_convert_yaml"
] | 2 | [
[
"read_and_convert_yaml",
"convert_hex_to_bin"
]
] | 1 | [] | false | [] | false | pytest | true | [
"yaml"
] | false | 08cc1e53a90299586a93f8bcfb80e17ed709567b | d3b95d216afa53b044458ab45079de0312e6ee8c | |||
v1.0 | instruct | Filter | Filter_22716_I | ### Insertion Sort Time Complexity
Insertion sort has a time complexity of **O(n^2)** in the worst-case scenario.
However, if the input array is **already sorted**, the time complexity is **O(n)**.
Can you write a code that can be used to test the time complexity of the Insertion Sort algorithm in both the average a... | import time
import random
def insertion_sort(arr):
"""
Sorts an array using the insertion sort algorithm.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def measu... | from solution import insertion_sort, measure_time
def test_sorted_array():
arr = list(range(1000))
time_taken = measure_time(arr)
print(f"Time taken for sorted array: {time_taken}")
assert sorted(arr) == arr # Ensure the array is still sorted
assert time_taken < 0.1 # Assuming it should be fast
... | [
{
"docstring": "Sorts an array using the insertion sort algorithm.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Measures the time it takes to sort an array using the insertion sort algorithm.",
"func... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport random\n\ndef insertion_sort(arr):\n \"\"\"\n Sorts an array using the insertion sort algorithm.\n \"\"\"\n for i in range(1, len(arr)):\n key = arr[i]\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022716",
"row_id": 22716,
"seed_ids": "['Llama-3.3-70B-Instruct_56853']"
} | 0.462392 | Filter_22716 | I | [
"insertion_sort",
"measure_time"
] | 2 | [
[
"measure_time",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7867921ea1b79c14314e8e04883df89be0c49e8d | 16ca3775e525089da5f39a9683d316abe363bf19 | |||
v1.0 | instruct | Filter | Filter_22731_I | ### System Design: Implementing a URL Shortener
#### Problem Statement
Design and implement a system to shorten a long URL into a shorter alias. The shortened URL should redirect to the original URL when accessed.
#### Requirements
* The system should be able to handle a large number of URLs.
* The system should be... | import hashlib
import sqlite3
from urllib.parse import urlparse
# Create a database connection
conn = sqlite3.connect('urls.db')
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE IF NOT EXISTS urls
(short_url text PRIMARY KEY, long_url text)''')
def shorten_url(long_url):
# Generate a uniqu... | from solution import shorten_url, get_long_url, redirect
def test_shorten_url():
long_url = "https://www.example.com/test"
short_url = shorten_url(long_url)
assert short_url == hashlib.sha256(long_url.encode()).hexdigest()[:6]
def test_get_long_url():
long_url = "https://www.example.com/test_get"
... | [
{
"docstring": null,
"function_declaration": "def shorten_url(long_url):",
"function_name": "shorten_url",
"parameter_list": "(long_url)"
},
{
"docstring": null,
"function_declaration": "def get_long_url(short_url):",
"function_name": "get_long_url",
"parameter_list": "(short_url... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport sqlite3\nimport os\n\n# Setup Database\nDATABASE_PATH = \"urls.db\"\nconn = sqlite3.connect(DATABASE_PATH)\nc = conn.cursor()\nc.execute('''CREATE TABLE IF NOT EXISTS ur... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022731",
"row_id": 22731,
"seed_ids": "['Llama-3.3-70B-Instruct_56880']"
} | 0.516414 | Filter_22731 | I | [
"shorten_url",
"get_long_url",
"redirect"
] | 3 | [
[
"redirect",
"get_long_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e1a71965f3b20f57b9d4695195ff278f06fdfced | a3c7eaa1afcf20ddbbdc917b375c0d48d7006f1c | |||
v1.0 | instruct | Filter | Filter_22759_I | Given a list of integers, find the majority element (the element that appears more than n/2 times where n is the length of the list) using the boyer moore algorithm.
Here is the code:
```python
def majority_element(nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candi... | import random
def majority_element(nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count = 1
elif candidate == num:
count += 1
else:
count -= 1
return candidate
def count_candidate(nums, candida... | import pytest
from solution import majority_element, count_candidate, is_majority
def test_majority_element_simple():
nums = [3, 3, 4, 2, 4, 4, 2, 4, 4]
assert majority_element(nums) == 4
def test_majority_element_even_length():
nums = [3, 3, 4, 2, 4, 4, 2, 4]
assert majority_element(nums) == 4
def t... | [
{
"docstring": null,
"function_declaration": "def majority_element(nums):",
"function_name": "majority_element",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def count_candidate(nums, candidate):",
"function_name": "count_candidate",
"parameter_list... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef majority_element(nums):\n \"\"\"\n Finds the majority element using the Boyer-Moore algorithm.\n \"\"\"\n count = 0\n candidate = None\n\n for num in num... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022759",
"row_id": 22759,
"seed_ids": "['Llama-3.3-70B-Instruct_56939']"
} | 0.499029 | Filter_22759 | I | [
"majority_element",
"count_candidate",
"is_majority",
"test_majority_element",
"main"
] | 5 | [
[
"is_majority",
"count_candidate"
],
[
"test_majority_element",
"is_majority"
],
[
"test_majority_element",
"majority_element"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | eadc309fd4377023d736d6a10c806177e32c2fee | cf462886f0ba1637b1c9881676042185ac01c5dd | |||
v1.0 | instruct | Filter | Filter_22800_I | Here's the problem:
I have a fitness studio with multiple classes, each with different schedules. I want to send a weekly email newsletter to my subscribers with upcoming classes for the following week (Monday to Sunday). The classes are stored in a database, and I can retrieve them. I can also send emails using a lib... | from datetime import datetime, timedelta
import calendar
# Sample data
classes = [
{
"id": 1,
"name": "Yoga",
"start_date": "2024-03-18",
"start_time": "09:00",
"end_time": "10:00",
"day_of_week": "Monday"
},
{
"id": 2,
"name": "Pilates",
"start_date": "2024-03-19",
"start... | from solution import prepare_email_content
def test_prepare_email_content():
classes = [
{"id": 1, "name": "Yoga", "start_date": "2024-03-18", "start_time": "09:00", "end_time": "10:00", "day_of_week": "Monday"},
{"id": 2, "name": "Pilates", "start_date": "2024-03-19", "start_time": "10:00", "end_t... | [
{
"docstring": "Retrieves classes for the upcoming week. ",
"function_declaration": "def get_upcoming_classes(classes, start_date):",
"function_name": "get_upcoming_classes",
"parameter_list": "(classes, start_date)"
},
{
"docstring": "Organizes the classes by day of the week. ",
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime, timedelta\n\ndef retrieve_classes_for_upcoming_week():\n \"\"\"\n Retrieves classes scheduled for the upcoming week from the database.\n This is a mock ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022800",
"row_id": 22800,
"seed_ids": "['Llama-3.3-70B-Instruct_57028']"
} | 0.37712 | Filter_22800 | I | [
"get_upcoming_classes",
"organize_classes_by_day",
"generate_newsletter_content",
"prepare_email_content"
] | 4 | [
[
"prepare_email_content",
"generate_newsletter_content"
],
[
"prepare_email_content",
"get_upcoming_classes"
],
[
"prepare_email_content",
"organize_classes_by_day"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f8071e2fae225c7b7fc5161d75625a2ac3a1aac4 | 04a8d8036ceeb86a209b918e243a136491e0056c | |||
v1.0 | instruct | Filter | Filter_22804_I | I have created a very efficient sorting algorithm, but it only uses one CPU core. Can you help me make it multi-core? | import concurrent.futures
def merge_sort(arr):
"""
A standard merge sort implementation.
"""
if len(arr) <= 1:
return arr
middle = len(arr) // 2
left = merge_sort(arr[:middle])
right = merge_sort(arr[middle:])
return merge(left, right)
def merge(left, right):
"""
Merges... | from solution import merge_sort, multi_core_sort
def test_merge_sort():
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([3, 2, 1]) == [1, 2, 3]
assert merge_sort([5, 2, 8, 3, 9, 1]) == [1, 2, 3, 5, 8, 9]
def test_multi_core_sort():
arr1 = [5, 2, 8, 3, 9, 1]
sorted_a... | [
{
"docstring": "A standard merge sort implementation.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def merge(left, right):",
"func... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\nfrom math import ceil\n\ndef merge_sort(array):\n if len(array) < 2:\n return array\n\n mid = len(array) // 2\n left = merge_sort(array[:mid])\n righ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022804",
"row_id": 22804,
"seed_ids": "['Llama-3.3-70B-Instruct_57038']"
} | 0.405467 | Filter_22804 | I | [
"merge_sort",
"merge",
"multi_core_sort"
] | 3 | [
[
"merge_sort",
"merge"
],
[
"multi_core_sort",
"merge"
],
[
"multi_core_sort",
"merge_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | fe87acc98eda1417d6d46d0acc9a328eb7fac7d2 | ecd6e923f4b4fb76fad9f9261b37c0472106ef62 | |||
v1.0 | instruct | Filter | Filter_22815_I | I have created a model that should be able to predict the expected output of a function given the function name, parameters, and body.
This model can be written as a mathematical function f that takes in the following parameters:
f(function_name, parameters, function_body)
My team wants me to implement 2 new featu... | def f(function_name, parameters, function_body):
"""
A simple model function that returns the sum of the parameters.
"""
return sum(parameters)
def handle_multiple(function_names, parameter_sets, function_bodies):
"""
A function that takes multiple function names, parameter sets, and function b... | from solution import handle_multiple
def test_handle_multiple_basic():
function_names = {"function_1", "function_2"}
parameter_sets = [(1, 2), (3, 4)]
function_bodies = {"body_1", "body_2"}
expected_outputs = [3, 7] # sum(1, 2) = 3, sum(3, 4) = 7
assert handle_multiple(function_names, paramet... | [
{
"docstring": "A simple model function that returns the sum of the parameters.",
"function_declaration": "def f(function_name, parameters, function_body):",
"function_name": "f",
"parameter_list": "(function_name, parameters, function_body)"
},
{
"docstring": "A function that takes multiple... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def f_multiple(function_names, parameters_set, function_bodies):\n \"\"\"\n This function takes multiple function names, parameter sets, and function bodies,\n and applies the model f... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022815",
"row_id": 22815,
"seed_ids": "['Llama-3.3-70B-Instruct_57054']"
} | 0.44136 | Filter_22815 | I | [
"f",
"handle_multiple"
] | 2 | [
[
"handle_multiple",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c4af87add6a895ab29a577e975e466c55c0d5231 | df7c576339898ba56d9ddd009770d4f0535765c3 | |||
v1.0 | instruct | Filter | Filter_22821_I | Below is a code implementing a Merge Sort Algorithm.
```python
def merge_sort(arr):
"""Merge sort algorithm
Args:
arr (list): list of elements to sort
Returns:
list: sorted list
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[... | def merge_sort(arr):
"""
Merge sort algorithm
Args:
arr (list): list of elements to sort
Returns:
list: sorted list
"""
# Base case: if the array has 1 or no elements, it's already sorted
if len(arr) <= 1:
return arr
# Split the array into two halves
mid = ... | def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
... | [
{
"docstring": "Merge sort algorithm\n\nArgs:\n arr (list): list of elements to sort\n\nReturns:\n list: sorted list",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge two arrays into one sorted array\n\nA... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Merge sort algorithm\n\n Args:\n arr (list): list of elements to sort\n\n Returns:\n list: sorted list\n \"\"\"\n # Base case: i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022821",
"row_id": 22821,
"seed_ids": "['Llama-3.3-70B-Instruct_57064']"
} | 0.650438 | Filter_22821 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 92b19b709b5f72b7cd2baa3d67dc1be07116cbdc | 1f48d22d39cbe68f39ca1af325a4fd8523a2ec24 | |||
v1.0 | instruct | Filter | Filter_22822_I | In Python, how do you generate all possible combinations of elements from a given list and also for a given sublist of that list? | import itertools
def generate_combinations(lst):
"""
Generates all possible combinations of elements from the given list.
"""
combinations = []
for r in range(len(lst) + 1):
combinations.extend(itertools.combinations(lst, r))
return combinations
def generate_combinations_for_sublist(ls... | from solution import generate_combinations, generate_combinations_for_sublist
def test_generate_combinations_empty_list():
assert generate_combinations([]) == [()]
def test_generate_combinations_single_element():
assert generate_combinations([1]) == [(), (1,)]
def test_generate_combinations_multiple_elements... | [
{
"docstring": "Generates all possible combinations of elements from the given list.",
"function_declaration": "def generate_combinations(lst):",
"function_name": "generate_combinations",
"parameter_list": "(lst)"
},
{
"docstring": "Generates all possible combinations of elements from the gi... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import combinations\n\ndef generate_combinations(lst, n):\n \"\"\"\n Generate all possible combinations of length n from the given list lst.\n \n :param lst: List fr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022822",
"row_id": 22822,
"seed_ids": "['Llama-3.3-70B-Instruct_57065']"
} | 0.734949 | Filter_22822 | I | [
"generate_combinations",
"generate_combinations_for_sublist"
] | 2 | [
[
"generate_combinations_for_sublist",
"generate_combinations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee4d47687de6483aa9ac062757161db6185debfa | 4f4016c3a6a0784b8e1e87d5e2c2b7c1203e4b3b | |||
v1.0 | instruct | Filter | Filter_22841_I | I've got a function that formats phone numbers in the international format.
It takes a phone number (as a string) and the country code (as a string) as an input, and returns a string of the formatted phone number.
Here is a simplified version of the function:
```python
def format_phone_number(phone_number: str, country... | def format_phone_number(phone_number: str, country_code: str) -> str:
"""
Returns the phone number formatted in the international format.
Args:
phone_number (str): The phone number to be formatted.
country_code (str): The country code to be added.
Returns:
str: Formatted phone numb... | def test_format_phone_number():
assert format_phone_number('123456789', '33') == '+33 123456789'
assert format_phone_number('987654321', '44') == '+44 987654321'
assert format_phone_number('5551234', '1') == '+1 5551234'
assert format_phone_number('0800123456', '81') == '+81 0800123456'
def test_format... | [
{
"docstring": "Returns the phone number formatted in the international format.\n\nArgs:\nphone_number (str): The phone number to be formatted.\ncountry_code (str): The country code to be added.\n\nReturns:\nstr: Formatted phone number in international format.",
"function_declaration": "def format_phone_num... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def format_phone_number(phone_number: str, country_code: str) -> str:\n \"\"\"\n Formats a phone number in the international format.\n \n Args:\n phone_number (str): The phone n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022841",
"row_id": 22841,
"seed_ids": "['Llama-3.3-70B-Instruct_57098']"
} | 0.620737 | Filter_22841 | I | [
"format_phone_number",
"format_all_phone_numbers"
] | 2 | [
[
"format_all_phone_numbers",
"format_phone_number"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6891887f3e6d39a9d7148744a3fd66d9ef78c977 | 797472186af8ff4371f394d881105d33bab16f65 | |||
v1.0 | instruct | Filter | Filter_22849_I | I have an Optical Character Recognition (OCR) application that receives a scanned image or PDF document and renders text from it. This application has a function call `ocr Besides the receiveDocument` function call that will be used to trigger the OCR process.
Here is an example of how this function call looks like:
... | def ocr_besides_receive_document(document_id, ocr_results_callback):
"""
Triggers the OCR process and returns the results to the callback function.
:param document_id: int, unique identifier of the document.
:param ocr_results_callback: callable, callback function to handle OCR results.
"""
# S... | from solution import ocr_besides_receive_document
def test_ocr_besides_receive_document():
# Callback function to capture OCR results
results = []
def ocr_results_callback(ocr_results):
results.append(ocr_results)
# Test the OCR function with document_id = 1
ocr_besides_receive_documen... | [
{
"docstring": "Triggers the OCR process and returns the results to the callback function.\n\n:param document_id: int, unique identifier of the document.\n:param ocr_results_callback: callable, callback function to handle OCR results.",
"function_declaration": "def ocr_besides_receive_document(document_id, ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def ocr_besides_receive_document(document_id, ocr_results_callback):\n \"\"\"\n Triggers the OCR process on the given document and calls the callback function with the OCR results.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022849",
"row_id": 22849,
"seed_ids": "['Llama-3.3-70B-Instruct_57121']"
} | 0.438119 | Filter_22849 | I | [
"ocr_besides_receive_document",
"perform_ocr"
] | 2 | [
[
"ocr_besides_receive_document",
"perform_ocr"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d6d7a6881aeb604aaa0ab3aab73b22b7eed03d3e | 817d44d077a9e5a41e6caf9a9227971ea5b2f47e | |||
v1.0 | instruct | Filter | Filter_22861_I | This is a coding challenge.
Write a program to find the maximum sum of a contiguous subset sum within an array using the "divide and conquer" approach.
Here is a sample input:
[-2, -3, 4, -1, -2, 1, 5, -3]
And here is the sample output:
7
The maximum sum of a contiguous subset sum within this array is 7, which is... | def max_crossing_sum(arr, left, mid, right):
left_sum = float('-inf')
total = 0
for i in range(mid, left - 1, -1):
total += arr[i]
if total > left_sum:
left_sum = total
right_sum = float('-inf')
total = 0
for i in range(mid + 1, right + 1):
total += arr[i]
... | from solution import max_sum_of_contiguous_subset
def test_example_case():
assert max_sum_of_contiguous_subset([-2, -3, 4, -1, -2, 1, 5, -3]) == 7
def test_all_negative_numbers():
assert max_sum_of_contiguous_subset([-8, -3, -6, -2, -5, -4]) == -2
def test_all_positive_numbers():
assert max_sum_of_contig... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(arr, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(arr, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_sub_array_sum(arr, left, right):",
"function_name": "... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(arr, left, mid, right):\n left_sum = float('-inf')\n total = 0\n for i in range(mid, left - 1, -1):\n total += arr[i]\n if total > left_sum:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00022861",
"row_id": 22861,
"seed_ids": "['Llama-3.3-70B-Instruct_57147']"
} | 0.664064 | Filter_22861 | I | [
"max_crossing_sum",
"max_sub_array_sum",
"max_sum_of_contiguous_subset"
] | 3 | [
[
"max_sub_array_sum",
"max_crossing_sum"
],
[
"max_sum_of_contiguous_subset",
"max_sub_array_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9d2018b3a7adac2c2247c1710fefe2ee3fcdbaf1 | e305192da28daacb2cbce7abeb88d9bfaf6a5fe6 | |||
v1.0 | instruct | Filter | Filter_22870_I | I have 8 nodes and want to create a fully connected graph with them. I want to fully apply Dijkstra's algorithm to each node to find the shortest path between every pair of nodes.
Here is an example of my nodes and edges:
```
import networkx as nx
import sys
import heapq
G = nx.Graph()
G.add_nodes_from([0, 1, 2, 3, 4... | import networkx as nx
import heapq
def dijkstra(graph, start_node):
"""
Perform Dijkstra's algorithm to find the shortest path from start_node to all other nodes.
"""
# Min-heap priority queue
queue = [(0, start_node)]
# Dictionary to store the shortest path to each node
shortest_paths = {n... | import networkx as nx
from solution import dijkstra, shortest_paths
def test_dijkstra_basic_case():
G = nx.Graph()
G.add_node(0)
G.add_node(1)
G.add_edge(0, 1, weight=1)
sp = dijkstra(G, 0)
assert sp[1][0] == 1 # Distance from node 0 to node 1 is 1
assert sp[1][1] == [0, 1] # Path is... | [
{
"docstring": "Perform Dijkstra's algorithm to find the shortest path from start_node to all other nodes.",
"function_declaration": "def dijkstra(graph, start_node):",
"function_name": "dijkstra",
"parameter_list": "(graph, start_node)"
},
{
"docstring": null,
"function_declaration": "d... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import networkx as nx\n\ndef dijkstra(graph, start):\n \"\"\"\n Implement Dijkstra's algorithm to find shortest paths from start node.\n \"\"\"\n # Priority queue to store (distanc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022870",
"row_id": 22870,
"seed_ids": "['Llama-3.3-70B-Instruct_57166']"
} | 0.554809 | Filter_22870 | I | [
"dijkstra",
"shortest_paths"
] | 2 | [
[
"shortest_paths",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [
"networkx"
] | false | 06f11568e76d707c681ad8d8a075cdb043a0a090 | 65ccbc57a304bbc43a88b899c1f1d70748baf101 | |||
v1.0 | instruct | Filter | Filter_22882_I | A palindromic number is one that reads the same forwards and backwards, like 121 or 5665. Write a Python function to find all the palindromic numbers in a list of numbers.
Here is the helper function and main function you can use as a template:
```python
def is_palindrome(n):
"""Check if a string representation ... | def is_palindrome(n):
"""Check if a string representation of n is a palindrome."""
n_str = str(n)
return n_str == n_str[::-1]
def find_palindromic_numbers(num_list):
"""Find all palindromic numbers in a given list."""
return [num for num in num_list if is_palindrome(num)]
# Example usage
numbers =... | from solution import is_palindrome, find_palindromic_numbers
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(1221) == True
assert is_palindrome(12321) == True
assert is_palindrome(123) == False
assert is_palindrome(10) == False
def test_find_palindromic_numbers():
... | [
{
"docstring": "Check if a string representation of n is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Find all palindromic numbers in a given list.",
"function_declaration": "def find_palindr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(n):\n \"\"\"Check if a string representation of n is a palindrome.\"\"\"\n n_str = str(n)\n return n_str == n_str[::-1]\n\ndef find_palindromic_numbers(num_list):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022882",
"row_id": 22882,
"seed_ids": "['Llama-3.3-70B-Instruct_57198']"
} | 0.688851 | Filter_22882 | I | [
"is_palindrome",
"find_palindromic_numbers"
] | 2 | [
[
"find_palindromic_numbers",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 137391482a38c8a1ed28351ad7545f95b0c9256d | 65eb62501ff824f73bff619c5406117b32197020 | |||
v1.0 | instruct | Filter | Filter_22918_I | ### Situation
You have been given a task to make a Rock, Paper, Scissors game in Python and you want to create the game with 2 players and give them the option to play multiple rounds.
### Goal
Implement a Rock, Paper, Scissors game for 2 players with multiple rounds and get the final winner. | import random
def get_winner(player1_choice, player2_choice):
"""
Determine the winner between two players based on their choices
in a round of Rock, Paper, Scissors.
Choices:
- 'rock'
- 'paper'
- 'scissors'
Returns:
- 'player1' if player1 wins
- 'player2' if player2 wins
... | from solution import get_winner, play_game
# Test the get_winner function
def test_easy_cases():
assert get_winner('rock', 'scissors') == 'player1'
assert get_winner('scissors', 'paper') == 'player1'
assert get_winner('paper', 'rock') == 'player1'
assert get_winner('scissors', 'rock') == 'player2'... | [
{
"docstring": "Determine the winner between two players based on their choices\nin a round of Rock, Paper, Scissors.\n\nChoices:\n- 'rock'\n- 'paper'\n- 'scissors'\n\nReturns:\n- 'player1' if player1 wins\n- 'player2' if player2 wins\n- 'tie' if it's a tie",
"function_declaration": "def get_winner(player1_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def play_round(player1_choice, player2_choice):\n \"\"\"\n Determines the winner of a round of Rock, Paper, Scissors.\n \n Parameters:\n - player1_choice (str): Player 1's choic... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022918",
"row_id": 22918,
"seed_ids": "['Llama-3.3-70B-Instruct_57271']"
} | 0.475691 | Filter_22918 | I | [
"get_winner",
"play_game"
] | 2 | [
[
"play_game",
"get_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86552f11fd59a5c1bd23df98ae450724aa4a2feb | dfcbaf0fc26f98d6b47d5f1c2adb44069069be62 | |||
v1.0 | instruct | Filter | Filter_22923_I | Create a simple Hangman game using Python. The game should have a word list that includes the word "test", for example. | import random
def get_random_word(word_list):
"""
Returns a random word from the provided word list.
"""
return random.choice(word_list)
def display_word(word, guessed_letters):
"""
Returns a string representation of the word with underscores for letters
not yet guessed, and the actual let... | import pytest
from solution import get_random_word, display_word, hangman
def test_get_random_word():
word_list = ["test", "python", "hangman"]
word = get_random_word(word_list)
assert word in word_list
def test_display_word():
assert display_word("test", {'t', 'e'}) == 't e _ t'
assert display_wo... | [
{
"docstring": "Returns a random word from the provided word list.",
"function_declaration": "def get_random_word(word_list):",
"function_name": "get_random_word",
"parameter_list": "(word_list)"
},
{
"docstring": "Returns a string representation of the word with underscores for letters\nnot... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Word list including the word \"test\"\nWORD_LIST = [\"test\", \"python\", \"hangman\", \"challenge\", \"programming\"]\n\ndef choose_word(word_list):\n \"\"\"\n Choose... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022923",
"row_id": 22923,
"seed_ids": "['Llama-3.3-70B-Instruct_57282']"
} | 0.515457 | Filter_22923 | I | [
"get_random_word",
"display_word",
"hangman"
] | 3 | [
[
"hangman",
"display_word"
],
[
"hangman",
"get_random_word"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4d0f74509bfd1029877250029983744b821d4d62 | 6ec2ed4ea0626065d72314f2ec5161bbd44ac2d9 | |||
v1.0 | instruct | Filter | Filter_22925_I | I've got an opencv assignment, and I'm struggling to fill in this function which aims to detect the angle between the two lines that are formed by the first and last points selected by a user on an image.
Here's my current code:
```python
import cv2
import numpy as np
def draw_line(img, point1, point2):
cv2.line(... | import cv2
import numpy as np
import math
def draw_line(img, point1, point2):
cv2.line(img, point1, point2, (0, 255, 0), 2)
return img
def get_angle(line1, line2):
# Calculate direction vectors
v1 = (line1[1][0] - line1[0][0], line1[1][1] - line1[0][1])
v2 = (line2[1][0] - line2[0][0], line2[1][1]... | from solution import get_angle
def test_get_angle_90_degrees():
line1 = [(0, 0), (0, 1)]
line2 = [(0, 0), (1, 0)]
assert abs(get_angle(line1, line2) - 90) < 1e-5
def test_get_angle_45_degrees():
line1 = [(0, 0), (1, 1)]
line2 = [(0, 0), (1, 0)]
assert abs(get_angle(line1, line2) - 45) < 1e-5
... | [
{
"docstring": null,
"function_declaration": "def draw_line(img, point1, point2):",
"function_name": "draw_line",
"parameter_list": "(img, point1, point2)"
},
{
"docstring": null,
"function_declaration": "def get_angle(line1, line2):",
"function_name": "get_angle",
"parameter_lis... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport numpy as np\n\ndef draw_line(img, point1, point2):\n cv2.line(img, point1, point2, (0, 255, 0), 2)\n return img\n\ndef get_angle(line1, line2):\n \"\"\"\n Calcul... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022925",
"row_id": 22925,
"seed_ids": "['Llama-3.3-70B-Instruct_57289']"
} | 0.530849 | Filter_22925 | I | [
"draw_line",
"get_angle",
"detect_angle"
] | 3 | [
[
"detect_angle",
"draw_line"
],
[
"detect_angle",
"get_angle"
]
] | 2 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | f8006190f51ca6869edd49cdaeeaa93e1a906e60 | cf8ef5a7834f0d999bbebfd18693e31f54e352d3 | |||
v1.0 | instruct | Filter | Filter_22952_I | Here is a code for generating fractals with Python and matplotlib. Can you describe a brief summary, provide some example use cases, and add at least 4 impactful visualizations? | import matplotlib.pyplot as plt
import numpy as np
# Function to plot Mandelbrot set
def plot_mandelbrot():
x, y = np.ogrid[-2:0.8:1000j, -1.2:1.2:1000j]
c = x + 1j * y
z = c
divtime = np.zeros(z.shape, dtype=int)
for i in range(1, 51):
z = z**2 + c
diverge = z*np.conj(z) > 4
... | import pytest
from solution import plot_mandelbrot, plot_sierpinski_main, plot_julia, plot_barnsley_fern
def test_plot_mandelbrot():
assert callable(plot_mandelbrot)
def test_plot_sierpinski_main():
assert callable(plot_sierpinski_main)
def test_plot_julia():
assert callable(plot_julia)
assert le... | [
{
"docstring": null,
"function_declaration": "def plot_mandelbrot():",
"function_name": "plot_mandelbrot",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def plot_sierpinski(ax, p1, p2, p3, depth):",
"function_name": "plot_sierpinski",
"parameter_list": "... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\nimport random\n\ndef sierpinski_triangle(iterations):\n \"\"\"\n Generates a Sierpinski Triangle fractal.\n \n Args:\n iterations (int): Num... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022952",
"row_id": 22952,
"seed_ids": "['Llama-3.3-70B-Instruct_57361']"
} | 0.437957 | Filter_22952 | I | [
"plot_mandelbrot",
"plot_sierpinski",
"plot_sierpinski_main",
"plot_julia",
"plot_barnsley_fern"
] | 5 | [
[
"plot_sierpinski_main",
"plot_sierpinski"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | f91aa20307b6b210b7f231337b0245ef468a33bb | 2a7368d547728b2e50cf5a96dc98f58963992f10 | |||
v1.0 | instruct | Filter | Filter_22957_I | I believe I have grasped the basics of Python; now I want to learn more about decorators. Can you give me a simple and complex example of Python decorators?
Also, I've "heard" about a `@property` decorator in conjunction with classes. What is its purpose and how does one use it?
### Simple Decorator Example
To get s... | # Acknowledgment of the understanding of decorators
# Simple Decorator Example:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say... | def test_simple_decorator(capsys):
say_hello()
captured = capsys.readouterr()
assert captured.out == "Something is happening before the function is called.\nHello!\nSomething is happening after the function is called.\n"
def test_complex_decorator(capsys):
greet("John")
captured = capsys.readouterr... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Acknowledging understanding of simple and complex decorators\n\n# You have demonstrated a solid grasp of both simple and complex decorators in Python.\n# Let's further expand on the `@proper... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022957",
"row_id": 22957,
"seed_ids": "['Llama-3.3-70B-Instruct_57376']"
} | 0.369414 | Filter_22957 | I | [
"my_decorator",
"say_hello",
"repeat",
"greet"
] | 4 | [
[
"greet",
"repeat"
]
] | 1 | [] | false | [
"Person",
"Circle"
] | true | pytest | false | [] | true | 9f066d556fab7d81dae6b76611d3ba64f2d81cf1 | f81fa82d05db0a7b8cc5965b6fb2c847f70d770b | |||
v1.0 | instruct | Filter | Filter_22983_I | I want to create a simple recursive algorithm that does the following:
- Check each directory recursively for files with the .txt extension
- For each .txt file, read the file and count the number of lines with non-zero length
- Sum up the line counts from each file and display the final result
I want this algorith... | import os
def count_lines_in_txt_file(file_path):
"""
Counts and returns the number of non-empty lines in a given .txt file.
"""
with open(file_path, 'r') as file:
return sum(1 for line in file if line.strip())
def count_lines_in_directory_recursive(directory):
"""
Recursively counts a... | import os
import tempfile
from solution import count_lines_in_directory_recursive, count_lines_in_directory_iterative
def test_count_lines_in_directory():
with tempfile.TemporaryDirectory() as tmpdirname:
# Setup directory structure and files
os.makedirs(os.path.join(tmpdirname, 'subdir'))
... | [
{
"docstring": "Counts and returns the number of non-empty lines in a given .txt file.",
"function_declaration": "def count_lines_in_txt_file(file_path):",
"function_name": "count_lines_in_txt_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Recursively counts and returns the total ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef count_lines_in_file(file_path):\n try:\n with open(file_path, 'r') as file:\n return sum(1 for line in file if line.strip())\n except Exception as e:\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022983",
"row_id": 22983,
"seed_ids": "['Llama-3.3-70B-Instruct_57432']"
} | 0.671185 | Filter_22983 | I | [
"count_lines_in_txt_file",
"count_lines_in_directory_recursive",
"count_lines_in_directory_iterative"
] | 3 | [
[
"count_lines_in_directory_iterative",
"count_lines_in_txt_file"
],
[
"count_lines_in_directory_recursive",
"count_lines_in_txt_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2dbcbef93c7905d19edcf8475ed846e4ca99910c | 26dc44057cd25370b670d4d8318c8757e58a3767 | |||
v1.0 | instruct | Filter | Filter_22993_I | I need help with changing the brightness of all the images in a folder using Python. I can use OpenCV.
Let's say the root directory is the directory where the script is being run from, and the folder with the images to be brightened is named `images`. The folder has `*.jpg` files.
Here's a initial code:
```python
im... | import cv2
import os
import numpy as np
def change_brightness(image, value):
"""
Adjusts the brightness of the given image.
"""
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
v = cv2.add(v, value)
v[v > 255] = 255
v[v < 0] = 0
final_hsv = cv2.merge((h, s, v))
... | import cv2
import os
import pytest
import numpy as np
from solution import change_brightness, process_images_in_folder
def test_change_brightness_increase():
img = np.ones((100, 100, 3), dtype=np.uint8) * 100
bright_img = change_brightness(img, 50)
assert bright_img.mean() > img.mean()
def test_change_br... | [
{
"docstring": "Adjusts the brightness of the given image.",
"function_declaration": "def change_brightness(image, value):",
"function_name": "change_brightness",
"parameter_list": "(image, value)"
},
{
"docstring": "Adjusts the brightness of all images in the given folder.",
"function_d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport os\nimport numpy as np\n\ndef change_brightness(image_path, alpha, beta):\n \"\"\"\n Change the brightness of the image.\n\n Parameters:\n - image_path: str, pat... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00022993",
"row_id": 22993,
"seed_ids": "['Llama-3.3-70B-Instruct_57451']"
} | 0.416477 | Filter_22993 | I | [
"change_brightness",
"process_images_in_folder"
] | 2 | [
[
"process_images_in_folder",
"change_brightness"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | dcf7d034e1e2004ce572e02bf999a5d71201e9b6 | a4c4c4616a7f45390386223be75e7c7d74b3c803 | |||
v1.0 | instruct | Filter | Filter_23025_I | ### Algorithm Description
The input to the algorithm is a series of 2D points, each point being a pair of float values. The algorithm should compute the convex hull of the set of points.
### Implementation Details
Your task is to create a Python function `convex_hull` that takes a list of pairs of float values as inp... | import math
def orientation(p, q, r):
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
if val == 0:
return 0 # Collinear
elif val > 0:
return 1 # Clockwise
else:
return 2 # Counter clockwise
def convex_hull(points):
n = len(points)
if n < 3:
... | from solution import convex_hull
def test_convex_hull_square():
assert convex_hull([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]) == [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
def test_convex_hull_square_with_inner_point():
assert convex_hull([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.5, 0.5... | [
{
"docstring": null,
"function_declaration": "def orientation(p, q, r):",
"function_name": "orientation",
"parameter_list": "(p, q, r)"
},
{
"docstring": null,
"function_declaration": "def convex_hull(points):",
"function_name": "convex_hull",
"parameter_list": "(points)"
}
] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef orientation(p, q, r):\n \"\"\"\n To find the orientation of the ordered triplet (p, q, r).\n Function returns:\n 0 --> p, q and r are collinear\n 1 --> Clockw... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023025",
"row_id": 23025,
"seed_ids": "['Llama-3.3-70B-Instruct_57517']"
} | 0.515007 | Filter_23025 | I | [
"orientation",
"convex_hull"
] | 2 | [
[
"convex_hull",
"orientation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aa39c49facafc7f5fb9514d9681e2e06c4018d82 | 13e0f44160ef879215f953e22643a0e21d0a3b31 | |||
v1.0 | instruct | Filter | Filter_23030_I | I'm working on developing an improvement to an existing peer-to-peer file sharing system. One feature I'm implementing is the ability to add comments to shared files. To start, I want to generate a large number of comments for testing purposes.
I. Can you help write a Python script that generates random comments, inc... | import random
import string
def generate_random_username(length=8):
"""
Generates a random username consisting of lowercase letters.
"""
return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
def generate_random_comment(length=50):
"""
Generates a random comment text cons... | from solution import generate_random_username, generate_random_comment, generate_comments
def test_generate_random_username():
username = generate_random_username()
assert isinstance(username, str)
assert len(username) == 8
assert all(c in string.ascii_lowercase for c in username)
def test_generate_ra... | [
{
"docstring": "Generates a random username consisting of lowercase letters.",
"function_declaration": "def generate_random_username(length=8):",
"function_name": "generate_random_username",
"parameter_list": "(length=8)"
},
{
"docstring": "Generates a random comment text consisting of lower... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_random_username(length=8):\n \"\"\"\n Generates a random username consisting of lowercase letters. Default length is 8.\n \"\"\"\n retu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023030",
"row_id": 23030,
"seed_ids": "['Llama-3.3-70B-Instruct_57531']"
} | 0.603831 | Filter_23030 | I | [
"generate_random_username",
"generate_random_comment",
"generate_comments"
] | 3 | [
[
"generate_comments",
"generate_random_comment"
],
[
"generate_comments",
"generate_random_username"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c3584201ab7f072a2a98943595d5547964fb9d0f | 6929bd1cf93961235726a328de3d3c33f8af20cc | |||
v1.0 | instruct | Filter | Filter_23041_I | ### Introduction to Gradient Descent
Gradient descent is a widely used optimization algorithm in machine learning for minimizing the loss function in various models. We will first introduce the concept of gradient descent and its types. Then, we'll implement it in Python to get hands-on experience.
In this task, we wi... | def quadratic_function(x):
"""
Computes the value and gradient of the quadratic function f(x) = x^2.
Parameters:
x (float): The input value.
Returns:
value (float): The value of the function at x.
gradient (float): The gradient of the function at x.
"""
value = x ** 2
g... | from solution import quadratic_function, gradient_descent
def test_quadratic_function_value():
assert quadratic_function(0)[0] == 0 # f(0) = 0^2 = 0
assert quadratic_function(1)[0] == 1 # f(1) = 1^2 = 1
assert quadratic_function(-1)[0] == 1 # f(-1) = (-1)^2 = 1
assert quadratic_function(2)[0] == 4 #... | [
{
"docstring": "Computes the value and gradient of the quadratic function f(x) = x^2.\n\nParameters:\nx (float): The input value.\n\nReturns:\nvalue (float): The value of the function at x.\ngradient (float): The gradient of the function at x.",
"function_declaration": "def quadratic_function(x):",
"fun... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gradient_descent(fn, dfn, initial_theta, learning_rate, num_iterations):\n \"\"\"\n Performs vanilla gradient descent.\n\n Parameters:\n fn (function): The function to minimize... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023041",
"row_id": 23041,
"seed_ids": "['Llama-3.3-70B-Instruct_57561']"
} | 0.513388 | Filter_23041 | I | [
"quadratic_function",
"gradient_descent"
] | 2 | [
[
"gradient_descent",
"quadratic_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 485fa8467438eb100106d737918f64b5ecb97638 | 7884da8f9e4029a999c63c822e5b327fa59e2a05 | |||
v1.0 | instruct | Filter | Filter_23064_I | # Create a program in Python that calculates and returns the sum of all prime numbers up to the number entered by the user.
# After getting the sum, the program checks if the sum is a prime number itself. Then it prints the results. | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True... | from solution import is_prime, sum_of_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(11) == True
assert is_prime(16) == False
assert is_prime(17) == True
def test_sum_of_primes_10():
sum_primes, is_sum_prime = s... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of all prime numbers up to the given limit.",
"function_declaration": "def sum_of_primes(limit):",
"func... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023064",
"row_id": 23064,
"seed_ids": "['Llama-3.3-70B-Instruct_57616']"
} | 0.686175 | Filter_23064 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05ed043e3a6a05610bdb88a3761ebd88a69850f6 | 0e9bc56aa6e79c4ff1d46f50cb13f865652f8a15 | |||
v1.0 | instruct | Filter | Filter_23080_I | Write a code that generates passwords of length 10 from a collection of letters and numbers and checks if the generated password is strong.
To qualify as a strong password, it must have at least one uppercase letter, one lowercase letter, one digit, one special character.
The list of special characters is !"# $%&'()*... | import random
import string
SPECIAL_CHARACTERS = "!\"# $%&'()*+,-./:;<=>?@[\]^_`{|}~"
def generate_password(length=10):
if length < 8:
print("Password length should be at least 8 characters.")
return None
while True:
password = ''.join(random.choice(string.ascii_letters + string.d... | from solution import generate_password, is_strong_password
def test_generate_password_length():
password = generate_password(10)
assert len(password) == 10
def test_generate_password_length_less_than_8():
password = generate_password(6)
assert password is None
def test_is_strong_password():
stron... | [
{
"docstring": null,
"function_declaration": "def generate_password(length=10):",
"function_name": "generate_password",
"parameter_list": "(length=10)"
},
{
"docstring": null,
"function_declaration": "def is_strong_password(password):",
"function_name": "is_strong_password",
"par... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\nSPECIAL_CHARACTERS = \"!\\\"# $%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\n\ndef generate_password(length=10):\n if length < 8:\n print(\"Password length should ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023080",
"row_id": 23080,
"seed_ids": "['Llama-3.3-70B-Instruct_57647']"
} | 0.701499 | Filter_23080 | I | [
"generate_password",
"is_strong_password",
"main"
] | 3 | [
[
"generate_password",
"is_strong_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c8b23f31202c27dc1badf3ade74b0d796071462e | c5e9ad9fba234ee3a0e2b1c07452cb15aa8fe2ba | |||
v1.0 | instruct | Filter | Filter_23089_I | I am in a coding competition and I am going through the problems. I need some help with a problem that involves binary search. I have an array and I want to find an element k using binary search. The array can be either sorted or unsorted.
Also, the array can be rotated, meaning the array is sorted but it has been ro... | def binary_search(arr, left, right, k):
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == k:
return mid
elif arr[mid] < k:
left = mid + 1
else:
right = mid - 1
return -1
def find_pivot(arr, left, right):
if left > right:... | from solution import search_in_rotated_array
def test_search_in_rotated_array():
assert search_in_rotated_array([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert search_in_rotated_array([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert search_in_rotated_array([1], 0) == -1
assert search_in_rotated_array([1], 1) == 0
asse... | [
{
"docstring": null,
"function_declaration": "def binary_search(arr, left, right, k):",
"function_name": "binary_search",
"parameter_list": "(arr, left, right, k)"
},
{
"docstring": null,
"function_declaration": "def find_pivot(arr, left, right):",
"function_name": "find_pivot",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(arr, left, right, k):\n while left <= right:\n mid = left + (right - left) // 2\n if arr[mid] == k:\n return mid\n elif arr[mid] < k:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023089",
"row_id": 23089,
"seed_ids": "['Llama-3.3-70B-Instruct_57664']"
} | 0.787629 | Filter_23089 | I | [
"binary_search",
"find_pivot",
"search_in_rotated_array"
] | 3 | [
[
"search_in_rotated_array",
"binary_search"
],
[
"search_in_rotated_array",
"find_pivot"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 65d2d989a88957e6ad0973b831a893041b61ea31 | c6b19d98ce89ec65a5b4c5431fb99608268e9a1c | |||
v1.0 | instruct | Filter | Filter_23090_I | Here is the code:
```python
from scipy.integrate import quad
import numpy as np
def func(x):
return x**2 | from scipy.integrate import quad
import numpy as np
def func(x):
return x**2
def integrate_func(a, b):
"""
Integrates the func function from a to b.
Parameters:
a (float): Lower limit of integration.
b (float): Upper limit of integration.
Returns:
result (float): The result of the in... | from solution import integrate_func
def test_integration_0_5():
result = integrate_func(0, 5)
assert np.isclose(result, 125.0 / 3.0), f"Expected approximately 41.6667, got {result}"
def test_integration_0_1():
result = integrate_func(0, 1)
assert np.isclose(result, 1.0 / 3.0), f"Expected approximately... | [
{
"docstring": null,
"function_declaration": "def func(x):",
"function_name": "func",
"parameter_list": "(x)"
},
{
"docstring": "Integrates the func function from a to b.\n\nParameters:\na (float): Lower limit of integration.\nb (float): Upper limit of integration.\n\nReturns:\nresult (float... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from scipy.integrate import quad\nimport numpy as np\n\ndef func(x):\n return x**2\n\ndef integrate_func():\n \"\"\"\n Integrates the function `func(x)` over the interval [0, 1].\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023090",
"row_id": 23090,
"seed_ids": "['Llama-3.3-70B-Instruct_57671']"
} | 0.585069 | Filter_23090 | I | [
"func",
"integrate_func"
] | 2 | [
[
"integrate_func",
"func"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 0ab711dece7f48d7f10f7cb37e7f0e46c6a8f9c0 | f769a2abdca1ffb5b3ba219cf6c2359d963dea13 | |||
v1.0 | instruct | Filter | Filter_23103_I | I want to create a automatic file copying program for WIndows that will copy the newest file from one directory to another. The program should be able to perform this task repeatedly at a user-specified interval.
I have some experience with Python, so I should be able to use that to solve the problem. I would you like... | import os
import shutil
import time
def get_newest_file(directory):
"""
Returns the path of the newest file in the given directory.
"""
files = [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
newest_file = max(files, key=os.path.getctime) if... | import os
import shutil
import tempfile
import time
from solution import get_newest_file, copy_newest_file, repeat_copy_newest_file
def test_get_newest_file():
with tempfile.TemporaryDirectory() as tempdir:
file1 = os.path.join(tempdir, 'file1.txt')
file2 = os.path.join(tempdir, 'file2.txt')
... | [
{
"docstring": "Returns the path of the newest file in the given directory.",
"function_declaration": "def get_newest_file(directory):",
"function_name": "get_newest_file",
"parameter_list": "(directory)"
},
{
"docstring": "Copies the newest file from src_directory to dst_directory.",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport time\n\ndef get_newest_file(directory):\n \"\"\"\n Returns the path of the newest file in the given directory.\n \"\"\"\n files = [os.path.join(dir... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023103",
"row_id": 23103,
"seed_ids": "['Llama-3.3-70B-Instruct_57691']"
} | 0.536431 | Filter_23103 | I | [
"get_newest_file",
"copy_newest_file",
"repeat_copy_newest_file"
] | 3 | [
[
"copy_newest_file",
"get_newest_file"
],
[
"repeat_copy_newest_file",
"copy_newest_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2554f2fc1fea4d5e7f7a31f897613e1146227416 | 9d8822da2b46495c4ebbeb6129c6042995b2ac95 | |||
v1.0 | instruct | Filter | Filter_23118_I | I have an array of integer pairs. The pairs represent coordinates of points on a 2D plane. I need to compute the convex hull of these points in counterclockwise order.
Here is my attempt:
```python
import math
def distance(point, center):
"""Calculate the Euclidean distance between a point and a center point"""
... | import math
def distance(point, center):
"""Calculate the Euclidean distance between a point and a center point"""
return math.sqrt((point[0] - center[0])**2 + (point[1] - center[1])**2)
def orientation(p, q, r):
"""
To find the orientation of the triplet (p, q, r).
Returns:
0 -> p, q and r ar... | from solution import convex_hull
def test_convex_hull_simple_case():
points = [(0, 0), (0, 3), (3, 3), (3, 0)]
assert convex_hull(points) == [(0, 0), (3, 0), (3, 3), (0, 3)]
def test_convex_hull_with_collinear_points():
points = [(0, 0), (1, 1), (2, 2), (3, 3), (0, 3), (3, 0)]
assert convex_hull(point... | [
{
"docstring": "Calculate the Euclidean distance between a point and a center point",
"function_declaration": "def distance(point, center):",
"function_name": "distance",
"parameter_list": "(point, center)"
},
{
"docstring": "To find the orientation of the triplet (p, q, r).\nReturns:\n0 -> ... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(point, center):\n \"\"\"Calculate the Euclidean distance between a point and a center point.\"\"\"\n return math.sqrt((point[0] - center[0])**2 + (point[1] - ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023118",
"row_id": 23118,
"seed_ids": "['Llama-3.3-70B-Instruct_57721']"
} | 0.510021 | Filter_23118 | I | [
"distance",
"orientation",
"convex_hull"
] | 3 | [
[
"convex_hull",
"distance"
],
[
"convex_hull",
"orientation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8174641c18d16c85c072155403d56cabc9d383da | 4610cb46ce49d085c171627ec00611be6122cd42 | |||
v1.0 | instruct | Filter | Filter_23160_I | In this task, you have to find all the occurrences of a word in a list of strings (which represent lines of code) and return the line numbers of all occurrences. For example, given the following list of strings ["import os", "print('Hello world')", "import pandas as pd"], the word 'import' occurs at line number 1 and 3... | import re
def find_word(lines, word, case_sensitive=True):
"""
Finds all occurrences of a word in a list of strings and returns the line numbers.
:param lines: List of strings representing lines of text.
:param word: Word to search for.
:param case_sensitive: Boolean flag for case sensitivity. Def... | from solution import find_word, find_word_from_file
def test_find_word_case_sensitive():
lines = ["import os", "print('Hello world')", "import pandas as pd"]
assert find_word(lines, 'import') == [1, 3]
def test_find_word_case_insensitive():
lines = ["import os", "print('Hello world')", "Import pandas as p... | [
{
"docstring": "Finds all occurrences of a word in a list of strings and returns the line numbers.\n\n:param lines: List of strings representing lines of text.\n:param word: Word to search for.\n:param case_sensitive: Boolean flag for case sensitivity. Default is True.\n:return: List of integers representing li... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef find_word(lines, word, case_sensitive=True):\n \"\"\"\n Finds all occurrences of a word in a list of strings and returns the line numbers.\n\n :param lines: List of s... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023160",
"row_id": 23160,
"seed_ids": "['Llama-3.3-70B-Instruct_57826']"
} | 0.59572 | Filter_23160 | I | [
"find_word",
"find_word_from_file"
] | 2 | [
[
"find_word_from_file",
"find_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6a5bdab4e8315f29359478d6ea84205681387007 | 1e0c2b4164b12dc0eea6570395e49f54e9e44c9b | |||
v1.0 | instruct | Filter | Filter_23167_I | You have been assigned the task of implementing a feature to find the shortest path between two points on a grid. The grid is represented as a 2D array where each cell can have a value of either 0 or 1. A value of 0 represents an open path, and a value of 1 represents a blocked path. | from collections import deque
def is_valid(x, y, grid):
"""Check if the cell (x,y) is within the grid bounds and is an open path."""
rows, cols = len(grid), len(grid[0])
return 0 <= x < rows and 0 <= y < cols and grid[x][y] == 0
def shortest_path(grid, start, end):
"""
Finds the shortest path betw... | from solution import shortest_path
def test_shortest_path_example():
grid = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]
start = (0, 0)
end = (4, 4)
assert shortest_path(grid, start, end) == 8
def test_no_path():
... | [
{
"docstring": "Check if the cell (x,y) is within the grid bounds and is an open path.",
"function_declaration": "def is_valid(x, y, grid):",
"function_name": "is_valid",
"parameter_list": "(x, y, grid)"
},
{
"docstring": "Finds the shortest path between start and end points on the grid usin... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_valid(x, y, grid):\n \"\"\"Check if the cell (x,y) is within the grid bounds and is an open path.\"\"\"\n rows, cols = len(grid), len(grid[0])\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023167",
"row_id": 23167,
"seed_ids": "['Llama-3.3-70B-Instruct_57836']"
} | 0.639038 | Filter_23167 | I | [
"is_valid",
"shortest_path"
] | 2 | [
[
"shortest_path",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2931240bd7bfcfc0f567c3b507108ca686dfa5b | 43a80928ceb36838c5e99ca363ca7746d1976a94 | |||
v1.0 | instruct | Filter | Filter_23179_I | In this problem, we will simulate rolling two six-sided dice. The outcomes of rolling two dice can result in 36 possible combinations (since each die has six faces, we have 6 x 6 = 36 total combinations). These outcomes can be represented as pairs of numbers (x, y), where x and y are integers from 1 to 6.
Using the ra... | import random
from collections import Counter
def roll_two_dice():
"""
Simulates rolling two six-sided dice.
Returns a tuple representing the outcomes of the two dice.
"""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return (die1, die2)
def simulate_rolls(trials=1000):
"""
... | import pytest
from solution import roll_two_dice, simulate_rolls, theoretical_probabilities, compare_probabilities
def test_roll_two_dice():
for _ in range(100):
die1, die2 = roll_two_dice()
assert 1 <= die1 <= 6
assert 1 <= die2 <= 6
def test_simulate_rolls():
trials = 1000
counts... | [
{
"docstring": "Simulates rolling two six-sided dice.\nReturns a tuple representing the outcomes of the two dice.",
"function_declaration": "def roll_two_dice():",
"function_name": "roll_two_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates rolling two dice a specified number of tim... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom collections import Counter\n\ndef roll_two_dice():\n \"\"\"\n Simulates rolling two six-sided dice and returns the sum of their faces.\n \"\"\"\n return random.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023179",
"row_id": 23179,
"seed_ids": "['Llama-3.3-70B-Instruct_57863']"
} | 0.607282 | Filter_23179 | I | [
"roll_two_dice",
"simulate_rolls",
"theoretical_probabilities",
"compare_probabilities"
] | 4 | [
[
"compare_probabilities",
"theoretical_probabilities"
],
[
"simulate_rolls",
"roll_two_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1270f3df9d41e5dd0a5494341d73299f2baf4407 | 8e6379f349d9b7d9bd85b7fb70f4f91bca8a1dd5 | |||
v1.0 | instruct | Filter | Filter_23199_I | Hi Dev,
I've missed having a laptop and CLI but my recently purchased ThinkPad didn't arrive yet. In the meantime, I find iPython useful.
I'm using the following Python code for interleaving simple operations in my workflow. What would be the best way in Python to verify checksums? | import hashlib
def generate_checksum(data: str, algorithm: str = 'md5') -> str:
"""
Generates checksum of the given data using the specified algorithm.
Args:
data (str): The input data to generate checksum for.
algorithm (str): The hashing algorithm to use. Defaults to 'md5'.
Returns:... | from solution import generate_checksum, verify_checksum
def test_generate_checksum_md5():
assert generate_checksum("hello", "md5") == "5d41402abc4b2a76b9719d911017c592"
def test_generate_checksum_sha1():
assert generate_checksum("hello", "sha1") == "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
def test_generate... | [
{
"docstring": "Generates checksum of the given data using the specified algorithm.\n\nArgs:\ndata (str): The input data to generate checksum for.\nalgorithm (str): The hashing algorithm to use. Defaults to 'md5'.\n\nReturns:\nstr: The generated checksum.",
"function_declaration": "def generate_checksum(dat... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef calculate_md5_checksum(file_path):\n \"\"\"\n Calculate MD5 checksum for a given file.\n \n Args:\n - file_path (str): Path to the file.\n \n Returns... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023199",
"row_id": 23199,
"seed_ids": "['Llama-3.3-70B-Instruct_57903']"
} | 0.484363 | Filter_23199 | I | [
"generate_checksum",
"verify_checksum"
] | 2 | [
[
"verify_checksum",
"generate_checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9c8092666faa42798e217fc72368dc4747babc01 | 3a67cb4b79082a4133e3ac0613b000969aab41f1 | |||
v1.0 | instruct | Filter | Filter_23200_I | I have some code that turns code into a string of dots and dashes in Morse code:
```
ASCII_TO_MORSE = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',
'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '-... | ASCII_TO_MORSE = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',
'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
'U': '..-', 'V': '...-', 'W': '.--', 'X':... | from solution import text_to_morse, morse_to_text
def test_text_to_morse():
assert text_to_morse("HELLO") == ".... . .-.. .-.. ---"
assert text_to_morse("SOS") == "... --- ..."
assert text_to_morse("123") == ".---- ..--- ...--"
assert text_to_morse("HELLO WORLD") == ".... . .-.. .-.. --- .-- --- .-. ... | [
{
"docstring": null,
"function_declaration": "def convert_to_morse(char):",
"function_name": "convert_to_morse",
"parameter_list": "(char)"
},
{
"docstring": null,
"function_declaration": "def text_to_morse(text):",
"function_name": "text_to_morse",
"parameter_list": "(text)"
}... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "ASCII_TO_MORSE = {\n 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',\n 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',\n 'K': '-.-', 'L': '.-..', 'M': '--', '... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023200",
"row_id": 23200,
"seed_ids": "['Llama-3.3-70B-Instruct_57904']"
} | 0.562444 | Filter_23200 | I | [
"convert_to_morse",
"text_to_morse",
"morse_to_text"
] | 3 | [
[
"text_to_morse",
"convert_to_morse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fa8575fa7ebf45130c646610c1a7464c12e1fa3a | f6d20fd4af1cd92f18f766ab94cdb1d60ca574d3 | |||
v1.0 | instruct | Filter | Filter_23238_I | I wrote a simple Python script that decorates over any function to print out the function name, arguments, and the returned value. The issue is, it feels repetitive to have to decorate every function, even though almost all the functions in my script share a common name prefix, such as being prefixed with ` ل` (`لا`, `... | import inspect
def print_info(func):
"""
Decorator to print out the function name, arguments, and the returned value.
"""
def wrapper(*args, **kwargs):
print(f"Function Name: {func.__name__}")
print(f"Arguments: {args} {kwargs}")
result = func(*args, **kwargs)
print(f"Re... | def test_decorator_applied():
# Capture print statements
import io
import sys
captured_output = io.StringIO()
sys.stdout = captured_output
# Call decorated functions
result_one = لا_function_one(1, 2)
result_two = لا_function_two(3)
# Restore stdout
sys.stdout = sys.__stdout__... | [
{
"docstring": "Decorator to print out the function name, arguments, and the returned value.",
"function_declaration": "def print_info(func):",
"function_name": "print_info",
"parameter_list": "(func)"
},
{
"docstring": "Decorate all functions in `module_globals` with names starting with `pr... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\ndef trace(func):\n \"\"\"\n A decorator that prints out the function name, arguments and the returned value.\n \"\"\"\n @functools.wraps(func)\n def wrapper(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023238",
"row_id": 23238,
"seed_ids": "['Llama-3.3-70B-Instruct_57970']"
} | 0.449916 | Filter_23238 | I | [
"print_info",
"decorate_functions_with_prefix",
"لا_function_one",
"لا_function_two",
"regular_function"
] | 5 | [
[
"decorate_functions_with_prefix",
"print_info"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9b92b09657fee170cacf690a0def7a185e343e1a | 82169805111750347a6cf37bf1fc32027456cdba | |||
v1.0 | instruct | Filter | Filter_23282_I | Here is a problem I'm trying to solve. If you could provide some high-quality, readable, and well-documented code to this problem, that would be great:
Detect collisions between a set of circles (each with its own radius) in a 2D space.
- Circles can be defined as (x, y, radius)
- Assume no circle is defined such that... | import math
def are_circles_colliding(circle1, circle2):
"""
Check if two circles are colliding.
:param circle1: A tuple (x, y, radius) representing the first circle.
:param circle2: A tuple (x, y, radius) representing the second circle.
:return: True if the circles overlap, otherwise False.
"... | import pytest
from solution import are_circles_colliding, detect_collisions
def test_are_circles_colliding_true():
circle1 = (0, 0, 5)
circle2 = (3, 4, 5)
assert are_circles_colliding(circle1, circle2) == True
def test_are_circles_colliding_false():
circle1 = (0, 0, 3)
circle2 = (7, 0, 3)
asse... | [
{
"docstring": "Check if two circles are colliding.\n\n:param circle1: A tuple (x, y, radius) representing the first circle.\n:param circle2: A tuple (x, y, radius) representing the second circle.\n:return: True if the circles overlap, otherwise False.",
"function_declaration": "def are_circles_colliding(ci... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef are_circles_colliding(circle1, circle2):\n \"\"\"\n Check if two circles are colliding.\n\n :param circle1: A tuple (x, y, radius) representing the first circle.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023282",
"row_id": 23282,
"seed_ids": "['Llama-3.3-70B-Instruct_58057']"
} | 0.602645 | Filter_23282 | I | [
"are_circles_colliding",
"detect_collisions"
] | 2 | [
[
"detect_collisions",
"are_circles_colliding"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e837796f02bb3427c5ba6eff9d7084b750c16c2b | d7c6f57f022823475ebc2f328dfd86042f52cd26 | |||
v1.0 | instruct | Filter | Filter_23286_I | I want to simulate the Monty Hall problem. I have 3 doors with a car behind one of them. I want to take the following approach.
- Choose a door randomly
- Ask the game show host (who knows where the car is), to "open" a door and show me either a goat or nothing (he can't show the car).
- Based on the outcome of what t... | import random
def monty_hall_simulation(num_trials):
"""
Simulate the Monty Hall problem over a number of trials.
Parameters:
num_trials (int): The number of trials to simulate.
Returns:
float: The probability of winning if you follow the strategy.
"""
wins = 0
for _ ... | from solution import monty_hall_simulation
def test_monty_hall_simulation_high_win_rate():
"""
Test to ensure that the win rate is within expected range.
Based on the strategy (switching when a goat is revealed), the win probability should be close to 2/3.
"""
win_rate = monty_hall_simulation(10000... | [
{
"docstring": "Simulate the Monty Hall problem over a number of trials.\n\nParameters:\nnum_trials (int): The number of trials to simulate.\n\nReturns:\nfloat: The probability of winning if you follow the strategy.",
"function_declaration": "def monty_hall_simulation(num_trials):",
"function_name": "mo... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef monty_hall_simulation(num_trials):\n \"\"\"\n Simulate the Monty Hall problem over a number of trials.\n \n Parameters:\n num_trials (int): The number of tr... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023286",
"row_id": 23286,
"seed_ids": "['Llama-3.3-70B-Instruct_58074']"
} | 0.398582 | Filter_23286 | I | [
"monty_hall_simulation",
"monty_hall"
] | 2 | [
[
"monty_hall",
"monty_hall_simulation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7edcf538971fcd8e676dd55b5b89d8644c186e1b | 1c9374f3d7feac12ae6ed8d3e235ded37c01a40d | |||
v1.0 | instruct | Filter | Filter_23304_I | I have a boolean function `f(x, y)` that takes two boolean values and returns a boolean value. I want to write a program that can generate all possible combinations of inputs for this function and print out the results.
Here are the details:
- The function `f(x, y)` is defined as `f(x, y) = (x AND y) OR (NOT x)`
- I... | def f(x, y):
"""
Returns the result of (x AND y) OR (NOT x).
"""
return (x and y) or (not x)
def generate_combinations_and_results():
x_values = [True, False]
y_values = [True, False]
results = [(x, y, f(x, y)) for x in x_values for y in y_values]
result_str = "x\t|\ty\t|\tf(x, y)... | from solution import f, generate_combinations_and_results
def test_f_true_true():
assert f(True, True) == True
def test_f_true_false():
assert f(True, False) == False
def test_f_false_true():
assert f(False, True) == True
def test_f_false_false():
assert f(False, False) == True
def test_generate_co... | [
{
"docstring": "Returns the result of (x AND y) OR (NOT x).",
"function_declaration": "def f(x, y):",
"function_name": "f",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def generate_combinations_and_results():",
"function_name": "generate_combinations_a... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def f(x, y):\n \"\"\"\n Function to compute (x AND y) OR (NOT x)\n \"\"\"\n return (x and y) or (not x)\n\ndef generate_and_print_results():\n \"\"\"\n Generate all possible ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023304",
"row_id": 23304,
"seed_ids": "['Llama-3.3-70B-Instruct_58120']"
} | 0.571706 | Filter_23304 | I | [
"f",
"generate_combinations_and_results"
] | 2 | [
[
"generate_combinations_and_results",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a53532bf26c7c6752bbe8b900a886f514c32c220 | 21834978a023d0043f9f6c4fa0f89b9f0bc26c94 | |||
v1.0 | instruct | Filter | Filter_23306_I | Program that generates and uses transducitve closure of a set of rules ( Horn Clauses).
Transducitve closure is the mallest possible set of rules that can't be added or updated
The algorithm for generating the transitive closure of a set of rules (given in the form of Horn clauses) is based on the following idea:
For... | def resolve(rules):
new_rules = set(rules)
added = True
while added:
added = False
# Convert rules from set to list to allow indexing
rules_list = list(new_rules)
for i, rule1 in enumerate(rules_list):
for j, rule2 in enumerate(rules_list):
... | from solution import transitive_closure
def test_basic_rules():
rules = [("a", "b"), ("b", "c")]
expected = [("a", "b"), ("b", "c"), ("a", "c")]
result = transitive_closure(rules)
assert sorted(result) == sorted(expected)
def test_self_loop():
rules = [("a", "b"), ("b", "a")]
expected = [("a",... | [
{
"docstring": null,
"function_declaration": "def resolve(rules):",
"function_name": "resolve",
"parameter_list": "(rules)"
},
{
"docstring": null,
"function_declaration": "def transitive_closure(rules):",
"function_name": "transitive_closure",
"parameter_list": "(rules)"
}
] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def resolve(rules):\n new_rules = set(rules)\n added = True\n\n while added:\n added = False\n # Convert rules from set to list to allow indexing\n rules_list = l... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023306",
"row_id": 23306,
"seed_ids": "['Llama-3.3-70B-Instruct_58126']"
} | 0.36437 | Filter_23306 | I | [
"resolve",
"transitive_closure"
] | 2 | [
[
"transitive_closure",
"resolve"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fabaaa99d6726c1d9930e098d08ebd9efff8276d | fb6e073f20c07182bdc7e1977343bdaf61d7ea8e | |||
v1.0 | instruct | Filter | Filter_23331_I | How do I use Python type hinting to create a user-defined type? | from typing import NewType, List
# Define a user-defined type.
UserId = NewType('UserId', int)
# Function that accepts the user-defined type.
def get_user_name(user_id: UserId) -> str:
user_names = {
1: 'Alice',
2: 'Bob',
3: 'Charlie'
}
# Simulating fetching user name based on user... | from solution import UserId, get_user_name, get_user_names
def test_get_user_name():
assert get_user_name(UserId(1)) == 'Alice'
assert get_user_name(UserId(2)) == 'Bob'
assert get_user_name(UserId(3)) == 'Charlie'
assert get_user_name(UserId(999)) == 'Unknown'
def test_get_user_names():
assert get... | [
{
"docstring": null,
"function_declaration": "def get_user_name(user_id):",
"function_name": "get_user_name",
"parameter_list": "(user_id)"
},
{
"docstring": null,
"function_declaration": "def get_user_names(user_ids):",
"function_name": "get_user_names",
"parameter_list": "(user... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import NewType\n\n# Creating a user-defined type for UserID\nUserID = NewType('UserID', int)\n\n# You can now use this UserID type in your functions\ndef get_user_name(user_id: Use... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023331",
"row_id": 23331,
"seed_ids": "['Llama-3.3-70B-Instruct_58183']"
} | 0.393038 | Filter_23331 | I | [
"get_user_name",
"get_user_names"
] | 2 | [
[
"get_user_names",
"get_user_name"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf0784c65fccc26e70103c66dddb01f17644ec68 | e73b3d547890d745178c5b36c1aef59424ca67bf | |||
v1.0 | instruct | Filter | Filter_23336_I | I want to write a program that can take a text file containing database tables, and convert the SQL into comma separated values (csv) format.
Rather than simply converting the complete string from SQL to csv, I would like it to be more clever and 'understand' the SQL schema and produce a useful csv output.
For exam... | import csv
import re
def parse_sql_schema(sql_schema):
tables = {}
current_table = None
# Regular expressions to match SQL statements
table_re = re.compile(r'CREATE TABLE (\w+) \(')
column_re = re.compile(r'(\w+) (INT|VARCHAR\(.*?\)|TEXT).*?')
foreign_key_re = re.compile(r'FOREIGN KEY \((\... | from solution import parse_sql_schema, generate_csv_structure, write_csv_structure
import os
def test_parse_sql_schema():
sql_schema = """
CREATE TABLE authors (
id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
);
CREATE TABLE books (
id INT PRIMARY KEY,
title VA... | [
{
"docstring": null,
"function_declaration": "def parse_sql_schema(sql_schema):",
"function_name": "parse_sql_schema",
"parameter_list": "(sql_schema)"
},
{
"docstring": null,
"function_declaration": "def generate_csv_structure(parsed_schema):",
"function_name": "generate_csv_structu... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport re\n\ndef parse_sql_schema(sql_schema):\n tables = {}\n current_table = None\n \n # Regular expressions to match SQL statements\n table_re = re.compile(r'CREA... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023336",
"row_id": 23336,
"seed_ids": "['Llama-3.3-70B-Instruct_58193']"
} | 0.518082 | Filter_23336 | I | [
"parse_sql_schema",
"generate_csv_structure",
"write_csv_structure",
"convert_sql_to_csv"
] | 4 | [
[
"convert_sql_to_csv",
"generate_csv_structure"
],
[
"convert_sql_to_csv",
"parse_sql_schema"
],
[
"convert_sql_to_csv",
"write_csv_structure"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d1dd5a8a694bcc8792fec74f02c90b69354e3dce | 6130d1e89f41f7af662aec40a2aa28092a0128e2 | |||
v1.0 | instruct | Filter | Filter_23341_I | I want to generate a random number between 0 and 99, and then generate a random string of characters
length 5. I want to generate this random number and string 5 times.
1. Provide the python code to accomplish this.
2. Can you explain what each part of the code is doing? | import random
import string
def generate_random_number():
"""
Generate a random number between 0 and 99.
"""
return random.randint(0, 99)
def generate_random_string(length=5):
"""
Generate a random string of characters of given length.
"""
letters = string.ascii_letters + string.digits... | from solution import generate_random_number, generate_random_string, generate_random_data
def test_generate_random_number():
for _ in range(100):
num = generate_random_number()
assert 0 <= num <= 99
def test_generate_random_string():
for _ in range(100):
rnd_string = generate_random_st... | [
{
"docstring": "Generate a random number between 0 and 99.",
"function_declaration": "def generate_random_number():",
"function_name": "generate_random_number",
"parameter_list": "()"
},
{
"docstring": "Generate a random string of characters of given length.",
"function_declaration": "de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_random_data():\n \"\"\"\n Generates a list of 5 tuples, each containing:\n - A random number between 0 and 99\n - A random string of le... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023341",
"row_id": 23341,
"seed_ids": "['Llama-3.3-70B-Instruct_58211']"
} | 0.630563 | Filter_23341 | I | [
"generate_random_number",
"generate_random_string",
"generate_random_data"
] | 3 | [
[
"generate_random_data",
"generate_random_number"
],
[
"generate_random_data",
"generate_random_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6c974e610c11c2151d8177971b76088c734c4224 | 668b30e6b82914cfe2c4324c0b21f1eefd90ec50 | |||
v1.0 | instruct | Filter | Filter_23378_I | Here's a problem:
We need a function that can delete a node with a given key from an arbitrary binary search tree (BST). The function should delete the node while maintaining the properties of a BST.
We are given the root of the BST and the key of the node to be deleted. Our function should return the root of the mo... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def deleteNode(root, key):
"""
Deletes the node with the given key in the BST and returns the root of the modified BST.
"""
if not root:
return root
... | from solution import TreeNode, deleteNode
def tree_to_list(root):
"""Helper function to convert BST to list (inorder traversal) for easy comparison in tests."""
result = []
if root:
result.extend(tree_to_list(root.left))
result.append(root.val)
result.extend(tree_to_list(root.right)... | [] | [
1,
1,
1
] | 3 | easy | 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 deleteNode(root, key):\n \"\"\"\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023378",
"row_id": 23378,
"seed_ids": "['Llama-3.3-70B-Instruct_58294']"
} | 0.446655 | Filter_23378 | I | [
"deleteNode",
"getMin"
] | 2 | [
[
"deleteNode",
"getMin"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 80169f2650bef2656bf7c49c85915981ddcfb0a5 | fe4ea00cccd4f785458f8567f536d3ad28d5ce56 | |||
v1.0 | instruct | Filter | Filter_23382_I | I have a table with two columns: "id" (a unique identifier) and "text" (a string). The table stores sentences or text chunks. Each text chunk is linked to a specific topic, but the topic is not stored in the table. I have a list of pre-defined topics and their corresponding keywords, which I will use to automatically i... | import re
from collections import defaultdict
def preprocess_text(text):
"""
Preprocess text by converting it to lower case and removing non-alphanumeric characters.
"""
return re.sub(r'\W+', ' ', text.lower())
def assign_topic_to_texts(table, topics_keywords):
"""
Assign topics to each text c... | from solution import assign_topic_to_texts
def test_assign_single_topic():
table = [{'id': 1, 'text': 'I love programming in Python and working on machine learning projects.'}]
topics_keywords = {'Technology': ['programming', 'Python']}
expected = {1: 'Technology'}
assert assign_topic_to_texts(table, t... | [
{
"docstring": "Preprocess text by converting it to lower case and removing non-alphanumeric characters.",
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": "Assign topics to each text chunk in the table bas... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import defaultdict\n\ndef preprocess_text(text):\n \"\"\"\n Preprocess text by converting it to lower case and removing non-alphanumeric characters.\n \"\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023382",
"row_id": 23382,
"seed_ids": "['Llama-3.3-70B-Instruct_58300']"
} | 0.43066 | Filter_23382 | I | [
"preprocess_text",
"assign_topic_to_texts"
] | 2 | [
[
"assign_topic_to_texts",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a5d74380fb2a69f1b1a737c28aedcb6a08dfaac | 05b2da2299c190ddccd529539196be34b15f40fb | |||
v1.0 | instruct | Filter | Filter_23392_I | Here is a piece of code written in Python:
```python
import os
def print_json (jsondata):
print(f'JSON DATA: {jsondata}')
def get_directory(path):
if not os.path.isdir(path):
return None
return path
def get_all_dirs(path):
if os.path.isfile(path):
return []
all_dirs = []
all... | import os
def print_json (jsondata):
print(f'JSON DATA: {jsondata}')
def get_directory(path):
if not os.path.isdir(path):
return None
return path
def get_all_dirs(path):
if os.path.isfile(path):
return []
all_dirs = []
all_dirs.append(get_directory(path))
for root, dirs,... | import tempfile
import os
from solution import get_all_files_by_extensions, get_all_dirs
def test_get_all_files_by_extensions_find_json():
with tempfile.TemporaryDirectory() as tmpdirname:
json_file_path = os.path.join(tmpdirname, 'test.json')
open(json_file_path, 'w').close()
directories ... | [
{
"docstring": null,
"function_declaration": "def print_json(jsondata):",
"function_name": "print_json",
"parameter_list": "(jsondata)"
},
{
"docstring": null,
"function_declaration": "def get_directory(path):",
"function_name": "get_directory",
"parameter_list": "(path)"
},
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef print_json(jsondata):\n print(f'JSON DATA: {jsondata}')\n\ndef get_directory(path):\n if not os.path.isdir(path):\n return None\n return path\n\ndef get_all_di... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023392",
"row_id": 23392,
"seed_ids": "['Llama-3.3-70B-Instruct_58323']"
} | 0.663207 | Filter_23392 | I | [
"print_json",
"get_directory",
"get_all_dirs",
"get_all_files_by_extensions"
] | 4 | [
[
"get_all_dirs",
"get_directory"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 499a0c924d761208eb079de8ec28004ed76e4e78 | 6eb56a2c84fff86bee2b7d0c5643e0456f8c4650 | |||
v1.0 | instruct | Filter | Filter_23404_I | Here is some code in pseudocode, that I'd like to convert to Python. I can't quite get the hill climb algorithm working correctly.
```
Input n
Create a grid of nxn
Initialize bestSolution (0)
Initialize bestFitness (0)
Set maxIterations (1000)
Set neighborhood size (10)
Iterate (maxIterations):
Create CurrentSolu... | import numpy as np
def calc_fitness(grid):
"""
Calculate the fitness of a solution.
For simplicity, fitness is defined as the sum of all cell values (sum of neighbors that are alive).
"""
return np.sum(grid)
def create_random_solution(n):
"""
Create a random nxn grid with values 0 or 1.
... | from solution import calc_fitness, create_random_solution, hill_climb_algorithm
def test_calc_fitness():
grid = np.array([[1, 0], [0, 1]])
assert calc_fitness(grid) == 2
def test_create_random_solution():
solution = create_random_solution(2)
assert solution.shape == (2, 2)
assert np.all(np.isin(so... | [
{
"docstring": "Calculate the fitness of a solution.\nFor simplicity, fitness is defined as the sum of all cell values (sum of neighbors that are alive).",
"function_declaration": "def calc_fitness(grid):",
"function_name": "calc_fitness",
"parameter_list": "(grid)"
},
{
"docstring": "Create... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef calc_fitness(grid, position):\n \"\"\"Calculate the fitness of a given solution\"\"\"\n x, y = position\n fitness = 0\n for i in range(x - 1, x + 2):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023404",
"row_id": 23404,
"seed_ids": "['Llama-3.3-70B-Instruct_58357']"
} | 0.434828 | Filter_23404 | I | [
"calc_fitness",
"create_random_solution",
"hill_climb_algorithm"
] | 3 | [
[
"hill_climb_algorithm",
"calc_fitness"
],
[
"hill_climb_algorithm",
"create_random_solution"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | bf4d98f7c6dc909d04656821d36a231701051b48 | bcc1523f29a27d0a4dc7013de80b28b1fabc3f8d | |||
v1.0 | instruct | Filter | Filter_23407_I | ### Primer on Distributed Systems
#### Chapter 5: Time, Clocks, and the Ordering of Events in a Distributed System
Utility functions for setting clocks and calculating the time using multiple reference clocks in a distributed system.
```python
import time
from datetime import datetime
def calculate_average_time(refer... | def calculate_average_time(reference_clocks):
"""
Calculate the average time from multiple reference clocks in a distributed system.
Args:
reference_clocks (list): A list of reference clocks, each represented as a tuple of (name, time_in_seconds).
Returns:
float: The average time in se... | def test_calculate_average_time():
ref_clocks = [("Clock1", 100), ("Clock2", 105), ("Clock3", 110)]
assert calculate_average_time(ref_clocks) == 105
def test_calculate_time_difference():
ref_clock = ("Clock1", 100)
local_clock = ("LocalClock", 90)
assert calculate_time_difference(ref_clock, local_c... | [
{
"docstring": "Calculate the average time from multiple reference clocks in a distributed system.\n\nArgs:\n reference_clocks (list): A list of reference clocks, each represented as a tuple of (name, time_in_seconds).\n\nReturns:\n float: The average time in seconds.",
"function_declaration": "def ca... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Solution to handle clock synchronization in a distributed system with no centralized clock\n\ndef calculate_average_time(reference_clocks):\n \"\"\"\n Calculate the average time from m... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023407",
"row_id": 23407,
"seed_ids": "['Llama-3.3-70B-Instruct_58363']"
} | 0.560323 | Filter_23407 | I | [
"calculate_average_time",
"calculate_time_difference",
"synchronize_clocks"
] | 3 | [
[
"synchronize_clocks",
"calculate_average_time"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 2c39670a84dc1ad7d56c3c61eb3ed1a3d875ae32 | c988e6d7ab6ee5ad3f175a6b1f97ce2424894027 | |||
v1.0 | instruct | Filter | Filter_23410_I | I see the tendency of users to end their comment with "[username], you are [adjective]" as a way to insult, mock, or simply describe another user. I'd like to automate this process with a Python script.
## Task
Write a simple Python script (`insult_generator.py`) that takes an input file with one username on each lin... | import random
# Adjectives list
adjectives = ["awesome", "amazing", "good", "great", "excellent", "cool", "bad", "awful", "terrible", "horrible"]
def generate_insult(username):
"""
Generate an insult or compliment for the given username.
Parameters:
username (str): The username to generate an insult ... | import os
from solution import generate_insult, process_usernames
def test_generate_insult():
username = "tester"
result = generate_insult(username)
assert result.startswith(username + ", you are ")
adjective = result.split(", you are ")[1]
assert adjective in ["awesome", "amazing", "good", "great"... | [
{
"docstring": "Generate an insult or compliment for the given username.\n\nParameters:\nusername (str): The username to generate an insult for.\n\nReturns:\nstr: A string with the format '[username], you are [adjective]'.",
"function_declaration": "def generate_insult(username):",
"function_name": "gen... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Adjectives list\nadjectives = [\"awesome\", \"amazing\", \"good\", \"great\", \"excellent\", \"cool\", \"bad\", \"awful\", \"terrible\", \"horrible\"]\n\ndef generate_insult... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023410",
"row_id": 23410,
"seed_ids": "['Llama-3.3-70B-Instruct_58372']"
} | 0.503517 | Filter_23410 | I | [
"generate_insult",
"process_usernames"
] | 2 | [
[
"process_usernames",
"generate_insult"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1bd6da5087c27b4d8993b76a1e64ee0840b75d3c | 118c2764120c179e05e96f79fe4b2ce9472a95fb | |||
v1.0 | instruct | Filter | Filter_23418_I | I need to generate a list of 100 random names for a project. I am looking for names that are both in English and Spanish. I have generated a list of first and last names in English and Spanish and would like some code to randomly generate names from these lists.
Here are the example lists of first and last names in En... | import random
english_first_names = ["John", "Sophia", "Jackson", "Isabella", "Aiden", "Olivia"]
english_last_names = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis"]
spanish_first_names = ["Santiago", "Lucia", "Matias", "Valentina", "Leon", "Gabriela"]
spanish_last_names = ["Gomez", "Rodriguez", "Martinez... | from solution import generate_random_names_list
def test_random_names_length():
names = generate_random_names_list(100)
assert len(names) == 100
def test_random_names_format():
names = generate_random_names_list(100)
for name in names:
assert len(name.split()) == 2, f"The name '{name}' does no... | [
{
"docstring": "Generates a random full name by randomly choosing from both English and Spanish names.",
"function_declaration": "def generate_random_name():",
"function_name": "generate_random_name",
"parameter_list": "()"
},
{
"docstring": "Generates a list of random full names with a give... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_names(english_first_names, english_last_names, spanish_first_names, spanish_last_names, total_names=100):\n \"\"\"\n Generate a list of random names ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023418",
"row_id": 23418,
"seed_ids": "['Llama-3.3-70B-Instruct_58397']"
} | 0.587846 | Filter_23418 | I | [
"generate_random_name",
"generate_random_names_list"
] | 2 | [
[
"generate_random_names_list",
"generate_random_name"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc04aeacb4baedc581354e5424a04f8cf5b7a575 | cf6371eb96d9f8ef9d436a8734302c819ee86a06 | |||
v1.0 | instruct | Filter | Filter_23421_I | To determine whether a number is a leap year, you can use the following rules:
* The year can be evenly divided by 4;
* If the year can also be evenly divided by 100, it is NOT a leap year, unless;
* The year is also evenly divisible by 400. Then it is a leap year.
I would like to write a function that sits on t... | def is_leap_year(year):
"""
Determines if a given year is a leap year.
Args:
year (int): The year to check.
Returns:
bool: True if the year is a leap year, False otherwise.
"""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
return False
de... | from solution import is_leap_year, find_leap_years
def test_is_leap_year():
assert is_leap_year(2000) == True
assert is_leap_year(1900) == False
assert is_leap_year(2004) == True
assert is_leap_year(2001) == False
assert is_leap_year(1600) == True
assert is_leap_year(1999) == False
def test_fi... | [
{
"docstring": "Determines if a given year is a leap year.\n\nArgs:\nyear (int): The year to check.\n\nReturns:\nbool: True if the year is a leap year, False otherwise.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"docs... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_leap_years(start_year, end_year):\n \"\"\"\n Returns a list of all leap years between start_year and end_year (inclusive).\n \n A year is a leap year if it satisfies the f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023421",
"row_id": 23421,
"seed_ids": "['Llama-3.3-70B-Instruct_58403']"
} | 0.611481 | Filter_23421 | I | [
"is_leap_year",
"find_leap_years"
] | 2 | [
[
"find_leap_years",
"is_leap_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16718398e2eafdc6797393197cc733f50bddcb4e | 3e4144bbd1207a39cf47f4764480f4f3578f5a54 | |||
v1.0 | instruct | Filter | Filter_23436_I | I have several text files (about 20000) containing a list of names. Each line of the file is in the format `last name, first name`. Names are separated by a comma and a space, then followed by a line break. Here is a sample list:
```
Doe, John
Smith, Jane
Johnson, Mike
Jones, Sarah
```
I'm looking for a way to search f... | def reverse_names_in_file(file_path):
"""
Reverse the order of names in the given file.
Format in file: "last name, first name"
Returns a list of reversed full names as "first name last name".
"""
reversed_names = []
with open(file_path, 'r') as file:
for line in file:
la... | from solution import reverse_names_in_file, search_for_full_name
def test_reverse_names_in_file(tmp_path):
file_path = tmp_path / "names.txt"
file_content = "Doe, John\nSmith, Jane\nJohnson, Mike\nJones, Sarah\n"
expected_output = ["John Doe", "Jane Smith", "Mike Johnson", "Sarah Jones"]
file_path.writ... | [
{
"docstring": "Reverse the order of names in the given file.\nFormat in file: \"last name, first name\"\nReturns a list of reversed full names as \"first name last name\".",
"function_declaration": "def reverse_names_in_file(file_path):",
"function_name": "reverse_names_in_file",
"parameter_list": ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef reverse_name(name):\n \"\"\"\n Reverse the order of the name from 'last name, first name' to 'first name last name'.\n \"\"\"\n last_name, first_name = name.split(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023436",
"row_id": 23436,
"seed_ids": "['Llama-3.3-70B-Instruct_58449']"
} | 0.609836 | Filter_23436 | I | [
"reverse_names_in_file",
"search_for_full_name"
] | 2 | [
[
"search_for_full_name",
"reverse_names_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 911d980d379d868e8c38774ab91c67407179ee59 | fd7931baf937132801e68aea6ccdc5de9a82914a | |||
v1.0 | instruct | Filter | Filter_23458_I | ### Sorted Array
Write a function that generates a sorted list of unique integers in a given range. The list should be sorted in ascending order.
Here is an example of how the function could be used:
```python
print(generate_sorted_array(1, 10)) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
### Unsorted Array
Wri... | import random
def generate_sorted_array(start, end):
"""
Generate a sorted list of unique integers in a given range without using sorted().
"""
return list(range(start, end + 1))
def generate_unsorted_array(start, end):
"""
Generate an unsorted list of unique integers in a given range.
"""... | from solution import generate_sorted_array, generate_unsorted_array
def test_generate_sorted_array():
assert generate_sorted_array(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert generate_sorted_array(5, 8) == [5, 6, 7, 8]
assert generate_sorted_array(0, 0) == [0]
assert generate_sorted_array(-3, 3) =... | [
{
"docstring": "Generate a sorted list of unique integers in a given range without using sorted().",
"function_declaration": "def generate_sorted_array(start, end):",
"function_name": "generate_sorted_array",
"parameter_list": "(start, end)"
},
{
"docstring": "Generate an unsorted list of un... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_sorted_array(start, end):\n \"\"\"\n Generate a sorted list of unique integers in a given range without using sorted().\n \"\"\"\n sorted_array = []\n for i in rang... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023458",
"row_id": 23458,
"seed_ids": "['Llama-3.3-70B-Instruct_58520']"
} | 0.63543 | Filter_23458 | I | [
"generate_sorted_array",
"generate_unsorted_array"
] | 2 | [
[
"generate_unsorted_array",
"generate_sorted_array"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0279dbb8273f3845dd4a6cdb37eb5a8c83ac0d2 | d5a79e6cf1a5bca595baa8e0bd491ce68b1d1c52 | |||
v1.0 | instruct | Filter | Filter_23468_I | Given a system of parabolic equations for a two-lane highway, the traffic density and velocity can be modeled as a system of nonlinear partial differential equations. Typically, the traffic density (ρ) is given by the Lighthill–Whitham–Richards model, where ρ satisfies:
∂ρ/∂t + ∂(ρv)/∂x = 0
where v is the traffic vel... | import numpy as np
def v(ρ, v_max, ρ_max):
"""
Compute traffic velocity based on density
Parameters:
ρ (float): traffic density
v_max (float): maximum velocity
ρ_max (float): maximum density
Returns:
float: traffic velocity
"""
return v_max * (1 - (ρ / ρ_max) ** 2)
def solve_... | from solution import v, solve_traffic_density
import numpy as np
def test_v_function():
assert np.isclose(v(0, 120, 200), 120)
assert np.isclose(v(200, 120, 200), 0)
assert np.isclose(v(100, 120, 200), 90)
def test_solve_traffic_density():
x = np.linspace(0, 10, 5)
t = np.linspace(0, 2, 5)
dx ... | [
{
"docstring": "Compute traffic velocity based on density\n\nParameters:\nρ (float): traffic density\nv_max (float): maximum velocity\nρ_max (float): maximum density\n\nReturns:\nfloat: traffic velocity",
"function_declaration": "def v(ρ, v_max, ρ_max):",
"function_name": "v",
"parameter_list": "(ρ,... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef v(ρ, v_max, ρ_max):\n \"\"\"\n Compute traffic velocity based on density\n\n Parameters:\n ρ (float): traffic density\n v_max (float): maximum velocity... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023468",
"row_id": 23468,
"seed_ids": "['Llama-3.3-70B-Instruct_58544']"
} | 0.400001 | Filter_23468 | I | [
"v",
"solve_traffic_density"
] | 2 | [
[
"solve_traffic_density",
"v"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 479cf4e9e7b76d30ccf55560b48f3d5fb04ebf47 | e2ed8edbb4bcaf2f0453392ca4a9ef5c7d5d95ea | |||
v1.0 | instruct | Filter | Filter_23490_I | I believe I have found an issue with the median calculation method used in a Python library. The median calculation is done by sorting the input list and then looking at the middle value(s) for even and odd length lists. However, I would like to explore alternatives that can calculate the median in linear time.
I nee... | import random
def quickselect_median(arr):
"""
Calculate the median using the QuickSelect algorithm,
which has an average-case time complexity of O(n).
"""
if len(arr) % 2 == 1:
return quickselect(arr, len(arr) // 2)
else:
return 0.5 * (quickselect(arr, len(arr) // 2 - 1) +
... | from solution import quickselect_median, median_of_stream
def test_quickselect_median_even_length():
assert quickselect_median([3, 1, 2, 4]) == 2.5
def test_quickselect_median_odd_length():
assert quickselect_median([3, 1, 2]) == 2
def test_quickselect_median_single_element():
assert quickselect_median([... | [
{
"docstring": "Calculate the median using the QuickSelect algorithm, \nwhich has an average-case time complexity of O(n).",
"function_declaration": "def quickselect_median(arr):",
"function_name": "quickselect_median",
"parameter_list": "(arr)"
},
{
"docstring": "QuickSelect algorithm to fi... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef quickselect_median(arr):\n \"\"\"\n Returns the median of the array using the QuickSelect algorithm,\n which works in expected linear time.\n \n arr: List o... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023490",
"row_id": 23490,
"seed_ids": "['Llama-3.3-70B-Instruct_58580']"
} | 0.721989 | Filter_23490 | I | [
"quickselect_median",
"quickselect",
"median_of_stream"
] | 3 | [
[
"quickselect_median",
"quickselect"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09bca3cbb50585da69fdef020ce6c0e58bea603e | c5f1ba053ca896e8ecc4532c90e364b4ddf9dd9a | |||
v1.0 | instruct | Filter | Filter_23505_I | I have an idea for a choose-your-own-adventure-style text-based game. I want to develop it in Python. Can you show me a basic structure for such a game? | def start():
print("Welcome to the Adventure Game!")
print("You are standing at a crossroads. You can go left or right.")
choice = input("Which way do you want to go? (left/right) ").strip().lower()
if choice == 'left':
left_path()
elif choice == 'right':
right_path()
else:
... | import pytest
from solution import start, left_path, right_path
def test_start(monkeypatch):
choices = iter(['left', 'swim'])
monkeypatch.setattr('builtins.input', lambda _: next(choices))
start()
def test_start_invalid(monkeypatch):
choices = iter(['invalid', 'right', 'run'])
monkeypatch.setattr(... | [
{
"docstring": null,
"function_declaration": "def start():",
"function_name": "start",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def left_path():",
"function_name": "left_path",
"parameter_list": "()"
},
{
"docstring": null,
"function_dec... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start():\n print(\"You are in a dark room.\")\n print(\"There is a door to your right and left, which one do you take?\")\n\n choice = input(\"> \")\n \n if choice == \"left... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023505",
"row_id": 23505,
"seed_ids": "['Llama-3.3-70B-Instruct_58621']"
} | 0.397813 | Filter_23505 | I | [
"start",
"left_path",
"right_path"
] | 3 | [
[
"start",
"left_path"
],
[
"start",
"right_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b3fdac7e6f7952d2250aaab20bb6d8c14b83ad0d | 525bbb01b66d4fd014a544e3173b9c076a7b4d45 | |||
v1.0 | instruct | Filter | Filter_23522_I | Here is a simulation of a dart game, where the number of darts thrown, the precision of the players, and the size of the board are defined:
- 2 players are playing
- Each player throws 5 darts
- The precision of the players is measured by their average distance to the target.
- The board size is 20 units in diameter.
... | import math
def calculate_distance(x, y):
"""
Calculate the Euclidean distance of a point (x, y) from the center (0, 0).
"""
return math.sqrt(x**2 + y**2)
def player_scores(player_throws):
"""
Calculate the scores for a player based on their throws.
Parameters:
player_throws (list... | from solution import calculate_distance, player_scores, game_results
def test_calculate_distance():
assert math.isclose(calculate_distance(3, 4), 5.0, rel_tol=1e-9)
assert math.isclose(calculate_distance(0, 0), 0.0, rel_tol=1e-9)
assert math.isclose(calculate_distance(1, 1), math.sqrt(2), rel_tol=1e-9)
de... | [
{
"docstring": "Calculate the Euclidean distance of a point (x, y) from the center (0, 0).",
"function_declaration": "def calculate_distance(x, y):",
"function_name": "calculate_distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Calculate the scores for a player based on their throws.\... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef calculate_distance_to_target(x, y):\n \"\"\"\n Calculates the distance from the point (x, y) to the target center (0, 0).\n \"\"\"\n return math.sqrt(x**2 + y**2... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023522",
"row_id": 23522,
"seed_ids": "['Llama-3.3-70B-Instruct_58664']"
} | 0.603808 | Filter_23522 | I | [
"calculate_distance",
"player_scores",
"game_results"
] | 3 | [
[
"game_results",
"player_scores"
],
[
"player_scores",
"calculate_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4f41a83a5fcfe4e38cfcb159b91c12b4aca0c50c | 904f1cc2311288fbc25386aa7bbd26877905d11c | |||
v1.0 | instruct | Filter | Filter_23529_I | In this task, you will be presented with a sequence of numbers that has both URL and non-url elements. You need to write a code to identify and separate the URL and non-url elements. After identification, you have to save these elements in two separate CSV files.
Example Input Data:
[
"http://test.com",
"This... | import csv
import re
def is_url(string):
"""
Checks if a string is a URL.
"""
url_pattern = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:\S+(?::\S*)?@)?' # optional user:pass authentication
r'(?:[A-Za-z0-9.-]+)?' # domain...
r'(?:\.[A-Za-z]{2,})' # ...... | import csv
import os
from solution import separate_urls, is_url
def test_is_url():
assert is_url("http://test.com") == True
assert is_url("This is a test") == False
assert is_url("https://example.com/abc?query=123") == True
assert is_url("ftp://example.com/file.txt") == True
assert is_url("example.... | [
{
"docstring": "Checks if a string is a URL.",
"function_declaration": "def is_url(string):",
"function_name": "is_url",
"parameter_list": "(string)"
},
{
"docstring": null,
"function_declaration": "def separate_urls(data):",
"function_name": "separate_urls",
"parameter_list": "(... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport re\n\ndef is_url(string):\n \"\"\"\n Checks if a string is a URL.\n \"\"\"\n url_pattern = re.compile(\n r'^(https?|ftp):\\/\\/[^\\s/$.?#].[^\\s]*$'\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023529",
"row_id": 23529,
"seed_ids": "['Llama-3.3-70B-Instruct_58685']"
} | 0.63115 | Filter_23529 | I | [
"is_url",
"separate_urls"
] | 2 | [
[
"separate_urls",
"is_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8473a383de74009f14b0b4fc171ce20aec1b3b02 | 74209ad77371ff9eb701583845e13c75b2b04fd2 | |||
v1.0 | instruct | Filter | Filter_23586_I | Write a program that checks if a series of numbers are prime or not
Step 1: Write a helper function primeChecker() that checks if a single number is prime
Step 2: Use the primeChecker() to write main program that takes an arbitrary list of integers and prints out whether each one is prime or not
Solution:
```python
... | def primeChecker(x):
"""
Check if a number is a prime.
Args:
x (int): The number to check.
Returns:
bool: True if the number is a prime, False otherwise.
"""
if x < 2:
return False
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return Fals... | from solution import primeChecker, check_primes
def test_primeChecker():
assert primeChecker(2) == True
assert primeChecker(3) == True
assert primeChecker(4) == False
assert primeChecker(5) == True
assert primeChecker(10) == False
assert primeChecker(11) == True
assert primeChecker(1) == Fa... | [
{
"docstring": "Check if a number is a prime.\n\nArgs:\nx (int): The number to check.\n\nReturns:\nbool: True if the number is a prime, False otherwise.",
"function_declaration": "def primeChecker(x):",
"function_name": "primeChecker",
"parameter_list": "(x)"
},
{
"docstring": "Check a list ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def primeChecker(x):\n \"\"\"\n Checks if a single number x is prime.\n \n Parameters:\n x (int): The number to check.\n \n Returns:\n bool: True if x is prime, False o... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023586",
"row_id": 23586,
"seed_ids": "['Llama-3.3-70B-Instruct_58796']"
} | 0.707829 | Filter_23586 | I | [
"primeChecker",
"check_primes"
] | 2 | [
[
"check_primes",
"primeChecker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3e6c7c164d0a2d7a659faa86be183c909e9d1dcd | 8a836122fbb4e073a55abeb43319a2b591dc2166 | |||
v1.0 | instruct | Filter | Filter_23599_I | In a famous card game, a deck of 52 cards consists of cards evenly divided into 4 suits, and each suit contains 13 ranks. In this game, the objective is to get a hand with certain patterns. The following patterns are defined:
- A "Prime" pattern is a sequence of 5 cards where all cards are of the same suit and the dif... | from typing import List, Tuple
def rank_to_value(rank: str) -> int:
"""
Converts a card rank to its corresponding integer value.
"""
rank_map = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13}
return rank_map[rank]
def is_prime_pattern(h... | from solution import is_prime_pattern
def test_prime_pattern_valid():
hand = [('A', 'H'), ('2', 'H'), ('3', 'H'), ('4', 'H'), ('5', 'H')]
assert is_prime_pattern(hand) == True
def test_prime_pattern_invalid_suit():
hand = [('A', 'H'), ('2', 'H'), ('3', 'H'), ('4', 'H'), ('5', 'D')]
assert is_prime_pat... | [
{
"docstring": "Converts a card rank to its corresponding integer value.",
"function_declaration": "def rank_to_value(rank):",
"function_name": "rank_to_value",
"parameter_list": "(rank)"
},
{
"docstring": "Verifies if a given hand satisfies the Prime pattern.",
"function_declaration": "... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef rank_to_value(rank: str) -> int:\n \"\"\"\n Converts a card rank to its corresponding value.\n \"\"\"\n rank_dict = {\n 'A': 1,\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023599",
"row_id": 23599,
"seed_ids": "['Llama-3.3-70B-Instruct_58822']"
} | 0.564555 | Filter_23599 | I | [
"rank_to_value",
"is_prime_pattern"
] | 2 | [
[
"is_prime_pattern",
"rank_to_value"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c325b82d59ea6dedc803047ee8006cf74f23a22 | 1e19478e7d3104d3cd83c53e4e124aaf32f8a821 | |||
v1.0 | instruct | Filter | Filter_23600_I | Write code for the Word Scramble game in Python.
Implement 3 difficulty levels: Easy, Medium and Hard.
In each level, 5 words will be scrambled at each level and the player can try to unscramble them.
The game will end if the player unscrambles all words or if the player fails to unscramble 3 words.
The word list can... | import random
# Initialize word lists for each difficulty level
word_lists = {
'Easy': ['apple', 'basic', 'cloud', 'dance', 'flute'],
'Medium': ['boundary', 'calendar', 'computer', 'generate', 'harmony'],
'Hard': ['accomplish', 'brilliant', 'cathedral', 'democratic', 'exhibition']
}
def scramble(word):
... | from solution import play_game
def test_easy_level_win():
difficulty = 'Easy'
guesses = ['apple', 'basic', 'cloud', 'dance', 'flute']
result, correct_guesses, failed_guesses, results = play_game(difficulty, guesses)
assert result == 'Won'
assert correct_guesses == 5
assert failed_guesses == 0
... | [
{
"docstring": "Scramble a word by shuffling its characters.",
"function_declaration": "def scramble(word):",
"function_name": "scramble",
"parameter_list": "(word)"
},
{
"docstring": "Check if the user's guess matches any word in the list from which scrambled word is drawn.",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Initialize word lists for each difficulty level\nword_lists = {\n 'Easy': ['apple', 'basic', 'cloud', 'dance', 'flute'],\n 'Medium': ['boundary', 'calendar', 'computer... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023600",
"row_id": 23600,
"seed_ids": "['Llama-3.3-70B-Instruct_58827']"
} | 0.674483 | Filter_23600 | I | [
"scramble",
"check_guess",
"play_game"
] | 3 | [
[
"play_game",
"check_guess"
],
[
"play_game",
"scramble"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f036b90a8d021872147f9e6d8726e70fd3446e90 | 1b000dbcd08acf1d261d7c2fbb29f804ace67659 | |||
v1.0 | instruct | Filter | Filter_23606_I | Given the following code:
```python
def divisible_by_3(n):
return True if n % 3 == 0 else False
def find_numbers(numbers):
divisible_numbers = []
for number in numbers:
if divisible_by_3(number):
divisible_numbers.append(number)
return divisible_numbers | def divisible_by_3(n):
return True if n % 3 == 0 else False
def find_numbers(numbers):
divisible_numbers = []
for number in numbers:
if divisible_by_3(number):
divisible_numbers.append(number)
return divisible_numbers | from solution import divisible_by_3, find_numbers
def test_divisible_by_3():
assert divisible_by_3(3) == True
assert divisible_by_3(6) == True
assert divisible_by_3(9) == True
assert divisible_by_3(4) == False
assert divisible_by_3(7) == False
assert divisible_by_3(11) == False
assert divis... | [
{
"docstring": null,
"function_declaration": "def divisible_by_3(n):",
"function_name": "divisible_by_3",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_numbers(numbers):",
"function_name": "find_numbers",
"parameter_list": "(numbers)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def divisible_by_3(n):\n return True if n % 3 == 0 else False\n\ndef find_numbers(numbers):\n return [number for number in numbers if divisible_by_3(number)]",
"test_code": "from sol... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023606",
"row_id": 23606,
"seed_ids": "['Llama-3.3-70B-Instruct_58847']"
} | 0.607754 | Filter_23606 | I | [
"divisible_by_3",
"find_numbers"
] | 2 | [
[
"find_numbers",
"divisible_by_3"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 618cda775e8cd1517a537bd42419531c168781c3 | ba03758669abb2cd0156ea68c670ab1ffc09db32 | |||
v1.0 | instruct | Filter | Filter_23626_I | Write a code snippet that accurately calculates the Fibonacci sequence up to the nth term.
```python
def fibonacci(n):
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
```
You want to test the Fibonacci sequence generator and also make it more eff... | def multiply_matrices(a, b):
"""Multiply two 2x2 matrices."""
result = [[0, 0], [0, 0]]
result[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]
result[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]
result[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]
result[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1]... | from solution import fibonacci
def test_fibonacci_0():
assert fibonacci(0) == 0
def test_fibonacci_1():
assert fibonacci(1) == 1
def test_fibonacci_2():
assert fibonacci(2) == 1
def test_fibonacci_3():
assert fibonacci(3) == 2
def test_fibonacci_4():
assert fibonacci(4) == 3
def test_fibonacci... | [
{
"docstring": "Multiply two 2x2 matrices.",
"function_declaration": "def multiply_matrices(a, b):",
"function_name": "multiply_matrices",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the nth power of a 2x2 matrix.",
"function_declaration": "def matrix_power(matrix, n):",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def multiply_matrices(a, b):\n \"\"\"Multiply two 2x2 matrices.\"\"\"\n result = [[0, 0], [0, 0]]\n result[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]\n result[0][1] = a[0][0] * ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023626",
"row_id": 23626,
"seed_ids": "['Llama-3.3-70B-Instruct_58891']"
} | 0.741779 | Filter_23626 | I | [
"multiply_matrices",
"matrix_power",
"fibonacci"
] | 3 | [
[
"fibonacci",
"matrix_power"
],
[
"matrix_power",
"multiply_matrices"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | df68ebd3b5d10e3c4eab0760fbefd008a893df8d | 522b6cddcb00885f7abcf60833a91e4de81b33c9 | |||
v1.0 | instruct | Filter | Filter_23643_I | I've got a superuser and an ordinary user in this system. The superuser has permissions to access all the areas of the system, while an ordinary user can only access certain areas.
I need to implement a decorator that will restrict access to certain functions based on user type. How do I do this in Python? | from functools import wraps
# Define a simple User class for demonstration
class User:
def __init__(self, username, is_superuser=False):
self.username = username
self.is_superuser = is_superuser
# Decorator to enforce access control based on user type
def restrict_access(allowed_user_type):
de... | from solution import User, restrict_access, restricted_function, open_function
def test_restricted_function_superuser():
superuser = User("admin", is_superuser=True)
assert restricted_function(superuser) == "Access granted to admin"
def test_restricted_function_ordinary_user():
ordinary_user = User("john_... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import wraps\n\ndef user_type_required(user_type):\n \"\"\"\n A decorator to restrict access to certain functions based on user type.\n \"\"\"\n def decorator(func):... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023643",
"row_id": 23643,
"seed_ids": "['Llama-3.3-70B-Instruct_58925']"
} | 0.355673 | Filter_23643 | I | [
"restrict_access",
"restricted_function",
"open_function"
] | 3 | [
[
"restricted_function",
"restrict_access"
]
] | 1 | [] | false | [
"User"
] | true | pytest | true | [] | true | 70378b96f09412a760eab3af11b333ca71e8aaf5 | a6c166dae69e084cb5cbe8cdbb8acf34e535db36 | |||
v1.0 | instruct | Filter | Filter_23647_I | Disquiet is an application that takes in sentences from an API, processes them, and outputs generated music. In the current implementation, I wish to transform sentences into music notes. Each character in the sentence has a corresponding musical note and the duration of each note is determined by the ASCII value of th... | def char_to_note_duration(char):
"""
Converts a character to a tuple of (note, duration).
Note is the character itself and duration is its ASCII value.
"""
note = char
duration = ord(char)
return (note, duration)
def sentence_to_music(sentence):
"""
Takes a sentence and returns a li... | from solution import char_to_note_duration, sentence_to_music
def test_char_to_note_duration():
assert char_to_note_duration('a') == ('a', 97)
assert char_to_note_duration('A') == ('A', 65)
assert char_to_note_duration(' ') == (' ', 32)
assert char_to_note_duration('1') == ('1', 49)
def test_sentence_... | [
{
"docstring": "Converts a character to a tuple of (note, duration).\nNote is the character itself and duration is its ASCII value.",
"function_declaration": "def char_to_note_duration(char):",
"function_name": "char_to_note_duration",
"parameter_list": "(char)"
},
{
"docstring": "Takes a se... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sentence_to_music_notes(sentence):\n \"\"\"\n Transforms a sentence into a list of music notes.\n Each character in the sentence corresponds to a musical note,\n and the durati... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023647",
"row_id": 23647,
"seed_ids": "['Llama-3.3-70B-Instruct_58930']"
} | 0.494032 | Filter_23647 | I | [
"char_to_note_duration",
"sentence_to_music"
] | 2 | [
[
"sentence_to_music",
"char_to_note_duration"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77b5d03cc2f6dc4f32058d4573851448dcd437cd | 2e89845636de719fd054640190bec0670ba97777 | |||
v1.0 | instruct | Filter | Filter_23677_I | I've been using Python to help a friend with some analysis on a dataset. It turns out that the data was originally written to a CAS (content addressable storage) system, which means that some fields are represented as URLs. Now the client wants to apply some specific rules on these URL fields. I'd like to implement the... | from urllib.parse import urlparse, urlunparse
def is_valid_url(url):
"""
Check if the input string is a valid URL.
"""
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False
def apply_rules_to_url(url, rules):
"""
Appl... | from solution import is_valid_url, apply_rules_to_url, rule_add_www, rule_ensure_https
def test_is_valid_url():
assert is_valid_url("http://example.com") == True
assert is_valid_url("https://example.com") == True
assert is_valid_url("ftp://example.com") == True
assert is_valid_url("http:///example.com"... | [
{
"docstring": "Check if the input string is a valid URL.",
"function_declaration": "def is_valid_url(url):",
"function_name": "is_valid_url",
"parameter_list": "(url)"
},
{
"docstring": "Apply given rules to transform a URL.\nRules is a list of functions that take a parsed URL and return an... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom urllib.parse import urlparse\n\n# URL validation regex pattern\nURL_REGEX = re.compile(\n r'^(https?|ftp):\\/\\/'\n r'(?:\\S+(?::\\S*)?@)?'\n r'(?!10(?:\\.\\d{1,3}){3}... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023677",
"row_id": 23677,
"seed_ids": "['Llama-3.3-70B-Instruct_59015']"
} | 0.417876 | Filter_23677 | I | [
"is_valid_url",
"apply_rules_to_url",
"rule_add_www",
"rule_ensure_https"
] | 4 | [
[
"apply_rules_to_url",
"is_valid_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e325ccba4f6d0546584546d18271698ce78a6d48 | aaa0c4fa2c8195b8a66b233673124652f6075617 | |||
v1.0 | instruct | Filter | Filter_23687_I | I have been copying the standard insertion sort code and pasting it into various programs to sort arrays, but the cost of comparing each element with each other is extremely high when the array is very large (n^2). Is there any other sorting algorithm which has a better performance than O(n^2)? | def merge_sort(arr):
"""
Sorts an array using the merge sort algorithm.
Parameters:
arr (list): The list to be sorted.
Returns:
list: The sorted list.
"""
if len(arr) <= 1:
return arr
# Find the middle point and divide the array
mid = len(arr) // 2
left... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([7]) == [7]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_list():
assert... | [
{
"docstring": "Sorts an array using the merge sort algorithm.\n\nParameters:\narr (list): The list to be sorted.\n\nReturns:\nlist: The sorted list.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorte... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array in ascending order using the merge sort algorithm.\n \n :param arr: List of elements to be sorted.\n :return: List of sorted eleme... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023687",
"row_id": 23687,
"seed_ids": "['Llama-3.3-70B-Instruct_59035']"
} | 0.433041 | Filter_23687 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 772ac93339cc3d479812ee3925b2a169d3613ab2 | 16e40f0f03c03cff73cbaeea4d86d8f673fc180d | |||
v1.0 | instruct | Filter | Filter_23689_I | ### Task
Create a multipurpose function called `command` that takes in a string argument `cmd_input`, processes it, and then performs an action based on the input given.
```python
def command(cmd_input):
"""
This function processes the input command and performs an action based on the input given.
Args:
... | def command(cmd_input):
"""
This function processes the input command and performs an action based on the input given.
Args:
cmd_input (str): The input command to be processed.
Returns:
str: The result of the command.
"""
# Check if the input is a string
if not isinstance(cmd_... | from solution import command
def test_command_hello():
assert command("hello") == "Hello! How can I assist you?"
def test_command_goodbye():
assert command("goodbye") == "Goodbye! Have a nice day!"
def test_command_add():
assert command("add 1 2 3") == "6"
assert command("add 5 -2 7") == "10"
ass... | [
{
"docstring": "This function processes the input command and performs an action based on the input given.\n\nArgs:\ncmd_input (str): The input command to be processed.\n\nReturns:\nstr: The result of the command.",
"function_declaration": "def command(cmd_input):",
"function_name": "command",
"para... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def command(cmd_input):\n \"\"\"\n This function processes the input command and performs an action based on the input given.\n\n Args:\n cmd_input (str): The input command to be p... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023689",
"row_id": 23689,
"seed_ids": "['Llama-3.3-70B-Instruct_59037']"
} | 0.561301 | Filter_23689 | I | [
"command",
"add_numbers",
"multiply_numbers"
] | 3 | [
[
"command",
"add_numbers"
],
[
"command",
"multiply_numbers"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c6d9ccfefbac79af5393e24ac1403ffe549650ce | e9cf4f9febc4dba9d7560d4bf267b7fc6a27e7e2 | |||
v1.0 | instruct | Filter | Filter_23694_I | Here is a Python code snippet that implements the merge sort algorithm using a top-down approach:
```python
def merge_sort_top_down(array):
if len(array) <= 1:
return array
mid = len(array) // 2
left = merge_sort_top_down(array[:mid])
right = merge_sort_top_down(array[mid:])
return merge... | def merge_sort_iterative(array):
"""
Implements the merge sort algorithm using an iterative approach.
"""
width = 1
n = len(array)
while width < n:
for i in range(0, n, 2 * width):
left = array[i:i + width]
right = array[i + width:i + 2 * width]
array[... | from solution import merge_sort_iterative
def test_merge_sort_iterative_empty():
assert merge_sort_iterative([]) == []
def test_merge_sort_iterative_single_element():
assert merge_sort_iterative([5]) == [5]
def test_merge_sort_iterative_sorted():
assert merge_sort_iterative([1, 2, 3, 4, 5]) == [1, 2, 3, ... | [
{
"docstring": "Implements the merge sort algorithm using an iterative approach.",
"function_declaration": "def merge_sort_iterative(array):",
"function_name": "merge_sort_iterative",
"parameter_list": "(array)"
},
{
"docstring": "Helper function to merge two sorted lists.",
"function_de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_iterative(array):\n \"\"\"\n Iterative implementation of the merge sort algorithm.\n \"\"\"\n n = len(array)\n width = 1\n while width < n:\n for i in r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023694",
"row_id": 23694,
"seed_ids": "['Llama-3.3-70B-Instruct_59049']"
} | 0.490704 | Filter_23694 | I | [
"merge_sort_iterative",
"merge"
] | 2 | [
[
"merge_sort_iterative",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4377f289d86da2ccf37e2df2ed70918a4c956911 | d9067e2e707fff94c9cdbfb956d67fe990abeb81 | |||
v1.0 | instruct | Filter | Filter_23721_I | ### Algorithms for repeated nearest neighbour search
Given a point `p` and a set of points `points` in a `d`-dimensional space, determine the nearest neighbour of `p` with respect to these points using the euclidean distance metric. However, we are looking to optimise this nearest neighbor search so it is suitable for... | import numpy as np
class Node:
def __init__(self, point, axis, left=None, right=None):
self.point = point
self.axis = axis
self.left = left
self.right = right
self.bbox = None
def __str__(self):
return str(self.point)
def build_kdtree(points, depth=0):
if l... | from solution import build_kdtree, nearest_neighbor, repeated_nn_query
def test_nearest_neighbor_single_query():
points = [
[2, 3], [5, 4], [9, 6],
[4, 7], [8, 1], [7, 2]
]
tree = build_kdtree(points)
point = [9, 2]
nearest, dist = nearest_neighbor(tree, point)
assert nearest ==... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\nclass Node:\n def __init__(self, point, axis, left=None, right=None):\n self.point = point\n self.axis = axis\n self.left = left\n self.rig... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023721",
"row_id": 23721,
"seed_ids": "['Llama-3.3-70B-Instruct_59119']"
} | 0.599726 | Filter_23721 | I | [
"build_kdtree",
"bbox_intersect",
"nearest_neighbor",
"repeated_nn_query"
] | 4 | [
[
"nearest_neighbor",
"bbox_intersect"
],
[
"repeated_nn_query",
"nearest_neighbor"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [
"numpy"
] | false | f04eff9aa40632b0d0a32eaa18eaf99f9eadd97e | 788c1df9e98eb83aa13b38575c4dd88a4a8a0239 | |||
v1.0 | instruct | Filter | Filter_23729_I | Create a Python program that takes a maximum number as input and creates a list of all prime numbers up to that number. | def is_prime(n):
"""
Check if the number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import is_prime, get_primes_up_to
def test_is_prime():
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(10)
assert is_prime(11)
assert is_prime(13)
assert is_prime(17)
... | [
{
"docstring": "Check if the number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Generate a list of all prime numbers up to max_num.",
"function_declaration": "def get_primes_up_to(max_num):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n retur... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023729",
"row_id": 23729,
"seed_ids": "['Llama-3.3-70B-Instruct_59139']"
} | 0.656733 | Filter_23729 | I | [
"is_prime",
"get_primes_up_to"
] | 2 | [
[
"get_primes_up_to",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f659aa97d8f09a2bc3ec9d9739ded76316568ec6 | e639ef5274f628f58382604ab3b214b95b8aa766 | |||
v1.0 | instruct | Filter | Filter_23739_I | I have two sorting algorithms applied on the array [6,10,5,1,9,8,7,2,3,4]. The algorithms are:
1. **QuickSort**: `quickSort([6,10,5,1,9,8,7,2,3,4])`
2. **MergeSort**: `mergeSort([6,10,5,1,9,8,7,2,3,4])`.
Upon inspection, both algorithms sort the array correctly, however, the sorting times vary significantly.
The i... | import random
def quickSort(arr):
if len(arr) <= 1:
return arr
pivot = random.choice(arr)
less = [x for x in arr if x < pivot]
equal = [x for x in arr if x == pivot]
greater = [x for x in arr if x > pivot]
return quickSort(less) + equal + quickSort(greater)
def mergeSort(arr):
if l... | from solution import quickSort, mergeSort
def test_quickSort():
array = [6, 10, 5, 1, 9, 8, 7, 2, 3, 4]
sorted_array = quickSort(array)
assert sorted_array == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def test_mergeSort():
array = [6, 10, 5, 1, 9, 8, 7, 2, 3, 4]
sorted_array = mergeSort(array)
asser... | [
{
"docstring": null,
"function_declaration": "def quickSort(arr):",
"function_name": "quickSort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def mergeSort(arr):",
"function_name": "mergeSort",
"parameter_list": "(arr)"
},
{
"docstring": nul... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quickSort(arr):\n \"\"\"\n QuickSort: Sorts an array using the QuickSort algorithm.\n \"\"\"\n import random\n \n if len(arr) <= 1:\n return arr\n pivot = rando... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023739",
"row_id": 23739,
"seed_ids": "['Llama-3.3-70B-Instruct_59156']"
} | 0.41152 | Filter_23739 | I | [
"quickSort",
"mergeSort",
"merge"
] | 3 | [
[
"mergeSort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c156949f2ecb38079adef73eb880db3059958eb2 | 809a4391bdad80edb214e0dab06668eb26afd427 | |||
v1.0 | instruct | Filter | Filter_23758_I | So I have a big list of programming languages, and each language has languages it can be compiled to or translated to. For example:
Language A can compile to Language B, Language C and Language D.
Language B can compile to Language D and Language E.
Language C can compile to Language E and Language F.
I want to write... | def compile_to(language, target, visited, compilation_data):
if language == target:
return True
if language in visited:
return False
visited.add(language)
for compilable_language in compilation_data.get(language, []):
if compile_to(compilable_language, target, visited, compilatio... | from solution import can_compile_to
def test_direct_compilation():
compilation_data = {
"Language A": ["Language F"],
"Language F": []
}
assert can_compile_to("Language A", "Language F", compilation_data) == True
def test_indirect_compilation():
compilation_data = {
"Language A... | [
{
"docstring": null,
"function_declaration": "def compile_to(language, target, visited, compilation_data):",
"function_name": "compile_to",
"parameter_list": "(language, target, visited, compilation_data)"
},
{
"docstring": null,
"function_declaration": "def can_compile_to(language, targ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compile_to(language, target, visited, compilation_data):\n \"\"\"\n Recursively checks if the target language can be compiled from the given language using DFS.\n \n :param lan... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023758",
"row_id": 23758,
"seed_ids": "['Llama-3.3-70B-Instruct_59202']"
} | 0.452176 | Filter_23758 | I | [
"compile_to",
"can_compile_to"
] | 2 | [
[
"can_compile_to",
"compile_to"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c00589a95fd025770f495e805e76778c46ef25b | 3048ead35e344945cd1422db1651548dd2b78187 | |||
v1.0 | instruct | Filter | Filter_23792_I | I can make a simple linear regression model in Python using the scikit-learn library. If I want to create a linear regression model from scratch without using a machine learning library, what steps would I need to take? | def mean(values):
return sum(values) / len(values)
def compute_coefficients(X, y):
x_mean = mean(X)
y_mean = mean(y)
numerator = sum((X[i] - x_mean) * (y[i] - y_mean) for i in range(len(X)))
denominator = sum((X[i] - x_mean) ** 2 for i in range(len(X)))
b1 = numerator / denominator
... | from solution import mean, compute_coefficients, predict, simple_linear_regression
def test_mean():
assert mean([1, 2, 3, 4, 5]) == 3
assert mean([10, 20, 30, 40, 50]) == 30
def test_compute_coefficients():
X = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
b0, b1 = compute_coefficients(X, y)
assert rou... | [
{
"docstring": null,
"function_declaration": "def mean(values):",
"function_name": "mean",
"parameter_list": "(values)"
},
{
"docstring": null,
"function_declaration": "def compute_coefficients(X, y):",
"function_name": "compute_coefficients",
"parameter_list": "(X, y)"
},
{
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def mean(values):\n \"\"\"\n Calculates the mean of a list of numbers.\n \"\"\"\n return sum(values) / len(values)\n\ndef calculate_coefficients(X, Y):\n \"\"\"\n Calculates ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023792",
"row_id": 23792,
"seed_ids": "['Llama-3.3-70B-Instruct_59282']"
} | 0.537016 | Filter_23792 | I | [
"mean",
"compute_coefficients",
"predict",
"simple_linear_regression"
] | 4 | [
[
"compute_coefficients",
"mean"
],
[
"simple_linear_regression",
"compute_coefficients"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 730885a4acaf2ebad1aa5ff62375d232adb09691 | 7422d23d75e4f8a21122928cdd1458972e464fd8 | |||
v1.0 | instruct | Filter | Filter_23795_I | ### Training Network for Low-Light Image Enhancement
Train a network to enhance low-light images. We will provide a paired dataset of (low-light image, normal-light image). Design a loss function, model architecture, and training strategy to solve the task. | import torch
import torch.nn as nn
class EnhancerCNN(nn.Module):
def __init__(self):
super(EnhancerCNN, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=3, stride=1, pad... | from solution import EnhancerCNN, loss_fn, structural_similarity_index_measure
import torch
def test_enhancer_model_output_size():
model = EnhancerCNN()
input_image = torch.randn(1, 3, 64, 64) # batch_size=1, channels=3, height=64, width=64
output_image = model(input_image)
assert output_image.shape =... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\n\nclass EnhancerCNN(nn.Module):\n def __init__(self):\n super(EnhancerCNN, self).__init__()\n self.encoder = nn.Sequential(\n n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023795",
"row_id": 23795,
"seed_ids": "['Llama-3.3-70B-Instruct_59289']"
} | 0.293784 | Filter_23795 | I | [
"loss_fn",
"structural_similarity_index_measure",
"train_model",
"create_dataloader"
] | 4 | [
[
"loss_fn",
"structural_similarity_index_measure"
],
[
"train_model",
"loss_fn"
]
] | 2 | [] | false | [
"EnhancerCNN"
] | true | pytest | true | [
"torch"
] | false | 8b1aa39e7488b8fc28e40265e75cd0855c98e1c2 | 12ac533b0a95e4b225c67bf37af6bf908418a860 | |||
v1.0 | instruct | Filter | Filter_23803_I | I want to generate a random word from a wordlist, and then, working backwards from that word, generate another word by changing one letter at a time, with each new word being a valid english word.
This can be helpful for word games, such as word chain or word ladder.
Here's an example:
Starting word: HOUSE
1. HOUSE ... | import random
from collections import deque
from typing import List
def get_word_list() -> List[str]:
"""
Returns a list of valid English words.
"""
# In an actual usage scenario, this function might load words from a dictionary file.
# Here, we mock it for simplicity.
return ["house", "mouse",... | from solution import get_word_list, is_valid_word, get_adjacent_words, generate_word_path, random_word_path
def test_get_word_list():
word_list = get_word_list()
assert "house" in word_list
assert "moose" in word_list
def test_is_valid_word():
word_list = get_word_list()
assert is_valid_word("hous... | [
{
"docstring": "Returns a list of valid English words.",
"function_declaration": "def get_word_list():",
"function_name": "get_word_list",
"parameter_list": "()"
},
{
"docstring": "Checks if a word is in the provided word list.",
"function_declaration": "def is_valid_word(word, word_list... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom collections import deque\n\n# Assuming we have a word list\nword_list = [\"house\", \"mouse\", \"mousse\", \"moose\", \"loose\", \"lose\", \"hose\", \"mose\", \"most\", \"l... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023803",
"row_id": 23803,
"seed_ids": "['Llama-3.3-70B-Instruct_59306']"
} | 0.652688 | Filter_23803 | I | [
"get_word_list",
"is_valid_word",
"get_adjacent_words",
"generate_word_path",
"random_word_path"
] | 5 | [
[
"generate_word_path",
"get_adjacent_words"
],
[
"generate_word_path",
"is_valid_word"
],
[
"get_adjacent_words",
"is_valid_word"
],
[
"random_word_path",
"generate_word_path"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 2100648681292f45942c97205d9c1efec7b07938 | 2d36d06bba55662972548d852177450a6d054a48 | |||
v1.0 | instruct | Filter | Filter_23806_I | ### Creating a Recommendation System Using Collaborative Filtering
#### Introduction
Recommendation systems with collaborative filtering are widely used in various applications, such as product recommendation, music recommendation, and movie recommendation. The idea behind collaborative filtering is to find similarity ... | import numpy as np
import pandas as pd
def pearson_correlation(user1, user2):
"""
Calculate the Pearson correlation coefficient between two users.
"""
common_ratings = {item: [user1[item], user2[item]] for item in user1 if item in user2}
if len(common_ratings) == 0:
return 0
user1_rati... | from solution import user_based_collaborative_filtering
def test_user_based_collaborative_filtering():
user_movie_ratings = {
1: {101: 4.0, 102: 2.0, 103: 5.0},
2: {101: 3.5, 102: 4.0, 105: 1.5},
3: {103: 4.5, 104: 3.0, 105: 2.0},
}
predictions = user_based_collaborative_filtering(... | [
{
"docstring": "Calculate the Pearson correlation coefficient between two users.",
"function_declaration": "def pearson_correlation(user1, user2):",
"function_name": "pearson_correlation",
"parameter_list": "(user1, user2)"
},
{
"docstring": "Get top N similar users for a given user based on... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef pearson_correlation(user_ratings_1, user_ratings_2):\n \"\"\"\n Returns the Pearson correlation coefficient between two users' ratings.\n \"\"\"\n common_... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023806",
"row_id": 23806,
"seed_ids": "['Llama-3.3-70B-Instruct_59314']"
} | 0.62168 | Filter_23806 | I | [
"pearson_correlation",
"get_top_n_similar_users",
"predict_rating",
"user_based_collaborative_filtering"
] | 4 | [
[
"get_top_n_similar_users",
"pearson_correlation"
],
[
"predict_rating",
"get_top_n_similar_users"
],
[
"predict_rating",
"pearson_correlation"
],
[
"user_based_collaborative_filtering",
"predict_rating"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 615bcbb0af180f23551e407fa9b45a1063cfa1e7 | 79375a209ea1924a099bbd7e7540395d175c0bcc | |||
v1.0 | instruct | Filter | Filter_23818_I | Here is the list of Python code lines that you need to follow to create the mergesort algorithm.
1. Oh no, there are no steps, I made a mistake!
2. Sort the list by recursively splitting the array into two halves until you can no longer split the array and then merge the halves to create the sorted list.
3. Here is e... | def mergesort(arr):
"""
Sorts an array of integers using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
middle = len(arr) // 2
left = mergesort(arr[:middle])
right = mergesort(arr[middle:])
return merge(left, right)
def merge(left, right):
"""
Merges two so... | from solution import mergesort
def test_mergesort_sorted_list():
assert mergesort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_mergesort_reverse_sorted_list():
assert mergesort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_mergesort_unsorted_list():
assert mergesort([3, 5, 1, 4, 2]) == [1, 2, 3, 4, 5]
de... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.",
"function_declaration": "def mergesort(arr):",
"function_name": "mergesort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"function_declaration": "def merge(l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def mergesort(arr):\n \"\"\"\n Sort the list using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n middle = len(arr) // 2\n left = mergesort(arr[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023818",
"row_id": 23818,
"seed_ids": "['Llama-3.3-70B-Instruct_59346']"
} | 0.62816 | Filter_23818 | I | [
"mergesort",
"merge"
] | 2 | [
[
"mergesort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd5303d4d24a1d8f3e0207afbed25a8813f7cbe0 | ac3f738a92950d61418caeb02eb479ebfd772e0d | |||
v1.0 | instruct | Filter | Filter_23839_I | Here is the code to create CSV files:
```python
import csv
from datetime import datetime
def write_to_csv(filename: str, writer: csv.writer):
for row in [{ 'name': 'John', 'age': 25 }, { 'name': 'Jane', 'age': 30 }]:
writer.writerow([row['name'], row['age'], datetime.now()])
def create_csv_file(filename: ... | import csv
from datetime import datetime
def write_to_csv(writer: csv.writer):
"""
Writes predefined rows of data to the provided CSV writer object.
"""
rows = [
{ 'name': 'John', 'age': 25 },
{ 'name': 'Jane', 'age': 30 }
]
for row in rows:
writer.writerow([row['name'],... | import csv
import os
from solution import create_csv_file
def test_create_csv_file():
filename = 'test.csv'
create_csv_file(filename)
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile)
rows = list(reader)
assert rows[0] == ['Name', 'Age', 'Created... | [
{
"docstring": "Writes predefined rows of data to the provided CSV writer object.",
"function_declaration": "def write_to_csv(writer):",
"function_name": "write_to_csv",
"parameter_list": "(writer)"
},
{
"docstring": "Creates a CSV file with the specified filename, adds headers, \nand writes... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nfrom datetime import datetime\n\ndef write_to_csv(filename: str, writer: csv.writer):\n \"\"\"\n Writes predefined rows to the provided csv.writer object.\n \n Args:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023839",
"row_id": 23839,
"seed_ids": "['Llama-3.3-70B-Instruct_59385']"
} | 0.702862 | Filter_23839 | I | [
"write_to_csv",
"create_csv_file"
] | 2 | [
[
"create_csv_file",
"write_to_csv"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50865b309b9c957e8654c3fc48de709c7f4b8992 | b2ae638e4c416a42c93b9795b172e25cae4227d8 | |||
v1.0 | instruct | Filter | Filter_23841_I | Given a binary search tree, write a function in Python that determines whether or not the tree is balanced.
A binary tree is balanced if the absolute difference between the height of the left subtree and the height of the right subtree is not greater than 1 for all nodes in the tree.
Here is a Python solution that I ... | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def check_height_balanced(node):
if node is None:
return 0, True
left_height, left_balanced = check_height_balanced(node.left)
right_height, right_balanced = check_heigh... | def test_is_balanced_empty_tree():
assert is_balanced(None) == True
def test_is_balanced_single_node():
root = TreeNode(1)
assert is_balanced(root) == True
def test_is_balanced_balanced_tree():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef is_balanced_helper(node):\n if node is None:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023841",
"row_id": 23841,
"seed_ids": "['Llama-3.3-70B-Instruct_59390']"
} | 0.785065 | Filter_23841 | I | [
"check_height_balanced",
"is_balanced"
] | 2 | [
[
"is_balanced",
"check_height_balanced"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | ae45d00b64e536f8d9ba2b21315ebc220a2aea1c | 621a7055d7f8995499115dc466b664485d7bcf26 | |||
v1.0 | instruct | Filter | Filter_23849_I | I have a square matrix of size (5,5) representing a room and a list of words to be placed horizontally, vertically, or diagonally. I need to place the words in the room in an efficient way such that no word overlaps with any other word (i.e., two words should not share the same cell).
Here is an example of the room rep... | import numpy as np
import random
def can_place_word(board, word, row, col, direction):
"""
Checks if a word can be placed on the board at the given starting position (row, col) in the specified direction.
direction can be 'H' for horizontal, 'V' for vertical, or 'D' for diagonal.
"""
word_len = len... | from solution import can_place_word, place_word, place_words
import numpy as np
def test_can_place_word_horizontal():
board = np.full((5, 5), '_')
assert can_place_word(board, "TABLE", 0, 0, 'H') == True
board[0][1] = 'X'
assert can_place_word(board, "TABLE", 0, 0, 'H') == False
def test_can_place_wor... | [
{
"docstring": "Checks if a word can be placed on the board at the given starting position (row, col) in the specified direction.\ndirection can be 'H' for horizontal, 'V' for vertical, or 'D' for diagonal.",
"function_declaration": "def can_place_word(board, word, row, col, direction):",
"function_name... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport random\n\ndef can_place_word(room, word, start_row, start_col, direction):\n rows, cols = room.shape\n if direction == 'H':\n if start_col + len(word) >... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023849",
"row_id": 23849,
"seed_ids": "['Llama-3.3-70B-Instruct_59418']"
} | 0.521449 | Filter_23849 | I | [
"can_place_word",
"place_word",
"place_words"
] | 3 | [
[
"place_words",
"can_place_word"
],
[
"place_words",
"place_word"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a02e5b812eb2abb7a5976790f5000ca7d16a34d6 | 9a3615b52d87b1e2dac08e25628d857d13822d55 | |||
v1.0 | instruct | Filter | Filter_23859_I | I need help in making a fast, reliable, and efficient algorithm to merge two balanced binary search trees. | class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder_traversal(root, res):
if root:
inorder_traversal(root.left, res)
res.append(root.key)
inorder_traversal(root.right, res)
def sorted_array_to_bst(arr, start, end):
... | from solution import Node, merge_trees, inorder_traversal
def test_merge_trees():
# Create first tree
root1 = Node(3)
root1.left = Node(1)
root1.right = Node(5)
# Create second tree
root2 = Node(4)
root2.left = Node(2)
root2.right = Node(6)
# Merge trees
merged_root = ... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n\ndef inorder_traversal(root, arr):\n \"\"\"\n Helper function... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023859",
"row_id": 23859,
"seed_ids": "['Llama-3.3-70B-Instruct_59440']"
} | 0.50384 | Filter_23859 | I | [
"inorder_traversal",
"sorted_array_to_bst",
"merge_arrays",
"merge_trees"
] | 4 | [
[
"merge_trees",
"inorder_traversal"
],
[
"merge_trees",
"merge_arrays"
],
[
"merge_trees",
"sorted_array_to_bst"
]
] | 3 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 3b8f80eb73157a67e759bc9ca26d1a7ca3d6452b | c6adff076d4067f1a354f7ad77ba636d57c1e246 | |||
v1.0 | instruct | Filter | Filter_23897_I | You can move in a grid in four directions: up, down, left and right. However, there is a constraint that if you move up, you cannot move right, and if you move down, you cannot move left. For example, if you move up from position (x, y) to (x, y+1), you cannot move right from (x, y+1) to (x+1, y+1), but you can move do... | from collections import deque
def is_valid_move(x, y, prev_move):
"""
Checks if a move is valid based on the previous move.
"""
if prev_move == "UP" and y == 1:
return False
if prev_move == "DOWN" and y == -1:
return False
if prev_move == "LEFT" and x == 1:
return False
... | from solution import shortest_path
def test_simple_path():
assert shortest_path((0, 0), (0, 0)) == 0
def test_move_up():
assert shortest_path((0, 0), (0, 1)) == 1
def test_move_down():
assert shortest_path((0, 1), (0, 0)) == 1
def test_move_left():
assert shortest_path((1, 0), (0, 0)) == 1
def test... | [
{
"docstring": "Checks if a move is valid based on the previous move.",
"function_declaration": "def is_valid_move(x, y, prev_move):",
"function_name": "is_valid_move",
"parameter_list": "(x, y, prev_move)"
},
{
"docstring": "Generates all valid moves from the current position based on the p... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_valid_move(x, y, prev_move):\n \"\"\"\n Checks if a move is valid based on the previous move.\n \"\"\"\n if prev_move == \"UP\" and y == 1:\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023897",
"row_id": 23897,
"seed_ids": "['Llama-3.3-70B-Instruct_59520']"
} | 0.625293 | Filter_23897 | I | [
"is_valid_move",
"valid_moves",
"shortest_path"
] | 3 | [
[
"shortest_path",
"valid_moves"
],
[
"valid_moves",
"is_valid_move"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a034a6fed846e6ecb9f035ac5279a70c461e61cd | 459cebb96af674772262ace56e9d9040cbd78b8d | |||
v1.0 | instruct | Filter | Filter_23921_I | Here's a Python code:
```python
def factorial(n):
"""Calculates the factorial of a given integer n."""
if n < 0:
raise ValueError("Factorial of negative number does not exist")
if n == 0:
return 1
result = 1
for i in range(1, n + 1):
result *= i
return result
```
How can ... | import json
def factorial(n):
"""Calculates the factorial of a given integer n."""
if n < 0:
raise ValueError("Factorial of negative number does not exist")
if n == 0:
return 1
result = 1
for i in range(1, n + 1):
result *= i
return result
def to_json(n):
"""Convert... | import pytest
from solution import factorial, to_json, from_json
def test_factorial_positive():
assert factorial(5) == 120
assert factorial(6) == 720
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_negative():
with pytest.raises(ValueError):
factorial(-1)
def test_to_j... | [
{
"docstring": "Calculates the factorial of a given integer n.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Converts the factorial result of n to a JSON string.",
"function_declaration": "def to_json(n):",
"fu... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef factorial(n):\n \"\"\"Calculates the factorial of a given integer n.\"\"\"\n if n < 0:\n raise ValueError(\"Factorial of negative number does not exist\")\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023921",
"row_id": 23921,
"seed_ids": "['Llama-3.3-70B-Instruct_59585']"
} | 0.520171 | Filter_23921 | I | [
"factorial",
"to_json",
"from_json"
] | 3 | [
[
"from_json",
"factorial"
],
[
"to_json",
"factorial"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0df8f4bceb37987b8f6ee8164e0c058ae14669ec | 603cb2fdb497b23a93b6c55b7d20c27a547a57cc | |||
v1.0 | instruct | Filter | Filter_23933_I | I want to build an application with Python and Flask that have random generated password sent to the user once they successfully registered.
I have one important condition, I do not want to store the password in my database.
How can I achieve this?
The best answer would be in the form:
**Step 1...**
**Step 2...**... | from flask import Flask, request, jsonify
import secrets
import string
# Initialize Flask application
app = Flask(__name__)
# Step 1: Function to generate a password
def generate_password(length=12):
alphabet = string.ascii_letters + string.digits + string.punctuation
while True:
password = ''.join(se... | import pytest
from solution import app, generate_password, users_db
# Function to generate a mock client for testing
@pytest.fixture
def client():
with app.test_client() as client:
yield client
# Test case for password generation
def test_generate_password():
password = generate_password()
assert ... | [
{
"docstring": null,
"function_declaration": "def generate_password(length=12):",
"function_name": "generate_password",
"parameter_list": "(length=12)"
},
{
"docstring": null,
"function_declaration": "def register():",
"function_name": "register",
"parameter_list": "()"
},
{
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nimport secrets\nimport string\n\n# Initialize Flask application\napp = Flask(__name__)\n\n# Step 1: Function to generate a password\ndef generate_pas... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023933",
"row_id": 23933,
"seed_ids": "['Llama-3.3-70B-Instruct_59623']"
} | 0.548782 | Filter_23933 | I | [
"generate_password",
"register",
"reset_password"
] | 3 | [
[
"register",
"generate_password"
],
[
"reset_password",
"generate_password"
]
] | 2 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 47968c62746a840dc29bb3040dd45b0f79f27746 | e055e2ff006196a3d66dfeccd6e227224915a725 | |||
v1.0 | instruct | Filter | Filter_23965_I | I have the following code:
```python
import os
import datetime
import time
def get_time():
return datetime.datetime.now().strftime('%A %B %d, %Y - %I:%M:%S %p')
def get_file_permissions(path):
permissions = []
if os.access(path, os.F_OK):
if os.access(path, os.R_OK):
permissions.appen... | import os
import datetime
import time
def get_time():
"""
Returns the current date and time as a formatted string.
"""
return datetime.datetime.now().strftime('%A %B %d, %Y - %I:%M:%S %p')
def get_file_permissions(path):
"""
Returns the file permissions as a string ('r', 'w', 'x').
"""
... | import pytest
from solution import get_time, get_file_permissions, file_details, is_valid_file_path
def test_get_time():
assert isinstance(get_time(), str)
def test_get_file_permissions(tmp_path):
file_path = tmp_path / "testfile.txt"
file_path.write_text("Sample text")
os.chmod(file_path, 0o444)... | [
{
"docstring": "Returns the current date and time as a formatted string.",
"function_declaration": "def get_time():",
"function_name": "get_time",
"parameter_list": "()"
},
{
"docstring": "Returns the file permissions as a string ('r', 'w', 'x').",
"function_declaration": "def get_file_p... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport datetime\n\ndef get_time():\n \"\"\"\n Returns the current time formatted as 'DayOfWeek Month Day, Year - HH:MM:SS AM/PM'\n \"\"\"\n return datetime.datetime.now(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023965",
"row_id": 23965,
"seed_ids": "['Llama-3.3-70B-Instruct_59730']"
} | 0.593689 | Filter_23965 | I | [
"get_time",
"get_file_permissions",
"file_details",
"is_valid_file_path",
"main"
] | 5 | [
[
"file_details",
"get_file_permissions"
],
[
"file_details",
"get_time"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a68488ee219e9d2f97950a601992c67effa8cace | bb18e69d860709457adcf913c27d5c53a819997d | |||
v1.0 | instruct | Filter | Filter_23967_I | I wrote a Python program to calculate "h-index" for given a list of citations which works fine. However when it comes to finding the h-index for a specific author among a multitude of authors I am stuck.
Suppose there are n authors and each author has n papers with x,y,z citations. My plan was to create n separate arr... | def calculate_h_index(citations):
"""
Returns the h-index for the given list of citations.
"""
citations.sort(reverse=True)
h_index = 0
for i, citation in enumerate(citations):
if citation >= i + 1:
h_index = i + 1
else:
break
return h_index
def autho... | import pytest
from solution import calculate_h_index, author_h_indices
def test_calculate_h_index():
assert calculate_h_index([3, 0, 6, 1, 5]) == 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([1, 1, 1, 1, 1]) == 1
assert c... | [
{
"docstring": "Returns the h-index for the given list of citations.",
"function_declaration": "def calculate_h_index(citations):",
"function_name": "calculate_h_index",
"parameter_list": "(citations)"
},
{
"docstring": "Returns a dictionary with the h-index for each author.",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_h_index(citations):\n \"\"\"\n Calculate the h-index for a given list of citations.\n \"\"\"\n citations.sort(reverse=True)\n h_index = 0\n for i, c in enumerat... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023967",
"row_id": 23967,
"seed_ids": "['Llama-3.3-70B-Instruct_59735']"
} | 0.400116 | Filter_23967 | I | [
"calculate_h_index",
"author_h_indices"
] | 2 | [
[
"author_h_indices",
"calculate_h_index"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dab6383c837e1eadc219742116c38d442726868e | 6694d737bf9b81b9347c9464f02d6a474b9cc8e2 | |||
v1.0 | instruct | Filter | Filter_23980_I | ### Importing Libraries and Defining the Solution Strategy
We'll start by defining our solution strategy and importing all necessary libraries.
Our goal is to write a function that takes an image file as input, processes it, and then generates a blurry version of the image.
To accomplish this, we can leverage the Pyt... | from PIL import Image, ImageFilter
def load_image(image_path):
"""
Load an image file.
Args:
image_path (str): The path to the image file.
Returns:
PIL.Image: The loaded image.
"""
return Image.open(image_path)
def apply_blur(image):
"""
Apply a blur effect to an imag... | import pytest
from PIL import Image
from solution import load_image, apply_blur, save_image, create_blurry_image
def test_load_image(tmp_path):
image_path = tmp_path / "test_image.jpg"
original_image = Image.new("RGB", (10, 10), "white")
original_image.save(image_path)
loaded_image = load_image(im... | [
{
"docstring": "Load an image file.\n\nArgs:\n image_path (str): The path to the image file.\n\nReturns:\n PIL.Image: The loaded image.",
"function_declaration": "def load_image(image_path):",
"function_name": "load_image",
"parameter_list": "(image_path)"
},
{
"docstring": "Apply a bl... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image, ImageFilter\n\ndef load_image(image_path):\n \"\"\"\n Load an image file.\n\n Args:\n image_path (str): The path to the image file.\n\n Returns:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00023980",
"row_id": 23980,
"seed_ids": "['Llama-3.3-70B-Instruct_59764']"
} | 0.77379 | Filter_23980 | I | [
"load_image",
"apply_blur",
"save_image",
"create_blurry_image"
] | 4 | [
[
"create_blurry_image",
"apply_blur"
],
[
"create_blurry_image",
"load_image"
],
[
"create_blurry_image",
"save_image"
]
] | 3 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 310684d0736b696fc9faef34d87854a210f50cf6 | 93b99c54fc45885f18e18633c8597fdd66b5fa21 | |||
v1.0 | instruct | Filter | Filter_23983_I | After TLA+ validation, the user of the PlusCal algorithm needs to validate the system against certain properties and rules defined by the business. For this, they need a user-friendly interface and an analytical lens through which they can analyze the behavior of the system when the rules change. Towards this, you will... | class DiscreteEventSimulator:
def __init__(self):
self.time = 0
self.event_queue = []
self.components = []
def add_component(self, component):
self.components.append(component)
def add_event(self, event, event_time):
self.event_queue.append((event_time, event))
... | from solution import DiscreteEventSimulator, Component
def test_event_execution_order():
events = []
def event_1(simulator):
events.append(('event_1', simulator.time))
def event_2(simulator):
events.append(('event_2', simulator.time))
simulator = DiscreteEventSimulator()
componen... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Event:\n def __init__(self, event_time, priority, function, *args, **kwargs):\n self.event_time = event_time\n self.priority = priority\n self.function = function... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023983",
"row_id": 23983,
"seed_ids": "['Llama-3.3-70B-Instruct_59776']"
} | 0.352237 | Filter_23983 | I | [
"example_event",
"example_usage"
] | 2 | [
[
"example_usage",
"example_event"
]
] | 1 | [] | false | [
"DiscreteEventSimulator",
"Component"
] | true | pytest | true | [] | true | 785853d26ce4c46c31f26a6b06ab57af0c6a8d6e | 19d17e96bd7aeee8e49ff1f43f80d23a33a18cfe | |||
v1.0 | instruct | Filter | Filter_23987_I | Can you write code for me to implement the Merge Sort algorithm, and explain the theory behind why and how it works? | def merge_sort(arr):
"""
Sorts an array of numbers using the merge sort algorithm.
Parameters:
arr (list): The list of elements to be sorted.
Returns:
list: A new list that is sorted.
"""
if len(arr) <= 1:
return arr
# Divide the array into halves and s... | def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_array():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_array():
assert merge_sort([5, 4, 3, 2, 1]) =... | [
{
"docstring": "Sorts an array of numbers using the merge sort algorithm.\n\nParameters:\n arr (list): The list of elements to be sorted.\n\nReturns:\n list: A new list that is sorted.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Implements the merge sort algorithm to sort arr.\n \"\"\"\n if len(arr) > 1:\n # Find the middle point to split the array into halves\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00023987",
"row_id": 23987,
"seed_ids": "['Llama-3.3-70B-Instruct_59785']"
} | 0.627978 | Filter_23987 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f9883d688645f39c788790ddc5dfea812179d90a | 7997cb128158499613f18c5da2b810e0400599a7 | |||
v1.0 | instruct | Filter | Filter_23999_I | ### Intermediate Python Project: To-Do List App
**Project Overview**
=====================
Create a command-line To-Do List application that allows users to create, read, update, and delete (CRUD) tasks.
**Requirements**
---------------
1. The application should display a menu with options to create, read, update, ... | import json
import os
TASKS_FILE = 'tasks.json'
def load_tasks():
if not os.path.exists(TASKS_FILE):
return []
with open(TASKS_FILE, 'r') as file:
return json.load(file)
def save_tasks(tasks):
with open(TASKS_FILE, 'w') as file:
json.dump(tasks, file, indent=4)
def create_task(ti... | import pytest
import os
import json
from solution import create_task, read_tasks, update_task, delete_task, TASKS_FILE
def setup_function():
""" Setup test environment """
if os.path.exists(TASKS_FILE):
os.remove(TASKS_FILE)
def teardown_function():
""" Teardown test environment """
if os.path... | [
{
"docstring": null,
"function_declaration": "def load_tasks():",
"function_name": "load_tasks",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def save_tasks(tasks):",
"function_name": "save_tasks",
"parameter_list": "(tasks)"
},
{
"docstring": n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport os\n\nTODO_FILE = 'todo_list.json'\n\ndef load_tasks():\n if not os.path.exists(TODO_FILE):\n return []\n with open(TODO_FILE, 'r') as file:\n return js... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00023999",
"row_id": 23999,
"seed_ids": "['Llama-3.3-70B-Instruct_59803']"
} | 0.567918 | Filter_23999 | I | [
"load_tasks",
"save_tasks",
"create_task",
"read_tasks",
"update_task",
"delete_task"
] | 6 | [
[
"create_task",
"load_tasks"
],
[
"create_task",
"save_tasks"
],
[
"delete_task",
"load_tasks"
],
[
"delete_task",
"save_tasks"
],
[
"read_tasks",
"load_tasks"
],
[
"update_task",
"load_tasks"
],
[
"update_task",
"save_tasks"
]
] | 7 | [] | false | [] | false | pytest | true | [] | true | 00c34ee215433c924a28378ddacd041f33931912 | 4adf0c5e59d8d01077bb8ed8f0a89de88e47025b | |||
v1.0 | instruct | Filter | Filter_24023_I | I have a dictionary that I am using as a collection of key-value pairs where the values are lists. I am using it to keep track of the (unique) friends of different people. For example:
```python
friends = {
'Alice': ['Bob', 'Charlie', 'Dave'],
'Bob': ['Alice', 'Charlie', 'Eve'],
'Charlie': ['Alice', 'Bob', ... | def are_mutual_friends(friends, person1, person2):
"""
Returns True if person1 and person2 are mutual friends, False otherwise.
"""
return person1 in friends[person2] and person2 in friends[person1]
def are_all_mutual_friends(friends, people):
"""
Returns True if everyone in the list `people` a... | def test_are_mutual_friends():
friends = {
'Alice': ['Bob', 'Charlie', 'Dave'],
'Bob': ['Alice', 'Charlie', 'Eve'],
'Charlie': ['Alice', 'Bob', 'Dave'],
'Dave': ['Alice', 'Charlie', 'Frank'],
'Eve': ['Bob'],
'Frank': ['Dave']
}
assert are_mutual_friends(friend... | [
{
"docstring": "Returns True if person1 and person2 are mutual friends, False otherwise.",
"function_declaration": "def are_mutual_friends(friends, person1, person2):",
"function_name": "are_mutual_friends",
"parameter_list": "(friends, person1, person2)"
},
{
"docstring": "Returns True if e... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def are_mutual_friends(friends, person1, person2):\n \"\"\"\n Determines whether person1 and person2 are mutual friends.\n \n Args:\n - friends (dict): A dictionary of people an... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024023",
"row_id": 24023,
"seed_ids": "['Llama-3.3-70B-Instruct_59856']"
} | 0.577139 | Filter_24023 | I | [
"are_mutual_friends",
"are_all_mutual_friends"
] | 2 | [
[
"are_all_mutual_friends",
"are_mutual_friends"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 17efcc92929457f4078374405eda1a5aad0fd531 | 719aa1b1308e2f129e6239c22ca3dca18df48dbd | |||
v1.0 | instruct | Filter | Filter_24024_I | I am completing a university course in Computer Science. The course that I am currently enrolled in is called "Data Structures and Algorithms" and I am using the textbook "Data Structures and Algorithms in Python" by Michael T. Goodrich, Roberto Tamassia and Michael H. Goldwasser.
To complete an assessment task, I ne... | class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def delete_node(root, key):
"""
Deletes a node with a specified key from the BST and returns the new root.
"""
if root is None:
return root
if key < root.key:
root... | from solution import TreeNode, delete_node, min_value_node
def tree_to_list(root):
""" Helper function to convert BST to list using inorder traversal """
if root is None:
return []
return tree_to_list(root.left) + [root.key] + tree_to_list(root.right)
def test_delete_leaf_node():
root = TreeNo... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n\ndef delete_node(root, key):\n \"\"\"\n Deletes a node with t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024024",
"row_id": 24024,
"seed_ids": "['Llama-3.3-70B-Instruct_59858']"
} | 0.470297 | Filter_24024 | I | [
"delete_node",
"min_value_node"
] | 2 | [
[
"delete_node",
"min_value_node"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | b4d551b335b038451feffa78973c835942cea93d | 3e67258b1e33fe45e40cebb9cd5f128a34ac9db8 | |||
v1.0 | instruct | Filter | Filter_24043_I | Can you create a Python script that implements the below:
1. Create a dictionary to hold the salary information for each employee.
2. Add employees and their salary information to the dictionary.
3. Allow the user to add, view, or delete employees from the dictionary.
4. Validate user input to ensure that the emplo... | def validate_name(name):
"""
Validates that the name is not empty.
"""
return bool(name.strip())
def validate_salary(salary):
"""
Validates that the salary is a positive number.
"""
try:
salary = float(salary)
return salary > 0
except ValueError:
return False... | import pytest
from solution import validate_name, validate_salary, add_employee, view_employee, delete_employee
def test_validate_name():
assert validate_name("John Doe") == True
assert validate_name(" ") == False
assert validate_name("") == False
def test_validate_salary():
assert validate_salary("50... | [
{
"docstring": "Validates that the name is not empty.",
"function_declaration": "def validate_name(name):",
"function_name": "validate_name",
"parameter_list": "(name)"
},
{
"docstring": "Validates that the salary is a positive number.",
"function_declaration": "def validate_salary(salar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class EmployeeManager:\n def __init__(self):\n self.employees = {\n 'John Doe': 50000,\n 'Jane Doe': 60000,\n 'Bob Smith': 70000\n }\n\n de... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024043",
"row_id": 24043,
"seed_ids": "['Llama-3.3-70B-Instruct_59901']"
} | 0.485308 | Filter_24043 | I | [
"validate_name",
"validate_salary",
"add_employee",
"view_employee",
"delete_employee"
] | 5 | [
[
"add_employee",
"validate_name"
],
[
"add_employee",
"validate_salary"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1af9422a4345fec097c7e1805ec2f703a27820f9 | c8f24db423cc2fabd00a6d817ca63ad2fc93ff4a | |||
v1.0 | instruct | Filter | Filter_24052_I | The rand7() API is pre-installed in your environment and returns a random integer in the range [1, 7] (inclusive). How would you use this API to generate a function rand10() that returns a random integer in the range [1, 10] (inclusive)? | import random
def rand7():
return random.randint(1, 7)
def rand10():
"""
Generates a random integer from 1 to 10 using rand7().
"""
while True:
# Generate a number in the range 1 to 49
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1 | from solution import rand10
def test_rand10_range():
for _ in range(1000):
result = rand10()
assert 1 <= result <= 10
def test_rand10_uniform_distribution():
results = [0] * 10
num_trials = 100000
for _ in range(num_trials):
result = rand10()
results[result - 1] +=... | [
{
"docstring": null,
"function_declaration": "def rand7():",
"function_name": "rand7",
"parameter_list": "()"
},
{
"docstring": "Generates a random integer from 1 to 10 using rand7().",
"function_declaration": "def rand10():",
"function_name": "rand10",
"parameter_list": "()"
}... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random \n\ndef rand7():\n return random.randint(1, 7)\n\ndef rand10():\n \"\"\"\n Generates a random integer in the range [1, 10] using the rand7() function.\n \"\"\"\n w... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024052",
"row_id": 24052,
"seed_ids": "['Llama-3.3-70B-Instruct_59923']"
} | 0.516564 | Filter_24052 | I | [
"rand7",
"rand10"
] | 2 | [
[
"rand10",
"rand7"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ff8ce130fa57de80596112185cdb1ef5cd31176a | e2379e2e23b4f6b7e77b78379954ddc91c953873 | |||
v1.0 | instruct | Filter | Filter_24064_I | Create a 3D Fractal Animation using Python and Matplotlib.
**Note:** You'll need to use NumPy to handle 3D coordinates.
First, let's create a simple 3D Sierpinski Tetrahedron using iteration.
Here is some sample data for points:
```python
points = [
[0, 0, 0],
[1, 0, 0],
[0.5, np.sqrt(3)/2, 0],
[0.5,... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
def midpoint(p1, p2):
"""
Returns the midpoint between two 3D points p1 and p2.
"""
return [(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2, (p1[2] + p2[2]) / 2]
def sierp... | from solution import midpoint, sierpinski_tetrahedron
import numpy as np
def test_midpoint():
p1 = [0, 0, 0]
p2 = [1, 1, 1]
assert midpoint(p1, p2) == [0.5, 0.5, 0.5]
def test_midpoint_with_negative_coords():
p1 = [-1, -1, -1]
p2 = [1, 1, 1]
assert midpoint(p1, p2) == [0, 0, 0]
def test_sierp... | [
{
"docstring": "Returns the midpoint between two 3D points p1 and p2.",
"function_declaration": "def midpoint(p1, p2):",
"function_name": "midpoint",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Generates Sierpinski Tetrahedron points for a given number of iterations.",
"function_decl... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport matplotlib.animation as animation\n\ndef sierpinski_tetrahedron(points, n):... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024064",
"row_id": 24064,
"seed_ids": "['Llama-3.3-70B-Instruct_59945']"
} | 0.616742 | Filter_24064 | I | [
"midpoint",
"sierpinski_tetrahedron",
"update"
] | 3 | [
[
"sierpinski_tetrahedron",
"midpoint"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"mpl_toolkits",
"numpy"
] | false | 2821d9005728184dbfed7a2d6fd7b609cb1ef887 | 40fc1d3966c638ef5a8bb7e937ae3d238b549c49 | |||
v1.0 | instruct | Filter | Filter_24073_I | I have a task to generate synthetic Aperture Radar (SAR) images.
My goal is to write a Python function to generate SAR images from simulated terrain data.
When I attempt to simulate the terrain, I know I need the mean and standard deviation of the terrain height.
I want the generated SAR image to look like the real... | import numpy as np
def generate_terrain_model(size, mean_height, std_dev):
"""
Generate a simulated terrain model using a mean height and standard deviation.
Arguments:
size -- tuple of integers (image_height, image_width)
mean_height -- mean terrain height
std_dev -- standard deviation of... | from solution import generate_terrain_model, generate_speckle_noise, add_speckle_noise, generate_sar_image
def test_generate_terrain_model():
size = (512, 512)
mean_height = 100
std_dev = 30
terrain_model = generate_terrain_model(size, mean_height, std_dev)
assert terrain_model.shape == size
as... | [
{
"docstring": "Generate a simulated terrain model using a mean height and standard deviation.\n\nArguments:\nsize -- tuple of integers (image_height, image_width)\nmean_height -- mean terrain height\nstd_dev -- standard deviation of terrain height\n\nReturns:\nterrain_model -- numpy array of size (image_height... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport cv2\n\ndef generate_terrain(image_size, mean_height, std_height):\n \"\"\"\n Generate a synthetic terrain model based on the mean and standard deviation of ter... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024073",
"row_id": 24073,
"seed_ids": "['Llama-3.3-70B-Instruct_59963']"
} | 0.351029 | Filter_24073 | I | [
"generate_terrain_model",
"generate_speckle_noise",
"add_speckle_noise",
"generate_sar_image"
] | 4 | [
[
"generate_sar_image",
"add_speckle_noise"
],
[
"generate_sar_image",
"generate_speckle_noise"
],
[
"generate_sar_image",
"generate_terrain_model"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b28363d6891eebe9eb8039244f42a084319e39fa | 43c4fafa47b1db2068de74109f080a3190022694 | |||
v1.0 | instruct | Filter | Filter_24082_I | In this exercise, you will create a Python program that creates a new WCA (World Cube Association) competition by:
1. Prompting the user to insert the name and location of the new competition
2. Ask user for the start date of the competition in the format dd/mm/yyyy, validates if date is correct and if date is not in t... | import json
from datetime import datetime
def validate_date(date_text):
try:
date = datetime.strptime(date_text, '%d/%m/%Y')
if date < datetime.now():
return False, "Date is in the past"
return True, date
except ValueError:
return False, "Invalid date format, should ... | import pytest
from datetime import datetime
from solution import validate_date, check_existing_event, load_competitions, save_competition
def test_validate_date():
assert validate_date("10/10/2025")[0] == True
assert validate_date("10/10/2020")[0] == False # Past date
assert validate_date("32/10/2025")[0]... | [
{
"docstring": null,
"function_declaration": "def validate_date(date_text):",
"function_name": "validate_date",
"parameter_list": "(date_text)"
},
{
"docstring": null,
"function_declaration": "def load_competitions(file_path):",
"function_name": "load_competitions",
"parameter_li... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport datetime\n\n# Function to validate date format\ndef validate_date_format(date_str):\n try:\n date = datetime.datetime.strptime(date_str, \"%d/%m/%Y\")\n re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024082",
"row_id": 24082,
"seed_ids": "['Llama-3.3-70B-Instruct_59985']"
} | 0.541369 | Filter_24082 | I | [
"validate_date",
"load_competitions",
"save_competition",
"check_existing_event",
"create_competition"
] | 5 | [
[
"create_competition",
"check_existing_event"
],
[
"create_competition",
"load_competitions"
],
[
"create_competition",
"save_competition"
],
[
"create_competition",
"validate_date"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 70793ea05d19ad5f61c8afc921070e8732d9f11e | 56708b8badaf2341325b4b3b7020218ddca2222e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.