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_77799_I | Given two strings `s1` and `s2`, and a number `k`, the task is to find a common subsequence of length `k` in `s1` and `s2`. If no such subsequence exists, return `-1`. A subsequence is defined as a sequence derived from one or both of the strings by deleting some characters without changing the order of the remaining c... | def longest_common_subsequence(s1, s2):
"""
Helper function to determine the longest common subsequence of two strings.
"""
m, n = len(s1), len(s2)
dp = [[""] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
... | from solution import common_subsequence_of_length_k
def test_common_subsequence_of_length_k_found():
assert common_subsequence_of_length_k("abcde", "ace", 2) == "ac"
assert common_subsequence_of_length_k("abcde", "ace", 3) == "ace"
assert common_subsequence_of_length_k("abc", "abc", 3) == "abc"
def test_c... | [
{
"docstring": "Helper function to determine the longest common subsequence of two strings.",
"function_declaration": "def longest_common_subsequence(s1, s2):",
"function_name": "longest_common_subsequence",
"parameter_list": "(s1, s2)"
},
{
"docstring": "Returns a common subsequence of leng... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def common_subsequence_length_k(s1, s2, k):\n \"\"\"\n Finds a common subsequence of length k in s1 and s2.\n If no such subsequence exists, return `-1`.\n \"\"\"\n m, n = len(s... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00077799",
"row_id": 77799,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_157991']"
} | 0.651688 | Filter_77799 | I | [
"longest_common_subsequence",
"common_subsequence_of_length_k"
] | 2 | [
[
"common_subsequence_of_length_k",
"longest_common_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58abb2f8dcc0608b5122d253b7aa5f6ae9d07f2d | cd275f8e5e8c3fc45e3eef94c49b9b2cadb4f1a4 | |||
v1.0 | instruct | Filter | Filter_78092_I | How can I use Python to simulate trading strategies on historical stock data? | import pandas as pd
import numpy as np
def simple_moving_average(data, window):
"""
Calculates the simple moving average for the given window.
"""
return data.rolling(window=window).mean()
def moving_average_crossover_strategy(stock_data, short_window=40, long_window=100):
"""
Simulates a movi... | def test_simple_moving_average():
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
result = simple_moving_average(data, window=3)
expected = pd.Series([np.nan, np.nan, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
pd.testing.assert_series_equal(result, expected)
def test_moving_average_crossover_strategy()... | [
{
"docstring": "Calculates the simple moving average for the given window.",
"function_declaration": "def simple_moving_average(data, window):",
"function_name": "simple_moving_average",
"parameter_list": "(data, window)"
},
{
"docstring": "Simulates a moving average crossover trading strate... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport yfinance as yf\n\ndef get_historical_data(ticker, start_date, end_date):\n \"\"\"\n Fetches historical stock data from Yahoo Finance.\n \n :param ticker... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00078092",
"row_id": 78092,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_158619']"
} | 0.52045 | Filter_78092 | I | [
"simple_moving_average",
"moving_average_crossover_strategy"
] | 2 | [
[
"moving_average_crossover_strategy",
"simple_moving_average"
]
] | 1 | [] | false | [] | false | pytest | false | [
"numpy",
"pandas",
"yfinance"
] | false | ffa6315d99d1fabbf3251bfff11e9ec77ef89887 | 5133af3946eb75fcc28db5f622b0462e8c48c10a | |||
v1.0 | instruct | Filter | Filter_78103_I | Write a Python function to calculate the total width of all characters in a given string based on their Unicode widths. Characters can have different widths, such as full-width, wide, narro, and combining marks, which can affect the total width of the string when displayed in certain terminals or fonts. | import unicodedata
def get_unicode_width(char):
"""
Returns the width of a given unicode character.
"""
if unicodedata.category(char) == "Mn": # Combining mark
return 0
else:
east_asian_width = unicodedata.east_asian_width(char)
if east_asian_width in ('F', 'W'): # Full-wi... | from solution import total_unicode_width
def test_total_unicode_width_empty_string():
assert total_unicode_width('') == 0
def test_total_unicode_width_ascii_string():
assert total_unicode_width('abc') == 3
def test_total_unicode_width_full_width_characters():
assert total_unicode_width('ABC') == 6
def t... | [
{
"docstring": "Returns the width of a given unicode character.",
"function_declaration": "def get_unicode_width(char):",
"function_name": "get_unicode_width",
"parameter_list": "(char)"
},
{
"docstring": "Returns the total width of all characters in the given string based on their Unicode w... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import unicodedata\n\ndef get_unicode_width(char):\n \"\"\"\n Returns the width of a specific character based on Unicode standards.\n \"\"\"\n if unicodedata.east_asian_width(char)... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00078103",
"row_id": 78103,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_158642']"
} | 0.621736 | Filter_78103 | I | [
"get_unicode_width",
"total_unicode_width"
] | 2 | [
[
"total_unicode_width",
"get_unicode_width"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | af865197bf8b5326ffd8dc182dc7c0b88487b78d | a8385241a8e5d2197abc18d8cb13f173fd88a287 | |||
v1.0 | instruct | Filter | Filter_78130_I | I want to create a Python script that monitors changes in a specific directory and triggers a function when a new file is added, modified, or deleted. How can I achieve this? | import time
import os
import hashlib
def get_file_hash(file_path):
"""
Computes the hash of the file specified by file_path.
"""
sha1 = hashlib.sha1()
try:
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
sha1.update(chunk)
return sha1.hexdig... | import os
import tempfile
from solution import monitor_directory, sample_callback
# Mocking the callback for testing purposes
changes_detected = []
def mock_callback(changes):
global changes_detected
changes_detected.append(changes)
def test_monitor_directory_add():
global changes_detected
changes_de... | [
{
"docstring": "Computes the hash of the file specified by file_path.",
"function_declaration": "def get_file_hash(file_path):",
"function_name": "get_file_hash",
"parameter_list": "(file_path)"
},
{
"docstring": "Monitors the specified directory for changes and triggers the callback\nfuncti... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport time\n\ndef monitor_directory(directory, callback):\n \"\"\"\n Monitors the specified directory and triggers the callback function when \n a new file is added, modif... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00078130",
"row_id": 78130,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_158692']"
} | 0.531882 | Filter_78130 | I | [
"get_file_hash",
"monitor_directory",
"sample_callback"
] | 3 | [
[
"monitor_directory",
"get_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0dac40d1a9e30260be9348120836aaa77037f4af | 4ba1bead5f29832a2f891f27ca228bb5a1108076 | |||
v1.0 | instruct | Filter | Filter_78184_I | Can you write a Python function that calculates the digits of pi using the Bailey-Borwein-Plouffe (BBP) formula? The BBP formula allows for the calculation of the nth digit of pi in base 16 (hexadecimal) without needing to calculate the preceding digits. The function should return the hexadecimal representation of the ... | def bbp_pi_digit(n):
"""
Calculate the nth digit of pi using the Bailey-Borwein-Plouffe (BBP) formula.
:param n: The position of the digit to calculate, where n is a non-negative integer.
:return: The nth hexadecimal digit of pi.
"""
n -= 1 # BBP formula is 0-based index
x = (4 * ... | from solution import nth_hex_digit_of_pi
def test_first_hex_digit_of_pi():
assert nth_hex_digit_of_pi(1) == '2'
def test_second_hex_digit_of_pi():
assert nth_hex_digit_of_pi(2) == '4'
def test_third_hex_digit_of_pi():
assert nth_hex_digit_of_pi(3) == '3'
def test_fourth_hex_digit_of_pi():
assert nth... | [
{
"docstring": "Calculate the nth digit of pi using the Bailey-Borwein-Plouffe (BBP) formula.\n\n:param n: The position of the digit to calculate, where n is a non-negative integer.\n:return: The nth hexadecimal digit of pi.",
"function_declaration": "def bbp_pi_digit(n):",
"function_name": "bbp_pi_digi... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def bbp_pi_digit(n):\n \"\"\"\n Returns the nth digit of pi in hexadecimal (base 16) based on the BBP formula.\n \"\"\"\n def S(j, n):\n s = 0.0\n for k in range(n + ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00078184",
"row_id": 78184,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_158809']"
} | 0.478416 | Filter_78184 | I | [
"bbp_pi_digit",
"bbp_sum",
"nth_hex_digit_of_pi"
] | 3 | [
[
"bbp_pi_digit",
"bbp_sum"
],
[
"nth_hex_digit_of_pi",
"bbp_pi_digit"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 72a35bfaa753ebd4ad2768dfb652ec78b72eef79 | a8e84bf1c176873faa437d64f2648284b1c0d9ff | |||
v1.0 | instruct | Filter | Filter_78416_I | Can you explain how the A* algorithm works and provide a simple implementation in Python? | import heapq
def a_star_search(start, goal, neighbors_func, h_func, cost_func):
"""
Performs the A* search algorithm.
Parameters:
start: The starting node.
goal: The goal node.
neighbors_func: Function that returns neighbors of a node.
h_func: Heuristic function estimating ... | from solution import a_star_search, reconstruct_path
def mock_neighbors(node):
neighbors = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
return neighbors.get(node, [])
def mock_h(start, goal):
h_values = {
('A', '... | [
{
"docstring": "Performs the A* search algorithm.\n\nParameters:\n start: The starting node.\n goal: The goal node.\n neighbors_func: Function that returns neighbors of a node.\n h_func: Heuristic function estimating the cost from the node to the goal.\n cost_func: Function that returns the cost ... | [
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.25 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef heuristic(a, b):\n return abs(b[0] - a[0]) + abs(b[1] - a[1])\n\ndef astar(grid, start, goal):\n # The open set with the start node\n open_set = []\n heapq.heap... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00078416",
"row_id": 78416,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_159271']"
} | 0.504247 | Filter_78416 | I | [
"a_star_search",
"reconstruct_path"
] | 2 | [
[
"a_star_search",
"reconstruct_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2499ed19bf0d3b2148250d732dcaaffc8f277302 | aa2f464395a68d3e5b012f463a5cf28aa0b3a02e | |||
v1.0 | instruct | Filter | Filter_78530_I | Design a Python function to find the closest pair of points in a 2D plane using a divide-and-conquer algorithm. The function should be efficient and handle large datasets effectively. | import math
def distance(point1, point2):
"""Calculate the Euclidean distance between two points."""
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def brute_force(points):
"""Find the minimum distance between points using brute force."""
min_dist = float('inf')
n = len(... | import pytest
from solution import closest_pair
def test_closest_pair_simple():
points = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
assert pytest.approx(closest_pair(points), 0.01) == 1.414
def test_closest_pair_single_pair():
points = [(0, 0), (1, 1)]
assert pytest.approx(closest_pair(points), 0.01) ==... | [
{
"docstring": "Calculate the Euclidean distance between two points.",
"function_declaration": "def distance(point1, point2):",
"function_name": "distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the minimum distance between points using brute force.",
"function_dec... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(point1, point2):\n \"\"\"\n Returns the Euclidean distance between two points in 2D space.\n \"\"\"\n return math.sqrt((point1[0] - point2[0])**2 + (poi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00078530",
"row_id": 78530,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_159503']"
} | 0.615613 | Filter_78530 | I | [
"distance",
"brute_force",
"strip_closest",
"closest_pair_util",
"closest_pair"
] | 5 | [
[
"brute_force",
"distance"
],
[
"closest_pair",
"closest_pair_util"
],
[
"closest_pair_util",
"brute_force"
],
[
"closest_pair_util",
"strip_closest"
],
[
"strip_closest",
"distance"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | b404faf3b474d952c41a433a564080caa9124fa0 | 4088f6243dcc0f1b41e2208b3b525bc6e03b6f37 | |||
v1.0 | instruct | Filter | Filter_78540_I | I need to create a Python script that can automatically download images from a list of URLs and save them to a local directory. The script should handle potential errors, such as invalid URLs or network issues, and should log the results for each image attempt. How can I achieve this? | import os
import requests
from urllib.parse import urlparse
def download_image(url, save_dir):
"""
Downloads an image from the specified URL and saves it to the given directory.
Returns True if the image was successfully downloaded and False otherwise.
"""
try:
response = requests.get(url, ... | import os
import shutil
from solution import download_image, download_images
TEST_DIR = "test_images"
def setup_module(module):
"""Setup any state specific to the execution of the given module."""
if os.path.exists(TEST_DIR):
shutil.rmtree(TEST_DIR)
os.makedirs(TEST_DIR)
def teardown_module(modul... | [
{
"docstring": "Downloads an image from the specified URL and saves it to the given directory.\nReturns True if the image was successfully downloaded and False otherwise.",
"function_declaration": "def download_image(url, save_dir):",
"function_name": "download_image",
"parameter_list": "(url, save_... | [
0,
0,
0,
0,
0,
1,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\nfrom urllib.parse import urlparse\n\ndef download_image(url, save_dir):\n try:\n response = requests.get(url, timeout=10) # Added timeout to handle hangi... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00078540",
"row_id": 78540,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_159519']"
} | 0.58239 | Filter_78540 | I | [
"download_image",
"download_images"
] | 2 | [
[
"download_images",
"download_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 35ed4dde6223d8f41b333b55aa07f5478ef271da | a94024d05d5cddf28494e8407119eafe6e7bb7af | |||
v1.0 | instruct | Filter | Filter_78608_I | How can I create a DHCP client in Python that can automatically obtain an IP address from a DHCP server? | import socket
import struct
import random
def get_mac_address():
"""Generate a random MAC address."""
return [random.randint(0x00, 0x7f) for _ in range(6)]
def dhcp_discover():
"""Send a DHCP Discover message and print the DHCP Offer."""
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
cl... | import socket
from unittest.mock import patch, MagicMock
@patch('solution.socket.socket')
def test_dhcp_discover(mock_socket):
mock_client = MagicMock()
mock_socket.return_value = mock_client
mock_client.recvfrom.return_value = (b'\x00' * 1024, ('192.168.1.1', 67))
dhcp_discover()
# ... | [
{
"docstring": "Generate a random MAC address.",
"function_declaration": "def get_mac_address():",
"function_name": "get_mac_address",
"parameter_list": "()"
},
{
"docstring": "Send a DHCP Discover message and print the DHCP Offer.",
"function_declaration": "def dhcp_discover():",
"f... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from pydhcplib.dhcp_packet import DhcpPacket\nfrom pydhcplib.dhcp_network import DhcpClient\n\nclass MyDhcpClient(DhcpClient):\n def __init__(self, listen_address):\n super().__init_... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00078608",
"row_id": 78608,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_159657']"
} | 0.529438 | Filter_78608 | I | [
"get_mac_address",
"dhcp_discover"
] | 2 | [
[
"dhcp_discover",
"get_mac_address"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6ecf9a747ac9d78cbc17acb4ec006e8610531e93 | fbdbd8c1af32a7e77b1e84a471f4ca2b6a4a205a | |||
v1.0 | instruct | Filter | Filter_78804_I | Write a Python script that takes a string input and counts the frequency of each character in the string. The script should then print the character frequencies in a sorted order based on the frequency of the characters, from highest to lowest. If two characters have the same frequency, they should be sorted by their A... | def character_frequency(s):
"""
Takes a string input and counts the frequency of each character.
Returns the character frequencies sorted by frequency and ASCII value.
"""
from collections import Counter
# Count the frequency of each character
freq_dict = Counter(s)
# Sort characte... | from solution import character_frequency, print_character_frequency
def test_character_frequency_no_repeats():
assert character_frequency("abc") == [('a', 1), ('b', 1), ('c', 1)]
def test_character_frequency_mixed():
assert character_frequency("banana") == [('a', 3), ('n', 2), ('b', 1)]
def test_character_fr... | [
{
"docstring": "Takes a string input and counts the frequency of each character.\nReturns the character frequencies sorted by frequency and ASCII value.",
"function_declaration": "def character_frequency(s):",
"function_name": "character_frequency",
"parameter_list": "(s)"
},
{
"docstring": ... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def character_frequency(s):\n \"\"\"\n Takes a string s and returns a list of tuples with the character frequencies in sorted order.\n Sorted first by frequency from highest to lowest... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00078804",
"row_id": 78804,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_160062']"
} | 0.743499 | Filter_78804 | I | [
"character_frequency",
"print_character_frequency"
] | 2 | [
[
"print_character_frequency",
"character_frequency"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8784c5bc832a8520cbc771a5bcc5caa43f948481 | 82b635057d91e41787704370f9b6f7d405bac0d1 | |||
v1.0 | instruct | Filter | Filter_79048_I | If I have a binary matrix of size m x n, how can I print all possible paths that go from the top-left corner to the bottom-right corner? In the matrix, 0 represents an open path and 1 represents an obstacle. You can only move right or down at each step. How can I achieve this? | def is_valid_move(matrix, x, y, m, n):
"""
Check if the next move is valid.
"""
return 0 <= x < m and 0 <= y < n and matrix[x][y] == 0
def find_paths(matrix, x, y, path, paths):
"""
Recursive helper function to find all paths.
"""
m, n = len(matrix), len(matrix[0])
# If reached the ... | from solution import get_all_paths
def test_get_all_paths_no_obstacles():
matrix = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
expected = [
[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)],
[(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)],
[(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)],
... | [
{
"docstring": "Check if the next move is valid.",
"function_declaration": "def is_valid_move(matrix, x, y, m, n):",
"function_name": "is_valid_move",
"parameter_list": "(matrix, x, y, m, n)"
},
{
"docstring": "Recursive helper function to find all paths.",
"function_declaration": "def f... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def print_all_paths(matrix):\n \"\"\"\n Print all possible paths from top-left to bottom-right in a binary matrix.\n 0 represents an open path and 1 represents an obstacle. You can on... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00079048",
"row_id": 79048,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_160594']"
} | 0.65641 | Filter_79048 | I | [
"is_valid_move",
"find_paths",
"get_all_paths"
] | 3 | [
[
"find_paths",
"is_valid_move"
],
[
"get_all_paths",
"find_paths"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6a4b6c9d209cece571ca115fcc55c9e18c32926b | 1f94a38431c1799451d8f2e95ca5b5a6dc50cdbb | |||
v1.0 | instruct | Filter | Filter_79062_I | I need a Python code to simulate a simple yet effective recommendation system for a movie database. Could you provide a collaborative filtering-based recommendation system? | import numpy as np
def cosine_similarity(vector1, vector2):
"""
Compute the cosine similarity between two vectors.
"""
dot_product = np.dot(vector1, vector2)
norm_vector1 = np.linalg.norm(vector1)
norm_vector2 = np.linalg.norm(vector2)
return dot_product / (norm_vector1 * norm_vector2)
def... | import numpy as np
from solution import collaborative_filtering
def test_cosine_similarity_positive_values():
vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])
actual = cosine_similarity(vector1, vector2)
expected = 0.9746318461970762
assert np.isclose(actual, expected, atol=1e-9)
def te... | [
{
"docstring": "Compute the cosine similarity between two vectors.",
"function_declaration": "def cosine_similarity(vector1, vector2):",
"function_name": "cosine_similarity",
"parameter_list": "(vector1, vector2)"
},
{
"docstring": "Recommends top N movies for a user based on collaborative f... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\ndef collaborative_filtering_recommender(user_ratings, user_id, num_recommendations=5):\n \"\"\"\n Recommends movies ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00079062",
"row_id": 79062,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_160619']"
} | 0.34376 | Filter_79062 | I | [
"cosine_similarity",
"collaborative_filtering"
] | 2 | [
[
"collaborative_filtering",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 237c0c492a13e2bf5846fc74778cd174bee9029f | c3ff023f5f43baaec3e8af965954e454de6c7107 | |||
v1.0 | instruct | Filter | Filter_79246_I | Can you provide a Python code that encapsulates the functionality of the given C code snippet for matrix multiplication using OpenMP? The Python code should use multiprocessing or a similar library to achieve parallelism, mimicking the OpenMP approach. | import numpy as np
from multiprocessing import Pool
def matrix_multiply_worker(args):
A, B, i = args
return np.dot(A[i, :], B)
def parallel_matrix_multiply(A, B, num_workers=None):
if A.shape[1] != B.shape[0]:
raise ValueError("Matrices cannot be multiplied, incompatible dimensions")
# Initia... | import numpy as np
from solution import parallel_matrix_multiply
def test_parallel_matrix_multiply_basic():
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
expected = np.array([[19, 22], [43, 50]])
result = parallel_matrix_multiply(A, B)
assert np.array_equal(result, expected)
def te... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply_worker(args):",
"function_name": "matrix_multiply_worker",
"parameter_list": "(args)"
},
{
"docstring": null,
"function_declaration": "def parallel_matrix_multiply(A, B, num_workers=None):",
"function_name": "parallel_... | [
0,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom multiprocessing import Pool\n\ndef matrix_multiply_worker(data):\n A_row, B, row_index = data\n result = []\n for j in range(B.shape[1]):\n sum = 0\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00079246",
"row_id": 79246,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_160993']"
} | 0.43349 | Filter_79246 | I | [
"matrix_multiply_worker",
"parallel_matrix_multiply"
] | 2 | [
[
"parallel_matrix_multiply",
"matrix_multiply_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 11074a0b5684a73cd142fcb489bb81c65227033b | 885d1bdcbcbeb7fb869d4ce9a22f11df2ed361e5 | |||
v1.0 | instruct | Filter | Filter_79277_I | Can you provide a Python code snippet to calculate the collaborative filtering recommendation system for a movie dataset? | import numpy as np
import pandas as pd
def cosine_similarity(matrix):
"""
Calculate the cosine similarity between rows of the input matrix.
"""
norm = np.linalg.norm(matrix, axis=1)
similarity = np.dot(matrix, matrix.T) / (norm[:, None] * norm[None, :])
return np.nan_to_num(similarity)
def pre... | from solution import collaborative_filtering, cosine_similarity, predict_ratings
import numpy as np
import pandas as pd
def test_cosine_similarity():
matrix = np.array([[1, 0], [0, 1]])
expected_similarity = np.array([[1, 0], [0, 1]])
assert np.allclose(cosine_similarity(matrix), expected_similarity)
def ... | [
{
"docstring": "Calculate the cosine similarity between rows of the input matrix.",
"function_declaration": "def cosine_similarity(matrix):",
"function_name": "cosine_similarity",
"parameter_list": "(matrix)"
},
{
"docstring": "Predict the ratings using the similarity matrix.",
"function... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndef collaborative_filtering(ratings_matrix, user_index, top_n=5):\n \"\"\"\n Calculate collaborative filteri... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00079277",
"row_id": 79277,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_161056']"
} | 0.448029 | Filter_79277 | I | [
"cosine_similarity",
"predict_ratings",
"collaborative_filtering"
] | 3 | [
[
"collaborative_filtering",
"cosine_similarity"
],
[
"collaborative_filtering",
"predict_ratings"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 132069d1e6ab8772da6acd35edb6d0903e797681 | 10c52915c2ac5e4ad29eb553254600dd75efaa78 | |||
v1.0 | instruct | Filter | Filter_79369_I | Can you provide a Python function that acts as an HTTP proxy? How can I run this function to handle incoming HTTP requests and forward them to the intended destinations? | import socket
import threading
import sys
BUFFER_SIZE = 8192
def handle_client(client_socket):
request = client_socket.recv(BUFFER_SIZE)
# Parse the first line
first_line = request.split(b'\n')[0]
# Get url
url = first_line.split(b' ')[1]
# Find the webserver and port
http_p... | import pytest
import socket
import threading
from solution import start_proxy_server, handle_client
def mock_server(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
while True:
client_socket, addr = server_so... | [
{
"docstring": null,
"function_declaration": "def handle_client(client_socket):",
"function_name": "handle_client",
"parameter_list": "(client_socket)"
},
{
"docstring": null,
"function_declaration": "def proxy_server(webserver, port, client_socket, client_request):",
"function_name"... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from http.server import BaseHTTPRequestHandler, HTTPServer\nimport requests\n\nclass SimpleHTTPProxy(BaseHTTPRequestHandler):\n def do_GET(self):\n url = self.path[1:] # Get the tar... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00079369",
"row_id": 79369,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_161250']"
} | 0.625208 | Filter_79369 | I | [
"handle_client",
"proxy_server",
"start_proxy_server"
] | 3 | [
[
"handle_client",
"proxy_server"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39d3571d223b4c147d83b1a2203574f3c03fa28d | 1ba66805f3b22e41904c448b843445ec8cac76ca | |||
v1.0 | instruct | Filter | Filter_79398_I | Write a Python script that reads an array of numbers from a file and calculates the mean, median, and mode of the numbers. The file is a text file where each number is on a new line. The script should also handle file reading errors and non-numeric values within the file gracefully. | import statistics
import os
def read_numbers_from_file(filepath):
"""
Reads numbers from a file and returns them as a list.
Each number should be on a new line in the file.
Non-numeric values in the file are ignored.
"""
if not os.path.exists(filepath):
raise FileNotFoundError(f"The fil... | import pytest
from solution import read_numbers_from_file, calculate_mean, calculate_median, calculate_mode, statistics_from_file
def test_read_numbers_from_file(tmp_path):
d = tmp_path / "sub"
d.mkdir()
p = d / "numbers.txt"
p.write_text("1\n2\nthree\n4\n5.0\nsix\n")
assert read_numbers_from_... | [
{
"docstring": "Reads numbers from a file and returns them as a list.\nEach number should be on a new line in the file.\nNon-numeric values in the file are ignored.",
"function_declaration": "def read_numbers_from_file(filepath):",
"function_name": "read_numbers_from_file",
"parameter_list": "(filep... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import statistics\n\ndef read_numbers_from_file(file_path):\n numbers = []\n try:\n with open(file_path, 'r') as file:\n for line in file:\n try:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00079398",
"row_id": 79398,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_161330']"
} | 0.696059 | Filter_79398 | I | [
"read_numbers_from_file",
"calculate_mean",
"calculate_median",
"calculate_mode",
"statistics_from_file"
] | 5 | [
[
"statistics_from_file",
"calculate_mean"
],
[
"statistics_from_file",
"calculate_median"
],
[
"statistics_from_file",
"calculate_mode"
],
[
"statistics_from_file",
"read_numbers_from_file"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 6973f83829f1b563bb3ada660d6bef58eaf117c8 | 72049d389fe5233f5bdea8945b2267c45c950934 | |||
v1.0 | instruct | Filter | Filter_79467_I | Write a Python function `count_prime_pairs(limit)` that counts the number of prime pairs within the range from 1 to `limit` (inclusive). A prime pair is defined as a pair of prime numbers where the second prime number is exactly two more than the first prime number (e.g., (3, 5), (11, 13)). | def is_prime(n):
""" Returns True if n is a prime number, otherwise False. """
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +=... | from solution import count_prime_pairs
def test_count_prime_pairs_below_ten():
assert count_prime_pairs(10) == 2 # (3,5) and (5,7)
def test_count_prime_pairs_zero_limit():
assert count_prime_pairs(0) == 0
def test_count_prime_pairs_limit_two():
assert count_prime_pairs(2) == 0
def test_count_prime_pair... | [
{
"docstring": "Returns True if n is a prime number, otherwise False. ",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Counts the number of prime pairs within the range from 1 to limit (inclusive).\nA prime pair is defined... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_prime_pairs(limit):\n \"\"\"\n Returns the number of prime pairs within the range from 1 to limit (inclusive).\n A prime pair is defined as a pair of prime numbers where the... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00079467",
"row_id": 79467,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_161465']"
} | 0.700775 | Filter_79467 | I | [
"is_prime",
"count_prime_pairs"
] | 2 | [
[
"count_prime_pairs",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eba5ee4e576341f33b9e2cab6ea3c3ad1da12099 | e7c8e080d95f1611e37101686183ba1872affcae | |||
v1.0 | instruct | Filter | Filter_79485_I | I want to create a simple web application using Python and Flask that allows users to upload an image and then process it to detect edges using OpenCV. How can I achieve this? | from flask import Flask, request, redirect, url_for, render_template, send_from_directory
import os
import cv2
import numpy as np
from werkzeug.utils import secure_filename
# Initialize the Flask application
app = Flask(__name__)
# Define a folder to store uploaded images and processed images
UPLOAD_FOLDER = 'uploads... | from solution import allowed_file
def test_allowed_file():
assert allowed_file("test.png") == True
assert allowed_file("test.jpg") == True
assert allowed_file("test.jpeg") == True
assert allowed_file("test.gif") == False
assert allowed_file("test.PNG") == True
assert allowed_file("test.JPG") ==... | [
{
"docstring": "Check if the file has one of the allowed extensions.",
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template, redirect, url_for\nimport cv2\nimport os\nimport numpy as np\nfrom werkzeug.utils import secure_filename\n\napp = Flask(__name__)\napp.config... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00079485",
"row_id": 79485,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_161498']"
} | 0.505719 | Filter_79485 | I | [
"allowed_file",
"index",
"upload_file",
"detect_edges",
"processed_file"
] | 5 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"detect_edges"
]
] | 2 | [] | false | [] | false | pytest | true | [
"cv2",
"flask",
"numpy",
"werkzeug"
] | false | ba77b66485d4f40e068cabc360f05dc20ea6a21b | 657f6318548e784ec80d88b554ae54f0fdcd4d2c | |||
v1.0 | instruct | Filter | Filter_79513_I | Can you provide a detailed explanation of how to create a simple TCP server in Python using the `socket` module? If possible, include a basic client that can connect to this server and send a message. | import socket
def create_tcp_server(host, port):
"""
Creates and returns a TCP server socket bound to the specified host and port.
"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
return server_socket
def handle_... | import threading
import socket
import time
from solution import create_tcp_server, create_tcp_client, handle_client_connection
def test_tcp_server_client_interaction():
server_thread = threading.Thread(target=run_tcp_server)
server_thread.daemon = True
server_thread.start()
time.sleep(1) # Give ... | [
{
"docstring": "Creates and returns a TCP server socket bound to the specified host and port.",
"function_declaration": "def create_tcp_server(host, port):",
"function_name": "create_tcp_server",
"parameter_list": "(host, port)"
},
{
"docstring": "Handles the client connection by receiving a... | [
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\n\ndef run_server(host='127.0.0.1', port=65432):\n \"\"\"\n Run a simple TCP server that listens for a connection and echoes back received messages.\n \"\"\"\n with s... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00079513",
"row_id": 79513,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_161564']"
} | 0.610969 | Filter_79513 | I | [
"create_tcp_server",
"handle_client_connection",
"run_tcp_server",
"create_tcp_client"
] | 4 | [
[
"run_tcp_server",
"create_tcp_server"
],
[
"run_tcp_server",
"handle_client_connection"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ec6d10385b8f575fe897c70df366a41de2ee215c | 10f20f1344ceb6d7931c9eddd12cedd975d50058 | |||
v1.0 | instruct | Filter | Filter_79749_I | Can you provide a Python script that can extract sentences from a text file and count the number of words in each sentence? The script should handle complex cases with multiple punctuation marks and nested quotes. | import re
def extract_sentences(text):
"""
Extracts sentences from a given text.
Parameters:
text (str): The text to extract sentences from.
Returns:
list: A list of sentences.
"""
# Using a more sophisticated regex to handle various punctuation and quotes
sentence_pattern = r... | from solution import extract_sentences, count_words_in_sentence, extract_and_count_words
def test_extract_sentences():
text = 'Hello there! How are you doing today? This is a test sentence. And another one. ' \
'Dr. Smith went to Washington. "What are you doing?" he asked.'
sentences = extract_sente... | [
{
"docstring": "Extracts sentences from a given text.\n\nParameters:\ntext (str): The text to extract sentences from.\n\nReturns:\nlist: A list of sentences.",
"function_declaration": "def extract_sentences(text):",
"function_name": "extract_sentences",
"parameter_list": "(text)"
},
{
"docst... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef extract_sentences_and_count_words(text):\n \"\"\"\n Extracts sentences from the provided text and counts the number of words in each sentence.\n \n Args:\n text... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00079749",
"row_id": 79749,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_162044']"
} | 0.664643 | Filter_79749 | I | [
"extract_sentences",
"count_words_in_sentence",
"extract_and_count_words"
] | 3 | [
[
"extract_and_count_words",
"count_words_in_sentence"
],
[
"extract_and_count_words",
"extract_sentences"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f0f460dbd03c2c635bd70996f1b46e810f56575a | 47c04d699cc13f283085acd5c02e0c744976a47c | |||
v1.0 | instruct | Filter | Filter_79861_I | I need to write a Python script to check for the presence of a specific pattern in text files. The pattern is "Error" in any case (uppercase, lowercase, or mixed). How can I modify the script to count the occurrences of this pattern across all text files in a directory as well? | import os
import re
def count_pattern_occurrences_in_file(file_path, pattern):
"""
Reads the file at file_path and counts the occurrences of the given pattern.
"""
count = 0
pattern_regex = re.compile(pattern, re.IGNORECASE) # Case insensitive
with open(file_path, 'r', encoding='utf-8') as fil... | import os
import tempfile
from solution import count_pattern_occurrences_in_file, count_pattern_in_directory
def test_count_pattern_occurrences_in_file():
with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as temp_file:
temp_file.write("Error in line 1\nAnother error in line 2\nNo issu... | [
{
"docstring": "Reads the file at file_path and counts the occurrences of the given pattern.",
"function_declaration": "def count_pattern_occurrences_in_file(file_path, pattern):",
"function_name": "count_pattern_occurrences_in_file",
"parameter_list": "(file_path, pattern)"
},
{
"docstring"... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport re\n\ndef count_pattern_occurrences(directory, pattern):\n \"\"\"\n Counts the occurrences of a specific pattern in text files within a directory.\n The pattern chec... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00079861",
"row_id": 79861,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_162276']"
} | 0.751384 | Filter_79861 | I | [
"count_pattern_occurrences_in_file",
"count_pattern_in_directory"
] | 2 | [
[
"count_pattern_in_directory",
"count_pattern_occurrences_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f58543b05f7e85d0121014b71e2ede56fa2a14ed | b2391d3bfe276da7913606b32b7b26eb7fe744fd | |||
v1.0 | instruct | Filter | Filter_79878_I | Create a Python program that takes user input for a list of numbers and calculates both the average and the standard deviation of the numbers. The program should handle any number of inputs and should include error handling for non-numeric inputs. | import math
def calculate_average(numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
def calculate_standard_deviation(numbers):
if not numbers:
return 0
mean = calculate_average(numbers)
variance = sum((x - mean) ** 2 for x in numbers) / len(numbers)
return m... | from solution import calculate_average_and_standard_deviation, process_user_input, calculate_average, calculate_standard_deviation
def test_process_user_input():
assert process_user_input("1 2 3 4 5") == [1.0, 2.0, 3.0, 4.0, 5.0]
assert process_user_input("1.5 2.5 3.5") == [1.5, 2.5, 3.5]
try:
proc... | [
{
"docstring": null,
"function_declaration": "def calculate_average(numbers):",
"function_name": "calculate_average",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def calculate_standard_deviation(numbers):",
"function_name": "calculate_standard_devia... | [
0,
0,
0,
0,
0,
1,
0,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef calculate_average_and_std_dev(numbers):\n \"\"\"\n Calculates the average and standard deviation of a list of numbers.\n \n :param numbers: List of numbers to ca... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00079878",
"row_id": 79878,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_162313']"
} | 0.699088 | Filter_79878 | I | [
"calculate_average",
"calculate_standard_deviation",
"process_user_input",
"calculate_average_and_standard_deviation"
] | 4 | [
[
"calculate_average_and_standard_deviation",
"calculate_average"
],
[
"calculate_average_and_standard_deviation",
"calculate_standard_deviation"
],
[
"calculate_average_and_standard_deviation",
"process_user_input"
],
[
"calculate_standard_deviation",
"calculate_average"... | 4 | [] | false | [] | false | pytest | true | [] | true | f723fcf246a000a57f4553f612b486625d70e787 | 9fd0f416125bfa82bff113f5ac4f4cc7ac9ad4db | |||
v1.0 | instruct | Filter | Filter_79898_I | Write a Python function to calculate the least common multiple (LCM) of two numbers using the greatest common divisor (GCD). Use this function to find the LCM of 12 and 18. Additionally, create a check function to verify the correctness of your LCM function with provided test cases. | import math
def gcd(a, b):
"""
Returns the greatest common divisor of a and b using Euclid's algorithm.
"""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""
Returns the least common multiple of a and b using the greatest common divisor (GCD).
"""
return abs(a * b) // gc... | from solution import gcd, lcm
def test_gcd():
assert gcd(12, 18) == 6
assert gcd(48, 18) == 6
assert gcd(20, 8) == 4
assert gcd(7, 3) == 1
def test_lcm():
assert lcm(12, 18) == 36
assert lcm(48, 18) == 144
assert lcm(20, 8) == 40
assert lcm(7, 3) == 21
def test_lcm_with_one():
ass... | [
{
"docstring": "Returns the greatest common divisor of a and b using Euclid's algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple of a and b using the greatest common divisor (GCD).",
... | [
0,
0,
0,
0,
1,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor of a and b using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00079898",
"row_id": 79898,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_162367']"
} | 0.730493 | Filter_79898 | I | [
"gcd",
"lcm"
] | 2 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | be79288e1a6be8443aa0309e6d4c9d0004ef811d | 902563c8cd2058027776fdb220724f98be1b4590 | |||
v1.0 | instruct | Filter | Filter_79932_I | Can you provide a sample code to draw a simple fractal using recursion in Python? | import matplotlib.pyplot as plt
def draw_fractal_line(x1, y1, x2, y2, depth):
"""
Draw a simple fractal line recursively.
Parameters:
x1, y1: Coordinates of the starting point.
x2, y2: Coordinates of the ending point.
depth: Recursion depth.
"""
if depth == 0:
plt.plot([x1,... | from solution import draw_fractal, draw_fractal_line
def test_draw_fractal_line_depth_zero():
# This test can't visually validate the output, but can ensure no error is raised
try:
draw_fractal_line(0, 0, 1, 1, 0)
except Exception:
assert False, "draw_fractal_line raised an exception with d... | [
{
"docstring": "Draw a simple fractal line recursively.\n\nParameters:\nx1, y1: Coordinates of the starting point.\nx2, y2: Coordinates of the ending point.\ndepth: Recursion depth.",
"function_declaration": "def draw_fractal_line(x1, y1, x2, y2, depth):",
"function_name": "draw_fractal_line",
"para... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef draw_fractal_line(tur, length, depth):\n \"\"\"\n Draw a fractal line using turtle graphics.\n \n :param tur: The turtle object to draw with.\n :param lengt... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00079932",
"row_id": 79932,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_162465']"
} | 0.440806 | Filter_79932 | I | [
"draw_fractal_line",
"draw_fractal"
] | 2 | [
[
"draw_fractal",
"draw_fractal_line"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | 852f84027fadebb5ab0df75244dcb990b212e03b | 3e05c125b05a2d2bf7cb11ff6b241855bbeae961 | |||
v1.0 | instruct | Filter | Filter_79949_I | Write a Python function to calculate the maximum sum of a submatrix within a given 2D matrix. The function should use a dynamic programming approach to efficiently find the maximum sum of any submatrix. The matrix can contain both positive and negative integers. | def max_submatrix_sum(matrix):
"""
Calculate the maximum sum of a submatrix within the given 2D matrix.
"""
if not matrix or not matrix[0]:
return 0
num_rows = len(matrix)
num_cols = len(matrix[0])
max_sum = float('-inf')
for left in range(num_cols):
row_sum = [... | from solution import max_submatrix_sum
def test_max_submatrix_sum_positive_numbers():
matrix = [
[1, 2, -1, -4, -20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]
]
assert max_submatrix_sum(matrix) == 29
def test_max_submatrix_sum_with_all_negative_numbers():... | [
{
"docstring": "Calculate the maximum sum of a submatrix within the given 2D matrix.",
"function_declaration": "def max_submatrix_sum(matrix):",
"function_name": "max_submatrix_sum",
"parameter_list": "(matrix)"
},
{
"docstring": "Kadane's algorithm to find the maximum subarray sum.",
"f... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_sum_submatrix(matrix):\n \"\"\"\n This function calculates the maximum sum of a submatrix in a given 2D matrix using dynamic programming.\n\n Args:\n matrix (List[List[int]... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00079949",
"row_id": 79949,
"seed_ids": "['Qwen2.5-Coder-32B-Instruct_162500']"
} | 0.599925 | Filter_79949 | I | [
"max_submatrix_sum",
"kadane"
] | 2 | [
[
"max_submatrix_sum",
"kadane"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbed849c4718f0916dec379490b140b4cf9b2892 | 482ffee7f294c2625a7b4ae6139c3c03a3ef85d6 | |||
v1.0 | instruct | Filter | Filter_80089_I | I have a problem that needs to be solved using a genetic algorithm. The problem is to find the minimum value of the function f(x) = x^2 - 5x + 6. Can you guide me on how to implement this using Python? | import random
def f(x):
return x**2 - 5*x + 6
def create_individual():
return random.uniform(-10, 10)
def create_population(size):
return [create_individual() for _ in range(size)]
def select_parents(population):
sorted_population = sorted(population, key=f)
return sorted_population[:2]
def cro... | from solution import f, select_parents, crossover, mutate, genetic_algorithm
def test_function():
assert f(0) == 6
assert f(2.5) == -0.25
assert f(3) == 0
def test_select_parents():
population = [10, -5, 3, 0, 2.5]
parents = select_parents(population)
assert parents == [2.5, 3]
def test_cross... | [
{
"docstring": null,
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def create_individual():",
"function_name": "create_individual",
"parameter_list": "()"
},
{
"docstring": null,
"fu... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef fitness_function(x):\n return x**2 - 5*x + 6\n\ndef create_individual():\n return random.uniform(-10, 10)\n\ndef create_population(size):\n return [create_individ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00080089",
"row_id": 80089,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_162720']"
} | 0.494541 | Filter_80089 | I | [
"f",
"create_individual",
"create_population",
"select_parents",
"crossover",
"mutate",
"genetic_algorithm"
] | 7 | [
[
"create_population",
"create_individual"
],
[
"genetic_algorithm",
"create_population"
],
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"f"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select_parents"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 5b2e59be62549de4c054a3e36bd0d49b8b3f5976 | 5bed444ea95334ad5d735b0e5dafea88c8362019 | |||
v1.0 | instruct | Filter | Filter_80393_I | I am working on a project that involves using the Chinese Remainder Theorem. I need a function in Python that can find the modular inverse of a number. Specifically, I need a function `mod_inverse(a, m)` that returns the modular inverse of `a` modulo `m`, or `None` if the inverse does not exist. Can you provide such a ... | def extended_gcd(a, b):
"""
Helper function to perform the Extended Euclidean Algorithm.
It returns a tuple (gcd, x, y) such that gcd is the greatest common divisor of a and b,
and x and y are the coefficients of Bézout's identity (i.e., a*x + b*y = gcd).
"""
if b == 0:
return a, 1, 0
... | from solution import mod_inverse
def test_mod_inverse_exists():
assert mod_inverse(3, 11) == 4
assert mod_inverse(10, 17) == 12
assert mod_inverse(2, 13) == 7
def test_mod_inverse_does_not_exist():
assert mod_inverse(2, 4) == None
assert mod_inverse(6, 9) == None
def test_mod_inverse_with_one():
... | [
{
"docstring": "Helper function to perform the Extended Euclidean Algorithm.\nIt returns a tuple (gcd, x, y) such that gcd is the greatest common divisor of a and b,\nand x and y are the coefficients of Bézout's identity (i.e., a*x + b*y = gcd).",
"function_declaration": "def extended_gcd(a, b):",
"func... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def mod_inverse(a, m):\n \"\"\"\n Returns the modular inverse of a modulo m, or None if no modular inverse exists.\n \"\"\"\n g, x, y = extended_gcd(a, m)\n if g != 1:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00080393",
"row_id": 80393,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163181']"
} | 0.555206 | Filter_80393 | I | [
"extended_gcd",
"mod_inverse"
] | 2 | [
[
"mod_inverse",
"extended_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | deab93dd0234186397f4f3e1cf0e8a2f3bca8246 | 72959717d8ad1239e5bada8152e79d8f633f81fb | |||
v1.0 | instruct | Filter | Filter_80594_I | Is it possible to implement a function in Python that can generate all permutations of a given list in lexicographic order without using the built-in `itertools.permutations` function? If so, could you provide an example or some guidance on how to do this? | def next_permutation(arr):
"""
Transforms the input array to the next lexicographic permutation.
Returns False if the array is the last permutation.
"""
n = len(arr)
# Step 1: Find the largest index k such that arr[k] < arr[k + 1].
k = -1
for i in range(n - 1):
if arr[i] < a... | from solution import generate_permutations
def test_generate_permutations():
result = generate_permutations([1, 2, 3])
expected = [
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[2, 3, 1],
[3, 1, 2],
[3, 2, 1]
]
assert result == expected
def test_generate_permutation... | [
{
"docstring": "Transforms the input array to the next lexicographic permutation.\nReturns False if the array is the last permutation.",
"function_declaration": "def next_permutation(arr):",
"function_name": "next_permutation",
"parameter_list": "(arr)"
},
{
"docstring": "Generates all lexic... | [
0,
0,
0,
0,
1,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def lexicographic_permutations(arr):\n \"\"\"\n Generate all permutations of a list in lexicographic order.\n This implementation does not use itertools.permutations.\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00080594",
"row_id": 80594,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163490']"
} | 0.54107 | Filter_80594 | I | [
"next_permutation",
"generate_permutations"
] | 2 | [
[
"generate_permutations",
"next_permutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a8623cd0a31b71b5514d1e4c02105a5e56dc81d | 7c5e0a70a03ee673eea77d2cad736f9da1c6f225 | |||
v1.0 | instruct | Filter | Filter_80650_I | I am working on a project to optimize the hyperparameters of a machine learning model using a genetic algorithm. Can you provide a step-by-step guide or some code examples to help me get started? | import random
def create_individual(length, min_value, max_value):
"""
Create a single individual with random genes.
"""
return [random.uniform(min_value, max_value) for _ in range(length)]
def create_population(count, length, min_value, max_value):
"""
Create a population of individuals.
... | from solution import create_individual, create_population, fitness_function, selection, crossover, mutate, genetic_algorithm
def test_create_individual():
individual = create_individual(5, 0, 1)
assert len(individual) == 5
assert all(0 <= gene <= 1 for gene in individual)
def test_create_population():
... | [
{
"docstring": "Create a single individual with random genes.",
"function_declaration": "def create_individual(length, min_value, max_value):",
"function_name": "create_individual",
"parameter_list": "(length, min_value, max_value)"
},
{
"docstring": "Create a population of individuals.",
... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_iris\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics impo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00080650",
"row_id": 80650,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163590']"
} | 0.232942 | Filter_80650 | I | [
"create_individual",
"create_population",
"fitness_function",
"selection",
"crossover",
"mutate",
"genetic_algorithm"
] | 7 | [
[
"create_population",
"create_individual"
],
[
"genetic_algorithm",
"create_population"
],
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"selection"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 45f4263666dfbcd817fbcf8daf5166850a74fb3a | 5a6d04d03d2cfad52f00cf1ef22513e39db7cf50 | |||
v1.0 | instruct | Filter | Filter_80779_I | I am working on a project to find the shortest path between two points on a map using Dijkstra's algorithm. How can I implement this in Python? | import heapq
def dijkstra(graph, start):
"""
Function to implement Dijkstra's Algorithm to find the shortest paths from the start node to all other nodes in the graph.
Parameters:
graph (dict): A dictionary where keys are nodes and values are dictionaries of neighboring nodes and their associated ... | from solution import dijkstra, shortest_path
def test_dijkstra_with_one_node():
graph = {'A': {}}
distances, previous_nodes = dijkstra(graph, 'A')
assert distances == {'A': 0}
assert previous_nodes == {'A': None}
def test_dijkstra_with_two_nodes():
graph = {'A': {'B': 1}, 'B': {}}
distances, p... | [
{
"docstring": "Function to implement Dijkstra's Algorithm to find the shortest paths from the start node to all other nodes in the graph.\n\nParameters:\ngraph (dict): A dictionary where keys are nodes and values are dictionaries of neighboring nodes and their associated distances.\nstart: The starting node.\n... | [
0,
0,
0,
1,
1,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(graph, start, end):\n \"\"\"\n Implements Dijkstra's algorithm to find the shortest path from start to end in a given graph.\n \n :param graph: A dicti... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00080779",
"row_id": 80779,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163799']"
} | 0.400942 | Filter_80779 | I | [
"dijkstra",
"shortest_path"
] | 2 | [
[
"shortest_path",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd6dc44245ed932fbd886ab180c27ed2114c730c | 4c1d43cab79a6a490cedc61b7a663c5e4684d63f | |||
v1.0 | instruct | Filter | Filter_80925_I | I am working on a project to implement the K Nearest Neighbors (KNN) algorithm in Python. I understand the basic concept of KNN, but I'm not sure how to start coding it. Can you provide me with a step-by-step guide on how to implement KNN in Python? | import numpy as np
from collections import Counter
def euclidean_distance(point1, point2):
distance = np.sqrt(np.sum((np.array(point1) - np.array(point2))**2))
return distance
def get_neighbors(training_set, labels, test_instance, k):
distances = []
for i in range(len(training_set)):
distance ... | from solution import euclidean_distance, get_neighbors, predict_classification, knn_predict
def test_euclidean_distance():
assert np.isclose(euclidean_distance([0, 0], [3, 4]), 5.0)
assert np.isclose(euclidean_distance([1, 1], [4, 5]), 5.0)
def test_get_neighbors():
training_set = [[1, 2], [2, 3], [3, 4],... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def get_neighbors(training_set, labels, test_instance, k):",
"function_... | [
0,
0,
0,
0,
1,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return np.... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00080925",
"row_id": 80925,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164028']"
} | 0.545722 | Filter_80925 | I | [
"euclidean_distance",
"get_neighbors",
"predict_classification",
"knn_predict"
] | 4 | [
[
"get_neighbors",
"euclidean_distance"
],
[
"knn_predict",
"get_neighbors"
],
[
"knn_predict",
"predict_classification"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 04b52df6cae040012372bd8da6fd7b246ce66ba1 | 824784c51323e3502ebb61ccef697f3eec05fb6f | |||
v1.0 | instruct | Filter | Filter_81061_I | I'm working on a project that involves training a machine learning model, and I need to understand how to implement mini-batch gradient descent in Python. Can you provide a code example and explain how it works? | import numpy as np
def compute_gradient(X, y, theta):
"""
Computes the gradient of the cost function for linear regression.
"""
m = len(y)
predictions = X.dot(theta)
errors = predictions - y
gradient = (1/m) * X.T.dot(errors)
return gradient
def mini_batch_gradient_descent(X, y, theta,... | import numpy as np
from solution import compute_gradient, mini_batch_gradient_descent
def test_compute_gradient():
X = np.array([[1, 1], [1, 2], [1, 3]])
y = np.array([1, 2, 3])
theta = np.array([0, 0])
expected_gradient = np.array([-2, -4.66666667])
gradient = compute_gradient(X, y, theta)
... | [
{
"docstring": "Computes the gradient of the cost function for linear regression.",
"function_declaration": "def compute_gradient(X, y, theta):",
"function_name": "compute_gradient",
"parameter_list": "(X, y, theta)"
},
{
"docstring": "Performs mini-batch gradient descent to learn theta.",
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef compute_cost(X, y, theta):\n \"\"\"\n Compute the cost for linear regression.\n X: numpy array of shape (m, n+1), feature dataset including bias unit\n y:... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00081061",
"row_id": 81061,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164240']"
} | 0.335164 | Filter_81061 | I | [
"compute_gradient",
"mini_batch_gradient_descent"
] | 2 | [
[
"mini_batch_gradient_descent",
"compute_gradient"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 1899cecdafb6148f1dea8dc0c23bbc894857dfa6 | 8cfbd49fca64e8e0dc6b722fa9ec101912cf2f4c | |||
v1.0 | instruct | Filter | Filter_81116_I | Is it possible to implement a genetic algorithm using PyTorch for a problem that involves integer variables and constraints, such as the knapsack problem or the traveling salesman problem? If so, could you provide some guidance on how to approach this? | import torch
import random
def generate_population(pop_size, chromosome_length):
return torch.randint(0, 10, (pop_size, chromosome_length))
def fitness_function(chromosome):
"""
Example fitness function: Maximize sum of chromosome elements.
"""
return chromosome.sum().item()
def selection(populat... | from solution import generate_population, fitness_function, selection, crossover, mutate, genetic_algorithm
def test_generate_population():
pop_size = 10
chromosome_length = 5
population = generate_population(pop_size, chromosome_length)
assert population.shape == (pop_size, chromosome_length)
asse... | [
{
"docstring": null,
"function_declaration": "def generate_population(pop_size, chromosome_length):",
"function_name": "generate_population",
"parameter_list": "(pop_size, chromosome_length)"
},
{
"docstring": "Example fitness function: Maximize sum of chromosome elements.",
"function_de... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef fitness_function(weights, values, capacity, solution):\n \"\"\"\n Calculate the fitness of a solution.\n solutions that exceed the capacity are penalized.\n \"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00081116",
"row_id": 81116,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164330']"
} | 0.32966 | Filter_81116 | I | [
"generate_population",
"fitness_function",
"selection",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness_function"
],
[
"genetic_algorithm",
"generate_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"selection"
]
] | 5 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 02cadf45c596f0b452ce46d1592f41c34a93257f | 64d946296cc6f0db7a0cf53771acddf077451daf | |||
v1.0 | instruct | Filter | Filter_81225_I | I need to create a Python function that checks if a given number is a prime number. If it is, the function should return the number itself. If it is not, the function should return the sum of its prime factors. How can I do this? | def is_prime(n):
"""
Check if a 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
re... | from solution import is_prime, prime_factors, check_number
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_prime_factors():
assert prime_factors(2) == [2]
assert prime_f... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Return a list of prime factors of a given number.",
"function_declaration": "def prime_factors(n):",
"function_na... | [
0,
0,
0,
0,
0,
1,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if the number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return Fa... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00081225",
"row_id": 81225,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164515']"
} | 0.770552 | Filter_81225 | I | [
"is_prime",
"prime_factors",
"check_number"
] | 3 | [
[
"check_number",
"is_prime"
],
[
"check_number",
"prime_factors"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6008e19dd8170b73d72ed0a112c13cae47fd22d7 | 2079fa7d321dc566628fbf24c2f20774b37e5225 | |||
v1.0 | instruct | Filter | Filter_81348_I | I am using Python to fit a curve to a set of data points. The curve I want to fit is of the form \( y = a \sin(bx + c) + d \). I have the data points in two lists, `x_data` and `y_data`. Can you provide a Python code snippet to fit this curve to my data? | import numpy as np
from scipy.optimize import curve_fit
def sinusoidal_model(x, a, b, c, d):
"""
Sinusoidal model function.
"""
return a * np.sin(b * x + c) + d
def fit_sinusoidal_curve(x_data, y_data):
"""
Fits a sinusoidal curve of the form y = a * sin(bx + c) + d to the given data points.
... | import numpy as np
from solution import sinusoidal_model, fit_sinusoidal_curve
def test_sinusoidal_model():
x = np.linspace(0, 2 * np.pi, 100)
a, b, c, d = 1, 1, 0, 0
y = sinusoidal_model(x, a, b, c, d)
assert np.allclose(y, np.sin(x))
def test_fit_sinusoidal_curve():
x_data = np.linspace(0, 2 * n... | [
{
"docstring": "Sinusoidal model function.",
"function_declaration": "def sinusoidal_model(x, a, b, c, d):",
"function_name": "sinusoidal_model",
"parameter_list": "(x, a, b, c, d)"
},
{
"docstring": "Fits a sinusoidal curve of the form y = a * sin(bx + c) + d to the given data points.\n\nPa... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.optimize import curve_fit\n\ndef sinusoidal_curve(x, a, b, c, d):\n \"\"\"\n Sinusoidal function of the form y = a * sin(b*x + c) + d\n \"\"\"\n retu... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00081348",
"row_id": 81348,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164710']"
} | 0.604709 | Filter_81348 | I | [
"sinusoidal_model",
"fit_sinusoidal_curve"
] | 2 | [
[
"fit_sinusoidal_curve",
"sinusoidal_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 46fe13d4be2a729193126129bb5552e72f5b58e5 | 55369866d2f4254b9b19cb42233453e200798d2d | |||
v1.0 | instruct | Filter | Filter_81531_I | In the context of a programming problem, what is the definition of a "boring" number, and how can I determine the count of "boring" numbers in a given range [a, b] in Python? A "boring" number is defined as a number that does not contain any digit more than once. | def is_boring_number(num):
"""
Determines if a number is 'boring', i.e., does not contain any digit more than once.
"""
num_str = str(num)
return len(set(num_str)) == len(num_str)
def count_boring_numbers_in_range(a, b):
"""
Counts the number of 'boring' numbers in the range [a, b].
"""... | from solution import is_boring_number, count_boring_numbers_in_range
def test_is_boring_number():
assert is_boring_number(1234) == True
assert is_boring_number(1123) == False
assert is_boring_number(0) == True
assert is_boring_number(444) == False
assert is_boring_number(987654321) == True
def... | [
{
"docstring": "Determines if a number is 'boring', i.e., does not contain any digit more than once.",
"function_declaration": "def is_boring_number(num):",
"function_name": "is_boring_number",
"parameter_list": "(num)"
},
{
"docstring": "Counts the number of 'boring' numbers in the range [a... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_boring(n):\n \"\"\"\n Checks if a number is boring, i.e., it does not contain any digit more than once.\n \"\"\"\n digits = str(n)\n return len(digits) == len(set(digits)... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00081531",
"row_id": 81531,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165014']"
} | 0.53581 | Filter_81531 | I | [
"is_boring_number",
"count_boring_numbers_in_range"
] | 2 | [
[
"count_boring_numbers_in_range",
"is_boring_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d752d4f6451ef2ceade1360ee5719d4e04835f8c | 5dee256681893cf97a3343f5c48172b5ff864ef5 | |||
v1.0 | instruct | Filter | Filter_81841_I | I am working on a project that requires implementing a linear regression model from scratch in Python. Can you guide me through the process step by step, including how to calculate the coefficients using the least squares method and how to evaluate the model's performance? | import numpy as np
def fit_linear_regression(X, y):
"""
Fits a linear regression model using the least squares method.
Parameters:
X (array-like): The input feature array.
y (array-like): The target values.
Returns:
tuple: Coefficients (slope and intercept) as a tuple.
"""
... | from solution import fit_linear_regression, predict, mean_squared_error, fit_and_evaluate
import numpy as np
def test_fit_linear_regression():
X = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
slope, intercept = fit_linear_regression(X, y)
assert np.isclose(slope, 2, rtol=1e-05)
ass... | [
{
"docstring": "Fits a linear regression model using the least squares method.\n\nParameters:\nX (array-like): The input feature array.\ny (array-like): The target values.\n\nReturns:\ntuple: Coefficients (slope and intercept) as a tuple.",
"function_declaration": "def fit_linear_regression(X, y):",
"fu... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def linear_regression(X, Y):\n \"\"\"\n Calculates the coefficients for linear regression using the least squares method.\n Args:\n X (list or array): Independent variable data\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00081841",
"row_id": 81841,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165528']"
} | 0.598017 | Filter_81841 | I | [
"fit_linear_regression",
"predict",
"mean_squared_error",
"fit_and_evaluate"
] | 4 | [
[
"fit_and_evaluate",
"fit_linear_regression"
],
[
"fit_and_evaluate",
"mean_squared_error"
],
[
"fit_and_evaluate",
"predict"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a3b9af22920520e07c22912c378cf4df269ffdd2 | 942ba13b28f158835b1c6a47092434c8b7784258 | |||
v1.0 | instruct | Filter | Filter_81880_I | We have a list of words, and we need to find the word that is the most similar to a given word based on their Levenshtein distance. The Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into the other. If there ar... | from typing import List
def levenshtein_distance(a: str, b: str) -> int:
"""
Compute the Levenshtein distance between two strings a and b.
"""
if len(a) < len(b):
return levenshtein_distance(b, a)
if len(b) == 0:
return len(a)
previous_row = range(len(b) + 1)
for i, c1 in ... | from solution import levenshtein_distance, find_most_similar_word
def test_levenshtein_distance():
assert levenshtein_distance("kitten", "sitting") == 3
assert levenshtein_distance("flaw", "lawn") == 2
assert levenshtein_distance("book", "back") == 2
assert levenshtein_distance("table", "tables") == 1
... | [
{
"docstring": "Compute the Levenshtein distance between two strings a and b.",
"function_declaration": "def levenshtein_distance(a, b):",
"function_name": "levenshtein_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Given a list of words, find the word most similar to the target wo... | [
0,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def levenshtein_distance(s1, s2):\n \"\"\"\n Computes the Levenshtein distance between two strings s1 and s2.\n \"\"\"\n if len(s1) < len(s2):\n return levenshtein_distance(... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00081880",
"row_id": 81880,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165598']"
} | 0.68004 | Filter_81880 | I | [
"levenshtein_distance",
"find_most_similar_word"
] | 2 | [
[
"find_most_similar_word",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ccc42a484ef8a06b30879506787b1a9c359f05d | 04941071873d18a8662df5750c5206535db9803d | |||
v1.0 | instruct | Filter | Filter_81918_I | Is it possible to use a Python function in a Cython function without converting the Python function to a Cython function? I want to use a Python function in a Cython function, but I don't want to convert the Python function to a Cython function. Is this possible? If so, how can I do it? If not, why not? | # Yes, it is possible to use a Python function inside a Cython function
# without converting the Python function to a Cython function.
# This can be done by simply calling the Python function directly within the Cython function.
from typing import List
def py_function(x: int) -> int:
"""A simple Python function... | from solution import py_function, c_function
def test_py_function():
assert py_function(1) == 2
assert py_function(0) == 1
assert py_function(-1) == 0
def test_c_function():
assert c_function(1) == 2
assert c_function(0) == 1
assert c_function(-1) == 0
def test_consistent_results():
# Ens... | [
{
"docstring": "A simple Python function that adds 1 to the input.",
"function_declaration": "def py_function(x):",
"function_name": "py_function",
"parameter_list": "(x)"
},
{
"docstring": "A Cython function that uses the Python function.",
"function_declaration": "def c_function(x):",
... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Yes, it is possible to use a Python function within a Cython function without converting it to a Cython function. \n# This can be done by simply calling the Python function from within the C... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00081918",
"row_id": 81918,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165644']"
} | 0.337501 | Filter_81918 | I | [
"py_function",
"c_function"
] | 2 | [
[
"c_function",
"py_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f8938ce6d98a122db87aba4dccef8e3124e40fc6 | a81940f3e0ba66004ed4e7c6e583b0ae66ade72d | |||
v1.0 | instruct | Filter | Filter_82017_I | I want to create a program that can recognize and interpret mathematical equations written in LaTeX format. How can I get started with this? | import re
def tokenize(latex_expr):
"""
Tokenizes a LaTeX expression into a list of tokens.
"""
token_pattern = re.compile(r'(\d+|[+*/()-]|\^|\\[a-zA-Z]+)')
tokens = token_pattern.findall(latex_expr)
return tokens
def parse(tokens):
"""
Parses the list of tokens into an Abstract Syntax... | from solution import tokenize, parse, interpret
def test_tokenize():
assert tokenize("3 + 5") == ['3', '+', '5']
assert tokenize("12 / 4") == ['12', '/', '4']
assert tokenize("2^3") == ['2', '^', '3']
assert tokenize("5 - 2 + 3") == ['5', '-', '2', '+', '3']
assert tokenize("(3 + 2) * 5") == ['(', ... | [
{
"docstring": "Tokenizes a LaTeX expression into a list of tokens.",
"function_declaration": "def tokenize(latex_expr):",
"function_name": "tokenize",
"parameter_list": "(latex_expr)"
},
{
"docstring": "Parses the list of tokens into an Abstract Syntax Tree (AST).\nThis is a simplified vers... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sympy.parsing.latex import parse_latex\n\ndef interpret_latex(latex_str):\n \"\"\"\n Takes a LaTeX string and returns the corresponding SymPy expression.\n \n Parameters:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00082017",
"row_id": 82017,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165841']"
} | 0.350466 | Filter_82017 | I | [
"tokenize",
"parse",
"interpret"
] | 3 | [
[
"interpret",
"parse"
],
[
"interpret",
"tokenize"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 40be834269468a89552af8b04f74ef248e7238b1 | 4391718e8a6d26753a4f57dde7462ac99900bbb7 | |||
v1.0 | instruct | Filter | Filter_82047_I | I am working on a project that involves implementing the k nearest neighbors (kNN) algorithm in Python. I need to write a function that takes a training set, a test set, and a value of k as inputs, and returns the predicted labels for the test set. Can you provide me with a basic implementation of the kNN algorithm in ... | import numpy as np
from collections import Counter
def euclidean_distance(point1, point2):
return np.sqrt(np.sum((np.array(point1) - np.array(point2))**2))
def k_nearest_neighbors(train_set, train_labels, test_set, k):
"""
Predict the label of each point in the test set based on the k nearest neighbors.
... | import pytest
from solution import k_nearest_neighbors
def test_k_nearest_neighbors_basic():
train_set = [[1, 2], [2, 3], [3, 4], [6, 7]]
train_labels = [0, 0, 1, 1]
test_set = [[1, 1], [5, 5]]
k = 3
predictions = k_nearest_neighbors(train_set, train_labels, test_set, k)
assert predictions == [... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Predict the label of each point in the test set based on the k nearest neighbors.\n\nParameters:\ntrain_set (... | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n return np.sqrt(np.sum((point1 - point2) ** 2))\n\ndef knn_predict(X_train, y_train, X_test, ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00082047",
"row_id": 82047,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165895']"
} | 0.555521 | Filter_82047 | I | [
"euclidean_distance",
"k_nearest_neighbors"
] | 2 | [
[
"k_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 9623e777c88d11ec2f798d54af5658ebeccf8de9 | 242376f3ac88bcb9722b2fb61cf437a63dc423a6 | |||
v1.0 | instruct | Filter | Filter_82156_I | I am trying to solve the following problem: Given a set of n points in a plane, find the two points that are closest to each other. I need to implement this in Python and I am looking for an efficient algorithm. Can you help me with this? | import math
def euclidean_distance(p1, p2):
"""
Calculates the Euclidean distance between points p1 and p2.
"""
return math.hypot(p1[0] - p2[0], p1[1] - p2[1])
def closest_pair_of_points(points):
"""
Finds the closest pair of points in a set of points using the divide and conquer approach.
... | from solution import closest_pair_of_points
def test_closest_pair_positive_coordinates():
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
assert closest_pair_of_points(points)[1] in [((2, 3), (3, 4)), ((3, 4), (2, 3))]
def test_closest_pair_negative_coordinates():
points = [(-2, -3), (-12,... | [
{
"docstring": "Calculates the Euclidean distance between points p1 and p2.",
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Finds the closest pair of points in a set of points using the divide... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import cmp_to_key\n\ndef distance_squared(p1, p2):\n \"\"\"\n Returns the squared distance between two points p1 and p2.\n \"\"\"\n return (p1[0] - p2[0... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00082156",
"row_id": 82156,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166090']"
} | 0.59245 | Filter_82156 | I | [
"euclidean_distance",
"closest_pair_of_points"
] | 2 | [
[
"closest_pair_of_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bc31cb6e6ef24a13c8b5b5c7355bb964548508e | 4f37649ac9455a58a6a523b12d7d82f7773f8e22 | |||
v1.0 | instruct | Filter | Filter_82179_I | I'm working on a project to implement a simple feedforward neural network in Python using numpy. The network should have an input layer, a hidden layer with a sigmoid activation function, and an output layer with a softmax activation function. The loss function should be cross-entropy, and the optimization algorithm sh... | import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(z):
return sigmoid(z) * (1 - sigmoid(z))
def softmax(z):
exp_z = np.exp(z - np.max(z, axis=1, keepdims=True))
return exp_z / np.sum(exp_z, axis=1, keepdims=True)
def cross_entropy(y_true, y_pred):
m = y_true.sh... | import numpy as np
from solution import sigmoid, softmax, cross_entropy, initialize_parameters
from solution import forward_propagation, backward_propagation, update_parameters
from solution import train, predict
def test_sigmoid():
assert np.isclose(sigmoid(0), 0.5)
assert np.isclose(sigmoid(np.inf), 1)
a... | [
{
"docstring": null,
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},
{
"docstring": null,
"function_declaration": "def sigmoid_derivative(z):",
"function_name": "sigmoid_derivative",
"parameter_list": "(z)"
},
{
"docstring... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(sig_x):\n return sig_x * (1 - sig_x)\n\ndef softmax(x):\n exp_x = np.exp(x - np.max(x)) ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00082179",
"row_id": 82179,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166130']"
} | 0.382745 | Filter_82179 | I | [
"sigmoid",
"sigmoid_derivative",
"softmax",
"cross_entropy",
"initialize_parameters",
"forward_propagation",
"backward_propagation",
"update_parameters",
"train",
"predict"
] | 10 | [
[
"backward_propagation",
"sigmoid_derivative"
],
[
"forward_propagation",
"sigmoid"
],
[
"forward_propagation",
"softmax"
],
[
"predict",
"forward_propagation"
],
[
"sigmoid_derivative",
"sigmoid"
],
[
"train",
"backward_propagation"
],
[
... | 10 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 88fa8c4e615580dfafdba52dbafc852f0a150a6a | a7e949c5e74f97ca194a598e3aff8937a693724b | |||
v1.0 | instruct | Filter | Filter_82330_I | You are given a set of points in a 2D plane. Write a Python function that returns the convex hull of these points. The convex hull of a set of points is the smallest convex polygon that contains all the points. The function should take a list of tuples as input, where each tuple represents a point in the form (x, y), a... | def get_orientation(p, q, r):
"""
Find orientation of the triplet (p, q, r).
0 -> p, q and r are collinear
>0 -> Clockwise
<0 -> Counterclockwise
"""
return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
def convex_hull(points):
"""
Returns the points making up the co... | from solution import convex_hull
def test_convex_hull_square():
points = [(0, 0), (1, 0), (1, 1), (0, 1)]
expected_hull = [(0, 0), (1, 0), (1, 1), (0, 1)]
result_hull = convex_hull(points)
assert sorted(result_hull) == sorted(expected_hull)
def test_convex_hull_triangle():
points = [(0, 0), (2, 0)... | [
{
"docstring": "Find orientation of the triplet (p, q, r).\n0 -> p, q and r are collinear\n>0 -> Clockwise\n<0 -> Counterclockwise",
"function_declaration": "def get_orientation(p, q, r):",
"function_name": "get_orientation",
"parameter_list": "(p, q, r)"
},
{
"docstring": "Returns the point... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def convex_hull(points):\n \"\"\"\n Returns the convex hull of a set of 2D points using the gift wrapping algorithm (Jarvis march).\n \n Args:\n points (list of tuples): A list ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00082330",
"row_id": 82330,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166419']"
} | 0.527852 | Filter_82330 | I | [
"get_orientation",
"convex_hull"
] | 2 | [
[
"convex_hull",
"get_orientation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 47204b95ac4066c2faa1570012c71a8aec7d53aa | a4ad40e113ba88f21330f398987fba109cfa81d2 | |||
v1.0 | instruct | Filter | Filter_82787_I | Here's a problem I'm trying to solve:
**Problem:** Design an algorithm to find the kth largest element in an unsorted array of integers.
**Constraints:**
* The input array can contain duplicates.
* The size of the array can be very large.
* The value of k can be very large.
**Requirements:**
* The algorithm should... | def quickselect(arr, left, right, k):
"""
This function returns the kth largest element in the array using the quickselect algorithm.
"""
if left == right: # If the list contains only one element
return arr[left]
pivot_index = partition(arr, left, right)
# Number of elements in the ri... | from solution import find_kth_largest
def test_find_kth_largest():
assert find_kth_largest([3, 2, 1, 5, 6, 4], 2) == 5
assert find_kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
assert find_kth_largest([1], 1) == 1
def test_find_kth_largest_large_k():
assert find_kth_largest([3, 1, 2, 4], 4) == 1
d... | [
{
"docstring": "This function returns the kth largest element in the array using the quickselect algorithm.",
"function_declaration": "def quickselect(arr, left, right, k):",
"function_name": "quickselect",
"parameter_list": "(arr, left, right, k)"
},
{
"docstring": "This function partitions... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef partition(nums, low, high):\n pivot = nums[high]\n i = low\n for j in range(low, high):\n if nums[j] > pivot:\n nums[i], nums[j] = nums[j], nums... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00082787",
"row_id": 82787,
"seed_ids": "['gemma-2-27b-it_167776']"
} | 0.515593 | Filter_82787 | I | [
"quickselect",
"partition",
"median_of_three",
"find_kth_largest"
] | 4 | [
[
"find_kth_largest",
"quickselect"
],
[
"partition",
"median_of_three"
],
[
"quickselect",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 3c9abf92b80c48a4b9ad1579d85454c31520ee38 | 8b81bcb5d000c69d7c4be092826e8a2a6137eb5d | |||
v1.0 | instruct | Filter | Filter_82977_I | This is the code I have so far
```python
import random
def guess_the_number():
number = random.randint(1, 100)
guesses_left = 7
print("Welcome to Guess the Number!")
print("I'm thinking of a number between 1 and 100.")
while guesses_left > 0:
print(f"You have {guesses_left} guesses left."... | import random
def get_number_range(difficulty):
if difficulty == 'easy':
return 1, 50
elif difficulty == 'medium':
return 1, 100
elif difficulty == 'hard':
return 1, 200
else:
raise ValueError("Invalid difficulty level")
def guess_the_number():
print("Welcome to Gue... | from solution import get_number_range
def test_get_number_range_easy():
assert get_number_range('easy') == (1, 50)
def test_get_number_range_medium():
assert get_number_range('medium') == (1, 100)
def test_get_number_range_hard():
assert get_number_range('hard') == (1, 200)
def test_get_number_range_inv... | [
{
"docstring": null,
"function_declaration": "def get_number_range(difficulty):",
"function_name": "get_number_range",
"parameter_list": "(difficulty)"
},
{
"docstring": null,
"function_declaration": "def guess_the_number():",
"function_name": "guess_the_number",
"parameter_list"... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef guess_the_number():\n def get_range_and_guesses(difficulty):\n if difficulty == 'easy':\n return 1, 50, 10\n elif difficulty == 'medium':\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00082977",
"row_id": 82977,
"seed_ids": "['gemma-2-27b-it_168346']"
} | 0.575582 | Filter_82977 | I | [
"get_number_range",
"guess_the_number"
] | 2 | [
[
"guess_the_number",
"get_number_range"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6cc32b8a2bd0fb970669bfd390639824c03b40ba | 0f389910b6a26c1396ffa18dbc18ca2a137d8877 | |||
v1.0 | instruct | Filter | Filter_83171_I | The Challenge:
You've been tasked with creating a simple card game for two players.
Game Name:
Nimble Numbers
Game Mechanics:
Players take turns drawing a card from a deck of 20 cards numbered 1 through 20.
On their turn, a player can either keep the card they drew or discard it and draw a new card.
The goal of... | import random
def initialize_deck():
"""
Initialize a shuffled deck of cards numbered 1 through 20.
"""
deck = list(range(1, 21))
random.shuffle(deck)
return deck
def draw_card(deck):
"""
Draws a card from the deck.
"""
return deck.pop()
def player_turn(deck, hand, player_name... | from solution import initialize_deck, draw_card, player_turn, calculate_total, nimble_numbers
def test_initialize_deck():
deck = initialize_deck()
assert len(deck) == 20
assert set(deck) == set(range(1, 21))
def test_draw_card():
deck = initialize_deck()
card = draw_card(deck)
assert card ... | [
{
"docstring": "Initialize a shuffled deck of cards numbered 1 through 20.",
"function_declaration": "def initialize_deck():",
"function_name": "initialize_deck",
"parameter_list": "()"
},
{
"docstring": "Draws a card from the deck.",
"function_declaration": "def draw_card(deck):",
"... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef nimble_numbers():\n # Create a deck of cards\n deck = list(range(1, 21))\n random.shuffle(deck)\n\n # Initialize player hands\n player1_hand = []\n playe... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00083171",
"row_id": 83171,
"seed_ids": "['gemma-2-27b-it_168919']"
} | 0.575112 | Filter_83171 | I | [
"initialize_deck",
"draw_card",
"player_turn",
"calculate_total",
"nimble_numbers"
] | 5 | [
[
"nimble_numbers",
"calculate_total"
],
[
"nimble_numbers",
"initialize_deck"
],
[
"nimble_numbers",
"player_turn"
],
[
"player_turn",
"draw_card"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b26c20b0116981e2a2b510f93a20abcc54f66b13 | be51c65b4d7ef0ca9688322066bdeee83e620e1f | |||
v1.0 | instruct | Filter | Filter_83579_I | Exercise 1: Word Embeddings
Instructions:
1. Download: Download the GloVe 300-dimensional pre-trained word embeddings from the Stanford NLP website:
[https://nlp.stanford.edu/projects/glove/](https://nlp. Stanford.edu/projects/glove/)
Note: Choose the zip file containing "glove.6B.zip".
2. Load Embeddings:
... | import numpy as np
def load_glove_embeddings(file_path):
"""
Loads GloVe embeddings from the given file and stores them in a dictionary.
Parameters:
file_path (str): Path to the GloVe embeddings file.
Returns:
dict: A dictionary where keys are words and values are 300-dime... | from solution import load_glove_embeddings, cosine_similarity, word_analogy
import numpy as np
def test_load_glove_embeddings():
# Using a small sample data for testing
file_content = "king 0.1 0.2 0.3\nman 0.4 0.5 0.6\nwoman 0.7 0.8 0.9\n"
with open('test_glove.txt', 'w') as f:
f.write(file_conten... | [
{
"docstring": "Loads GloVe embeddings from the given file and stores them in a dictionary.\n\nParameters:\n file_path (str): Path to the GloVe embeddings file.\n \nReturns:\n dict: A dictionary where keys are words and values are 300-dimensional numpy arrays.",
"function_declaration": "def load_gl... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef load_glove_embeddings(file_path):\n \"\"\"\n Loads the GloVe embeddings from the given file path and returns a dictionary where\n keys are words and values a... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00083579",
"row_id": 83579,
"seed_ids": "['gemma-2-27b-it_170196']"
} | 0.511197 | Filter_83579 | I | [
"load_glove_embeddings",
"cosine_similarity",
"word_analogy"
] | 3 | [
[
"word_analogy",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 1706bad91c9f52efd38c5f2dfa611d0d987b06ae | b73abd5dfba8ff88cec462bf8f59412619ec98c9 | |||
v1.0 | instruct | Filter | Filter_83713_I | Given a list of words, return the longest word(s) with the most vowels.
Example Input:
```
words = ["apple", "banana", "orange", "kiwi", "grapefruit"]
```
Example Output:
```
['grapefruit']
```
Explanation:
Both "grapefruit" and "orange" have the same number of vowels (5), but "grapefruit" is longer, so it is the o... | def count_vowels(word):
vowels = "aeiouAEIOU"
return sum(1 for char in word if char in vowels)
def longest_most_vowels(words):
if not words:
return []
max_vowels = -1
max_length = -1
result = []
for word in words:
vowel_count = count_vowels(word)
word_length = ... | from solution import longest_most_vowels
def test_longest_most_vowels_single_word():
assert longest_most_vowels(["apple"]) == ["apple"]
def test_longest_most_vowels_simple_case():
assert longest_most_vowels(["apple", "banana", "orange", "kiwi", "grapefruit"]) == ["grapefruit"]
def test_longest_most_vowels_ti... | [
{
"docstring": null,
"function_declaration": "def count_vowels(word):",
"function_name": "count_vowels",
"parameter_list": "(word)"
},
{
"docstring": null,
"function_declaration": "def longest_most_vowels(words):",
"function_name": "longest_most_vowels",
"parameter_list": "(words... | [
0,
0,
0,
0,
1,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_word_with_most_vowels(words):\n \"\"\"\n Returns the longest word(s) with the most vowels.\n \"\"\"\n vowels = {'a', 'e', 'i', 'o', 'u'}\n \n def count_vowels(wor... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00083713",
"row_id": 83713,
"seed_ids": "['gemma-2-27b-it_170602']"
} | 0.691555 | Filter_83713 | I | [
"count_vowels",
"longest_most_vowels"
] | 2 | [
[
"longest_most_vowels",
"count_vowels"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f535adfac2032b0731ebf690ee9a63f6c99f26d9 | a4e3688e348b99f10c3bc701bd0fc89013898f5c | |||
v1.0 | instruct | Filter | Filter_83826_I | This is my situation:
I am working on a project that involves simulating the motion of a charged particle in an electric field.
I am using Python to write the code.
I have successfully implemented the equations of motion for a charged particle in a uniform electric field.
Now, I want to introduce a non-uniform elec... | import numpy as np
def calculate_field_at_point(E, x, y, z):
"""
Calculate the electric field at a given point in space.
Parameters:
E (function): A function that takes coordinates (x, y, z) and returns the electric field (Ex, Ey, Ez) at that point.
x, y, z (float): Coordinates of the point.
... | def test_calculate_field_at_point():
def E(x, y, z):
return (x, y, z)
Ex, Ey, Ez = calculate_field_at_point(E, 1, 2, 3)
assert (Ex, Ey, Ez) == (1, 2, 3)
def test_simulate_motion_constant_field():
def E_const(x, y, z):
return (1, 0, 0)
q = 1 # Charge
m = 1 # Mass
... | [
{
"docstring": "Calculate the electric field at a given point in space.\n\nParameters:\nE (function): A function that takes coordinates (x, y, z) and returns the electric field (Ex, Ey, Ez) at that point.\nx, y, z (float): Coordinates of the point.\n\nReturns:\nEx, Ey, Ez (float): Components of the electric fie... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef electric_field_non_uniform(x, y, z):\n \"\"\"\n Returns the components of the electric field at a given point (x, y, z).\n In this example, we'll assume a hy... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00083826",
"row_id": 83826,
"seed_ids": "['gemma-2-27b-it_170959']"
} | 0.269047 | Filter_83826 | I | [
"calculate_field_at_point",
"simulate_motion"
] | 2 | [
[
"simulate_motion",
"calculate_field_at_point"
]
] | 1 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | c0784656dff3c088091f82f4d4d0f55c8ad53b16 | 2bb905dce3a46295cb5f7470d3e461757ee04405 | |||
v1.0 | instruct | Filter | Filter_84121_I | This is my code for a simple Blackjack game with Python. The game itself works fine, but I want to add a feature that allows the player to choose to "double down" on their hand. | import random
def draw_card():
"""
Draws a card from the deck.
"""
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
return random.choice(cards)
def calculate_hand(hand):
"""
Calculates the total value of a hand.
"""
total = sum(hand)
ace_count = hand.count(11)
whil... | from solution import draw_card, calculate_hand, play_blackjack
def test_draw_card():
card = draw_card()
assert card in [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
def test_calculate_hand_no_ace():
assert calculate_hand([2, 3, 4]) == 9
def test_calculate_hand_with_ace():
assert calculate_hand([2, 3, 11]) == 16
... | [
{
"docstring": "Draws a card from the deck.",
"function_declaration": "def draw_card():",
"function_name": "draw_card",
"parameter_list": "()"
},
{
"docstring": "Calculates the total value of a hand.",
"function_declaration": "def calculate_hand(hand):",
"function_name": "calculate_h... | [
0,
0,
0,
1,
0,
1,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef deal_card():\n \"\"\"\n Returns a random card from the deck. Cards are represented as integers.\n \"\"\"\n cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00084121",
"row_id": 84121,
"seed_ids": "['gemma-2-27b-it_171746']"
} | 0.412297 | Filter_84121 | I | [
"draw_card",
"calculate_hand",
"play_blackjack"
] | 3 | [
[
"play_blackjack",
"calculate_hand"
],
[
"play_blackjack",
"draw_card"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 118c2a248ab95df48fff2ab9d54e169c971c41f7 | 8c1183ff3a89b4d9f363ca2e938e6e990a86822b | |||
v1.0 | instruct | Filter | Filter_84515_I | The Challenge:
Write a program that implements a simple text-based adventure game.
Details:
The game should:
Present the player with a scenario and choices.
Allow the player to input their choice.
Update the game state based on the player's choice.
Keep track of the player's inventory.
End the game when a spec... | inventory = []
def start_game():
"""Starts the game by presenting the initial scenario."""
print("You find yourself in a dark forest. A path leads north, and a faint light flickers to the east.")
print("What do you do?")
print("1. Go North")
print("2. Go East")
choice = input("Enter your choice... | from solution import start_game, inventory, go_north, go_east, end_game
def mock_input(prompt):
responses = iter(["1", "1", "2", "1"])
return lambda _: next(responses)
def test_start_game(monkeypatch):
monkeypatch.setattr('builtins.input', mock_input(""))
start_game()
assert inventory == ['Boat']
... | [
{
"docstring": "Starts the game by presenting the initial scenario.",
"function_declaration": "def start_game():",
"function_name": "start_game",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def go_north():",
"function_name": "go_north",
"parameter_list... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "inventory = []\n\ndef start_game():\n \"\"\"Starts the game by presenting the initial scenario and handling choices.\"\"\"\n print(\"Welcome to the Adventure Game!\")\n print(\"You fi... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00084515",
"row_id": 84515,
"seed_ids": "['gemma-2-27b-it_173039']"
} | 0.474199 | Filter_84515 | I | [
"start_game",
"go_north",
"go_east",
"end_game"
] | 4 | [
[
"go_east",
"end_game"
],
[
"go_east",
"start_game"
],
[
"go_north",
"end_game"
],
[
"go_north",
"start_game"
],
[
"start_game",
"go_east"
],
[
"start_game",
"go_north"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 125be3d388ee0ea3fea459b08ca903735f149877 | 945a333c7f764f08a00be696cb60e742e35d8be4 | |||
v1.0 | instruct | Filter | Filter_84997_I | I want to learn how to program a tic-tac-toe game.
## Tic-tac-toe rules
Players take turns marking a 3x3 grid with either an 'X' or 'O'. The first player to mark three consecutive spaces (horizontally, vertically, or diagonally) wins. If all spaces are filled and no player wins, the game is a draw.
## Code structure... | BOARD_SIZE = 3
PLAYER_X = 'X'
PLAYER_O = 'O'
def print_board(board):
"""
Prints the game board in a readable format.
"""
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_win(board):
"""
Checks if any player has won the game.
Returns True if a player has won... | from solution import print_board, check_win, player_turn, PLAYER_X, PLAYER_O
def test_print_board(capsys):
board = [
[PLAYER_X, ' ', PLAYER_O],
[' ', PLAYER_X, ' '],
[PLAYER_O, ' ', PLAYER_X]
]
print_board(board)
captured = capsys.readouterr()
expected_output = "X | | O\n"... | [
{
"docstring": "Prints the game board in a readable format.",
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": "Checks if any player has won the game.\nReturns True if a player has won, False otherwise.",
"fu... | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Constants for game board size and player symbols\nBOARD_SIZE = 3\nPLAYER_X = 'X'\nPLAYER_O = 'O'\n\ndef print_board(board):\n \"\"\"\n Prints the game board in a user-friendly way.\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00084997",
"row_id": 84997,
"seed_ids": "['gemma-2-27b-it_174393']"
} | 0.523417 | Filter_84997 | I | [
"print_board",
"check_win",
"player_turn"
] | 3 | [
[
"player_turn",
"check_win"
],
[
"player_turn",
"print_board"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d6d1c2b0610d2ccf3915286888312b48667cf4bf | b8613d6db8db213712e4defc19ed0978812c84ac | |||
v1.0 | instruct | Filter | Filter_85131_I | This is an example of a text-based game where the players choose their path by typing in numbers.
```python
def game():
print("You wake up in a dark forest.")
print("1. Head north.")
print("2. Head east.")
choice = input("> ")
if choice == "1":
print("You encounter a friendly goblin.")
... | def game():
while True:
print("You wake up in a dark forest.")
print("1. Head north.")
print("2. Head east.")
print("3. Exit game.")
choice = input("> ")
if choice == "1":
north()
elif choice == "2":
east()
elif choice == "3":... | from unittest.mock import patch
import builtins
from solution import game, north, east
def test_game_north(monkeypatch, capsys):
inputs = iter(['1', '3'])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
game()
captured = capsys.readouterr()
assert "You encounter a friendly goblin... | [
{
"docstring": null,
"function_declaration": "def game():",
"function_name": "game",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def north():",
"function_name": "north",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration":... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def game():\n print(\"You wake up in a dark forest.\")\n print(\"1. Head north.\")\n print(\"2. Head east.\")\n\n choice = input(\"> \")\n\n if choice == \"1\":\n north()... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00085131",
"row_id": 85131,
"seed_ids": "['gemma-2-27b-it_174751']"
} | 0.445486 | Filter_85131 | I | [
"game",
"north",
"east"
] | 3 | [
[
"game",
"east"
],
[
"game",
"north"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6e5e274f4784e6da4b60f8a3fda9c242454e482 | 14d0b1a019eb358ecc08ef1506ad8868bcd3b088 | |||
v1.0 | instruct | Filter | Filter_85212_I | You are tasked with developing a Python script to automate the process of extracting URLs from a text file.
Input: A text file containing text and URLs.
Output:
A new text file containing only the extracted URLs, one URL per line.
Requirements:
1. Use regular expressions for URL extraction.
2. Handle various ... | import re
def extract_urls(filename):
"""
Extracts URLs from a text file and returns them as a list.
Args:
filename (str): The name of the input text file.
Returns:
list: A list of extracted URLs.
"""
url_pattern = re.compile(
r'(?i)\b((?:https?://|www\d{0,3}[.]|https?... | import os
from solution import extract_urls, save_urls, process_file
def test_extract_urls():
input_text = """
Here are some URLs:
http://example.com
https://secure.example.com/path
www.example.org
This is not a URL: ftp://example.com
Another URL: http://www.example.co.uk
"""
with o... | [
{
"docstring": "Extracts URLs from a text file and returns them as a list.\n\nArgs:\n filename (str): The name of the input text file.\n\nReturns:\n list: A list of extracted URLs.",
"function_declaration": "def extract_urls(filename):",
"function_name": "extract_urls",
"parameter_list": "(fil... | [
0,
0,
0,
1,
0,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef extract_urls(filename):\n \"\"\"\n Extracts URLs from a text file.\n\n Args:\n filename (str): The name of the input text file.\n\n Returns:\n list: ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00085212",
"row_id": 85212,
"seed_ids": "['gemma-2-27b-it_174996']"
} | 0.649811 | Filter_85212 | I | [
"extract_urls",
"save_urls",
"process_file"
] | 3 | [
[
"process_file",
"extract_urls"
],
[
"process_file",
"save_urls"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dc42cf59653fd0f3b8ce2309b79469e755235664 | 45fa09e75fcbf9f8c54733b6f9ab925a3d3e01a4 | |||
v1.0 | instruct | Filter | Filter_85321_I | Here are the rules to the card game “War”:
* Each player receives half of a standard
52-card deck.
* Players simultaneously reveal the
top card of their deck.
* The player with the higher-ranking card wins both cards and adds them to the bottom of
their deck.
* If the cards have the same rank, it’s "War"!
* **Du... | import random
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
deck = [(rank, suit) for rank in ranks for suit in suits]
rank_value = {rank: index for index, rank in enumerate(ranks)}
random.shuffle(deck)
# Split the deck into t... | def test_create_deck():
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
deck = [(rank, suit) for rank in ranks for suit in suits]
assert len(deck) == 52
def test_split_deck():
suits = ["Hearts", "Diamonds", "Cl... | [
{
"docstring": null,
"function_declaration": "def play_turn(deck1, deck2, pot=None):",
"function_name": "play_turn",
"parameter_list": "(deck1, deck2, pot=None)"
},
{
"docstring": null,
"function_declaration": "def play_game():",
"function_name": "play_game",
"parameter_list": "(... | [
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Suits and ranks for the cards\nsuits = [\"Hearts\", \"Diamonds\", \"Clubs\", \"Spades\"]\nranks = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00085321",
"row_id": 85321,
"seed_ids": "['gemma-2-27b-it_175353']"
} | 0.538471 | Filter_85321 | I | [
"play_turn",
"play_game"
] | 2 | [
[
"play_game",
"play_turn"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bdf8157d7a0e30938bc30c60a6d8143100f5dde2 | da47ebf48fbc8492b9394666545eaeed01ba0a90 | |||
v1.0 | instruct | Filter | Filter_85342_I | This document describes a method for generating a complex password, using the following scheme:
* **Phrase:** A memorable phrase that is at least 8 words long.
* **Acronym:** The first letter of each word in the phrase.
* **Random Number:** A randomly generated number between 1 and 999.
* **Symbol Substitution:** Repl... | import random
def get_phrase():
"""Prompts the user for a memorable phrase that is at least 8 words long."""
while True:
phrase = input("Enter a memorable phrase (at least 8 words): ")
words = phrase.split()
if len(words) >= 8:
return phrase
else:
print("... | def test_get_acronym():
phrase = "This is a memorable phrase that is very secure"
expected_acronym = "Tiamptivs"
assert get_acronym(phrase) == expected_acronym
def test_generate_random_number():
random_number = generate_random_number()
assert 1 <= random_number <= 999
def test_substitute_symbols()... | [
{
"docstring": "Prompts the user for a memorable phrase that is at least 8 words long.",
"function_declaration": "def get_phrase():",
"function_name": "get_phrase",
"parameter_list": "()"
},
{
"docstring": "Takes a phrase as input and returns its acronym.",
"function_declaration": "def g... | [
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef symbol_substitution(acronym):\n \"\"\"\n Replaces characters in the acronym with symbols based on a predefined mapping.\n \"\"\"\n symbol_map = {\n 'a':... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00085342",
"row_id": 85342,
"seed_ids": "['gemma-2-27b-it_175421']"
} | 0.685801 | Filter_85342 | I | [
"get_phrase",
"get_acronym",
"generate_random_number",
"substitute_symbols",
"generate_password"
] | 5 | [
[
"generate_password",
"generate_random_number"
],
[
"generate_password",
"get_acronym"
],
[
"generate_password",
"substitute_symbols"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | fc86350042434bfa40537180e3815ad1ad8c9a46 | 89117d723e50b914004b75cb1fbfdccb8b765172 | |||
v1.0 | instruct | Filter | Filter_85567_I | You've been provided with a large text file containing various sentences. Your task is to write a Python program that identifies and extracts all the imperative sentences from this file.
Explanation:
Imperative sentences are sentences that give a command or make a request. They typically start with a verb and often ... | import re
def is_imperative_sentence(sentence):
"""
Determines if a given sentence is an imperative sentence.
An imperative sentence typically starts with a verb and makes a request or gives a command.
Args:
sentence (str): The sentence to check.
Returns:
bool: Tr... | def test_is_imperative_sentence():
assert is_imperative_sentence("Close the door.") == True
assert is_imperative_sentence("Please pass the salt.") == True
assert is_imperative_sentence("Go home!") == True
assert is_imperative_sentence("The door is closed.") == False
assert is_imperative_sentence("He... | [
{
"docstring": "Determines if a given sentence is an imperative sentence.\n\nAn imperative sentence typically starts with a verb and makes a request or gives a command.\n\nArgs:\n sentence (str): The sentence to check.\n \nReturns:\n bool: True if the sentence is imperative, False otherwise.",
"fun... | [
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_imperative(sentence):\n \"\"\"\n Checks if a sentence is an imperative sentence.\n \n Args:\n sentence (str): The sentence to check.\n \n Returns:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00085567",
"row_id": 85567,
"seed_ids": "['gemma-2-27b-it_176011']"
} | 0.533737 | Filter_85567 | I | [
"is_imperative_sentence",
"extract_imperative_sentences"
] | 2 | [
[
"extract_imperative_sentences",
"is_imperative_sentence"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c624379f19c71fe8d5e8b628e7a58015f801e0df | e7bf448f47da43a3ae4d23dd684074bcd89ba896 | |||
v1.0 | instruct | Filter | Filter_85735_I | Here is some code:
```python
import random
def guess_the_number():
"""Plays a number guessing game with the user."""
number = random.randint(1, 100)
guesses_left = 7
print("I'm thinking of a number between 1 and 100.")
while guesses_left > 0:
print(f"You have {guesses_left} guesses left.")
try:
... | import random
def get_random_number():
return random.randint(1, 100)
def check_guess(guess, number, attempts):
if guess < number:
return "Too low!"
elif guess > number:
return "Too high!"
else:
return f"Congratulations! You guessed the number in {attempts} tries!"
def provide_... | from solution import get_random_number, check_guess, provide_hint
def test_get_random_number_within_range():
for _ in range(1000):
number = get_random_number()
assert 1 <= number <= 100
def test_check_guess_too_low():
assert check_guess(50, 75, 1) == "Too low!"
def test_check_guess_too_high()... | [
{
"docstring": null,
"function_declaration": "def get_random_number():",
"function_name": "get_random_number",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def check_guess(guess, number, attempts):",
"function_name": "check_guess",
"parameter_list": "(g... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef play_round(number_range, attempts):\n \"\"\"Plays a single round of the number guessing game.\"\"\"\n number = random.randint(1, number_range)\n guesses_left = at... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00085735",
"row_id": 85735,
"seed_ids": "['gemma-2-27b-it_176578']"
} | 0.559914 | Filter_85735 | I | [
"get_random_number",
"check_guess",
"provide_hint",
"guess_the_number"
] | 4 | [
[
"guess_the_number",
"check_guess"
],
[
"guess_the_number",
"get_random_number"
],
[
"guess_the_number",
"provide_hint"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 20d0d5768b899ace19e83f70d95387822726248e | 7cff00b14bac76575db99b48f13b7b9429e7fafe | |||
v1.0 | instruct | Filter | Filter_85740_I | Objective: Develop a Python script named `text_analyzer.py` that analyzes the textual content of a file.
2. File Input:
- The script should accept the filename as a command-line argument.
For example:
```bash
python text_analyzer.py my_document.txt
```
3. Analysis:
- Word Count: Count the total n... | import sys
import re
def count_words(text):
"""Returns the total number of words in the input text."""
words = text.split()
return len(words)
def count_characters(text):
"""Returns the total number of characters in the input text (excluding whitespace)."""
characters = re.sub(r'\s+', '', text)
... | from solution import count_words, count_characters, count_lines, count_sentences
def test_count_words():
text = "Hello world! This is a test."
assert count_words(text) == 6
def test_count_characters():
text = "Hello world! This is a test."
assert count_characters(text) == 23
def test_count_lines():
... | [
{
"docstring": "Returns the total number of words in the input text.",
"function_declaration": "def count_words(text):",
"function_name": "count_words",
"parameter_list": "(text)"
},
{
"docstring": "Returns the total number of characters in the input text (excluding whitespace).",
"funct... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport re\n\ndef text_analyzer(file_name):\n \"\"\"\n Analyzes the textual content of a file.\n \n Parameters:\n file_name (str): The name of the file to analyze.\n\... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00085740",
"row_id": 85740,
"seed_ids": "['gemma-2-27b-it_176592']"
} | 0.634337 | Filter_85740 | I | [
"count_words",
"count_characters",
"count_lines",
"count_sentences",
"analyze_file"
] | 5 | [
[
"analyze_file",
"count_characters"
],
[
"analyze_file",
"count_lines"
],
[
"analyze_file",
"count_sentences"
],
[
"analyze_file",
"count_words"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 466a77676e1533ea6c815c8b85cb1f52371f467c | 634a5773ad01222c613aa5d8cc42a2b9e7847bbc | |||
v1.0 | instruct | Filter | Filter_85762_I | This is what I am trying to achieve and the code I have so far:
**Goal:**
I want to build a simple text-based adventure game in Python where the player navigates through different rooms described by text and makes choices that affect the story.
**What I Have:**
```python
rooms = {
"hallway": {
"descript... | import re
import pickle
def save_game(state, filename="savegame.pkl"):
with open(filename, "wb") as f:
pickle.dump(state, f)
def load_game(filename="savegame.pkl"):
with open(filename, "rb") as f:
return pickle.load(f)
rooms = {
"hallway": {
"description": "You are in a dimly lit ... | import pytest
from solution import parse_command, save_game, load_game
def test_parse_command_move():
assert parse_command("go north") == ("move", "north")
assert parse_command("walk east") == ("move", "east")
assert parse_command("move south") == ("move", "south")
def test_parse_command_take():
asser... | [
{
"docstring": null,
"function_declaration": "def save_game(state, filename='savegame.pkl'):",
"function_name": "save_game",
"parameter_list": "(state, filename='savegame.pkl')"
},
{
"docstring": null,
"function_declaration": "def load_game(filename='savegame.pkl'):",
"function_name"... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\n# Define room structure\nrooms = {\n \"hallway\": {\n \"description\": \"You are in a dimly lit hallway. There is a door to the north and a door to the east.\",\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00085762",
"row_id": 85762,
"seed_ids": "['gemma-2-27b-it_176655']"
} | 0.423952 | Filter_85762 | I | [
"save_game",
"load_game",
"parse_command",
"game_loop"
] | 4 | [
[
"game_loop",
"load_game"
],
[
"game_loop",
"parse_command"
],
[
"game_loop",
"save_game"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8beda2abe1bf38ef1d248636a50dde43e887f470 | 434900fc5594b4f4b6eb444a61e2aa5d544055b3 | |||
v1.0 | instruct | Filter | Filter_85905_I | Learning Objective: To create a program that can efficiently solve Sudoku puzzles of various difficulties. | def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
for i in range(3):
for j in range(3):
if board[start_row + i][start_col + j] == num:
... | from solution import solve_sudoku, find_empty, is_valid
def test_is_valid():
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
... | [
{
"docstring": null,
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": null,
"function_declaration": "def solve_sudoku(board):",
"function_name": "solve_sudoku",
"parameter_list... | [
0,
0,
0,
0,
1,
0,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if placing num at board[row][col] is valid according to\n Sudoku rules.\n \"\"\"\n for x in range(9):\n if board[row]... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00085905",
"row_id": 85905,
"seed_ids": "['gemma-2-27b-it_177096']"
} | 0.496664 | Filter_85905 | I | [
"is_valid",
"solve_sudoku",
"find_empty"
] | 3 | [
[
"solve_sudoku",
"find_empty"
],
[
"solve_sudoku",
"is_valid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 010cf068176e0d85cb0bfc3809c68415e9c6138f | 74c8ca7b2a32f6b5a593a8fa6c43019aff5f3f75 | |||
v1.0 | instruct | Filter | Filter_85928_I | I want to build a simple chatbot using Python and basic machine learning techniques.
Here's my approach:
1. **Dataset:** Use a publicly available dataset of dialogues or conversations.
2. **Preprocessing:** Clean the text data, tokenize it, and create a vocabulary.
3. **Training:**
* **Choose a simple Machine le... | # Step 1: Dataset
import pandas as pd
# We'll use a simple dataset for demonstration. Here, 'data.csv' is a CSV file with dialogs.
try:
df = pd.read_csv('data.csv')
conversations = df['dialogues'].tolist()
except FileNotFoundError:
conversations = [
"Hello, how are you?",
"I am fine, thank ... | import pytest
from solution import preprocess_text, chatbot_response, pipeline
def test_preprocess_text():
assert preprocess_text("Hello, World!") == "hello world"
assert preprocess_text("Python3.9!") == "python39"
assert preprocess_text("Why is this!") == "why is this"
def test_chatbot_response_basic():
... | [
{
"docstring": null,
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def chatbot_response(input_text, pipeline):",
"function_name": "chatbot_response",
"parameter... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import nltk\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nimport random\n\nnltk.download... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00085928",
"row_id": 85928,
"seed_ids": "['gemma-2-27b-it_177165']"
} | 0.382305 | Filter_85928 | I | [
"preprocess_text",
"chatbot_response"
] | 2 | [
[
"chatbot_response",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 3bc19fc81c2091a9f916ad567c66d3496ce969d6 | 2ef1dd9cd5c68270427e858d26099d0f0fa3309a | |||
v1.0 | instruct | Filter | Filter_86141_I | This is an example input file for the algorithm:
```
example
word1,word3,word2
word2,word1,word3
word3,word2,word1
example2
word4,word5
word5,word4
```
This file contains pairs of words which represent connections.
For example, "word1,word3,word2" means that there is a connection between word1 and word3, and also be... | from collections import deque
def build_graph(file_path):
graph = {}
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line and "," in line:
words = line.split(',')
for i in range(len(words) - 1):
if w... | from solution import build_graph, bfs, find_shortest_path
def test_build_graph():
file_path = 'test_input.txt'
with open(file_path, 'w') as file:
file.write("example\nword1,word3,word2\nword2,word1,word3\nword3,word2,word1\nexample2\nword4,word5\nword5,word4\n")
expected_graph = {
'word1':... | [
{
"docstring": null,
"function_declaration": "def build_graph(file_path):",
"function_name": "build_graph",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def bfs(graph, start, end):",
"function_name": "bfs",
"parameter_list": "(graph, start, end... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import collections\n\ndef read_input_file(file_path):\n \"\"\"\n Reads the input file and builds a graph.\n \"\"\"\n graph = collections.defaultdict(list)\n with open(file_path,... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00086141",
"row_id": 86141,
"seed_ids": "['gemma-2-27b-it_177752']"
} | 0.566758 | Filter_86141 | I | [
"build_graph",
"bfs",
"find_shortest_path"
] | 3 | [
[
"find_shortest_path",
"bfs"
],
[
"find_shortest_path",
"build_graph"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ef646d096c92457088796b96d760c33ba8dfe17e | 4ca66e4a64dd06bc6a72d6e591b945c062e97fed | |||
v1.0 | instruct | Filter | Filter_86219_I | Exercise
Implement a function `count_overlapping_rectangles(rectangles)` that takes a list of rectangles as input and returns the number of overlapping rectangles.
A rectangle is represented by a tuple of four integers `(x1, y1, x2, y2)`, where:
`(x1, y1)` are the coordinates of the bottom-left corner.
`(x2, y2)`... | def do_overlap(rect1, rect2):
"""
Check if two rectangles overlap.
"""
(x1, y1, x2, y2) = rect1
(a1, b1, a2, b2) = rect2
# If one rectangle is on the left side of the other
if x1 >= a2 or a1 >= x2:
return False
# If one rectangle is above the other
if y1 >= b2 or b1... | from solution import count_overlapping_rectangles
def test_non_overlapping_rectangles():
rectangles = [(1, 1, 3, 3), (4, 4, 6, 6)]
assert count_overlapping_rectangles(rectangles) == 0
def test_all_overlapping_rectangles():
rectangles = [(1, 1, 3, 3), (2, 2, 4, 4), (3, 3, 5, 5)]
assert count_overlappin... | [
{
"docstring": "Check if two rectangles overlap.",
"function_declaration": "def do_overlap(rect1, rect2):",
"function_name": "do_overlap",
"parameter_list": "(rect1, rect2)"
},
{
"docstring": "Count the number of overlapping rectangles in the given list.",
"function_declaration": "def co... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def compare_rectangles(rect1, rect2):\n \"\"\"\n Checks if rect1 and rect2 overlap. Rectangles overlap if they share any common area.\n \"\"\"\n x1, y1, x2, y2 = rect1\n x3, y3,... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00086219",
"row_id": 86219,
"seed_ids": "['gemma-2-27b-it_177989']"
} | 0.64148 | Filter_86219 | I | [
"do_overlap",
"count_overlapping_rectangles"
] | 2 | [
[
"count_overlapping_rectangles",
"do_overlap"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ae441e3975a90b8793947085b13d5cbb69b560d | 7518baf4c2ff7944259174e41cbc29aa8a416798 | |||
v1.0 | instruct | Filter | Filter_86299_I | This is a Python project where you write a program to guess a randomly generated number between 1 and 100. Implement the following:
1. **Random Number Generation:** Generate a random integer between 1 and 100 (inclusive) using the `random` module.
2. **User Input:** Prompt the user to enter their guess using the `inp... | import random
def generate_random_number():
"""
Generate a random integer between 1 and 100 (inclusive).
"""
return random.randint(1, 100)
def get_user_guess():
"""
Prompt the user to enter their guess.
"""
while True:
try:
guess = int(input("Enter your guess (1-100... | import pytest
from unittest.mock import patch
from solution import generate_random_number, get_user_guess, compare_guess, play_game
def test_generate_random_number():
random_number = generate_random_number()
assert 1 <= random_number <= 100
def test_get_user_guess_valid_input():
with patch('builtins.input... | [
{
"docstring": "Generate a random integer between 1 and 100 (inclusive).",
"function_declaration": "def generate_random_number():",
"function_name": "generate_random_number",
"parameter_list": "()"
},
{
"docstring": "Prompt the user to enter their guess.",
"function_declaration": "def ge... | [
0,
0,
0,
0,
1,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef guess_the_number():\n target = random.randint(1, 100)\n attempts = 7\n guess_count = 0\n \n print(\"Guess the number between 1 and 100! You have 7 attempts.... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00086299",
"row_id": 86299,
"seed_ids": "['gemma-2-27b-it_178209']"
} | 0.57976 | Filter_86299 | I | [
"generate_random_number",
"get_user_guess",
"compare_guess",
"play_game"
] | 4 | [
[
"play_game",
"compare_guess"
],
[
"play_game",
"generate_random_number"
],
[
"play_game",
"get_user_guess"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 779c382f1936cd4799f95ed33c49d2383a527ec1 | 133a163c9738a78e6d42cc588946fab2de576208 | |||
v1.0 | instruct | Filter | Filter_86497_I | Objective: To build a Python program that calculates the sum of all prime numbers within a user-specified range. | def is_prime(n):
"""
Check if the number n 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 ... | 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(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(0) == Fals... | [
{
"docstring": "Check if the number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Return the sum of all prime numbers within the range [start, end].",
"function_declaration": "def sum_of_primes(start, end... | [
0,
0,
0,
1,
1,
1,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number n 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 re... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00086497",
"row_id": 86497,
"seed_ids": "['gemma-2-27b-it_178734']"
} | 0.684209 | Filter_86497 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 822dd0c3c78fee68f723eb4cca85a399904578e8 | d045155b533291df26b9d6cfe854981d1cca348a | |||
v1.0 | instruct | Filter | Filter_86732_I | This is a task for you.
You are given a string, "abcde".
Your task is to find all the possible palindromic substrings within "abcde".
A palindrome is a word, phrase, or sequence that reads the same backward as forward.
Here are the palindromic substrings of "abcde":
a
b
c
d
e
aa
bb
cc
dd
ee
aba
aca
ada
These a... | def find_palindromic_substrings(s):
"""
Finds all palindromic substrings in the given string `s`.
:param s: Input string in which to find palindromic substrings
:return: A set of all palindromic substrings in `s`
"""
n = len(s)
palindromic_substrings = set()
for i in range(n):
... | from solution import find_palindromic_substrings, expand_around_center
def test_find_palindromic_substrings():
# Test with the given string "abcde"
assert find_palindromic_substrings("abcde") == {'a', 'b', 'c', 'd', 'e'}
# Test with a string that has multiple palindromes
assert find_palindromic_su... | [
{
"docstring": "Finds all palindromic substrings in the given string `s`.\n\n:param s: Input string in which to find palindromic substrings\n:return: A set of all palindromic substrings in `s`",
"function_declaration": "def find_palindromic_substrings(s):",
"function_name": "find_palindromic_substrings"... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_palindromic_substrings(s):\n \"\"\"\n Finds all palindromic substrings within the given string s.\n \"\"\"\n n = len(s)\n palindromic_substrings = set()\n \n for ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00086732",
"row_id": 86732,
"seed_ids": "['gemma-2-27b-it_179412']"
} | 0.703393 | Filter_86732 | I | [
"find_palindromic_substrings",
"expand_around_center"
] | 2 | [
[
"find_palindromic_substrings",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7fc19a6639472a492d9ec105686fa1b2f0a3d5b0 | 0b59f85c26cefd05c578cd8eabb4ef95efe9e47d | |||
v1.0 | instruct | Filter | Filter_86746_I | You are presented with a text file containing a collection of words. Your task is to write a program that identifies the palindromes within the text file and outputs them to the console. | def is_palindrome(word):
"""
Checks if a given word is a palindrome.
"""
return word == word[::-1]
def find_palindromes_in_file(file_path):
"""
Reads a text file and prints all palindrome words found in it.
"""
with open(file_path, 'r') as file:
words = file.read().split()
... | import os
from solution import is_palindrome, find_palindromes_in_file
def test_is_palindrome():
assert is_palindrome("madam")
assert not is_palindrome("hello")
assert is_palindrome("racecar")
assert not is_palindrome("python")
assert is_palindrome("level")
def test_find_palindromes_in_file(tmp_pa... | [
{
"docstring": "Checks if a given word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Reads a text file and prints all palindrome words found in it.",
"function_declaration": "def find... | [
0,
0,
0,
0,
1,
1,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_palindromes(filepath):\n \"\"\"\n Reads a file and identifies all palindromes within the file.\n Outputs the palindromes to the console.\n \"\"\"\n def is_palindrome(wo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00086746",
"row_id": 86746,
"seed_ids": "['gemma-2-27b-it_179446']"
} | 0.656716 | Filter_86746 | I | [
"is_palindrome",
"find_palindromes_in_file"
] | 2 | [
[
"find_palindromes_in_file",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1bb7eabcbb3d3c802888d420cacfb37a075082fc | d73bf6980f577507d5e9829bd70581a078ed14a2 | |||
v1.0 | instruct | Filter | Filter_86920_I | I am trying to build a basic chat bot which can respond to greetings, farewells, and
questions about the user's name.
Here is the code I have so far:
```python
# Greeting responses
greetings = ["Hello!", "Hi there!", "Hey!"]
# Farewell responses
farewells = ["Goodbye!", "See you later!", "Take care!"]
# Function t... | import random
# Greeting responses
greetings = ["Hello!", "Hi there!", "Hey!"]
# Farewell responses
farewells = ["Goodbye!", "See you later!", "Take care!"]
# Basic responses about the bot itself
bot_responses = {
"how are you": "I'm just a bot, but I'm functioning as expected!",
"what are you": "I'm a basic... | import pytest
from unittest.mock import patch
from solution import get_random_response, chatbot
# Test get_random_response function
def test_get_random_response():
responses = ["Hello!", "Hi!", "Hey!"]
result = get_random_response(responses)
assert result in responses
# Test chatbot function for greetings... | [
{
"docstring": null,
"function_declaration": "def get_random_response(responses):",
"function_name": "get_random_response",
"parameter_list": "(responses)"
},
{
"docstring": null,
"function_declaration": "def chatbot():",
"function_name": "chatbot",
"parameter_list": "()"
}
] | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Greeting responses\ngreetings = [\"Hello!\", \"Hi there!\", \"Hey!\"]\n\n# Farewell responses\nfarewells = [\"Goodbye!\", \"See you later!\", \"Take care!\"]\n\n# Function to get a random re... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00086920",
"row_id": 86920,
"seed_ids": "['gemma-2-27b-it_179966']"
} | 0.422412 | Filter_86920 | I | [
"get_random_response",
"chatbot"
] | 2 | [
[
"chatbot",
"get_random_response"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a880350ab780bb52abe8077e0e70098a422d4c5 | 73fd1454b34ca26c2ce67b8a38f06da28ff3b198 | |||
v1.0 | instruct | Filter | Filter_87215_I | I'm working on a coding project and need to determine if a list of strings contains any duplicate words.
```python
sentences = [
"the quick brown fox jumps over the lazy dog",
"now is the time for all good men",
"the sky is blue",
"the early bird gets the worm"
]
```
Can you help me write Python code ... | def has_duplicate_words(sentence):
"""
Checks if a sentence contains any duplicate words.
Parameters:
sentence (str): The sentence to check.
Returns:
bool: True if there are duplicate words, False otherwise.
"""
words = sentence.split()
return len(words) != len(set(words))
... | from solution import has_duplicate_words, any_sentences_with_duplicates
def test_has_duplicate_words():
assert has_duplicate_words("the quick brown brown fox") == True
assert has_duplicate_words("the quick brown fox") == False
assert has_duplicate_words("hello hello") == True
assert has_duplicate_words... | [
{
"docstring": "Checks if a sentence contains any duplicate words.\n\nParameters:\nsentence (str): The sentence to check.\n\nReturns:\nbool: True if there are duplicate words, False otherwise.",
"function_declaration": "def has_duplicate_words(sentence):",
"function_name": "has_duplicate_words",
"pa... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def contains_duplicate(sentences):\n \"\"\"\n Checks if any duplicate words exist in the list of sentences.\n \n :param list sentences: List of sentences (strings).\n :return: T... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00087215",
"row_id": 87215,
"seed_ids": "['gemma-2-27b-it_180773']"
} | 0.651711 | Filter_87215 | I | [
"has_duplicate_words",
"any_sentences_with_duplicates"
] | 2 | [
[
"any_sentences_with_duplicates",
"has_duplicate_words"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f4accd38c0d3cade3d1f7317480d87fd811af5db | 59233de8583b470d6d7eb4a6e53b21826d69942d | |||
v1.0 | instruct | Filter | Filter_87424_I | This is going to be an exciting project!
I'm looking for help building a program that generates random art with the following capabilities:
**Core Features:**
1. **Shape Generation:** Ability to generate simple geometric shapes (circles, squares, triangles, lines) at random positions and sizes within a specified can... | import random
from PIL import Image, ImageDraw
import math
def generate_random_color():
"""
Generates a random RGB color.
"""
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def generate_circle(draw, width, height):
"""
Generates a random circle within the given... | from solution import generate_random_art
import pytest
def test_generate_random_art():
image = generate_random_art(400, 400, 10)
assert image.size == (400, 400)
def test_generate_random_art_with_zero_shapes():
image = generate_random_art(400, 400, 0)
assert image.size == (400, 400)
def test_gener... | [
{
"docstring": "Generates a random RGB color.",
"function_declaration": "def generate_random_color():",
"function_name": "generate_random_color",
"parameter_list": "()"
},
{
"docstring": "Generates a random circle within the given width and height on the provided draw object.",
"function... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport pygame\nimport math\nfrom pygame.locals import *\n\ndef random_color():\n \"\"\"\n Generate a random color.\n Returns a tuple representing an RGB color.\n \"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00087424",
"row_id": 87424,
"seed_ids": "['gemma-2-27b-it_181389']"
} | 0.55802 | Filter_87424 | I | [
"generate_random_color",
"generate_circle",
"generate_square",
"generate_triangle",
"generate_line",
"generate_random_art"
] | 6 | [
[
"generate_circle",
"generate_random_color"
],
[
"generate_line",
"generate_random_color"
],
[
"generate_square",
"generate_random_color"
],
[
"generate_triangle",
"generate_random_color"
]
] | 4 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 78fe141bfa3b98e0b958676e8102d2c677718882 | 195a13d651c6da673e55262d4a1f96fe266c7adf | |||
v1.0 | instruct | Filter | Filter_87539_I | Let's design a simple programming quiz.
Here are some requirements:
* The quiz should be in Python.
* It should consist of 5 multiple choice questions.
* Each question should have 4 possible answers, only one of which is correct.
* The quiz should keep track of the user's score.
```python
# Python Programming Qu... | # Python Programming Quiz
def ask_question(question, options):
"""
Displays the question and options, captures and returns the user's answer.
"""
print(question)
for i, option in enumerate(options):
print(f"{i+1}. {option}")
while True:
try:
user_answer = int(input("... | from solution import run_quiz
def test_quiz_all_correct(monkeypatch):
# Mock the inputs to return the correct answers
inputs = iter([1, 3, 2, 4, 3])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
assert run_quiz(questions) == None
def test_quiz_all_incorrect(monkeypatch):
# Mock the... | [
{
"docstring": "Displays the question and options, captures and returns the user's answer.",
"function_declaration": "def ask_question(question, options):",
"function_name": "ask_question",
"parameter_list": "(question, options)"
},
{
"docstring": "Run the quiz with provided questions and tr... | [
0,
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def ask_question(question, options):\n \"\"\"\n Asks a question and returns the user's answer.\n \"\"\"\n print(question)\n for i, option in enumerate(options):\n print(f... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00087539",
"row_id": 87539,
"seed_ids": "['gemma-2-27b-it_181783']"
} | 0.524123 | Filter_87539 | I | [
"ask_question",
"run_quiz"
] | 2 | [
[
"run_quiz",
"ask_question"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c408825773cef71ab38cfac2ef721f9391031fe9 | dc606c0e60f8f31b82bf96b7a0853c6fddd72b18 | |||
v1.0 | instruct | Filter | Filter_87633_I | This is an example of an array of arrays where "1" represents land and "0" represents water
```
myArray = [
[1, 1, 0, 0, 0],
[1, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1],
[1, 0, 0, 0, 1]]
```
From this array, I need to find and print all the groups (islands) of connected land.
... | def dfs(myArray, visited, i, j):
stack = [(i, j)]
n = len(myArray)
m = len(myArray[0])
while stack:
x, y = stack.pop()
if visited[x][y]:
continue
visited[x][y] = True
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx, ny = x + dx, y + dy
... | from solution import find_islands
def test_no_islands():
myArray = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
assert find_islands(myArray) == 0
def test_one_island():
myArray = [
[1, 1, 0],
[0, 1, 0],
[0, 0, 0]
]
assert find_islands(myArray) == 1
def t... | [
{
"docstring": null,
"function_declaration": "def dfs(myArray, visited, i, j):",
"function_name": "dfs",
"parameter_list": "(myArray, visited, i, j)"
},
{
"docstring": null,
"function_declaration": "def find_islands(myArray):",
"function_name": "find_islands",
"parameter_list": "... | [
0,
0,
0,
0,
1,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_islands(matrix):\n \"\"\"\n Given a 2D matrix where '1' represents land and '0' represents water,\n this function returns a list of all groups (islands) of connected land.\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00087633",
"row_id": 87633,
"seed_ids": "['gemma-2-27b-it_182099']"
} | 0.471394 | Filter_87633 | I | [
"dfs",
"find_islands"
] | 2 | [
[
"find_islands",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8d5d76771aa1d4366f0765d887e1919811a70e93 | b7a0d1ae29517228b82aae1d263c64fe0f04c43e | |||
v1.0 | instruct | Filter | Filter_87634_I | There is a large, open field with an uncountable number of equally spaced points on a rectangular grid. At each point there lies a single firefly. Each firefly can change its state from on (glowing) to off (not glowing) every second. There is a global signal that simultaneously alerts all fireflies to change their stat... | import numpy as np
def initialize_grid(rows, cols):
"""
Initializes a grid with the given number of rows and cols,
where each cell is randomly assigned a state: 1 (on) or 0 (off).
"""
return np.random.randint(2, size=(rows, cols))
def get_neighbors(grid, x, y):
"""
Returns the states of th... | import numpy as np
from solution import initialize_grid, get_neighbors, update_grid
def test_initialize_grid():
grid = initialize_grid(5, 5)
assert grid.shape == (5, 5)
assert np.all((grid == 0) | (grid == 1)) # Check if all elements are 0 or 1
def test_get_neighbors():
grid = np.array([
[0, ... | [
{
"docstring": "Initializes a grid with the given number of rows and cols,\nwhere each cell is randomly assigned a state: 1 (on) or 0 (off).",
"function_declaration": "def initialize_grid(rows, cols):",
"function_name": "initialize_grid",
"parameter_list": "(rows, cols)"
},
{
"docstring": "R... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport random\n\ndef initialize_grid(rows, cols):\n \"\"\"\n Initialize grid with random states (0 for off, 1 for on).\n \"\"\"\n return np.random.randint(2, si... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00087634",
"row_id": 87634,
"seed_ids": "['gemma-2-27b-it_182101']"
} | 0.446383 | Filter_87634 | I | [
"initialize_grid",
"get_neighbors",
"update_grid",
"simulate_fireflies",
"visualize_grid"
] | 5 | [
[
"simulate_fireflies",
"initialize_grid"
],
[
"simulate_fireflies",
"update_grid"
],
[
"update_grid",
"get_neighbors"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | f209115599a1107702b9f640489c0ca80e22f10b | ccf52285b8bba20e91cb2ad979a31f690560d412 | |||
v1.0 | instruct | Filter | Filter_87795_I | This is what I've started creating.
```python
import random
def guess_the_number_game():
number = random.randint(1, 100)
guesses_left = 7
print("Welcome to the Guess the Number Game!")
print("I'm thinking of a number between 1 and 100.")
while guesses_left > 0:
print(f"You have {guesses_left} guesses l... | import random
def get_hint(number):
hints = []
if number % 2 == 0:
hints.append("The number is even.")
else:
hints.append("The number is odd.")
if number % 3 == 0:
hints.append("The number is divisible by 3.")
else:
hints.append("The number is not divisible by 3.")
... | from solution import get_hint
def test_get_hint_even_number():
hints = get_hint(4)
assert "The number is even." in hints
assert "The number is divisible by 3." not in hints
def test_get_hint_odd_number():
hints = get_hint(7)
assert "The number is odd." in hints
assert "The number is divisible ... | [
{
"docstring": null,
"function_declaration": "def get_hint(number):",
"function_name": "get_hint",
"parameter_list": "(number)"
},
{
"docstring": null,
"function_declaration": "def guess_the_number_game():",
"function_name": "guess_the_number_game",
"parameter_list": "()"
}
] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_random_number(difficulty):\n if difficulty == \"easy\":\n return random.randint(1, 50)\n elif difficulty == \"medium\":\n return random.randint(1, ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00087795",
"row_id": 87795,
"seed_ids": "['gemma-2-27b-it_182542']"
} | 0.599992 | Filter_87795 | I | [
"get_hint",
"guess_the_number_game"
] | 2 | [
[
"guess_the_number_game",
"get_hint"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | acb7819cff62c7f122977bcff6aa6ce732fdfcba | 94264d6928c7d7d01df90c8bd59a1c9051b1699d | |||
v1.0 | instruct | Filter | Filter_87827_I | This is the code I have so far for a tic tac toe game using Python:
```python
board = [' ' for _ in range(9)]
def print_board():
print('-------------')
for i in range(3):
print('|', board[i], '|', board[i + 3], '|', board[i + 6], '|')
print('-------------')
def player_input():
marker = ''... | board = [' ' for _ in range(9)]
def print_board():
print('-------------')
for i in range(3):
print('|', board[i * 3], '|', board[i * 3 + 1], '|', board[i * 3 + 2], '|')
print('-------------')
def player_input():
marker = ''
while not (marker == 'X' or marker == 'O'):
marker = i... | from solution import board, place_marker, check_win, is_board_full
def test_place_marker():
board[:] = [' ' for _ in range(9)]
place_marker('X', 1)
assert board[0] == 'X'
place_marker('O', 5)
assert board[4] == 'O'
place_marker('X', 9)
assert board[8] == 'X'
def test_check_win():... | [
{
"docstring": null,
"function_declaration": "def print_board():",
"function_name": "print_board",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def player_input():",
"function_name": "player_input",
"parameter_list": "()"
},
{
"docstring": null,... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "board = [' ' for _ in range(9)]\n\ndef print_board():\n print('-------------')\n for i in range(3):\n print('|', board[i * 3], '|', board[i * 3 + 1], '|', board[i * 3 + 2], '|')\n... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00087827",
"row_id": 87827,
"seed_ids": "['gemma-2-27b-it_182640']"
} | 0.416186 | Filter_87827 | I | [
"print_board",
"player_input",
"place_marker",
"check_win",
"choose_position",
"is_board_full",
"play_game"
] | 7 | [
[
"play_game",
"check_win"
],
[
"play_game",
"choose_position"
],
[
"play_game",
"is_board_full"
],
[
"play_game",
"place_marker"
],
[
"play_game",
"player_input"
],
[
"play_game",
"print_board"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 7619b8867ec0f0389be22a64bc66d7ed128d1360 | 6c8dcce601a06e8ae7784d225055478661b312fa | |||
v1.0 | instruct | Filter | Filter_87846_I | Here is some code that simulates a simple dice game:
```python
import random
def roll_dice():
return random.randint(1, 6)
def play_game():
score = 0
for _ in range(3):
roll = roll_dice()
score += roll
print(f"You rolled a {roll}. Your current score is {score}.")
print(f"Your final score is {score... | import random
def roll_dice():
return random.randint(1, 6)
def player_decision():
decision = input("Do you want to 'roll' or 'hold'? ")
while decision not in ['roll', 'hold']:
print("Invalid input. Please enter 'roll' or 'hold'.")
decision = input("Do you want to 'roll' or 'hold'? ")
r... | from solution import roll_dice, player_decision, computer_decision, play_game
import builtins
def test_roll_dice_within_range():
for _ in range(100):
roll = roll_dice()
assert 1 <= roll <= 6
def test_computer_decision_hold():
assert computer_decision(15) == 'hold'
assert computer_decision(... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def player_decision():",
"function_name": "player_decision",
"parameter_list": "()"
},
{
"docstring": nul... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n return random.randint(1, 6)\n\ndef player_turn(player_name, score):\n while True:\n choice = input(f\"{player_name}: Do you want to 'roll' or '... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00087846",
"row_id": 87846,
"seed_ids": "['gemma-2-27b-it_182697']"
} | 0.540305 | Filter_87846 | I | [
"roll_dice",
"player_decision",
"computer_decision",
"play_game"
] | 4 | [
[
"play_game",
"computer_decision"
],
[
"play_game",
"player_decision"
],
[
"play_game",
"roll_dice"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 1e5a6e7e46697056841d647cc86c1c96f9f79f78 | 75a3a2df2e3bfeb5ce6d50c02620132f2ab870ad | |||
v1.0 | instruct | Filter | Filter_87900_I | This program aims to translate user inputted English text into the corresponding Pig Latin word.
The user inputs English text and the program outputs Pig Latin text.
Example:
Input: hello world
Output: ellohay orldway
Here are the rules for converting English words to Pig Latin:
1. If a word begins with a consonan... | def pig_latin(word):
"""
Translates a single English word into Pig Latin.
"""
vowels = "aeiouAEIOU"
if word[0] in vowels:
return word + "way"
else:
# Find the first vowel
for i in range(1, len(word)):
if word[i] in vowels:
return word[i:] + wo... | from solution import pig_latin, translate_sentence
def test_pig_latin_with_vowel():
assert pig_latin("apple") == "appleway", "Test with a word starting with a vowel failed."
def test_pig_latin_with_consonant():
assert pig_latin("hello") == "ellohay", "Test with a word starting with a consonant failed."
def t... | [
{
"docstring": "Translates a single English word into Pig Latin.",
"function_declaration": "def pig_latin(word):",
"function_name": "pig_latin",
"parameter_list": "(word)"
},
{
"docstring": "Translates an entire English sentence into Pig Latin.",
"function_declaration": "def translate_se... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def pig_latin(word):\n \"\"\"\n Translates a single English word into Pig Latin.\n \n If a word begins with a consonant, move the first consonant or consonant cluster \n to the ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00087900",
"row_id": 87900,
"seed_ids": "['gemma-2-27b-it_182848']"
} | 0.605265 | Filter_87900 | I | [
"pig_latin",
"translate_sentence"
] | 2 | [
[
"translate_sentence",
"pig_latin"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26b55763e59886d0ce881c83586b3762611de5c1 | c42ea5d008065284721a32f3bb94290be77437d8 | |||
v1.0 | instruct | Filter | Filter_88716_I | How can I use Python to generate and evaluate a random set of equations with the following properties:
* **Linear:** The equations should be linear.
* **Two variables:** Each equation should involve two variables.
* **Integer coefficients:** The coefficients should be integers.
* **Solvable:** The system of equations ... | import random
from sympy import symbols, Eq, solve
def generate_random_coefficients():
"""Generates random integer coefficients a, b, c where -10 <= a, b, c <= 10"""
a = random.randint(-10, 10)
b = random.randint(-10, 10)
c = random.randint(-10, 10)
return a, b, c
def generate_system_of_equations(... | from solution import generate_system_of_equations, generate_equations_and_solve
from sympy import symbols, Eq, solve
def test_generate_system_of_equations():
a1, b1, c1, a2, b2, c2 = generate_system_of_equations()
determinant = a1 * b2 - a2 * b1
assert determinant != 0
def test_generate_equations_and_solv... | [
{
"docstring": "Generates random integer coefficients a, b, c where -10 <= a, b, c <= 10",
"function_declaration": "def generate_random_coefficients():",
"function_name": "generate_random_coefficients",
"parameter_list": "()"
},
{
"docstring": "Generates a system of two linear equations with... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import symbols, Eq, solve\n\ndef generate_solvable_equation(variables):\n \"\"\"Generates a system of linear equations with two variables that has a unique solutio... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00088716",
"row_id": 88716,
"seed_ids": "['gemma-2-27b-it_185353']"
} | 0.521859 | Filter_88716 | I | [
"generate_random_coefficients",
"generate_system_of_equations",
"generate_equations_and_solve"
] | 3 | [
[
"generate_equations_and_solve",
"generate_system_of_equations"
],
[
"generate_system_of_equations",
"generate_random_coefficients"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | cca45909af0aa7d71a40b024c1207e90d49b41f5 | 4f187189d799783ad755e76f00ed4967388ed85e | |||
v1.0 | instruct | Filter | Filter_88901_I | This is my final project for a Python course.
I need to create a program that plays a game of Tic-Tac-Toe against the user.
I have already implemented the game board and player input.
**Here's what I have so far:**
```python
def print_board(board):
print("-------------")
for row in board:
print("|", ... | def print_board(board):
print("-------------")
for row in board:
print("|", end="")
for cell in row:
print(f" {cell} |", end="")
print("\n-------------")
def get_player_move():
while True:
try:
row, col = map(int, input("Enter your move (row, column) ... | import pytest
from solution import check_win, check_draw, get_ai_move
def test_check_win_row():
board = [
["X", "X", "X"],
[" ", " ", " "],
[" ", " ", " "]
]
assert check_win(board, "X") == True
def test_check_win_column():
board = [
["X", " ", " "],
["X", " ", ... | [
{
"docstring": null,
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def get_player_move():",
"function_name": "get_player_move",
"parameter_list": "()"
},
{
"d... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef print_board(board):\n print(\"-------------\")\n for row in board:\n print(\"|\", end=\"\")\n for cell in row:\n print(f\" {cell} |\", end=\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00088901",
"row_id": 88901,
"seed_ids": "['gemma-2-27b-it_185875']"
} | 0.562701 | Filter_88901 | I | [
"print_board",
"get_player_move",
"check_win",
"check_draw",
"get_ai_move",
"tic_tac_toe"
] | 6 | [
[
"tic_tac_toe",
"check_draw"
],
[
"tic_tac_toe",
"check_win"
],
[
"tic_tac_toe",
"get_ai_move"
],
[
"tic_tac_toe",
"get_player_move"
],
[
"tic_tac_toe",
"print_board"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 99eac225e94b3a3c927bfaa1f0676b63f75a6e75 | 8fe1c68219576d96b8a84bb0836bbbe182449452 | |||
v1.0 | instruct | Filter | Filter_88992_I | These are the rules of the game:
1. Each player starts with 100 points.
2. A player rolls a single six-sided die.
3. The number rolled is added to the player's score.
4. If a player rolls a 6, they lose all their points and their turn ends.
5. A player can choose to hold their turn and keep their points.
6. Play contin... | import random
def roll_die():
"""Simulates rolling a six-sided die."""
return random.randint(1, 6)
def play_turn(player_name, current_score):
"""Plays a single turn for a player."""
print(f"{player_name}'s turn. Current score: {current_score}")
while True:
choice = input("Roll or hold? ").... | from solution import roll_die, play_turn
def test_roll_die():
for _ in range(100):
roll = roll_die()
assert 1 <= roll <= 6
def test_play_turn_hold(monkeypatch):
inputs = iter(['hold'])
monkeypatch.setattr('builtins.input', lambda _: next(inputs))
assert play_turn("Player 1", 50) == 50
... | [
{
"docstring": "Simulates rolling a six-sided die.",
"function_declaration": "def roll_die():",
"function_name": "roll_die",
"parameter_list": "()"
},
{
"docstring": "Plays a single turn for a player.",
"function_declaration": "def play_turn(player_name, current_score):",
"function_n... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_die():\n \"\"\"Simulates rolling a six-sided die.\"\"\"\n return random.randint(1, 6)\n\ndef play_turn(player_name, current_score):\n \"\"\"Plays a single tu... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00088992",
"row_id": 88992,
"seed_ids": "['gemma-2-27b-it_186140']"
} | 0.546295 | Filter_88992 | I | [
"roll_die",
"play_turn",
"game"
] | 3 | [
[
"game",
"play_turn"
],
[
"play_turn",
"roll_die"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4fdb52b265d3abafca742049f896968c132fbaee | b0477005747969016f0c17018a419898f2457dfa | |||
v1.0 | instruct | Prefill | Prefill_24_I | Write a function to calculate the maximum area of a rectangle in a 2D grid where all sides are parallel to the grid axes. The rectangle can be formed by selecting any two distinct points in the grid and extending them horizontally and vertically to form a rectangle. | def max_rectangle_area(grid):
"""
Given a 2D grid of points, calculate the maximum area of a rectangle
that can be formed with sides parallel to the grid axes.
:param grid: List[List[int]] - A 2D grid of points (1 represents a point, 0 represents empty space)
:return: int - The maximum area of ... | from solution import max_rectangle_area
def test_empty_grid():
assert max_rectangle_area([]) == 0
assert max_rectangle_area([[]]) == 0
def test_single_point():
assert max_rectangle_area([[1]]) == 1
assert max_rectangle_area([[0]]) == 0
def test_rectangle_area_all_ones():
grid = [
[1, 1],
... | [
{
"docstring": "Given a 2D grid of points, calculate the maximum area of a rectangle\nthat can be formed with sides parallel to the grid axes.\n\n:param grid: List[List[int]] - A 2D grid of points (1 represents a point, 0 represents empty space)\n:return: int - The maximum area of a rectangle that can be formed... | [
1,
1,
1,
0,
0,
1,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_area_rectangle(grid):\n \"\"\"\n Return the maximum area of a rectangle in a 2D grid.\n \"\"\"\n if not grid or not grid[0]:\n return 0\n\n rows = len(grid)\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00000024",
"row_id": 24,
"seed_ids": "['magpie_prefill_24']"
} | 0.720764 | Prefill_24 | I | [
"max_rectangle_area",
"largest_rectangle_area"
] | 2 | [
[
"max_rectangle_area",
"largest_rectangle_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | feb063307fe99ece1c973248f6339bc1923f8655 | 90ae853e7834730a3b2587e74d50242e994e2a57 | |||
v1.0 | instruct | Prefill | Prefill_229_I | Write a function to reverse a stack without using any additional data structures. You can only use recursive calls. How can I approach this problem? | # Function to insert an element at the bottom of a stack.
def insert_at_bottom(stack, item):
if not stack:
stack.append(item)
else:
top = stack.pop()
insert_at_bottom(stack, item)
stack.append(top)
# Recursive function to reverse the stack.
def reverse_stack(stack):
if stack... | from solution import reverse_stack
def test_reverse_empty_stack():
stack = []
reverse_stack(stack)
assert stack == []
def test_reverse_single_element_stack():
stack = [1]
reverse_stack(stack)
assert stack == [1]
def test_reverse_two_element_stack():
stack = [1, 2]
reverse_stack(stack)... | [
{
"docstring": null,
"function_declaration": "def insert_at_bottom(stack, item):",
"function_name": "insert_at_bottom",
"parameter_list": "(stack, item)"
},
{
"docstring": null,
"function_declaration": "def reverse_stack(stack):",
"function_name": "reverse_stack",
"parameter_list... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insert_at_bottom(stack, item):\n \"\"\"\n Helper function to insert an item at the bottom of a stack.\n \"\"\"\n if not stack:\n stack.append(item)\n else:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00000229",
"row_id": 229,
"seed_ids": "['magpie_prefill_229']"
} | 0.504302 | Prefill_229 | I | [
"insert_at_bottom",
"reverse_stack"
] | 2 | [
[
"reverse_stack",
"insert_at_bottom"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e23112becbe0c07c2ba7e154795e2b640c7b0ee4 | 987f3985aacc460e9ce59a308d1b35a1cba1381a | |||
v1.0 | instruct | Prefill | Prefill_446_I | Write a function to check if a given string is a palindrome and if its length is a prime number. A palindrome is a string that reads the same backward as forward. A prime number is a number greater than 1 that is divisible only by 1 and itself. | def is_palindrome(s):
"""
Check if the given string is a palindrome.
"""
return s == s[::-1]
def is_prime(n):
"""
Check if the given number is a prime number.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in rang... | from solution import is_palindrome, is_prime, is_palindrome_and_prime_length
def test_is_palindrome():
assert is_palindrome("racecar") == True
assert is_palindrome("hello") == False
assert is_palindrome("level") == True
assert is_palindrome("A") == True
assert is_palindrome("ab") == False
def test... | [
{
"docstring": "Check if the given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Check if the given number is a prime number.",
"function_declaration": "def is_prime(n):",
"funct... | [
0,
0,
1,
0,
1,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if the given number is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000446",
"row_id": 446,
"seed_ids": "['magpie_prefill_446']"
} | 0.683594 | Prefill_446 | I | [
"is_palindrome",
"is_prime",
"is_palindrome_and_prime_length"
] | 3 | [
[
"is_palindrome_and_prime_length",
"is_palindrome"
],
[
"is_palindrome_and_prime_length",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 678f62693d988df13aef6acd171ea69238a85ca1 | ca81529794a624019437d68df90faf41a1c12907 | |||
v1.0 | instruct | Prefill | Prefill_479_I | Write a function to find the sum of all prime numbers within a given range [start, end] inclusively in Python. | def is_prime(n):
"""
Helper function to 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 +... | from solution import sum_of_primes_in_range
def test_sum_of_primes_in_small_range():
assert sum_of_primes_in_range(1, 10) == 17 # primes are 2, 3, 5, 7
def test_sum_of_primes_with_single_prime():
assert sum_of_primes_in_range(11, 11) == 11 # is a prime
def test_sum_of_primes_no_primes():
assert sum_of_... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers within the range [start, end] inclusively.",
"function_declaration": "... | [
1,
1,
0,
1,
1,
0,
1,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a nuimber is a prime number.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00000479",
"row_id": 479,
"seed_ids": "['magpie_prefill_479']"
} | 0.689692 | Prefill_479 | I | [
"is_prime",
"sum_of_primes_in_range"
] | 2 | [
[
"sum_of_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a5653704248ace2a4834c903a19ae10ad6e95221 | 223a67004c730cbf9c82064b87c70108a5161a1a | |||
v1.0 | instruct | Prefill | Prefill_493_I | Write a function to calculate the factorial of a number \( n \) using event-driven programming in Python. Fibonacci is an event-driven process, and we can use a similar concept here. The function will take an input number \( n \) and calculate the factorial of \( n! \). | import asyncio
class FactorialEvent:
def __init__(self):
self.subscribers = []
def register(self, function):
self.subscribers.append(function)
async def notify(self, n, result):
for subscriber in self.subscribers:
await subscriber(n, result)
class FactorialCalculator:... | from solution import factorial
def test_factorial_of_zero():
assert factorial(0) == 1
def test_factorial_of_one():
assert factorial(1) == 1
def test_factorial_of_five():
assert factorial(5) == 120
def test_factorial_of_six():
assert factorial(6) == 720
def test_factorial_of_ten():
assert factor... | [] | [
1,
1,
1,
0,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def factorial_event(n):\n if n == 0:\n return 1\n else:\n event_loop = asyncio.get_event_loop()\n return n * await event_loop.create_task(fa... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00000493",
"row_id": 493,
"seed_ids": "['magpie_prefill_493']"
} | 0.582857 | Prefill_493 | I | [
"main",
"factorial"
] | 2 | [
[
"factorial",
"main"
]
] | 1 | [] | false | [
"FactorialEvent",
"FactorialCalculator"
] | true | pytest | true | [] | true | 473827c2795d1dd3ab3cd6df26df71ef2b603ecb | 1a6e4fcc25f9f2c88bbc38b9de5261912dbb2a47 | |||
v1.0 | instruct | Prefill | Prefill_515_I | Write a function to delete a node with a given key in a binary search tree (BST). Please provide a detailed explanation of your solution and handle all possible edge cases. | class TreeNode:
"""
A node in a binary search tree.
"""
def __init__(self, key=0, left=None, right=None):
self.key = key
self.left = left
self.right = right
def deleteNode(root, key):
"""
Deletes a node with the given key in a BST and returns the new root.
"""
... | from solution import TreeNode, deleteNode, getMin
def bst_to_list(root):
"""
Converts a BST to a sorted list of keys.
"""
if not root:
return []
return bst_to_list(root.left) + [root.key] + bst_to_list(root.right)
def test_delete_node_not_present():
root = TreeNode(4, TreeNode(2, TreeN... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key=0, left=None, right=None):\n self.key = key\n self.left = left\n self.right = right\n\ndef delete_node(root, key):\n if not... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00000515",
"row_id": 515,
"seed_ids": "['magpie_prefill_515']"
} | 0.471474 | Prefill_515 | I | [
"deleteNode",
"getMin"
] | 2 | [
[
"deleteNode",
"getMin"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | da02c1a1073d3cb4225be1b29f37f28bb6d7e6ce | 7280438579d347063cc7d9a609d15f360eaf698d | |||
v1.0 | instruct | Prefill | Prefill_628_I | Write a function to create a binary search tree (BST) from an array of integers. The function should take an array of integers as input and return the root of the BST. | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
... | from solution import TreeNode, create_bst_from_array
def inorder_traversal(root):
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) if root else []
def test_empty_array():
assert create_bst_from_array([]) is None
def test_single_element_array():
root = create_bst_from_array... | [] | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef insert_into_bst(root, value):... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00000628",
"row_id": 628,
"seed_ids": "['magpie_prefill_628']"
} | 0.660152 | Prefill_628 | I | [
"insert_into_bst",
"create_bst_from_array"
] | 2 | [
[
"create_bst_from_array",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9ae886836326ff3fbcffe7577680a7dd4be33735 | 6ca91d4cbf7cfde54b2ef0ce5246455b8cfa6295 | |||
v1.0 | instruct | Prefill | Prefill_632_I | Write a function to find the factorial of a given number using recursion. Also, ensure to handle potential stack overflow errors that might occur for large inputs. Discuss optimization techniques to prevent stack overflows in recursive functions. | def factorial(n):
"""
Returns the factorial of a given number using recursion.
Handles ValueError for negative inputs.
"""
if n < 0:
raise ValueError("Input must be a non-negative integer.")
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
def safe_factorial(n):
... | from solution import factorial, safe_factorial
def test_factorial_regular_cases():
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(5) == 120
def test_factorial_negative_input():
try:
factorial(-1)
except ValueError as e:
assert str(e) == "Input must be a non-nega... | [
{
"docstring": "Returns the factorial of a given number using recursion.\nHandles ValueError for negative inputs.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Returns the factorial of a given number using recursion wi... | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n Returns the factorial of n using recursion. Raises ValueError for negative inputs.\n \"\"\"\n if n < 0:\n raise ValueError(\"Factorial is not d... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00000632",
"row_id": 632,
"seed_ids": "['magpie_prefill_632']"
} | 0.570738 | Prefill_632 | I | [
"factorial",
"safe_factorial"
] | 2 | [
[
"safe_factorial",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1840dd2bc22f199563a01dece0931caeb0c40be8 | 28557f6d61d6d68f0a17ce1b6f549e829ee52e7f | |||
v1.0 | instruct | Prefill | Prefill_636_I | Write a function to find all the prime divisors of a given number and return them in a sorted list. A prime divisor of a number is a divisor that is a prime number. | def is_prime(num):
"""
Helper function to check whether a number is prime.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num ** 0.5) + 1, 2):
if num % i == 0:
return False
return True... | from solution import prime_divisors
def test_prime_divisors_positive_number():
assert prime_divisors(28) == [2, 7]
assert prime_divisors(30) == [2, 3, 5]
assert prime_divisors(84) == [2, 3, 7]
def test_prime_divisors_prime_number():
assert prime_divisors(13) == [13]
assert prime_divisors(2) == [2]... | [
{
"docstring": "Helper function to check whether a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a sorted list of all prime divisors of n.",
"function_declaration": "def prime_divisors(n)... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_prime_divisors(n):\n \"\"\"\n Returns a sorted list of prime divisors of the given number n.\n \"\"\"\n def is_prime(k):\n if k <= 1:\n return False\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00000636",
"row_id": 636,
"seed_ids": "['magpie_prefill_636']"
} | 0.663451 | Prefill_636 | I | [
"is_prime",
"prime_divisors"
] | 2 | [
[
"prime_divisors",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 42344b4d1ef4c83d98fbdafbb8941b1f13d341cc | 1e9341c082aace06c95dbdfa25e48255acc55cc5 | |||
v1.0 | instruct | Prefill | Prefill_812_I | Write a function to compare two arrays and return the index of the first occurrence of common elements between the two arrays. If no common elements are found, return -1. Compare the arrays using binary search for efficiency. | def binary_search(arr, x):
"""
A helper function to perform binary search on a sorted array.
:param arr: The sorted array in which to search for the element x.
:param x: The element to search for in the array.
:return: True if the element is found, False otherwise.
"""
low, high = 0, le... | from solution import compare_arrays
def test_no_common_element():
assert compare_arrays([1, 2, 3], [4, 5, 6]) == -1
def test_common_element_at_start():
assert compare_arrays([1, 2, 3], [1, 5, 6]) == 0
def test_common_element_in_middle():
assert compare_arrays([4, 2, 3], [1, 5, 2]) == 1
def test_common_e... | [
{
"docstring": "A helper function to perform binary search on a sorted array.\n\n:param arr: The sorted array in which to search for the element x.\n:param x: The element to search for in the array.\n:return: True if the element is found, False otherwise.",
"function_declaration": "def binary_search(arr, x)... | [
1,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search(arr, x):\n \"\"\"\n Helper function to perform binary search on a sorted array.\n Returns the index of x in arr if present, else returns -1.\n \"\"\"\n left, ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00000812",
"row_id": 812,
"seed_ids": "['magpie_prefill_812']"
} | 0.648372 | Prefill_812 | I | [
"binary_search",
"compare_arrays"
] | 2 | [
[
"compare_arrays",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c5bf25a1774eeb5b3517f1b42cdad503a5d35cbb | 79b2cd0d822f97b8811c074f68112cc90618fc6c | |||
v1.0 | instruct | Prefill | Prefill_870_I | Write a function to solve the puzzle of Lights Out on a 3x3 grid. The goal is to turn off all the lights by toggling them or the lights directly above, below, to the left, and to the right of each button. Assume all lights are initially on. | def toggle(grid, r, c):
"""
Toggle the light at (r, c) and its neighbors.
"""
directions = [(0, 0), (0, 1), (1, 0), (0, -1), (-1, 0)]
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < 3 and 0 <= nc < 3:
grid[nr][nc] = 1 - grid[nr][nc] # Toggles the light
de... | from solution import solve_lights_out, toggle
def setup_all_lights_on():
return [[1 for _ in range(3)] for _ in range(3)]
def test_toggle_function():
grid = setup_all_lights_on()
toggle(grid, 1, 1)
assert grid == [
[1, 0, 1],
[0, 0, 0],
[1, 0, 1],
]
def test_solve_lights_o... | [
{
"docstring": "Toggle the light at (r, c) and its neighbors.",
"function_declaration": "def toggle(grid, r, c):",
"function_name": "toggle",
"parameter_list": "(grid, r, c)"
},
{
"docstring": "Solve the Lights Out puzzle on a 3x3 grid. The function assumes all lights are initially on.\nEach... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def toggle_lights(grid, x, y):\n \"\"\"\n Toggles the light at (x, y) and its neighbors.\n \"\"\"\n def toggle(grid, i, j):\n if 0 <= i < 3 and 0 <= j < 3:\n gri... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00000870",
"row_id": 870,
"seed_ids": "['magpie_prefill_870']"
} | 0.414598 | Prefill_870 | I | [
"toggle",
"solve_lights_out"
] | 2 | [
[
"solve_lights_out",
"toggle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71b4055a9cdd54245b818334ba92b3cc0f4b52bd | a8897c5c7b224493a7e5495e512587b454321b06 | |||
v1.0 | instruct | Prefill | Prefill_881_I | Write a function to sort an array in-place using the QuickSort algorithm. | def quicksort(arr, low, high):
"""
Sorts an array in-place using the QuickSort algorithm.
"""
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
def partition(arr, low, high):
"""
Helper function to partition the array on t... | from solution import quicksort
def test_quicksort_already_sorted():
arr = [1, 2, 3, 4, 5]
quicksort(arr, 0, len(arr)-1)
assert arr == [1, 2, 3, 4, 5]
def test_quicksort_reverse_sorted():
arr = [5, 4, 3, 2, 1]
quicksort(arr, 0, len(arr)-1)
assert arr == [1, 2, 3, 4, 5]
def test_quicksort_unsor... | [
{
"docstring": "Sorts an array in-place using the QuickSort algorithm.",
"function_declaration": "def quicksort(arr, low, high):",
"function_name": "quicksort",
"parameter_list": "(arr, low, high)"
},
{
"docstring": "Helper function to partition the array on the pivot element.",
"functio... | [
1,
1,
1,
1,
0,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quicksort(arr, low, high):\n \"\"\"\n Sorts the array in place using the QuickSort algorithm.\n \n Parameters:\n arr (list): The list to be sorted.\n low (int): The star... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00000881",
"row_id": 881,
"seed_ids": "['magpie_prefill_881']"
} | 0.725079 | Prefill_881 | I | [
"quicksort",
"partition"
] | 2 | [
[
"quicksort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5df7d8508c3edfc076967c814c7b186cdc9f07a2 | 9a91b17900892e318c22529ea73b0c4fe8a90c75 | |||
v1.0 | instruct | Prefill | Prefill_899_I | Write a function to reverse a stack using recursion. A stack is a LIFO data structure. How can you reverse it without using any additional data structure? | def reverse_stack(stack):
"""
Reverses the given stack using recursion.
"""
# base case: if the stack is empty, return
if not stack:
return
# remove the top item
top = stack.pop()
# reverse the stack recursively
reverse_stack(stack)
# insert the top item at... | from solution import reverse_stack, insert_at_bottom
def test_reverse_stack_empty():
stack = []
reverse_stack(stack)
assert stack == []
def test_reverse_stack_single_element():
stack = [1]
reverse_stack(stack)
assert stack == [1]
def test_reverse_stack_two_elements():
stack = [1, 2]
r... | [
{
"docstring": "Reverses the given stack using recursion.",
"function_declaration": "def reverse_stack(stack):",
"function_name": "reverse_stack",
"parameter_list": "(stack)"
},
{
"docstring": "Inserts an item at the bottom of the given stack using recursion.",
"function_declaration": "d... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_stack(stack):\n \"\"\"\n Reverses a stack using recursion.\n \n :param stack: List representing the stack to be reversed\n \"\"\"\n if not stack:\n return... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00000899",
"row_id": 899,
"seed_ids": "['magpie_prefill_899']"
} | 0.527008 | Prefill_899 | I | [
"reverse_stack",
"insert_at_bottom"
] | 2 | [
[
"reverse_stack",
"insert_at_bottom"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 79b57ce264af1bdde0e64964ca18b14098a46649 | 6452604eda3f75415a3a83671b894184531c05f7 | |||
v1.0 | instruct | Prefill | Prefill_935_I | Write a function to identify all prime numbers within a given range. The range will be provided as two parameters: `start` (inclusive) and `end` (exclusive). The function should return a list of all prime numbers within the range, sorted in ascending order. | def is_prime(n):
"""
Checks if a number n 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 T... | from solution import primes_in_range
def test_primes_in_empty_range():
assert primes_in_range(10, 10) == []
def test_primes_in_single_element_range():
assert primes_in_range(11, 12) == [11]
assert primes_in_range(15, 16) == []
def test_primes_in_small_range():
assert primes_in_range(10, 20) == [11, 1... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers in the range [start, end).",
"function_declaration": "def primes_in_range(start, end):",
... | [
0,
1,
1,
1,
0,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number n is a prime number.\n \"\"\"\n if n <= 1: return False\n if n <= 3: return True\n if n % 2 == 0 or n % 3 ==... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00000935",
"row_id": 935,
"seed_ids": "['magpie_prefill_935']"
} | 0.633837 | Prefill_935 | I | [
"is_prime",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fb13396cf98e51de27506df9d23e223921119f9e | 84a470325e3d26f7a5b23e8aa2b0a16cd3f99443 | |||
v1.0 | instruct | Prefill | Prefill_971_I | Write a function to find all prime numbers up to a given number using the Sieve of Eratosthenes algorithm. Then, modify this function to find all prime numbers within a given range (start and end). | def sieve_of_eratosthenes(n):
"""
Returns a list of all prime numbers up to n using the Sieve of Eratosthenes algorithm.
"""
if n < 2:
return []
primes = [True] * (n + 1)
primes[0] = primes[1] = False
for start in range(2, int(n**0.5) + 1):
if primes[start]:
for... | from solution import sieve_of_eratosthenes, primes_in_range
def test_sieve_of_eratosthenes():
assert sieve_of_eratosthenes(1) == []
assert sieve_of_eratosthenes(2) == [2]
assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]
assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]
assert sieve_o... | [
{
"docstring": "Returns a list of all prime numbers up to n using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers within th... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sieve_of_eratosthenes(n):\n \"\"\"\n Finds all prime numbers up to a given number n using the Sieve of Eratosthenes algorithm.\n \n Parameters:\n n (int): The upper boundar... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00000971",
"row_id": 971,
"seed_ids": "['magpie_prefill_971']"
} | 0.61542 | Prefill_971 | I | [
"sieve_of_eratosthenes",
"primes_in_range"
] | 2 | [
[
"primes_in_range",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f07e38f09343ff05229d1667ffe1a59f8fa5c2f4 | 4b6006186a51857f2d0c1e6e857f9aea90506926 | |||
v1.0 | instruct | Prefill | Prefill_1012_I | Write a function to check if a binary tree is a mirror of itself (i.e., a palindrome). A binary tree is a palindrome if the sequence of values from the tree when read from left to right and from right to left are identical. | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_mirror_tree(root):
"""
Returns True if the binary tree is a mirror of itself (i.e., a palindrome).
"""
if not root:
return True
return is_mirror(root.left, root.right)
... | from solution import TreeNode, is_mirror_tree
def test_symmetric_tree():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
root.right.right = TreeNode(3)
assert is_mirror_tree... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_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 is_mirror(left, right):\n if not... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00001012",
"row_id": 1012,
"seed_ids": "['magpie_prefill_1012']"
} | 0.687214 | Prefill_1012 | I | [
"is_mirror_tree",
"is_mirror"
] | 2 | [
[
"is_mirror_tree",
"is_mirror"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f1f1bc646da7f479f8c56daf8a7dc68cf252129b | e7bdfccdced99f0d82c8223f24b8ca3f381ebd96 | |||
v1.0 | instruct | Prefill | Prefill_1104_I | Write a function to determine whether a number is Fibonacci number or not. A Fibonacci number is one that appears in the Fibonacci sequence, where each number after the first two (0 and 1) is the sum of the two preceding ones. Additionally, check for the fact that a Fibonacci number square is also a Fibonacci number. | def is_fibonacci_number(num):
"""
Check if a number is a Fibonacci number.
"""
def is_perfect_square(x):
s = int(x**0.5)
return s*s == x
if num < 0:
return False
# A number is a Fibonacci number if and only if one (or both) of (5*n^2 + 4) or (5*n^2 - 4) is a per... | from solution import is_fibonacci_number, is_fibonacci_square
def test_is_fibonacci_number():
assert is_fibonacci_number(0) == True
assert is_fibonacci_number(1) == True
assert is_fibonacci_number(2) == True
assert is_fibonacci_number(3) == True
assert is_fibonacci_number(5) == True
assert is_f... | [
{
"docstring": "Check if a number is a Fibonacci number.",
"function_declaration": "def is_fibonacci_number(num):",
"function_name": "is_fibonacci_number",
"parameter_list": "(num)"
},
{
"docstring": "Check if a Fibonacci number's square is also a Fibonacci number.",
"function_declaratio... | [
0,
0,
0,
0,
1,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_fibonacci(n):\n \"\"\"\n Returns True if n is a Fibonacci number, False otherwise.\n \"\"\"\n if n < 0:\n return False\n if n == 0:\n return... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00001104",
"row_id": 1104,
"seed_ids": "['magpie_prefill_1104']"
} | 0.673717 | Prefill_1104 | I | [
"is_fibonacci_number",
"is_fibonacci_square"
] | 2 | [
[
"is_fibonacci_square",
"is_fibonacci_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d91371279c6428b8ab6e59c78369e4f1a6801b08 | de5802a1f2ba980eec1529acfea534d6a9d8a893 | |||
v1.0 | instruct | Prefill | Prefill_1139_I | Write a function to sort an array of numbers in ascending order using the radix sort algorithm. The function should take an array as an argument and return the sorted array. Additionally, describe the time complexity of the radix sort algorithm. | def radix_sort(arr):
"""
Sorts an array of integers in ascending order using the radix sort algorithm.
"""
if not arr:
return []
# Find the maximum number to figure out the number of digits
max_num = max(arr)
# Implement counting sort for each digit. Exponent grows as 10^0, 10^1, 1... | from solution import radix_sort
def test_radix_sort_empty_array():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_sorted_array():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_reverse_sorted_array():
ass... | [
{
"docstring": "Sorts an array of integers in ascending order using the radix sort algorithm.",
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
},
{
"docstring": "A helper function to perform counting sort based on digit represented by... | [
0,
0,
1,
1,
1,
1,
0,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n for i in range(n):\n index = arr[i] // exp\n count[index % 10] += 1\n\n for ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00001139",
"row_id": 1139,
"seed_ids": "['magpie_prefill_1139']"
} | 0.670298 | Prefill_1139 | I | [
"radix_sort",
"counting_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f4d90fbff4dbab07e0ef6353a8b4e3dca178898 | 0363483a8af7bd170e1a5037b5ef56a88673360e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.