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
complete
Docs
Docs: Python310_21812_C
def create_capsule(pointer: int, name: str, destructor: callable = None) -> dict: """ Create a PyCapsule encapsulating the pointer. Parameters: pointer (int): An integer representing the memory address (simulated pointer). name (str): A string name for the capsule. destructor (callable, optiona...
def create_capsule(pointer: int, name: str, destructor: callable = None) -> dict: """ Create a PyCapsule encapsulating the pointer. Parameters: pointer (int): An integer representing the memory address (simulated pointer). name (str): A string name for the capsule. destructor (callable, optiona...
from solution import create_capsule, is_capsule_valid, get_capsule_pointer, set_capsule_name def test_create_capsule(): capsule = create_capsule(123456789, "module.attribute") assert capsule["pointer"] == 123456789 assert capsule["name"] == "module.attribute" assert capsule["destructor"] is None def t...
[ { "docstring": "Create a PyCapsule encapsulating the pointer.\n\nParameters:\npointer (int): An integer representing the memory address (simulated pointer).\nname (str): A string name for the capsule.\ndestructor (callable, optional): A destructor function to be called upon capsule deletion.\n\nReturns:\ndict: ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_capsule(pointer: int, name: str, destructor: callable = None) -> dict:\n \"\"\"\n Create a PyCapsule encapsulating the pointer.\n\n Parameters:\n ...
trial_gpt4o_2
{ "original_instruction": "### PyCapsule Manipulation in Python\n\nYou are provided with several C API functions to create and manipulate PyCapsule objects in Python. Implement the following functions in Python that would simulate the behavior of some of these C API functions while maintaining the encapsulated pointe...
0.352512
Docs: Python310_21812
C
[ "create_capsule", "is_capsule_valid", "get_capsule_pointer", "set_capsule_name" ]
4
[ [ "get_capsule_pointer", "is_capsule_valid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11bb9f98f836ae4d15b1c4cc0f48518624734c50
367a4ddfcaac6e86e7c6a7346c54658138d29578
v1.0
complete
Docs
Docs: Python310_27567_C
def mycustomobject_initialization(id: int, flag: bool): """ Initialize a custom object with given `id` and `flag` attributes. >>> mycustomobject_initialization(10, True) id = 10, flag = True, refcount = 1 """ def is_custom_type(obj: 'MyCustomObject') -> int: """ Checks if the object is of MyCustomO...
# This is a conceptual example of the solution approach from ctypes import Structure, c_int, c_bool, POINTER, byref class MyCustomObject(Structure): _fields_ = [("refcount", c_int), ("id", c_int), ("flag", c_bool)] def __init__(self, id, flag): self.refcount = 1 ...
def test_mycustomobject_initialization(): obj = MyCustomObject(id=10, flag=True) assert obj.id == 10 assert obj.flag is True assert obj.refcount == 1 def test_is_custom_type(): obj = MyCustomObject(id=10, flag=True) assert is_custom_type(obj) == 1 assert is_custom_type(None) == 0 assert...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "c\n#include <Python.h>\n\n// Define the custom object structure\ntypedef struct {\n PyObject_HEAD\n int id;\n int flag; // Use int to represent boolean (C does...
trial_gpt4o_1
{ "original_instruction": "#### Objective\n\nYou are to implement a custom Python object type in C compatible with the Python C API containing the following features:\n1. A reference count for memory management.\n2. Type identification and attribute manipulation.\n3. Function that checks if the object is of a specifi...
0.42499
Docs: Python310_27567
C
[ "is_custom_type", "increment_ref", "decrement_ref", "is_none", "is_flag_true" ]
5
[ [ "decrement_ref", "is_custom_type" ], [ "increment_ref", "is_custom_type" ], [ "is_flag_true", "is_custom_type" ] ]
3
[]
false
[ "MyCustomObject" ]
true
pytest
false
[]
true
6e05ffd862e35c9d6dcac14010998f4d0429a45d
4efbb9d07668e15011446dc4c42814c3eba3ac8f
v1.0
complete
Docs
Docs: Scikit_33605_C
import numpy as np from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import HashingVectorizer def stream_documents(file_path): """ Generator function to stream documents from a file. Parameters: - file_path (str): Path to the file containing the dataset. ...
import numpy as np from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import HashingVectorizer def stream_documents(file_path): """ Generator function to stream documents from a file. Parameters: - file_path (str): Path to the file containing the dataset. ...
import pytest from solution import stream_documents, incremental_learning import os def test_stream_documents(tmp_path): test_file = tmp_path / "test_file.txt" test_content = "document1\tclass1\ndocument2\tclass2\ndocument3\tclass1" test_file.write_text(test_content) streamed_docs = list(stream_docume...
[ { "docstring": "Generator function to stream documents from a file.\n\nParameters:\n- file_path (str): Path to the file containing the dataset.\n\nYields:\n- document (str), category (str): A single document and its category from the file.", "function_declaration": "def stream_documents(file_path):", "f...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.feature_extraction.text import HashingVectorizer\n\ndef stream_documents(file_path):\n ...
trial_gpt4o_8
{ "original_instruction": "### Out-of-Core Learning with scikit-learn\n\n**Objective**: Implement an out-of-core learning system using scikit-learn that processes data too large to fit into memory, by performing incremental learning with streaming instances and feature extraction.\n\n**Problem Statement**:\n\nYou are...
0.47492
Docs: Scikit_33605
C
[ "stream_documents", "incremental_learning" ]
2
[ [ "incremental_learning", "stream_documents" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
95a8d3065959d1f3e645c4fbf307720e767ab8e3
5f2bd5db58c4d76c5db5ccf560f00ed0699cbbe4
v1.0
complete
Docs
Docs: Python310_34748_C
import asyncio import random from typing import List, Dict async def fetch_content(url: str) -> str: """ Simulates fetching content from a URL by introducing a random network delay. Parameters: url (str): The URL to fetch content from. Returns: str: Simulated content of the URL. ...
import asyncio import random from typing import List, Dict async def fetch_content(url: str) -> str: """ Simulates fetching content from a URL by introducing a random network delay. """ # Simulate network delay await asyncio.sleep(random.randint(1, 3)) return f"Content of {url}" async def fetc...
import asyncio import pytest from solution import fetch_content, fetch_all_contents @pytest.mark.asyncio async def test_fetch_content(): url = "http://example.com/page1" result = await fetch_content(url) assert result == f"Content of {url}" @pytest.mark.asyncio async def test_fetch_all_contents_success():...
[]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List, Dict\n\nasync def fetch_content(url: str) -> str:\n \"\"\"\n Simulates fetching content from a URL by slee...
trial_gpt4o_7
{ "original_instruction": "#### **Title**: Implementing and Managing Asynchronous Tasks with `asyncio` in Python\n\n#### **Objective**:\nTo assess the student's ability to use the `asyncio` library in Python to manage multiple asynchronous tasks, interact with the event loop, and handle task results efficiently.\n\n#...
0.600101
Docs: Python310_34748
C
[ "fetch_content", "fetch_all_contents" ]
2
[ [ "fetch_all_contents", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ebad4d04a701491fda6e77d8a4ebe47bb31f3a0
2a40403b0391fa6f5a3bce982d37a159629d6103
v1.0
complete
Docs
Docs: Pytorch_34752_C
import torch from typing import Tuple def lu_decomposition(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Perform the LU Decomposition of a square matrix A (n x n). Args: A (torch.Tensor): Input square matrix of shape (n, n). Returns: Tuple[torch.Tensor, torch.Tensor]: A tuple containi...
import torch from typing import Tuple def lu_decomposition(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Perform LU Decomposition of matrix A using simple Doolittle's method. Args: A (torch.Tensor): A square matrix of shape (n, n). Returns: Tuple[torch.Tensor, torch.Tenso...
import torch from solution import lu_decomposition, solve_system_lu, inverse_qr def test_lu_decomposition(): A = torch.tensor([[3.0, 2.0], [1.0, 4.0]]) L, U = lu_decomposition(A) # Reconstruct A from L and U A_reconstructed = torch.matmul(L, U) assert torch.allclose(A, A_reconstructed, atol=1e-4) ...
[ { "docstring": "Perform LU Decomposition of matrix A using simple Doolittle's method.\n\nArgs:\nA (torch.Tensor): A square matrix of shape (n, n).\n\nReturns:\nTuple[torch.Tensor, torch.Tensor]: Lower and Upper triangular matrices L and U.", "function_declaration": "def lu_decomposition(A):", "function_...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import torch\nfrom typing import Tuple\n\ndef lu_decomposition(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Performs...
trial_gpt4o_8
{ "original_instruction": "**Title: Solving Linear Systems and Matrix Decompositions with PyTorch**\n\n#### Objective:\nYou are required to implement several functions to demonstrate your understanding of PyTorch's linear algebra capabilities, focusing on solving linear systems, and performing matrix decompositions a...
0.533991
Docs: Pytorch_34752
C
[ "lu_decomposition", "solve_system_lu", "inverse_qr" ]
3
[ [ "solve_system_lu", "lu_decomposition" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
d7f5dbdf42e05782235ea40f34d2bd001e951d3c
a8f847aec7c93324c243535e1abfd090bf16e17d
v1.0
complete
Docs
Docs: Python310_37755_C
import aifc def process_aiff(input_filename: str, output_filename: str): """ Open an AIFF file, modify its frame rate and convert it to stereo if necessary, and save it to a new file. Args: input_filename (str): The input AIFF filename. output_filename (str): The output AIFF filename. """ # Ope...
import aifc def process_aiff(input_filename: str, output_filename: str): # Open the input file and read properties with aifc.open(input_filename, 'r') as input_file: nchannels = input_file.getnchannels() sampwidth = input_file.getsampwidth() framerate = input_file.getframerate() ...
import aifc import os import pytest def create_test_aiff(filename, channels, sampwidth, framerate, frames): with aifc.open(filename, 'w') as f: f.setnchannels(channels) f.setsampwidth(sampwidth) f.setframerate(framerate) f.writeframes(frames) def read_aiff_properties(filename): ...
[ { "docstring": null, "function_declaration": "def process_aiff(input_filename, output_filename):", "function_name": "process_aiff", "parameter_list": "(input_filename, output_filename)" }, { "docstring": null, "function_declaration": "def convert_to_stereo(frames, nchannels, sampwidth, n...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aifc\n\ndef process_aiff(input_filename: str, output_filename: str):\n # Open the input file and read properties\n with aifc.open(input_filename, 'r') as i...
trial_gpt4o_3
{ "original_instruction": "Manipulating Audio Files with `aifc`\n\n#### Objective:\nWrite a Python script using the `aifc` module to manipulate an AIFF file. Your task is to:\n1. Open an AIFF file named `input.aiff` and read its properties.\n2. Create a stereo (2 channels) version of the same audio with a modified fr...
0.411576
Docs: Python310_37755
C
[ "process_aiff", "convert_to_stereo" ]
2
[ [ "process_aiff", "convert_to_stereo" ] ]
1
[]
false
[]
false
pytest
false
[]
true
606036a9e34b4985d536e18219f05020a1163dc1
add2353dba83196244e15ee4bebf73873d3b1fbd
v1.0
complete
Docs
Docs: Python310_39147_C
import base64 def secure_data_transmission(data: str) -> str: """ Safely encode a string into base64 format. Args: data (str): The data to be encoded Returns: str: Base64 encoded string >>> secure_data_transmission("sensitive data") 'c2Vuc2l0aXZlIGRhdGE=' >>> ...
import base64 def secure_data_transmission(data: str) -> str: """ Encodes the input string data into base64 format. Args: data (str): The data to be encoded Returns: str: Base64 encoded string """ # Convert string data to bytes bytes_data = data.encode('utf-8') ...
from solution import secure_data_transmission, secure_data_storage import base64 import os def test_secure_data_transmission(): data = "sensitive data" encoded_data = secure_data_transmission(data) expected_encoded_data = base64.b64encode(data.encode('utf-8')).decode('utf-8') assert encoded_data == exp...
[ { "docstring": "Encodes the input string data into base64 format.\n\nArgs:\n data (str): The data to be encoded\n\nReturns:\n str: Base64 encoded string", "function_declaration": "def secure_data_transmission(data):", "function_name": "secure_data_transmission", "parameter_list": "(data)" },...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import base64\n\ndef secure_data_transmission(data: str) -> str:\n \"\"\"\n Safely encodes a string into base64 format.\n\n Args:\n data (str): The data to ...
trial_gpt4o_9
{ "original_instruction": "### Secure Data Transmission and Storage\n\nIn this task, you are required to implement two functions in Python to demonstrate secure data handling practices. Your implementation should consider the outlined security considerations and aim to mitigate potential vulnerabilities.\n\n#### Func...
0.656042
Docs: Python310_39147
C
[ "secure_data_transmission", "secure_data_storage" ]
2
[ [ "secure_data_storage", "secure_data_transmission" ] ]
1
[]
false
[]
false
pytest
true
[]
true
77ec643c7db7bab41094aec5be62bb48df35aca4
e540c7635b0acf7fa31e0fceb06c61b1e39e04f6
v1.0
complete
Docs
Docs: Scikit_40218_C
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.covariance import (EmpiricalCovariance, ShrunkCovariance, LedoitWolf, OAS, GraphicalLasso, MinCovDet) def load_data(file_path): """ Loads the dataset from a given CSV file p...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.covariance import (EmpiricalCovariance, ShrunkCovariance, LedoitWolf, OAS, GraphicalLasso, MinCovDet) def load_data(file_path): """ Loads the dataset from a given CSV file p...
import numpy as np import pandas as pd from solution import load_data, compute_covariances, mean_squared_error, compare_covariances, visualize_covariances def test_load_data(tmp_path): data_csv = tmp_path / 'data.csv' data_csv.write_text("A,B,C,D,E\n1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n16,17,18,19,20\n21,22,...
[ { "docstring": "Loads the dataset from a given CSV file path.\n\nParameters:\n- file_path: str, path to the CSV file\n\nReturns:\n- DataFrame containing the loaded data", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.covariance import (EmpiricalCovariance, ShrunkCovariance,\...
trial_gpt4o_2
{ "original_instruction": "### Covariance Estimation with scikit-learn\n\n#### Background\nCovariance estimation is crucial in statistics and machine learning, often required for analyzing the relationships between various features of a dataset. The `sklearn.covariance` module in scikit-learn provides several methods...
0.744997
Docs: Scikit_40218
C
[ "load_data", "compute_covariances", "mean_squared_error", "compare_covariances", "visualize_covariances", "main" ]
6
[ [ "compare_covariances", "mean_squared_error" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "seaborn", "sklearn" ]
false
496c655058e698ca4bbff4cd05ba06955d4515a0
c3a9c3595f0c133e87238d31e140a3e966428491
v1.0
complete
Docs
Docs: Python310_40216_C
import quopri def encode_text(text: str, quotetabs: bool, header: bool = False) -> str: """ Encodes a string using quoted-printable encoding. Args: text (str): The string to be encoded. quotetabs (bool): A flag to indicate whether to encode embedded spaces and tabs. header (bool): A flag t...
import quopri def encode_text(text, quotetabs, header=False): """ Returns the quoted-printable encoded string. :param text: str :param quotetabs: bool :param header: bool :return: str """ encoded_bytes = quopri.encodestring(text.encode('utf-8'), quotetabs, header=header) return...
import os import pytest from solution import encode_text, decode_text, encode_file, decode_file def test_encode_text(): assert encode_text("Hello World! This is a test.", quotetabs=True) == ( "Hello=20World!=20This=20is=20a=20test." ) assert encode_text("A test with\ttab", quotetabs=True) == "A=20t...
[ { "docstring": "Returns the quoted-printable encoded string.\n\n:param text: str\n:param quotetabs: bool\n:param header: bool\n:return: str", "function_declaration": "def encode_text(text, quotetabs, header=False):", "function_name": "encode_text", "parameter_list": "(text, quotetabs, header=False)"...
[ 0, 1, 0, 1, 1, 1, 1, 1, 0 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import quopri\n\ndef encode_text(text, quotetabs=False, header=False):\n \"\"\"\n Encodes a given text using quoted-printable encoding.\n \n Parameters:\n ...
trial_gpt4o_1
{ "original_instruction": "You are tasked with implementing a set of utility functions that leverage the `quopri` module to encode and decode text data. The following functions need to be implemented:\n\n1. **Function name:** `encode_text`\n - **Input:**\n - `text` (str): A string containing the text to be enco...
0.615358
Docs: Python310_40216
C
[ "encode_text", "decode_text", "encode_file", "decode_file" ]
4
[ [ "decode_file", "decode_text" ], [ "encode_file", "encode_text" ] ]
2
[]
false
[]
false
pytest
true
[]
true
dfd9920cdde94c644089436301759f51c5d32b38
abaec34af158fb00b4205dcf81886ae041c120ca
v1.0
complete
Docs
Docs: Python310_45405_C
from email.charset import Charset, add_charset def initialize_charset(input_charset: str) -> Charset: """ Initialize and return a Charset object for the given input_charset. >>> cs = initialize_charset('iso-8859-1') >>> cs.input_charset == 'iso-8859-1' True """ pass def encode_header(inpu...
from email.charset import Charset, add_charset, QP, BASE64 def initialize_charset(input_charset: str) -> Charset: """ Initialize and return a Charset object for the given input_charset. """ return Charset(input_charset) def encode_header(input_charset: str, header_string: str) -> str: """ Enco...
import pytest from email.charset import Charset, QP, BASE64 from solution import initialize_charset, encode_header, encode_body, register_charset def test_initialize_charset(): charset = initialize_charset('iso-8859-1') assert isinstance(charset, Charset) assert charset.input_charset == 'iso-8859-1' def t...
[ { "docstring": "Initialize and return a Charset object for the given input_charset.", "function_declaration": "def initialize_charset(input_charset):", "function_name": "initialize_charset", "parameter_list": "(input_charset)" }, { "docstring": "Encode a string for use in an email header for...
[ 1, 1, 0, 0, 0, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from email.charset import Charset, add_charset, QP, BASE64\n\ndef initialize_charset(input_charset: str) -> Charset:\n \"\"\"\n Initialize and return a Charset ob...
trial_gpt4o_0
{ "original_instruction": "**Objective:**\nYou are required to write code that demonstrates your understanding of the `email.charset` module within the legacy email API. This will involve manipulating character sets and their encodings as they apply to email headers and bodies.\n\n### Problem Statement:\nYou are work...
0.5533
Docs: Python310_45405
C
[ "initialize_charset", "encode_header", "encode_body", "register_charset" ]
4
[ [ "encode_body", "initialize_charset" ], [ "encode_header", "initialize_charset" ] ]
2
[]
false
[]
false
pytest
true
[]
true
837c111d9f95207eb9579b77d03415f9a14b5c30
547445e117aceee79a20c381c381d916191f387a
v1.0
complete
Docs
Docs: Scikit_46189_C
import numpy as np from typing import Tuple, List, Set def bistochastization(A: np.ndarray) -> np.ndarray: """ Normalize the matrix A to be bistochastic using iterative scaling. >>> bistochastization(np.array([[1, 2], [3, 4]])) array([[0.2, 0.4], [0.6, 0.8]]) """ def compute_singular_vectors(A: n...
import numpy as np from scipy.linalg import svd from sklearn.cluster import KMeans from typing import Tuple, List, Set def bistochastization(A: np.ndarray, max_iter: int = 100, tol: float = 1e-6) -> np.ndarray: """ Normalize the matrix A to be bistochastic """ A = A / np.sum(A) for i in range(max_i...
import numpy as np from solution import bistochastization, compute_singular_vectors, find_best_singular_vectors, cluster_rows_and_columns, jaccard_index, evaluate_biclustering def test_bistochastization(): A = np.array([[0.2, 0.3, 0.5], [0.6, 0.3, 0.1], [0.2, 0.4, 0.4]]) bistochastized_A = bistochastization(A)...
[ { "docstring": "Normalize the matrix A to be bistochastic", "function_declaration": "def bistochastization(A, max_iter=100, tol=1e-06):", "function_name": "bistochastization", "parameter_list": "(A, max_iter=100, tol=1e-06)" }, { "docstring": "Compute singular vectors", "function_declara...
[ 1, 0, 0, 1, 1, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom scipy.linalg import svd\nfrom scipy.sparse.csgraph import connected_components\nfrom sklearn.cluster import KMeans\nfrom typing import List, Se...
trial_gpt4o_7
{ "original_instruction": "### Spectral Biclustering Question\n\n**Objective**: Implement the Spectral Biclustering algorithm from scratch and evaluate its performance using the Jaccard index.\n\n### Problem Statement\n\nYou are required to implement the Spectral Biclustering algorithm and apply it to a given dataset...
0.54765
Docs: Scikit_46189
C
[ "bistochastization", "compute_singular_vectors", "find_best_singular_vectors", "cluster_rows_and_columns", "jaccard_index", "evaluate_biclustering" ]
6
[ [ "evaluate_biclustering", "jaccard_index" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
28c4bf69dbf7487f669d13b4071aed6b53fcb090
6f93cd26bc018443dd3f8c0f2f8b7d21af0c982b
v1.0
complete
Docs
Docs: Python310_46743_C
import asyncio from typing import List, Tuple clients = [] async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """Handle communication with a connected client. Read messages from the client and broadcast them to all other connected clients. Ensure proper disconnection...
import asyncio from typing import List, Tuple clients = [] async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): addr = writer.get_extra_info('peername') clients.append((reader, writer)) print(f"Connected to {addr}") try: while True: data = await rea...
import asyncio import pytest from solution import start_chat_server, clients @pytest.mark.asyncio async def test_server_communication(): host, port = '127.0.0.1', 8888 server_task = asyncio.create_task(start_chat_server(host, port)) await asyncio.sleep(1) # Give the server a moment to start reader1...
[]
[ 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nclients = []\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n addr = write...
trial_gpt4o_0
{ "original_instruction": "### Python Coding Assessment Question\n\n**Objective:**\nYou are to write a Python program using the `asyncio` streams functionality. The task involves creating a simple TCP chat server that can handle multiple clients simultaneously using async/await. Each client's messages should be broad...
0.62451
Docs: Python310_46743
C
[ "handle_client", "start_chat_server" ]
2
[ [ "start_chat_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
aade475c91a695e4758bceb02a76b23f79ba0f09
ebde1ab7f6d780c5d08f8a127cd3ba5b1d1af606
v1.0
complete
Docs
Docs: Python310_48560_C
def encode_text(text: str, encoding: str) -> bytes: """ Encode a given string into bytes using the specified encoding. >>> encode_text('hello', 'utf-8') == b'hello' >>> encode_text('hello', 'latin-1') == b'hello' >>> encode_text('Café', 'ascii') == b'Caf?' """ pass def decode_text(encoded_bytes...
import codecs # 1. Encode text function def encode_text(text, encoding): return codecs.encode(text, encoding, errors='replace') # 2. Decode text function def decode_text(encoded_bytes, encoding): return codecs.decode(encoded_bytes, encoding, errors='replace') # 3. Caesar Cipher encode def caesar_encode(text)...
def test_encode_text(): assert encode_text('hello', 'utf-8') == b'hello' assert encode_text('hello', 'latin-1') == b'hello' assert encode_text('Café', 'ascii') == b'Caf?' def test_decode_text(): assert decode_text(b'hello', 'utf-8') == 'hello' assert decode_text(b'hello', 'latin-1') == 'hello' ...
[ { "docstring": null, "function_declaration": "def encode_text(text, encoding):", "function_name": "encode_text", "parameter_list": "(text, encoding)" }, { "docstring": null, "function_declaration": "def decode_text(encoded_bytes, encoding):", "function_name": "decode_text", "para...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\ndef encode_text(text: str, encoding: str) -> bytes:\n \"\"\"\n Encodes the given text using the specified encoding.\n \"\"\"\n return codec...
trial_gpt4o_4
{ "original_instruction": "**Problem Statement:**\n\nYou are tasked with creating a system to encode and decode text using custom and standard codecs. The following operations must be supported:\n\n1. **Encode and Decode Text**: Using any of the standard codecs provided by the `codecs` module, encode a given string i...
0.718478
Docs: Python310_48560
C
[ "encode_text", "decode_text", "caesar_encode", "caesar_decode", "caesar_codec", "register_caesar_codec", "custom_encode", "custom_error_handler", "main" ]
9
[ [ "register_caesar_codec", "caesar_codec" ] ]
1
[]
false
[]
false
pytest
false
[]
true
dd43430c7b35ff170d7bf79448a291808a1feb6f
c2fbdb1be0c572bdaf15e27f7cd4a5a8e281569e
v1.0
complete
Docs
Docs: Scikit_48774_C
from typing import List def stream_data(file_path: str, chunk_size: int): """ Generator function that yields chunks of `chunk_size` text data and labels from the file. Parameters: file_path (str): Path to the text data file. chunk_size (int): The number of records to return at each step of the ...
from typing import List from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path: str, chunk_size: int): with open(file_path, 'r') as file: data = [] labels = [] for line...
import pytest from solution import stream_data, incremental_text_classifier def test_stream_data(): file_path = 'test_train_data.txt' chunk_size = 2 # Create a dummy file with sample data with open(file_path, 'w') as file: file.write("This is document 1,1\n") file.write("This is documen...
[ { "docstring": null, "function_declaration": "def stream_data(file_path, chunk_size):", "function_name": "stream_data", "parameter_list": "(file_path, chunk_size)" }, { "docstring": null, "function_declaration": "def incremental_text_classifier(file_path, test_data, test_labels):", "...
[ 0, 0, 1, 0, 0, 1, 1, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom typing import List\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nf...
trial_gpt4o_6
{ "original_instruction": "**Coding Assessment Question:**\n\n**Objective:**\nDesign and implement an out-of-core learning system using scikit-learn for a text classification problem. The goal is to classify text data from a simulated streaming source using incremental learning.\n\n**Problem Statement:**\n\nYou are p...
0.635569
Docs: Scikit_48774
C
[ "stream_data", "incremental_text_classifier" ]
2
[ [ "incremental_text_classifier", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
213cd337b655cf47370fe05048c37089baeead26
6d61fffa70b7193256bd1e592dbe1eea88f631c6
v1.0
complete
Docs
Docs: Python310_49642_C
import asyncio import contextvars from typing import List # ContextVar declarations username_var: contextvars.ContextVar[str] = contextvars.ContextVar('username') operation_history_var: contextvars.ContextVar[List[str]] = contextvars.ContextVar('operation_history', default=[]) async def handle_session(username: str, ...
import asyncio import contextvars from typing import List # ContextVar declarations username_var: contextvars.ContextVar[str] = contextvars.ContextVar('username') operation_history_var: contextvars.ContextVar[List[str]] = contextvars.ContextVar('operation_history', default=[]) async def handle_session(username: str, ...
import asyncio from solution import handle_session def test_handle_session_single_user(): result = asyncio.run(handle_session("alice", ["login", "view_product", "logout"])) assert result == ["alice:login", "alice:view_product", "alice:logout"] def test_handle_session_another_single_user(): result = asynci...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# ContextVar declarations\nusername_var: contextvars.ContextVar = contextvars.ContextVar('username')\noperation_history_var: conte...
trial_gpt4o_1
{ "original_instruction": "#### Objective:\nImplementing and working with `ContextVar` and `Context` in the `contextvars` module to handle state management within asynchronous tasks.\n\n#### Problem Statement:\nYou are tasked with implementing a server that maintains user sessions using context variables. Each sessio...
0.401775
Docs: Python310_49642
C
[ "handle_session", "server" ]
2
[ [ "server", "handle_session" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3bf9025a170605994433e4bb355835bdd1fbb66e
3f390e0600342294b6b448472730ac3b1ba8bb4f
v1.0
complete
Docs
Docs: Python310_9837_C
import logging from logging.handlers import RotatingFileHandler class ContextFilter(logging.Filter): def __init__(self, task_id, user): super().__init__() self.task_id = task_id self.user = user def filter(self, record): record.task_id = self.task_id record.user = self....
import logging import threading from logging.handlers import RotatingFileHandler import time class ContextFilter(logging.Filter): def __init__(self, task_id, user): super().__init__() self.task_id = task_id self.user = user def filter(self, record): record.task_id = self.task_i...
import os import threading import logging import time from solution import setup_logging, task_function, ContextFilter def test_single_task_logging(): task_id, user = 0, 'TestUser' logger = setup_logging(task_id, user) logger.info("Test task started") assert logger.handlers[0].level == logging.INFO ...
[]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import logging\nfrom logging.handlers import RotatingFileHandler\nimport threading\nfrom functools import wraps\nimport time\n\nclass ContextFilter(logging.Filter):\n ...
trial_gpt4o_6
{ "original_instruction": "### Question: Advanced Python Logging System\n\n#### Objective:\nYou are required to design and implement a logging system for a Python application that processes multiple tasks concurrently. The system should utilize advanced logging features such as multiple handlers, custom formatters, f...
0.565357
Docs: Python310_9837
C
[ "setup_logging", "task_function" ]
2
[ [ "task_function", "setup_logging" ] ]
1
[]
false
[ "ContextFilter" ]
true
pytest
true
[]
true
993e2bd915c42fa571caf98a6e0e2579192f0553
835d048e8a84bc0fd0c5207cd7554510fca8dd98
v1.0
complete
Docs
Docs: Python310_10164_C
import os import tkinter as tk from tkinter import filedialog, simpledialog from typing import List, Dict, Optional def select_directory() -> str: """ Prompts the user to select a directory and returns the directory path as a string. """ def list_text_files(directory: str) -> List[str]: """ Takes ...
import os import tkinter as tk from tkinter import filedialog, messagebox, simpledialog from typing import List, Dict, Optional def select_directory() -> str: """ Prompts the user to select a directory and returns the directory path as a string. """ root = tk.Tk() root.withdraw() dir_path = fil...
import os import pytest import tkinter as tk from tkinter import simpledialog from solution import select_directory, list_text_files, show_search_dialog, search_in_files # Assuming you have a folder structure to test against (mock file system for integration tests) @pytest.fixture def mock_directory_structure(tmpdir):...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport tkinter as tk\nfrom tkinter import filedialog, messagebox, simpledialog\nfrom typing import List, Dict, Optional\n\ndef select_directory() -> str:\n ...
trial_gpt4o_1
{ "original_instruction": "### Custom File Operations with Tkinter Dialogs\n\nYou are given the task of creating a small program that helps users to search for text files within a directory and read the contents of these files. You will need to make use of tkinter dialogs to handle directory selection and file readin...
0.540823
Docs: Python310_10164
C
[ "select_directory", "list_text_files", "show_search_dialog", "search_in_files" ]
4
[ [ "search_in_files", "list_text_files" ] ]
1
[]
false
[ "SearchDialog" ]
true
pytest
true
[]
true
0a8d535a48bb94bc1bcbd1181cc8fe2d0b2c156c
449fceb6fa09801967b41615f562b30b331c4616
v1.0
complete
Docs
Docs: Pytorch_10184_C
import subprocess import logging def launch_distributed_training(module_name: str, num_nodes: int, nproc_per_node: int, min_nodes: int, max_restarts: int, rdzv_id: str, rdzv_backend: str = "c10d"): """ Launches a distributed training job using torchrun. """ # Your impl...
import subprocess import logging def validate_inputs(module_name, num_nodes, nproc_per_node, min_nodes, max_restarts, rdzv_id, rdzv_backend): if not isinstance(module_name, str) or not module_name.endswith(".py"): raise ValueError("module_name must be a string ending with .py") if not isinstance(num_no...
import pytest from solution import launch_distributed_training def test_valid_input(): try: launch_distributed_training("train.py", 1, 1, 1, 3, "rdzv_id", "c10d") except Exception: pytest.fail("Exception raised for valid input") def test_invalid_module_name(): with pytest.raises(ValueError...
[ { "docstring": null, "function_declaration": "def validate_inputs(module_name, num_nodes, nproc_per_node, min_nodes, max_restarts, rdzv_id, rdzv_backend):", "function_name": "validate_inputs", "parameter_list": "(module_name, num_nodes, nproc_per_node, min_nodes, max_restarts, rdzv_id, rdzv_backend)...
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import subprocess\nimport logging\n\ndef launch_distributed_training(module_name: str, num_nodes: int, nproc_per_node: int, min_nodes: int, \n ...
trial_gpt4o_8
{ "original_instruction": "#### Objective\nDesign a function to initiate a distributed training job using PyTorch's `torchrun` (Elastic Launch). This function should configure the necessary settings and handle the launch process, ensuring the job can scale elastically and recover from failures.\n\n#### Problem Statem...
0.507746
Docs: Pytorch_10184
C
[ "validate_inputs", "launch_distributed_training" ]
2
[ [ "launch_distributed_training", "validate_inputs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4b990df050fd958b618e23b54f0ba956f3976d92
3c8743319fa8615632f8ab19235e5b88862b0ea0
v1.0
complete
Docs
Docs: Python310_11247_C
import asyncio async def broadcast_message(message: str, writer: asyncio.StreamWriter): """ Broadcast a message to all connected clients except the sender. Args: message (str): The message to broadcast. writer (asyncio.StreamWriter): The writer stream of the sender. """ pass async def handle_c...
import asyncio clients = [] async def broadcast_message(message, writer): for client_writer in clients: if client_writer != writer: client_writer.write(message.encode()) await client_writer.drain() async def handle_client(reader, writer): addr = writer.get_extra_info('peernam...
import asyncio import pytest from asyncio import StreamWriter, StreamReader from solution import main, handle_client, broadcast_message @pytest.mark.asyncio async def test_broadcast_message(monkeypatch): messages = [] class MockWriter: def __init__(self): self.data = b'' ...
[]
[ 0, 0, 0, 0, 0, 1, 1, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport sys\n\nasync def handle_client(reader, writer):\n clients.append(writer)\n addr = writer.get_extra_info('peername')\n print(f\"{addr} is...
trial_gpt4o_5
{ "original_instruction": "#### Objective\nImplement a simple chat server and client using the `asyncio` streams module. The purpose is to demonstrate your understanding of asynchronous networking, particularly employing `StreamReader` and `StreamWriter`.\n\n#### Requirements\n1. Implement an asynchronous chat server...
0.589372
Docs: Python310_11247
C
[ "broadcast_message", "handle_client", "main" ]
3
[ [ "handle_client", "broadcast_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cc3e8ea6fe2fac724c95c93e9a3665fba4d38b09
2725a799a43825619135ec85680ae88a1b1f1dfe
v1.0
complete
Docs
Docs: Python310_13291_C
import itertools import functools class FibonacciSequence: """ A class to represent an infinite sequence of Fibonacci numbers. The class is iterable. Usage: >>> fib_seq = FibonacciSequence() >>> first_10_fibs = take(10, fib_seq) >>> first_10_fibs [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> s...
import itertools import functools class FibonacciSequence: def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self def __next__(self): a = self.a self.a, self.b = self.b, self.a + self.b return a def take(n, iterable): return list(itertools.i...
from solution import FibonacciSequence, take, sum_of_squares def test_fibonacci_sequence(): fib_seq = FibonacciSequence() first_10_fibs = take(10, fib_seq) assert first_10_fibs == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] def test_take(): fib_seq = FibonacciSequence() first_5_fibs = take(5, fib_seq) a...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\nfrom functools import reduce\n\nclass FibonacciSequence:\n def __init__(self):\n self.a, self.b = 0, 1\n\n def __iter__(self):\n r...
trial_gpt4o_2
{ "original_instruction": "#### **Title:** Implementing a Custom Iterable Data Structure with Functional Utilities\n\n#### **Objective:**\nDesign and implement a custom iterable data structure in Python using generators. Extend the functionality of this data structure with utility functions using features from the `i...
0.760853
Docs: Python310_13291
C
[ "take", "sum_of_squares" ]
2
[ [ "sum_of_squares", "take" ] ]
1
[]
false
[ "FibonacciSequence" ]
true
pytest
true
[]
true
1219e228b27901d6d6bc87cec06b2e8ef51536d4
455be1c952d36f15bbffa622df207ccc7b29d47d
v1.0
complete
Docs
Docs: Python310_11361_C
import asyncio import contextvars client_id_var = contextvars.ContextVar('client_id') connected_clients = {} async def broadcast_message(message: str, sender_id: str): """Send the message to all connected clients except the sender.""" for client_id, writer in connected_clients.items(): if client_id !=...
import asyncio import contextvars from asyncio import StreamReader, StreamWriter from typing import Dict, Set client_id_var = contextvars.ContextVar('client_id') connected_clients: Dict[str, StreamWriter] = {} async def broadcast_message(message: str, sender_id: str): for client_id, writer in connected_clients.it...
import asyncio import pytest import contextvars from contextvars import ContextVar from typing import Dict, Set from asyncio import StreamReader, StreamWriter from solution import handle_client, main, connected_clients, client_id_var @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\nclient_id_var = contextvars.ContextVar('client_id')\nclients = {}\n\nasync def handle_client(reader, writer):\n client_id = f\"...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nImplement a mini asynchronous chat server using the `contextvars` module to manage client-specific states.\n\n#### Problem Statement\nYou need to create a simple asynchronous chat server that supports multiple clients connecting and sending messages. Use the `contextvars` mo...
0.56367
Docs: Python310_11361
C
[ "broadcast_message", "handle_client", "main" ]
3
[ [ "handle_client", "broadcast_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3afe3662f1b259fa94bb3c583d81fb194dde385c
1a917efc8fab8e8be8cd1e7f9f279b18af035f1d
v1.0
complete
Docs
Docs: Pytorch_13431_C
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(10, 50)...
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(10, 50)...
from solution import SimpleNet, generate_fake_data def test_simple_net(): model = SimpleNet() sample_input = torch.randn(1, 10) output = model(sample_input) assert output.shape == (1, 2) def test_generate_fake_data(): dataset = generate_fake_data(100) assert len(dataset) == 100 sample_inpu...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nfrom torch.distributed.elastic.multiprocessing import run\nfrom torch...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nImplement a fault-tolerant distributed training script using the `torch.distributed.elastic` module. Your task is to create a script that performs distributed training on a simple neural network while being able to gracefully handle node failures and automatically rescale th...
0.61356
Docs: Pytorch_13431
C
[ "generate_fake_data", "train_fn" ]
2
[ [ "train_fn", "generate_fake_data" ] ]
1
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
e18ac20b718c4184dbed9eafe534213bb6bb16d9
b9b13e1eef3263734ceec7e9cb58269dc6856b21
v1.0
complete
Docs
Docs: Python310_25266_C
from typing import List from multiprocessing import Pool def compute_sum_of_squares(numbers: List[int]) -> int: """ Compute the sum of squares of a list of integers using multiple processes. Use Python's `multiprocessing.Pool` for parallel computation. Args: numbers: List[int] - A list of integers...
from multiprocessing import Pool def sum_of_squares(numbers): """Helper function to compute sum of squares of a list of numbers.""" return sum(x ** 2 for x in numbers) def compute_sum_of_squares(numbers): """ Compute the sum of squares of a list of integers using multiple processes. """ if not...
from solution import compute_sum_of_squares def test_sum_of_squares_small_list(): assert compute_sum_of_squares([1, 2, 3, 4, 5]) == 55 def test_sum_of_squares_single_element(): assert compute_sum_of_squares([4]) == 16 def test_sum_of_squares_empty_list(): assert compute_sum_of_squares([]) == 0 def test_...
[ { "docstring": "Helper function to compute sum of squares of a list of numbers.", "function_declaration": "def sum_of_squares(numbers):", "function_name": "sum_of_squares", "parameter_list": "(numbers)" }, { "docstring": "Compute the sum of squares of a list of integers using multiple proces...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool\n\ndef sum_of_squares(numbers):\n \"\"\"Helper function to compute sum of squares of a list of numbers.\"\"\"\n return sum(x ** 2...
trial_gpt4o_0
{ "original_instruction": "You are tasked with parallelizing the execution of a computationally intensive function while managing the results efficiently. You must use Python’s `multiprocessing` package to achieve this. Specifically, you will create a program that computes the sum of squares for a given list of integ...
0.758486
Docs: Python310_25266
C
[ "sum_of_squares", "compute_sum_of_squares" ]
2
[ [ "compute_sum_of_squares", "sum_of_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a57fd3b6a172e7a6ba2b570470829294f3e0c776
86d16f3b2850737f6468b007028ac2b0681e2090
v1.0
complete
Docs
Docs: Python310_19495_C
import marshal def is_supported_type(obj): """Check if the object is of a supported type. Args: obj: The object to check. Returns: bool: True if obj is of a supported type, False otherwise. """ if isinstance(obj, (int, float, str, bool, type(None))): return True elif i...
import marshal def is_supported_type(obj): if isinstance(obj, (int, float, str, bool, type(None))): return True elif isinstance(obj, (list, tuple, set)): return all(is_supported_type(item) for item in obj) elif isinstance(obj, dict): return all(isinstance(key, (str, int)) and is_sup...
def test_supported_types(): file_path = 'test_supported.marshal' # Test with int secure_marshal_dump(123, file_path) assert secure_marshal_load(file_path) == 123 # Test with float secure_marshal_dump(123.45, file_path) assert secure_marshal_load(file_path) == 123.45 # Test with str ...
[ { "docstring": null, "function_declaration": "def is_supported_type(obj):", "function_name": "is_supported_type", "parameter_list": "(obj)" }, { "docstring": null, "function_declaration": "def secure_marshal_dump(value, file_path):", "function_name": "secure_marshal_dump", "param...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import marshal\n\ndef is_supported_type(obj):\n if isinstance(obj, (int, float, str, bool, type(None))):\n return True\n elif isinstance(obj, (list, tuple,...
trial_gpt4o_2
{ "original_instruction": "**Question: Implement a Secure Data Serialization Process**\n\nYou are to implement a secure data serialization and deserialization process for a set of Python objects using the `marshal` module. Due to the known security issue of the `marshal` module, you must incorporate additional checki...
0.529349
Docs: Python310_19495
C
[ "is_supported_type", "secure_marshal_dump", "secure_marshal_load" ]
3
[ [ "secure_marshal_dump", "is_supported_type" ], [ "secure_marshal_load", "is_supported_type" ] ]
2
[]
false
[]
false
pytest
false
[]
true
a1458b733cd376ebcfc7912e367f01b6186233a4
e14352ac52de451aeb029eebdce963d3a713acf2
v1.0
complete
Docs
Docs: Python310_13143_C
import importlib import inspect def generate_doc(target: str) -> str: """ Generates the documentation for a specified module, class, or function. Args: target (str): The name of the module, class, or function as a string. Returns: str: The documentation string if available, otherwise ...
import importlib import inspect def generate_doc(target: str) -> str: """ Generates the documentation for a specified module, class, or function. Args: target (str): The name of the module, class, or function as a string. Returns: str: The documentation string if available, otherwise ...
import pytest from io import StringIO import sys from solution import generate_doc, print_doc def test_generate_doc_module(): assert generate_doc('os') == inspect.getdoc(importlib.import_module('os')) def test_generate_doc_class(): assert generate_doc('os.path') == inspect.getdoc(importlib.import_module('os')...
[ { "docstring": "Generates the documentation for a specified module, class, or function.\n\nArgs:\ntarget (str): The name of the module, class, or function as a string.\n\nReturns:\nstr: The documentation string if available, otherwise \"No documentation available.\"", "function_declaration": "def generate_d...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import importlib\nimport inspect\n\ndef generate_doc(target: str) -> str:\n \"\"\"\n Generates documentation for the given module, class, or function.\n \n ...
trial_gpt4o_9
{ "original_instruction": "Python's `pydoc` module is a comprehensive tool for generating documentation from Python modules. For this assessment, you will implement a simplified version of some functionalities described in the `pydoc` documentation.\n\n#### Objectives\n1. **Generate Documentation**: Create a function...
0.523695
Docs: Python310_13143
C
[ "generate_doc", "print_doc" ]
2
[ [ "print_doc", "generate_doc" ] ]
1
[]
false
[]
false
pytest
true
[]
true
56bc862533f423f5200d27ff192af77cda515a4d
d60acd903c4308989675f8a261fed0d7a8b792cb
v1.0
complete
Docs
Docs: Python310_23156_C
import itertools from typing import List, Tuple, Iterator class RangeIterator: """Custom iterator to iterate over each number in all ranges sequentially. """ def __init__(self, ranges: List[Tuple[int, int]]): self.ranges = ranges self.current_range = None self.current = None ...
import itertools from typing import List, Tuple, Iterator class RangeIterator: def __init__(self, ranges: List[Tuple[int, int]]): self.ranges = ranges self.current_range = None self.current = None self.index = 0 self._prepare_next_range() def _prepare_next_range...
from solution import RangeIterator, even_numbers, combine_even_numbers def test_RangeIterator_normal_case(): ranges = [(1, 4), (10, 13)] iterator = RangeIterator(ranges) output = list(iterator) assert output == [1, 2, 3, 4, 10, 11, 12, 13] def test_RangeIterator_single_range(): ranges = [(5, 7)] ...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\nfrom typing import List, Tuple, Iterator\n\nclass RangeIterator:\n def __init__(self, ranges: List[Tuple[int, int]]):\n self.ranges = ranges...
trial_gpt4o_0
{ "original_instruction": "### Advanced Coding Assessment: Custom Iterator and Generator\n\n#### Objective:\nDesign and implement custom iterators and generators using Python's functional programming features.\n\n#### Task:\nYou are provided with a list of tuples where each tuple represents a range (inclusive).\n\nFo...
0.713189
Docs: Python310_23156
C
[ "even_numbers", "combine_even_numbers" ]
2
[ [ "combine_even_numbers", "even_numbers" ] ]
1
[]
false
[ "RangeIterator" ]
true
pytest
true
[]
true
c49cbba86172a7d32d7c840768b065d0bb98da60
d15a990ae48388eed313c2d33f0ae7d2e2671f0d
v1.0
complete
Docs
Docs: Python310_30836_C
from typing import List import concurrent.futures def sum_of_squares(numbers: List[int], method: str = 'threading') -> int: """ Calculate the sum of squares of a list of numbers using either threading or multiprocessing. Args: numbers (List[int]): A list of integers for which the sum of squares ne...
from typing import List import concurrent.futures def chunkify(numbers: List[int], n: int) -> List[List[int]]: """Break the list into n-sized chunks.""" return [numbers[i:i + n] for i in range(0, len(numbers), n)] def square_numbers(nums: List[int]) -> int: """Return the sum of squares of the given list o...
import pytest from solution import sum_of_squares def test_sum_of_squares_threading(): numbers = [1, 2, 3, 4, 5] result = sum_of_squares(numbers, method='threading') assert result == 55 def test_sum_of_squares_multiprocessing(): numbers = [1, 2, 3, 4, 5] result = sum_of_squares(numbers, method='mu...
[ { "docstring": "Break the list into n-sized chunks.", "function_declaration": "def chunkify(numbers, n):", "function_name": "chunkify", "parameter_list": "(numbers, n)" }, { "docstring": "Return the sum of squares of the given list of numbers.", "function_declaration": "def square_number...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport concurrent.futures\n\ndef chunkify(numbers: List[int], n: int) -> List[List[int]]:\n \"\"\"Break the list into n-sized chunks.\"\"\"\...
trial_gpt4o_0
{ "original_instruction": "You are required to implement a program that calculates the sum of squares of a list of numbers using parallel processing techniques. You'll need to create a function `sum_of_squares` that can leverage both multi-threading and multi-processing.\n\n### Function Signature\n```python\nfrom typ...
0.714353
Docs: Python310_30836
C
[ "chunkify", "square_numbers", "sum_of_squares" ]
3
[ [ "sum_of_squares", "chunkify" ], [ "sum_of_squares", "square_numbers" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4d6ddc0db93aba1917d08a34b8640e1761941b16
31b3a97b213114a4c4cfc72a74f21be5c2b08c84
v1.0
complete
Docs
Docs: Python310_34947_C
import cProfile import pstats from pstats import SortKey # Provided function to profile def process_data(data): result = [] for item in data: processed = compute(item) result.append(processed) return aggregate(result) def compute(item): return item ** 2 # Example computation def aggr...
import cProfile import pstats from pstats import SortKey # Provided function to profile def process_data(data): result = [] for item in data: processed = compute(item) result.append(processed) return aggregate(result) def compute(item): return item ** 2 # Example computation def aggr...
import os import pstats from solution import process_data, profile_and_analyze def read_analysis_file(): with open("analysis_output.txt", "r") as file: return file.read() def test_profiling_results_file_exists(): profile_and_analyze() assert os.path.exists('profiling_results'), "Profiling results ...
[ { "docstring": null, "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def compute(item):", "function_name": "compute", "parameter_list": "(item)" }, { "docstring...
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cProfile\nimport pstats\nfrom pstats import SortKey\n\n# Provided function to profile\ndef process_data(data):\n result = []\n for item in data:\n p...
trial_gpt4o_1
{ "original_instruction": "### Question\n\n**Profiling and Analysis of a Function**\n\nYou are provided with a function `process_data()` which performs several computations on a dataset. Your task is to profile `process_data()` using the `cProfile` module to gather detailed execution statistics. You need to save the ...
0.537644
Docs: Python310_34947
C
[ "process_data", "compute", "aggregate", "profile_and_analyze" ]
4
[ [ "process_data", "aggregate" ], [ "process_data", "compute" ], [ "profile_and_analyze", "process_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
f1059d0bfd33315d52ab94ab83973099847188f3
04217316b2319562143bfcd418beb38db919c1d0
v1.0
complete
Docs
Docs: Python310_25277_C
import hmac import hashlib def generate_file_hmac(filepath: str, key: bytes, digestmod: str) -> str: """ Calculates the HMAC for a given file. Parameters: filepath (str): Path to the file for which HMAC needs to be calculated. key (bytes): Secret key used to calculate the HMAC. dig...
import hmac import hashlib def generate_file_hmac(filepath: str, key: bytes, digestmod: str) -> str: """ Calculates the HMAC for a given file. Parameters: filepath (str): Path to the file for which HMAC needs to be calculated. key (bytes): Secret key used to calculate the HMAC. ...
import pytest from solution import generate_file_hmac, verify_file_hmac import os # Prepare test setup def setup_module(module): with open("testfile.txt", "w") as file: file.write("This is a test file.") def teardown_module(module): os.remove("testfile.txt") # Test cases for generate_file_hmac def te...
[ { "docstring": "Calculates the HMAC for a given file.\n\nParameters:\n filepath (str): Path to the file for which HMAC needs to be calculated.\n key (bytes): Secret key used to calculate the HMAC.\n digestmod (str): Name of the digest algorithm to use (e.g., 'sha256', 'sha1').\n \nReturns:\n str:...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\nimport os\n\ndef generate_file_hmac(filepath: str, key: bytes, digestmod: str) -> str:\n if not os.path.isfile(filepath):\n raise...
trial_gpt4o_1
{ "original_instruction": "### Secure File Integrity Verification with HMAC\n\nYou have been hired as a security expert to ensure the data integrity of files sent over a network. To achieve this, you need to calculate and verify the HMAC of files using different hash algorithms. Implement the following two functions:...
0.733436
Docs: Python310_25277
C
[ "generate_file_hmac", "verify_file_hmac" ]
2
[ [ "verify_file_hmac", "generate_file_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
af56f14c8ed34f0c4fa7b5c6dbb0d104c4abf7d2
d00194ee7753db512aa6c7c3c9b636126fb5208d
v1.0
complete
Docs
Docs: Python310_31535_C
import asyncio async def run_server(): """ Create an asyncio-based server that listens for incoming connections. The server should handle multiple client connections and print all received messages. """ pass async def run_client(messages): """ Create an asyncio-based client that connects to the se...
import asyncio import sys async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received from {addr}: {message}") writer.close() await writer.wait_closed() async def run_server(): server = await asy...
import asyncio import pytest import sys from solution import run_server, run_client, choose_event_loop @pytest.mark.asyncio async def test_server_client_communication(capfd): server_task = asyncio.create_task(run_server()) await asyncio.sleep(1) # Give the server a moment to start up client_messages = [...
[ { "docstring": null, "function_declaration": "def choose_event_loop():", "function_name": "choose_event_loop", "parameter_list": "()" } ]
[ 0, 1, 1, 1, 1, 0, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\n\nasync def handle_client(reader, writer):\n while True:\n data = await reader.read(100)\n message = data.decode()\n ...
trial_gpt4o_6
{ "original_instruction": "### Asyncio Platform-Specific Implementation Challenge\n\n#### Objective:\nYou are tasked with creating a function that utilizes the `asyncio` module to set up a simple server and client communication system. However, due to platform-specific limitations described in the documentation, you ...
0.615854
Docs: Python310_31535
C
[ "handle_client", "run_server", "run_client", "choose_event_loop" ]
4
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
33e84d24c76be284185349d8cbfb4eedd4412f18
2358d4d5108a99853289dc87eae6b80108ef2049
v1.0
complete
Docs
Docs: Scikit_31537_C
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import os import numpy as np def data_stream(directory): """ Generator function to stream text data and their labels from a directory """ for filename in os.li...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import os import numpy as np def data_stream(directory): """ Generator function to stream text data and their labels from a directory """ for filename in os.li...
import os import pytest from solution import data_stream, out_of_core_text_classification def test_data_stream(): # Setup: Create a temporary directory and populate it with sample data files os.makedirs('test_dir', exist_ok=True) with open('test_dir/sports_1.txt', 'w') as f: f.write('This is a spor...
[ { "docstring": "Generator function to stream text data and their labels from a directory ", "function_declaration": "def data_stream(directory):", "function_name": "data_stream", "parameter_list": "(directory)" }, { "docstring": null, "function_declaration": "def out_of_core_text_classif...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nim...
trial_gpt4o_2
{ "original_instruction": "Out-of-Core Learning for Text Classification\n\n#### Objective\nYou need to design an out-of-core learning algorithm to classify a large dataset of text documents that cannot fit into the main memory at once. Your task involves streaming the data, extracting features, and applying an increm...
0.620728
Docs: Scikit_31537
C
[ "data_stream", "out_of_core_text_classification" ]
2
[ [ "out_of_core_text_classification", "data_stream" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
94614d1f89bff43af2dd41d1dc4da9c69a02c363
e8aa2e8c662458c74d258d2db82c29432c4e1794
v1.0
complete
Docs
Docs: Python310_25585_C
def custom_encode(input_string: str) -> bytes: """ Function to encode an input string where each character is replaced by its Unicode code point shifted by 3 positions. """ encoded_bytes = bytearray() for char in input_string: try: encoded_char = chr(ord(char) + 3) en...
def custom_encode(input_string: str) -> bytes: """ Function to encode an input string where each character is replaced by its Unicode code point shifted by 3 positions. """ encoded_bytes = bytearray() for char in input_string: try: encoded_char = chr(ord(char) + 3) en...
from solution import custom_encode, custom_decode def test_custom_encode(): assert custom_encode("HELLO") == b'KHOOR' assert custom_encode("WORLD") == b'ZRUOG' assert custom_encode("a") == b'd' def test_custom_decode(): assert custom_decode(b'KHOOR') == "HELLO" assert custom_decode(b'ZRUOG') == "W...
[ { "docstring": "Function to encode an input string where each character is replaced by its Unicode code point shifted by 3 positions.", "function_declaration": "def custom_encode(input_string):", "function_name": "custom_encode", "parameter_list": "(input_string)" }, { "docstring": "Function...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def custom_encode(input_string: str) -> bytes:\n \"\"\"\n Function to encode an input string where each character is replaced by its Unicode code point shifted by...
trial_gpt4o_0
{ "original_instruction": "### Custom Codec Implementation and Error Handling\n\n**Objective**: Implement a custom codec for a hypothetical encoding and additionally, design a custom error handling strategy for any encoding errors encountered during the use of this codec.\n\n**Task 1**: Custom Codec Implementation\n\...
0.6822
Docs: Python310_25585
C
[ "custom_encode", "custom_decode", "handle_encoding_error" ]
3
[ [ "custom_encode", "handle_encoding_error" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4e1336ec2547be0b4e2359c5c832e15a87a1280e
64eb5834a6c12ca98a1d52a3c6643f75e1aab586
v1.0
complete
Docs
Docs: Python310_34763_C
import gc def enable_gc() -> None: """ Enables garbage collection. """ pass def disable_gc() -> None: """ Disables garbage collection. """ pass def is_gc_enabled() -> bool: """ Returns True if garbage collection is enabled, otherwise False. """ pass def collect_garbag...
import gc def enable_gc() -> None: """ Enables garbage collection. """ gc.enable() def disable_gc() -> None: """ Disables garbage collection. """ gc.disable() def is_gc_enabled() -> bool: """ Returns True if garbage collection is enabled, otherwise False. """ return gc...
import gc from solution import enable_gc, disable_gc, is_gc_enabled, collect_garbage, get_gc_stats, get_tracked_objects, memory_usage_report def test_enable_disable_gc(): disable_gc() assert not is_gc_enabled() enable_gc() assert is_gc_enabled() def test_collect_garbage(): assert collect_garbage()...
[ { "docstring": "Enables garbage collection.", "function_declaration": "def enable_gc():", "function_name": "enable_gc", "parameter_list": "()" }, { "docstring": "Disables garbage collection.", "function_declaration": "def disable_gc():", "function_name": "disable_gc", "parameter_...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import gc\n\ndef enable_gc() -> None:\n \"\"\"\n Enable the garbage collector.\n \"\"\"\n gc.enable()\n\ndef disable_gc() -> None:\n \"\"\"\n Disable ...
trial_gpt4o_7
{ "original_instruction": "## Question: Implementing Advanced Garbage Collection Control and Analysis\n\nYou are tasked with creating a utility in Python that leverages the `gc` module to provide advanced control over garbage collection and analysis of object memory usage. This utility should expose functionalities t...
0.44115
Docs: Python310_34763
C
[ "enable_gc", "disable_gc", "is_gc_enabled", "collect_garbage", "get_gc_stats", "get_tracked_objects", "memory_usage_report" ]
7
[ [ "memory_usage_report", "collect_garbage" ], [ "memory_usage_report", "get_gc_stats" ], [ "memory_usage_report", "get_tracked_objects" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d438d58c5a3035ba5e1a7eff5783b8ac8f7e7971
2fba8d83256ea93825f08948cfca4ac2ed30dfba
v1.0
complete
Docs
Docs: Pytorch_41001_C
def train_model_with_distributed_optimizer(device_ids: list, epochs: int) -> None: """ Set up a distributed optimizer for a simple neural network training loop in PyTorch. Args: device_ids (list): A list of integer device IDs to be used for training (e.g., [0, 1, 2] for training on three GPUs). epochs (...
import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp import random # Define a simple neural network class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(10, 50) self...
from solution import train_model_with_distributed_optimizer import pytest # This test requires the code to be executed within a proper distributed environment. # Hence, it's more of an E2E test. For simplicity, we won't run this here but this is # how one could structure the test. @pytest.mark.skip(reason="This test r...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\n# Si...
trial_gpt4o_9
{ "original_instruction": "**Advanced Distributed Training in PyTorch**\n\n### Background\nDistributed training is an essential technique for scaling the training of neural network models across multiple GPUs or machines. PyTorch provides several optimizers to facilitate distributed training, such as `DistributedOpti...
0.461498
Docs: Pytorch_41001
C
[ "setup", "cleanup", "synthetic_data", "train", "train_model_with_distributed_optimizer" ]
5
[ [ "train", "cleanup" ], [ "train", "setup" ], [ "train", "synthetic_data" ], [ "train_model_with_distributed_optimizer", "train" ] ]
4
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
94ca1a152b70d182b263b9f22f4c60d34ec23b0b
4dbdea4b5f364226658a33a26a519704809cf24f
v1.0
complete
Docs
Docs: Python310_38055_C
import concurrent.futures import urllib.request from typing import List, Tuple, Dict def async_web_scraper(urls: List[str], timeout: float) -> Tuple[Dict[str, str], Dict[str, Exception]]: """ Asynchronously fetches multiple web pages and processes the content. :param urls: List of URLs to fetch :param...
import concurrent.futures import urllib.request from typing import List, Tuple, Dict def fetch_url(url: str, timeout: float) -> str: """ Fetches the content of a URL with a specified timeout. :param url: URL to fetch :param timeout: Timeout in seconds :return: Content of the fetched URL :r...
from solution import async_web_scraper import pytest def test_async_web_scraper_successful(): urls = [ "http://www.example.com/", "https://www.google.com/" ] timeout = 5.0 success, errors = async_web_scraper(urls, timeout) assert len(success) == 2 assert len(errors) == 0 ...
[ { "docstring": "Fetches the content of a URL with a specified timeout.\n\n:param url: URL to fetch\n:param timeout: Timeout in seconds\n:return: Content of the fetched URL\n:raises: Exception if the fetch fails", "function_declaration": "def fetch_url(url, timeout):", "function_name": "fetch_url", "...
[ 0, 0, 1, 0, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport urllib.request\nfrom urllib.error import URLError, HTTPError\nfrom typing import List, Tuple, Dict\n\ndef fetch_url_content(url: str, ...
trial_gpt4o_6
{ "original_instruction": "### Asynchronous Web Scraping with Error Handling\n\nYou are tasked with designing a function that asynchronously fetches multiple web pages and processes the content. You will use the `concurrent.futures.ThreadPoolExecutor` for this purpose. The function should handle potential errors grac...
0.625322
Docs: Python310_38055
C
[ "fetch_url", "async_web_scraper" ]
2
[ [ "async_web_scraper", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3be2108da73a69ffc47a271e3c30011ae1cc394f
e38847d56b9d7028e9568b0858b6f35279831c58
v1.0
complete
Docs
Docs: Python310_38190_C
import asyncio async def run_commands(commands: list[str]) -> str: """ Runs a list of shell commands concurrently and returns the combined output. Each command is executed asynchronously and their outputs are concatenated in the order given. If any command fails, its standard error is included in...
import asyncio async def run_command(command: str) -> str: process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() output = stdout.decode() + stderr.decode() retur...
import asyncio from solution import run_commands async def test_run_commands_single_successful_command(): commands = ['echo "Hello, World!"'] result = await run_commands(commands) assert result == "Hello, World!\n" async def test_run_commands_multiple_successful_commands(): commands = ['echo "Hello, W...
[]
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def run_command(command):\n proc = await asyncio.create_subprocess_shell(\n command,\n stdout=asyncio.subprocess.PIPE,\n ...
trial_gpt4o_5
{ "original_instruction": "### Asynchronous Subprocess Management\n\nYou are tasked with creating a Python script that spawns multiple subprocesses to perform various system operations concurrently. Your goal is to implement a function that accepts a list of shell commands and runs them concurrently using asyncio. Th...
0.655904
Docs: Python310_38190
C
[ "run_command", "run_commands" ]
2
[ [ "run_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e1c5f39326d927cbef2130a17408e8bc9ef74729
d3a94a25b8672bd7059d6d68fa8106120ee19f3e
v1.0
complete
Docs
Docs: Python310_28101_C
def is_whitespace(ch): """ Check if the given character is a whitespace using Py_UNICODE_ISSPACE. """ pass def to_lowercase(ch): """ Convert the given character to its lowercase equivalent using Py_UNICODE_TOLOWER. """ pass def to_decimal_str(ch): """ Convert the given decimal ...
def is_whitespace(ch): """ Check if the given character is a whitespace. """ return ch.isspace() def to_lowercase(ch): """ Convert the given character to its lowercase equivalent. """ return ch.lower() def to_decimal_str(ch): """ Convert the given decimal character to its Unico...
from solution import unicode_transformer, is_whitespace, to_lowercase, to_decimal_str def test_is_whitespace(): assert is_whitespace(' ') == True assert is_whitespace('\t') == True assert is_whitespace('A') == False assert is_whitespace('1') == False def test_to_lowercase(): assert to_lowercase('A...
[ { "docstring": "Check if the given character is a whitespace.", "function_declaration": "def is_whitespace(ch):", "function_name": "is_whitespace", "parameter_list": "(ch)" }, { "docstring": "Convert the given character to its lowercase equivalent.", "function_declaration": "def to_lower...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_whitespace(ch):\n \"\"\"\n Checks if a character is a whitespace.\n \"\"\"\n return ch.isspace()\n\ndef to_lowercase(ch):\n \"\"\"\n Converts a...
trial_gpt4o_2
{ "original_instruction": "**Objective:** Demonstrate your understanding of Unicode handling in Python by writing functions that manipulate Unicode strings and characters using the APIs discussed in the documentation.\n\n**Problem Statement:**\n\nYou are required to implement a function `unicode_transformer` that tak...
0.582433
Docs: Python310_28101
C
[ "is_whitespace", "to_lowercase", "to_decimal_str", "unicode_transformer" ]
4
[ [ "unicode_transformer", "is_whitespace" ], [ "unicode_transformer", "to_decimal_str" ], [ "unicode_transformer", "to_lowercase" ] ]
3
[]
false
[]
false
pytest
true
[]
true
390d70cda034968ea3fd1c30e7e0d27912d57aa9
5515b7da517fde5b767659c084aa115dd39cd78a
v1.0
complete
Docs
Docs: Seaborn_31357_C
import seaborn as sns import numpy as np import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * 0.5) * (n + 2 - i) * flip) def customized_plot(n=10, theme='darkgrid', style='darkgrid', context='notebook', remove_spine...
import seaborn as sns import numpy as np import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * 0.5) * (n + 2 - i) * flip) def customized_plot(n=10, theme='darkgrid', style='darkgrid', context='notebook', remove_spine...
import pytest import matplotlib.pyplot as plt from solution import customized_plot def test_customized_plot_default_params(): customized_plot() # Here we test the plot creation; in real test environments, we would capture the plot object plt.close() def test_customized_plot_custom_params(): customized...
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": null, "function_declaration": "def customized_plot(n=10, theme='darkgrid', style='darkgrid', context='notebook', remove_spines=False...
[ 0, 0, 1, 0, 0, 1, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):...
trial_gpt4o_8
{ "original_instruction": "### Question\n\nUsing the seaborn library, write a function named `customized_plot` that generates a series of sine wave plots with different aesthetic customizations. Your function should:\n\n1. Accept the following parameters:\n - `n` (int): The number of sine waves to plot. Default is ...
0.704145
Docs: Seaborn_31357
C
[ "sinplot", "customized_plot" ]
2
[ [ "customized_plot", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
b8a0c5c2720a6d059d7ebb43f657f9546436fa41
0d60383a432572444c4365837d3f85e830593163
v1.0
complete
Docs
Docs: Python310_38013_C
import sys def my_audit_hook(event, args): """ Audit hook to log triggered events with their arguments. Args: event (str): The event that is being audited. args (tuple): The arguments associated with the event. """ pass def track_memory_usage(obj): """ Track memory usage by print...
import sys def my_audit_hook(event, args): print(f"Audit Event: {event}, Arguments: {args}") def track_memory_usage(obj): print(f"Allocated Blocks: {sys.getallocatedblocks()}") return sys.getsizeof(obj) def test_audit_and_memory(): sys.addaudithook(my_audit_hook) # Allocating different objec...
from solution import my_audit_hook, track_memory_usage, test_audit_and_memory def test_audit_hook_registration(): sys.addaudithook(my_audit_hook) sys.audit("test.event", ("arg1",)) # This should show the audit event output def test_track_memory_usage(): sample_list = [1, 2, 3] assert track_memory_...
[ { "docstring": null, "function_declaration": "def my_audit_hook(event, args):", "function_name": "my_audit_hook", "parameter_list": "(event, args)" }, { "docstring": null, "function_declaration": "def track_memory_usage(obj):", "function_name": "track_memory_usage", "parameter_li...
[ 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\ndef my_audit_hook(event, args):\n \"\"\"\n Audit hook that logs all audit events with their arguments.\n \"\"\"\n print(f\"Audit Event: {event...
trial_gpt4o_3
{ "original_instruction": "### Advanced Python Assessment Question: System Audit and Memory Management\n\n**Objective:**\nYour task is to write a Python script that demonstrates the use of audit hooks and memory management using the `sys` module.\n\n**Problem Statement:**\n1. Implement an auditing system using the fu...
0.492063
Docs: Python310_38013
C
[ "my_audit_hook", "track_memory_usage", "test_audit_and_memory" ]
3
[ [ "test_audit_and_memory", "my_audit_hook" ], [ "test_audit_and_memory", "track_memory_usage" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bf33ea6a479638372e483cf96f275bd70a22448c
aa3cf49afa1ba75ceebb400acaabde614cc81628
v1.0
complete
Docs
Docs: Python310_31259_C
import hashlib def secure_log_verifier(log_entries, secret_key, salt): """ Generates a BLAKE2b hexadecimal digest for the given log entries using the provided secret key and salt. Args: log_entries (list of str): A list of log entries. secret_key (bytes): A bytes object representing the secret...
import hashlib def secure_log_verifier(log_entries, secret_key, salt): """ Generates a BLAKE2b hexadecimal digest for the given log entries using the provided secret key and salt. """ hasher = hashlib.blake2b(key=secret_key, salt=salt) for entry in log_entries: hasher.update(entry.encode())...
from solution import secure_log_verifier, validate_log def test_secure_log_verifier_single_entry(): log_entries = ["Login: User A"] secret_key = b'supersecretkey' salt = b'unique_salt' expected_digest = hashlib.blake2b(b'Login: User A', key=secret_key, salt=salt).hexdigest() assert secure_log_verif...
[ { "docstring": "Generates a BLAKE2b hexadecimal digest for the given log entries using the provided secret key and salt.", "function_declaration": "def secure_log_verifier(log_entries, secret_key, salt):", "function_name": "secure_log_verifier", "parameter_list": "(log_entries, secret_key, salt)" ...
[ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef secure_log_verifier(log_entries, secret_key, salt):\n \"\"\"\n Computes a secure hash digest for the log entries using blake2b with a secret...
trial_gpt4o_8
{ "original_instruction": "### Secure Log Verifier\n\nYou are tasked with creating a secure log verifier for a system that logs user activities. The verifier ensures that logged data has not been tampered with. You will use the hashlib library in Python to accomplish this.\n\n### Requirements:\n\n1. **Function Implem...
0.566731
Docs: Python310_31259
C
[ "secure_log_verifier", "validate_log" ]
2
[ [ "validate_log", "secure_log_verifier" ] ]
1
[]
false
[]
false
pytest
true
[]
true
669b36bdc51a1f3d6a7f991e23d66046749d593e
1044c693084e85a4ce9adc430dd9411e4a51a935
v1.0
complete
Docs
Docs: Python310_38274_C
import aiohttp import asyncio async def fetch_data(url: str) -> str: """ Fetch data from a URL asynchronously. Parameters: url (str): The URL to fetch data from. Returns: str: The data fetched from the URL. """ pass async def gather_data(urls: list) -> list: """ Fetch data from multipl...
import aiohttp import asyncio async def fetch_data(url: str) -> str: """ Fetch data from a URL asynchronously. Parameters: url (str): The URL to fetch data from. Returns: str: The data fetched from the URL. """ async with aiohttp.ClientSession() as session: async with session....
import asyncio from solution import fetch_data, gather_data async def test_fetch_data_valid_url(): url = 'https://jsonplaceholder.typicode.com/posts/1' data = await fetch_data(url) assert isinstance(data, str) and len(data) > 0 async def test_fetch_data_invalid_url(): url = 'https://jsonplaceholder.ty...
[]
[ 1, 1, 1, 0, 0, 1, 1, 1, 0 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Fetches the data from the provided URL asynchronously.\n\n :param url: The ...
trial_gpt4o_5
{ "original_instruction": "### Asynchronous Data Fetcher\n\n**Objective**: \nImplement an asynchronous data fetcher that retrieves data from multiple sources concurrently using the `asyncio` library.\n\n**Background**:\nYou are tasked with creating a utility that can fetch data from multiple URLs concurrently. This u...
0.58662
Docs: Python310_38274
C
[ "fetch_data", "gather_data", "main" ]
3
[ [ "gather_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
a5d7a8b3d8c9218df821a9d897204f9c0a31568c
fc20156f0f9263f91787719c4307648a25ae8b07
v1.0
complete
Docs
Docs: Python310_41490_C
import curses def main(stdscr): """ Main function to run the scrollable text viewer using curses. """ # Your code starts here def run_curses_program(): """ Function to properly start the curses application. """ # Your code starts here if __name__ == "__main__": run_curses_program(...
import curses def main(stdscr): """ Main function to run the scrollable text viewer using curses. """ # Turn off cursor blinking curses.curs_set(0) # Load a large block of text (hardcoded for this example) lines = [f"Line {i}: This is a sample text viewer using Python curses." for i in ran...
import curses from unittest import mock from io import StringIO from solution import run_curses_program def test_curses_program_initialization(): """ Test if the curses program initializes and closes without error. """ with mock.patch('curses.wrapper') as mock_curses_wrapper: run_curses_program...
[ { "docstring": "Main function to run the scrollable text viewer using curses.", "function_declaration": "def main(stdscr):", "function_name": "main", "parameter_list": "(stdscr)" }, { "docstring": "Function to properly start the curses application.", "function_declaration": "def run_curs...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef main(stdscr):\n # Disable cursor blinking\n curses.curs_set(0)\n \n # Load a large block of text (hard-coded for the example)\n line...
trial_gpt4o_4
{ "original_instruction": "### Advanced Curses Window Management in Python\n\nLet's create a text-based user interface that mimics a basic text viewer/editor:\n\n**Task**: Implement a Python program using the `curses` module to create a scrollable text viewer.\n\n**Requirements**:\n1. Initialize the `curses` library ...
0.385613
Docs: Python310_41490
C
[ "main", "run_curses_program" ]
2
[ [ "run_curses_program", "main" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95d8a42880b62b6374599d4914c192f8f0aaa2c0
858809ffda2fb09a73c91f237ab89cf110492852
v1.0
complete
Docs
Docs: Python310_31653_C
import hashlib import os from typing import Optional, List def hash_data(data: bytes, algorithm: str) -> str: """ Returns the hexadecimal digest of the hashed data using the specified algorithm. >>> hash_data(b'example data', 'sha256') '3a0f4507f26b22d7c3dfc5dc7945c7026871c0ca7299a5e02e48e28b41b523b8' ...
import hashlib import os from typing import Optional, List def hash_data(data: bytes, algorithm: str) -> str: """ Returns the hexadecimal digest of the hashed data using the specified algorithm. """ if algorithm not in hashlib.algorithms_available: raise ValueError(f"Algorithm {algorithm} is no...
import pytest import hashlib from solution import hash_data, iterative_hash, secure_hash_with_salt, verify_secure_hash def test_hash_data_valid_algorithm(): data = b'example data' expected = hashlib.sha256(data).hexdigest() assert hash_data(data, 'sha256') == expected def test_hash_data_invalid_algorithm(...
[ { "docstring": "Returns the hexadecimal digest of the hashed data using the specified algorithm.", "function_declaration": "def hash_data(data, algorithm):", "function_name": "hash_data", "parameter_list": "(data, algorithm)" }, { "docstring": "Returns the hexadecimal digest of the concatena...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport os\nfrom typing import Optional\n\ndef hash_data(data: bytes, algorithm: str) -> str:\n \"\"\"\n Returns the hexadecimal digest of the hash...
trial_gpt4o_7
{ "original_instruction": "### Hashing Challenge with Python's hashlib\n\n#### Problem Statement\nYou are tasked with implementing a secure data integrity check system using Python's hashlib module. Your functions will handle hashing for different data inputs and include features like updating the hash iteratively, u...
0.765742
Docs: Python310_31653
C
[ "hash_data", "iterative_hash", "secure_hash_with_salt", "verify_secure_hash" ]
4
[ [ "verify_secure_hash", "secure_hash_with_salt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
036fc7bc9d0236795953474ccb5c638a7c1b0c1e
ac4b3b95684769b318604525186479954d19ba96
v1.0
complete
Docs
Docs: Python310_40883_C
from multiprocessing import Pool, Queue, Lock, Process # Define the function to calculate the square of a number. def calculate_square(n): """ Calculate the square of a number. Args: n (int): The input number Returns: int: The square of the input number """ pass def worker_task(n...
from multiprocessing import Pool, Queue, Lock, Process def calculate_square(n): return n ** 2 def worker_task(n, output_queue, lock): result = calculate_square(n) with lock: print(f"Process-{n}: {n}^2 = {result}") output_queue.put(result) def main(): numbers = list(range(1, 21)) pool ...
from solution import calculate_square, worker_task from multiprocessing import Queue, Lock def test_calculate_square(): assert calculate_square(2) == 4 assert calculate_square(3) == 9 assert calculate_square(4) == 16 def test_worker_task(capsys): output_queue = Queue() lock = Lock() # Tes...
[ { "docstring": null, "function_declaration": "def calculate_square(n):", "function_name": "calculate_square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def worker_task(n, output_queue, lock):", "function_name": "worker_task", "parameter_list": "(n, ...
[ 0, 0, 0, 0, 1, 1, 0, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool, Queue, Lock, current_process\n\ndef calculate_square(n):\n \"\"\"\n Returns the square of the given number n.\n \"\"\"\n r...
trial_gpt4o_4
{ "original_instruction": "### Python Coding Assessment Question\n\n#### Objective\nTo assess your proficiency in using Python's `multiprocessing` module to create and manage processes, establish communication between them, and ensure proper synchronization.\n\n#### Problem Statement\nYou are tasked with creating a p...
0.645635
Docs: Python310_40883
C
[ "calculate_square", "worker_task", "main" ]
3
[ [ "worker_task", "calculate_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f1a29ae8a0669c8586bada055d1ead905db70468
0484dbc1df000bab5ebf90a9c7e0494c64a085a3
v1.0
complete
Docs
Docs: Python310_35253_C
import asyncio async def start_server(host: str, port: int): """ Implement a TCP server using asyncio's low-level event loop APIs, capable of handling multiple clients concurrently. The server should: - Start listening on a specified host and port. - Accept new client connections. - Read messages f...
import asyncio import logging async def handle_client(reader, writer): addr = writer.get_extra_info('peername') logging.info(f"Connection from {addr}") while True: data = await reader.read(100) message = data.decode() logging.info(f"Received {message} from {addr}") if mess...
import asyncio import pytest from solution import start_server async def client_task(host, port, messages): reader, writer = await asyncio.open_connection(host, port) responses = [] for msg in messages: writer.write(msg.encode()) await writer.drain() data = await reader.read(100)...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n ...
trial_gpt4o_1
{ "original_instruction": "**Question**: Implement a TCP server using asyncio's low-level event loop APIs, capable of handling multiple clients concurrently. The server should:\n- Start listening on a specified host and port.\n- Accept new client connections.\n- Read messages from clients and echo back the received m...
0.636375
Docs: Python310_35253
C
[ "handle_client", "start_server" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
636833f3ca6144764e8b0df48a3ceceb07247f86
1c10c93ea531d387d62666864b6d781cb4298983
v1.0
complete
Docs
Docs: Python310_25272_C
import tarfile import os def safe_extract_tarfile(tar_file_path: str, extract_to: str, file_extension: str) -> None: """ Extracts files with a specific extension from a tar archive to a given directory safely. Parameters: tar_file_path (str): Path to the tar file. extract_to (str): Directory w...
import os import tarfile def is_safe_path(base_path, target_path, follow_symlinks=True): if follow_symlinks: return os.path.realpath(target_path).startswith(os.path.realpath(base_path)) return os.path.abspath(target_path).startswith(os.path.abspath(base_path)) def safe_extract_tarfile(tar_file_path: s...
from solution import safe_extract_tarfile import os def test_safe_extract_txt_files(tmp_path): # Create a mock tar file tar_file_path = tmp_path / "test_archive.tar" extract_to = tmp_path / "extracted" file_content = "This is a test file." with tarfile.open(tar_file_path, "w") as tar: # Cr...
[ { "docstring": null, "function_declaration": "def is_safe_path(base_path, target_path, follow_symlinks=True):", "function_name": "is_safe_path", "parameter_list": "(base_path, target_path, follow_symlinks=True)" }, { "docstring": "Extracts files with a specific extension from a tar archive t...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport tarfile\n\ndef is_safe_path(base_path, target_path):\n # Ensure the target path is within the base path\n base_path = os.path.abspath(base_path)...
trial_gpt4o_2
{ "original_instruction": "### Objective:\nImplement a function that demonstrates the utilization of the `tarfile` module for safe extraction of files from a tar archive, applying necessary security filters. \n\n### Problem Statement:\nYou are provided with a tar archive file that contains multiple files and folders....
0.657343
Docs: Python310_25272
C
[ "is_safe_path", "safe_extract_tarfile" ]
2
[ [ "safe_extract_tarfile", "is_safe_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
66764eda54e98741c3b2fdf49c15d714ee8fa1bc
d640237d4f19bf2026e5f2be0503854f3bc65b16
v1.0
complete
Docs
Docs: Python310_41480_C
import warnings from typing import Callable def issue_warnings(): """ Issue a DeprecationWarning and a UserWarning. >>> issue_warnings() """ def set_warning_filter(action: str, category: str): """ Set a filter on warnings using warnings.filterwarnings(). Parameters: - action (str): The action...
import warnings def issue_warnings(): """ Issue a DeprecationWarning and a UserWarning. """ warnings.warn("Deprecated feature", DeprecationWarning) warnings.warn("User alert", UserWarning) def set_warning_filter(action, category): """ Set a filter on warnings using warnings.filterwarnings(...
import warnings from solution import issue_warnings, set_warning_filter, suppress_warnings_temporarily, test_warnings def test_issue_warnings(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") issue_warnings() assert len(w) == 2 assert any(isinstance(...
[ { "docstring": "Issue a DeprecationWarning and a UserWarning.", "function_declaration": "def issue_warnings():", "function_name": "issue_warnings", "parameter_list": "()" }, { "docstring": "Set a filter on warnings using warnings.filterwarnings().\n\nParameters:\n- action (str): The action t...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\ndef issue_warnings():\n \"\"\"\n Issues two types of warnings:\n - DeprecationWarning with the message \"Deprecated feature\".\n - UserWa...
trial_gpt4o_6
{ "original_instruction": "### Python Coding Assessment\n\n#### Objective:\nTo assess your understanding of the Python `warnings` module, including issuing warnings, handling them through filtering mechanisms, and using context managers to manage the behavior of warnings. \n\n#### Problem Statement:\nYou are required...
0.553281
Docs: Python310_41480
C
[ "issue_warnings", "set_warning_filter", "suppress_warnings_temporarily", "test_warnings" ]
4
[ [ "test_warnings", "issue_warnings" ], [ "test_warnings", "set_warning_filter" ], [ "test_warnings", "suppress_warnings_temporarily" ] ]
3
[]
false
[]
false
pytest
true
[]
true
681d3c2fffafbe13ef30145ac2a48e71b01d45cf
c957bb08192fb2af6588ee3ff73336f8d3804e4a
v1.0
complete
Docs
Docs: Python310_43979_C
def create_capsule(data: int, name: str): """ Create a PyCapsule with the given integer data and name. """ pass def get_capsule_data(name: str) -> int: """ Retrieve the integer data from a PyCapsule with the given name. >>> create_capsule(42, 'example.capsule') >>> get_capsule_data('example.cap...
# solution.py from typing import Dict # Simulate the PyCapsule in Python class PyCapsule: def __init__(self, data, name, destructor): self.data = data self.name = name self.destructor = destructor # Dictionary to store PyCapsules by name capsules: Dict[str, PyCapsule] = {} def create_caps...
# test_solution.py from solution import ( create_capsule, get_capsule_data, set_capsule_data, is_capsule_valid, cleanup_capsules ) def test_create_and_get_capsule_data(): create_capsule(42, 'example.capsule') assert get_capsule_data('example.capsule') == 42 def test_set_capsule_data(): create_cap...
[]
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from cffi import FFI\n\nffi = FFI()\n\nmodule_code = \"\"\"\n#include <Python.h>\n\nstatic PyObject *capsule_dict = NULL;\n\nstatic void capsule_destructor(PyObject *ca...
trial_gpt4o_6
{ "original_instruction": "### Advanced Coding Assessment Question: Managing PyCapsules\n\n**Objective**: Implement a Python C extension module that creates, manages, and verifies PyCapsule objects to encapsulate data and ensure data consistency throughout the module.\n\n### Requirements:\n\n1. **Create and Manage Py...
0.444591
Docs: Python310_43979
C
[ "create_capsule", "get_capsule_data", "set_capsule_data", "is_capsule_valid", "capsule_destructor", "cleanup_capsules" ]
6
[ [ "create_capsule", "capsule_destructor" ] ]
1
[]
false
[ "PyCapsule" ]
true
pytest
true
[]
true
0108595e98defbc5c2edf791aeafd2ee4e088d6b
2b3c389eb07a99e603706b19db55bdc73cdbaac9
v1.0
complete
Docs
Docs: Python310_35350_C
import asyncio import aiohttp from typing import List, Dict, Union async def fetch_all(urls: List[str]) -> Dict[str, Union[str, Exception]]: """ Function to concurrently download multiple URLs and gather their responses. Args: urls (List[str]): A list of URLs to be downloaded asynchronously. ...
import asyncio import aiohttp from typing import List, Dict, Union async def download(url: str) -> str: async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def fetch_all(urls: List[str]) -> Dict[str, Union[str, Exception]]:...
import asyncio import pytest from unittest.mock import patch, MagicMock from aiohttp import ClientError from solution import fetch_all @pytest.mark.asyncio async def test_fetch_all_success(): urls = ["http://example.com"] expected_content = "Example Domain" with patch('aiohttp.ClientSession.get') as m...
[]
[ 1, 1, 0, 0, 1, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom typing import List, Dict, Union\n\nasync def download(url: str) -> str:\n async with aiohttp.ClientSession() as session:\n ...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nYour task is to implement a function that utilizes `asyncio.Future` objects to concurrently download multiple URLs and gather their responses. The function should handle any exceptions that occur during the downloads and ensure that all results or exceptions are properly co...
0.726399
Docs: Python310_35350
C
[ "download", "fetch_all" ]
2
[ [ "fetch_all", "download" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
e912fc65231063566c040c54631af11c1917d422
a473ffcf352d21ba9b1b9f6a640c5ef55b673436
v1.0
complete
Docs
Docs: Python310_41276_C
import random import threading from multiprocessing import Pool from concurrent.futures import ThreadPoolExecutor def execute_pipeline(N: int) -> int: """ Simulate a simplified data processing pipeline using concurrent execution techniques. The pipeline involves data generation, data processing, and data aggre...
import random import threading from multiprocessing import Pool from concurrent.futures import ThreadPoolExecutor def generate_data(N): random.seed(42) # For reproducibility in tests return [random.randint(1, 100) for _ in range(N)] def process_data_chunk(chunk): return [x * 2 for x in chunk] def execut...
from solution import execute_pipeline, generate_data, process_data_chunk def test_generate_data(): data = generate_data(10) assert len(data) == 10 assert all(1 <= x <= 100 for x in data) def test_process_data_chunk(): chunk = [1, 2, 3, 4, 5] result = process_data_chunk(chunk) assert result == ...
[ { "docstring": null, "function_declaration": "def generate_data(N):", "function_name": "generate_data", "parameter_list": "(N)" }, { "docstring": null, "function_declaration": "def process_data_chunk(chunk):", "function_name": "process_data_chunk", "parameter_list": "(chunk)" }...
[ 1, 1, 0, 0, 0, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport threading\nfrom multiprocessing import Pool\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef generate_data(N):\n \"\"\"\n Generates...
trial_gpt4o_9
{ "original_instruction": "### Problem Description\n\nYou are required to simulate a simplified data processing pipeline using concurrent execution techniques. The pipeline consists of three stages:\n\n1. **Data Generation**: Generate a list of integers.\n2. **Data Processing**: Multiply each integer by 2.\n3. **Data...
0.615977
Docs: Python310_41276
C
[ "generate_data", "process_data_chunk", "execute_pipeline" ]
3
[ [ "execute_pipeline", "generate_data" ], [ "execute_pipeline", "process_data_chunk" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e3cd22b0415bdd922c85b611c30956c23982a242
4cd15d0e52b9303d6e99f70182b7175cac7ec3dc
v1.0
complete
Docs
Docs: Python310_49781_C
import os import shutil import zlib import gzip import bz2 import lzma import zipfile from pathlib import Path def compress_and_extract(action: str, compression_type: str, source_path: str, destination_path: str, options: dict = None) -> None: """ Manage compression and extraction of various file formats. ...
import os import shutil import zlib import gzip import bz2 import lzma import zipfile from pathlib import Path def compress_and_extract(action: str, compression_type: str, source_path: str, destination_path: str, options: dict = None) -> None: if action not in ["compress", "extract"]: raise ValueError("Act...
import os import pytest import gzip import shutil from pathlib import Path from solution import compress_and_extract # Helper function to create a test file def create_test_file(file_path, content): with open(file_path, 'w') as f: f.write(content) def test_compress_extract_gzip(tmp_path): source_file ...
[ { "docstring": null, "function_declaration": "def compress_and_extract(action, compression_type, source_path, destination_path, options=None):", "function_name": "compress_and_extract", "parameter_list": "(action, compression_type, source_path, destination_path, options=None)" }, { "docstrin...
[ 0, 1, 1, 0, 0, 1, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport zlib\nimport gzip\nimport bz2\nimport lzma\nimport zipfile\nimport shutil\n\ndef compress_and_extract(action: str, compression_type: str, source_path:...
trial_gpt4o_2
{ "original_instruction": "**Objective:**\n\nDesign a Python function that manages compression and extraction of various file formats using multiple modules provided. The function should demonstrate your understanding of `zlib`, `gzip`, `bz2`, `lzma`, and `zipfile` modules.\n\n**Task:**\n\nYou are required to impleme...
0.721336
Docs: Python310_49781
C
[ "compress_and_extract", "compress", "compress_zlib", "compress_gzip", "compress_bz2", "compress_lzma", "compress_zip", "extract", "extract_zlib", "extract_gzip", "extract_bz2", "extract_lzma", "extract_zip" ]
13
[ [ "compress", "compress_bz2" ], [ "compress", "compress_gzip" ], [ "compress", "compress_lzma" ], [ "compress", "compress_zip" ], [ "compress", "compress_zlib" ], [ "compress_and_extract", "compress" ], [ "compress_and_extract", "extrac...
12
[]
false
[]
false
pytest
true
[]
true
0d720628712cf2641e5911c9df333ac2bc862ac3
0d390f48889be6d936197cbcef46c03213567b3f
v1.0
complete
Docs
Docs: Python310_28694_C
import asyncio import socket import ssl async def start_server(host: str, port: int, ssl_context: ssl.SSLContext): """ Starts an asynchronous chat server that accepts multiple connections securely. Parameters: host (str): Address to bind the server. port (int): Port to bind the server. ssl_con...
import asyncio import socket import ssl clients = [] async def start_server(host: str, port: int, ssl_context: ssl.SSLContext): server = await asyncio.start_server(handle_client, host, port, ssl=ssl_context) async with server: await server.serve_forever() async def handle_client(reader: asyncio.Strea...
import asyncio import ssl import pytest from solution import start_server, connect_to_server, create_ssl_context pytestmark = pytest.mark.asyncio async def test_server_client_communication(): certfile = "server.crt" keyfile = "server.key" ssl_context = create_ssl_context(certfile, keyfile) server = a...
[ { "docstring": null, "function_declaration": "def create_ssl_context(certfile, keyfile):", "function_name": "create_ssl_context", "parameter_list": "(certfile, keyfile)" } ]
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport socket\nimport ssl\n\nclients = []\n\nasync def start_server(host: str, port: int, ssl_context: ssl.SSLContext):\n server = await asyncio.star...
trial_gpt4o_0
{ "original_instruction": "### Coding Challenge\n\n**Objective**: You are to create a networked chat application using Python that demonstrates your understanding of the `asyncio`, `socket`, and `ssl` modules. The application should have both server-side and client-side components and should securely communicate usin...
0.658447
Docs: Python310_28694
C
[ "start_server", "handle_client", "connect_to_server", "create_ssl_context" ]
4
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6f34d304c8f31f6e972f285d1ff3dd02ff931966
6a72d9d02e67a5a64c109afee5f42d9bccbe0b0d
v1.0
complete
Docs
Docs: Python310_38091_C
import ossaudiodev def switch_stereo_channels(data: bytes, sample_width: int) -> bytes: """ Switch the stereo channels in the provided audio data. :param data: Bytes containing stereo audio data. :param sample_width: Width of each audio sample in bytes. :return: Bytes containing stereo audio data w...
import ossaudiodev import time def switch_stereo_channels(data): """ Switch the stereo channels in the provided audio data. :param data: Bytes containing stereo audio data. :return: Bytes containing stereo audio data with switched channels. """ new_data = bytearray() for i in range(0, len(d...
def test_switch_stereo_channels(): # Original stereo data; two frames of 16-bit stereo (left, right) original_data = bytes([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) # Expected output after switching channels expected_data = bytes([0x03, 0x04, 0x01, 0x02, 0x07, 0x08, 0x05, 0x06]) result_...
[ { "docstring": "Switch the stereo channels in the provided audio data.\n:param data: Bytes containing stereo audio data.\n:return: Bytes containing stereo audio data with switched channels.", "function_declaration": "def switch_stereo_channels(data):", "function_name": "switch_stereo_channels", "par...
[ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ossaudiodev\n\ndef switch_stereo_channels(data):\n \"\"\"\n Switches stereo channels (left and right) in the given audio data.\n \n Args:\n data (...
trial_gpt4o_6
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nDesign and implement a Python script using the `ossaudiodev` module that records audio from a microphone, modifies the audio data, and then plays it back. The modification should involve switching stereo channels (left and right) or reversing ...
0.427229
Docs: Python310_38091
C
[ "switch_stereo_channels", "record_and_play" ]
2
[ [ "record_and_play", "switch_stereo_channels" ] ]
1
[]
false
[]
false
pytest
false
[]
true
65967ee52e769728f10869d9bb60e60a20f14210
2172888775e989f4d925a7f6d9c91486e0aa268d
v1.0
complete
Docs
Docs: Pytorch_15348_C
import os import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim from torch.multiprocessing import spawn def setup(rank, world_size, master_addr='localhost', master_port='12355'): """ Set up the environment variables and initialize the process group. >>> setup(0, 2, 'lo...
import os import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim from torch.multiprocessing import spawn from torch.utils.data import DataLoader, TensorDataset # 1. Environment variables setup def setup(rank, world_size, master_addr='localhost', master_port='12355'): os.env...
import pytest import torch import torch.distributed as dist from torch.multiprocessing import spawn from solution import setup, SimpleNN, train_model def test_setup(): rank = 0 world_size = 2 master_addr = 'localhost' master_port = '12355' setup(rank, world_size, master_addr, master_port) asser...
[]
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.multiprocessing import spawn\n\n# 1. Environme...
trial_gpt4o_5
{ "original_instruction": "### Distributed Training with PyTorch: Implementing a Simple Distributed Data-Parallel Model\n\n**Objective:**\nYour task is to implement a basic distributed data-parallel model using the `torch.distributed` package. This will involve initializing the process group, defining a simple neural...
0.545065
Docs: Pytorch_15348
C
[ "setup", "train_model", "main" ]
3
[ [ "train_model", "setup" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
532a46cb93f894ddabef137e029ca633f947c326
295b337d64b3958cb7b1962073ee8de068605efb
v1.0
complete
Docs
Docs: Scikit_41105_C
import numpy as np from sklearn.metrics import pairwise_distances def compute_pairwise_distances(X, Y=None, metric='euclidean'): """ Computes pairwise distances between the rows of array X and the rows of array Y. Parameters: - X: 2D numpy array of shape (n_samples_X, n_features) - Y: (optiona...
import numpy as np from sklearn.metrics import pairwise_distances def custom_distance(a, b): """ Custom distance metric defined as: d_custom(a, b) = sqrt(sum((a - b)^2) / (1 + sum((a + b)^2))) """ return np.sqrt(np.sum((a - b) ** 2) / (1 + np.sum((a + b) ** 2))) def compute_pairwise_distances(X, Y...
import numpy as np import pytest from solution import compute_pairwise_distances def test_euclidean_distances(): X = np.array([[2, 3], [3, 5], [5, 8]]) Y = np.array([[1, 0], [2, 1]]) expected = pairwise_distances(X, Y, metric='euclidean') result = compute_pairwise_distances(X, Y, metric='euclidean') ...
[ { "docstring": "Custom distance metric defined as:\nd_custom(a, b) = sqrt(sum((a - b)^2) / (1 + sum((a + b)^2)))", "function_declaration": "def custom_distance(a, b):", "function_name": "custom_distance", "parameter_list": "(a, b)" }, { "docstring": "Computes pairwise distances between the r...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.metrics import pairwise_distances\n\ndef custom_metric(a, b):\n \"\"\"\n Custom distance metric: sqrt(sum((a - b)^2) / (1 + sum((...
trial_gpt4o_8
{ "original_instruction": "### Coding Challenge: Implementing Custom Pairwise Distance Function\n\n#### Objective:\nYour task is to implement a custom function that calculates pairwise distances between samples using various distance metrics supported by `scikit-learn`. In addition to implementing standard metrics, y...
0.676698
Docs: Scikit_41105
C
[ "custom_distance", "compute_pairwise_distances" ]
2
[ [ "compute_pairwise_distances", "custom_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
92e0628609269ca614680ee3f9cd774ff787f5c5
7554ec28cdc9a0a4fe73740f00da2affa8105073
v1.0
complete
Prefill
Prefill_24_C
def max_rectangle_area(grid: List[List[int]]) -> int: """ 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": "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.", "prompt_id": "000000...
0.795014
Prefill_24
C
[ "max_rectangle_area", "largest_rectangle_area" ]
2
[ [ "max_rectangle_area", "largest_rectangle_area" ] ]
1
[]
false
[]
false
pytest
true
[]
true
46600eb265b4b0a4de6aaf0e71d707e17c6e577c
90ae853e7834730a3b2587e74d50242e994e2a57
v1.0
complete
Prefill
Prefill_229_C
def insert_at_bottom(stack: list, item): """ Insert an element at the bottom of the stack. Args: stack (list): The stack to insert into. item: The item to insert at the bottom. """ pass def reverse_stack(stack: list): """ Reverse a stack without using any additional data structures. Arg...
# 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": "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?", "prompt_id": "00000229", "row_id": 229, "seed_ids": "['magpie_prefill_229']" }
0.565341
Prefill_229
C
[ "insert_at_bottom", "reverse_stack" ]
2
[ [ "reverse_stack", "insert_at_bottom" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e9f54f8d3ac4f59312bae04fe0ce4413befb715d
987f3985aacc460e9ce59a308d1b35a1cba1381a
v1.0
complete
Prefill
Prefill_479_C
def sum_of_primes_in_range(start: int, end: int) -> int: """ Returns the sum of all prime numbers within the range [start, end] inclusively. >>> sum_of_primes_in_range(1, 10) 17 >>> sum_of_primes_in_range(11, 11) 11 >>> sum_of_primes_in_range(8, 10) 0 >>> sum_of_primes_in_range(1, ...
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": "Write a function to find the sum of all prime numbers within a given range [start, end] inclusively in Python.", "prompt_id": "00000479", "row_id": 479, "seed_ids": "['magpie_prefill_479']" }
0.680182
Prefill_479
C
[ "is_prime", "sum_of_primes_in_range" ]
2
[ [ "sum_of_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
202bfb2beaf9e5d5e4b05515b4b87f6c0600312e
223a67004c730cbf9c82064b87c70108a5161a1a
v1.0
complete
Prefill
Prefill_628_C
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: ...
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": "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.", "prompt_id": "00000628", "row_id": 628, "seed_ids": "['magpie_prefill_628']" }
0.55498
Prefill_628
C
[ "insert_into_bst", "create_bst_from_array" ]
2
[ [ "create_bst_from_array", "insert_into_bst" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
17c3b25cc68211ce48c987ee7735e952f114ee02
6ca91d4cbf7cfde54b2ef0ce5246455b8cfa6295
v1.0
complete
Prefill
Prefill_446_C
def is_palindrome(s: str) -> bool: """ Check if the given string is a palindrome. >>> is_palindrome("racecar") True >>> is_palindrome("hello") False >>> is_palindrome("level") True >>> is_palindrome("A") True >>> is_palindrome("ab") False """ def is_prime(n: int) -> bool: """ Ch...
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": "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.", "prompt_id": "00000446", "row_id": 446, ...
0.735355
Prefill_446
C
[ "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
55df7443548bfa28fc5de7ab3e4224ad9f6aee80
ca81529794a624019437d68df90faf41a1c12907
v1.0
complete
Prefill
Prefill_636_C
def prime_divisors(n: int) -> List[int]: """ 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. >>> prime_divisors(28) == [2, 7] >>> prime_divisors(30) == [2, 3, 5] >>> prime_divisors(13) == [13] ...
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": "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.", "prompt_id": "00000636", "row_id": 636, "seed_ids": "['magpie_prefill_636']" }
0.68211
Prefill_636
C
[ "is_prime", "prime_divisors" ]
2
[ [ "prime_divisors", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9af740c95de79626f5a898a5c7a4e4068d2a2072
1e9341c082aace06c95dbdfa25e48255acc55cc5
v1.0
complete
Prefill
Prefill_493_C
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:...
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": "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! \\).", "prompt_id...
0.512406
Prefill_493
C
[ "main", "factorial" ]
2
[ [ "factorial", "main" ] ]
1
[]
false
[ "FactorialEvent", "FactorialCalculator" ]
true
pytest
true
[]
true
e265a90337818bc09cb911d43644131759cc6cc9
1a6e4fcc25f9f2c88bbc38b9de5261912dbb2a47
v1.0
complete
Prefill
Prefill_935_C
def is_prime(n: int) -> bool: """ Checks if a number n is prime. >>> is_prime(2) True >>> is_prime(4) False """ def primes_in_range(start: int, end: int) -> list: """ Returns a list of prime numbers in the range [start, end). >>> primes_in_range(10, 20) [11, 13, 17, 19] ...
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": "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.", "prompt_id": "00000935", "r...
0.756667
Prefill_935
C
[ "is_prime", "primes_in_range" ]
2
[ [ "primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
da71108d8d039dc10dd2ebabbd2cd603e7bde1b3
84a470325e3d26f7a5b23e8aa2b0a16cd3f99443
v1.0
complete
Prefill
Prefill_632_C
def factorial(n: int) -> int: """ Returns the factorial of a given number using recursion. Handles ValueError for negative inputs. >>> factorial(0) 1 >>> factorial(1) 1 >>> factorial(5) 120 >>> try: ... factorial(-1) ... except ValueError as e: ... str(e) ...
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": "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.", "prompt_id": "00000632", "row_id": 632...
0.691271
Prefill_632
C
[ "factorial", "safe_factorial" ]
2
[ [ "safe_factorial", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f54bb6ef54e053b6cd2ae50c2dbe7aa01c19265b
28557f6d61d6d68f0a17ce1b6f549e829ee52e7f
v1.0
complete
Prefill
Prefill_899_C
def reverse_stack(stack): """ Reverses the given stack using recursion. >>> reverse_stack([1, 2, 3, 4]) [4, 3, 2, 1] >>> reverse_stack([1]) [1] >>> reverse_stack([]) [] """ def insert_at_bottom(stack, item): """ Inserts an item at the bottom of the given stack using recursion. >...
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": "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?", "prompt_id": "00000899", "row_id": 899, "seed_ids": "['magpie_prefill_899']" }
0.495141
Prefill_899
C
[ "reverse_stack", "insert_at_bottom" ]
2
[ [ "reverse_stack", "insert_at_bottom" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5b13f770f9aab34a272f34a14cf854732fdd7e94
6452604eda3f75415a3a83671b894184531c05f7
v1.0
complete
Prefill
Prefill_881_C
def quicksort(arr, low, high): """ Sort an array in-place using the QuickSort algorithm. >>> arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] >>> quicksort(arr, 0, len(arr)-1) >>> arr [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] >>> arr = [5, 4, 3, 2, 1] >>> quicksort(arr, 0, len(arr)-1) >>> arr [1, 2, ...
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": "Write a function to sort an array in-place using the QuickSort algorithm.", "prompt_id": "00000881", "row_id": 881, "seed_ids": "['magpie_prefill_881']" }
0.682232
Prefill_881
C
[ "quicksort", "partition" ]
2
[ [ "quicksort", "partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4a4ab09579850831eee1ffee09bb8d4e176bd903
9a91b17900892e318c22529ea73b0c4fe8a90c75
v1.0
complete
Prefill
Prefill_1173_C
def primes_in_range(start: int, end: int) -> List[int]: """ Returns a list of prime numbers in the range [start, end). >>> primes_in_range(2, 25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> primes_in_range(10, 10) [] >>> primes_in_range(4, 6) [5] """
def is_prime(n): """ Helper function to determine 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 ...
from solution import primes_in_range def test_empty_range(): assert primes_in_range(10, 10) == [] assert primes_in_range(25, 20) == [] def test_no_primes_in_range(): assert primes_in_range(4, 6) == [5] assert primes_in_range(24, 25) == [] def test_primes_in_small_range(): assert primes_in_range(2...
[ { "docstring": "Helper function to determine if a number 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_ran...
[ 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 ==...
trial_gpt4o_5
{ "original_instruction": "Write a function to identify all prime numbers within a given range. The function should return a list of prime numbers that are greater than or equal to the start of the range and less than the end of the range. A prime number is defined as a natural number greater than 1 that has no posit...
0.668352
Prefill_1173
C
[ "is_prime", "primes_in_range" ]
2
[ [ "primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e086c821100f49bc9e6513dd9273ca16cdf5397
a7c9b6a582d86528144cdc794650dff71a8075b2
v1.0
complete
Prefill
Prefill_1104_C
def is_fibonacci_number(num: int) -> bool: """ Check if a number is a Fibonacci number. >>> is_fibonacci_number(0) True >>> is_fibonacci_number(1) True >>> is_fibonacci_number(2) True >>> is_fibonacci_number(22) False >>> is_fibonacci_number(-1) False >>> is_fibonacci_number(144) True ""...
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": "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 ...
0.749735
Prefill_1104
C
[ "is_fibonacci_number", "is_fibonacci_square" ]
2
[ [ "is_fibonacci_square", "is_fibonacci_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c543fc9eada083958abfb0ae734a82137ac06f52
de5802a1f2ba980eec1529acfea534d6a9d8a893
v1.0
complete
Prefill
Prefill_1148_C
def merge_sort(arr): """ Perform a merge sort on an array. >>> merge_sort([]) == [] >>> merge_sort([1]) == [1] >>> merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] >>> merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] >>> merge_sort([3, 6, 2, 8, 4, 5, 7, 1]) == [1, 2, 3, 4, 5, 6, 7, 8] >>> me...
def merge_sort(arr): """ Perform a merge sort on an array. """ if len(arr) <= 1: return arr # Split the array into two halves mid = len(arr) // 2 left_half = arr[:mid] right_half = arr[mid:] # Recursively split and merge the halves left_sorted = merge_sort(left_half) ...
from solution import merge_sort def test_merge_sort_empty_array(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_array(): ass...
[ { "docstring": "Perform a merge sort on an array.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": "Merge two sorted arrays into one sorted array.", "function_declaration": "def merge(left, right):", "functio...
[ 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 merge_sort(arr):\n \"\"\"\n Function to perform merge sort on an array.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left = merge_sort(...
trial_gpt4o_9
{ "original_instruction": "Write a function to perform a merge sort on an array.", "prompt_id": "00001148", "row_id": 1148, "seed_ids": "['magpie_prefill_1148']" }
0.685668
Prefill_1148
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fd961012d72cab5dbdda720572d23919041c885c
dbc956d26da0b1f8a0bd09ff6e2125bf0fac67d7
v1.0
complete
Prefill
Prefill_1428_C
class TreeNode: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def delete_node(root: TreeNode, key: int) -> TreeNode: """ Write a function to delete a node from a binary tree in Python. The function should take in the root of...
class TreeNode: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def delete_node(root, key): if root is None: return root if key < root.key: root.left = delete_node(root.left, key) elif key > root.key: ro...
from solution import TreeNode, delete_node def inorder_traversal(root): return inorder_traversal(root.left) + [root.key] + inorder_traversal(root.right) if root else [] def test_delete_leaf_node(): root = TreeNode(5, TreeNode(3), TreeNode(7)) root = delete_node(root, 3) assert inorder_traversal(root) ...
[]
[ 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 deleteNode(root, key):\n if not ...
trial_gpt4o_8
{ "original_instruction": "Write a function to delete a node from a binary tree in Python. The function should take in the root of the binary tree and the key of the node to be deleted. The function should return the root of the modified tree.", "prompt_id": "00001428", "row_id": 1428, "seed_ids": "['magpie_pre...
0.590274
Prefill_1428
C
[ "delete_node", "find_min" ]
2
[ [ "delete_node", "find_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
77e35daa0c4024d7b8fb72ecbac57cf0a9f5dfa3
b3dad25367a8f1bb8eed82dae1a74b8d733d49a3
v1.0
complete
Prefill
Prefill_1223_C
def reverse_stack(stack): """ Reverses the stack using recursion. >>> stack = [] >>> reverse_stack(stack) >>> stack == [] True >>> stack = [1] >>> reverse_stack(stack) >>> stack == [1] True >>> stack = [1, 2] >>> reverse_stack(stack) >>> stack == [2, 1] True ...
def reverse_stack(stack): """ Reverses the stack using recursion. """ if not stack: return top = stack.pop() reverse_stack(stack) insert_at_bottom(stack, top) def insert_at_bottom(stack, item): """ Helper function to insert an element at the bottom of the stack. """ ...
from solution import reverse_stack 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] reverse_stack(stack...
[ { "docstring": "Reverses the stack using recursion.", "function_declaration": "def reverse_stack(stack):", "function_name": "reverse_stack", "parameter_list": "(stack)" }, { "docstring": "Helper function to insert an element at the bottom of the stack.", "function_declaration": "def inse...
[ 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 represented as a list using recursion.\n \"\"\"\n if not stack:\n return\n top = stack.pop()\n reverse_stack(sta...
trial_gpt4o_9
{ "original_instruction": "Write a function to reverse a stack using recursion. The stack is represented as a list in Python.", "prompt_id": "00001223", "row_id": 1223, "seed_ids": "['magpie_prefill_1223']" }
0.58253
Prefill_1223
C
[ "reverse_stack", "insert_at_bottom" ]
2
[ [ "reverse_stack", "insert_at_bottom" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5dd1ee5194e7ef960daaa01386cbe2840f858dc8
f7492467544fb21518566b205d2231b711123088
v1.0
complete
Prefill
Prefill_515_C
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: TreeNode, key: int) -> TreeNode: """ Deletes a node with the given key in a BST and returns t...
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": "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.", "prompt_id": "00000515", "row_id": 515, "seed_ids": "['magpie_prefill_515']" }
0.591453
Prefill_515
C
[ "deleteNode", "getMin" ]
2
[ [ "deleteNode", "getMin" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
5faba2a1b5529c76a326c5db7c8ba54930278050
7280438579d347063cc7d9a609d15f360eaf698d
v1.0
complete
Prefill
Prefill_1296_C
def find_maximum_subarray_sum(arr): """ Write a function to find the maximum subarray sum in a given array of integers. The function should use a divide and conquer approach. >>> find_maximum_subarray_sum([1, 2, 3, 4, 5]) 15 >>> find_maximum_subarray_sum([1, -2, 3, 4, -1, 2, 1, -5, 4]) ...
def max_crossing_sum(arr, left, mid, right): """ Helper function to find the maximum sum of the crossing subarray. """ # Include elements on left of mid. left_sum = float('-inf') total = 0 for i in range(mid, left - 1, -1): total += arr[i] if total > left_sum: lef...
import pytest from solution import find_maximum_subarray_sum def test_max_subarray_sum_all_positive(): assert find_maximum_subarray_sum([1, 2, 3, 4, 5]) == 15 def test_max_subarray_sum_mixed(): assert find_maximum_subarray_sum([1, -2, 3, 4, -1, 2, 1, -5, 4]) == 9 def test_max_subarray_sum_all_negative(): ...
[ { "docstring": "Helper function to find the maximum sum of the crossing subarray.", "function_declaration": "def max_crossing_sum(arr, left, mid, right):", "function_name": "max_crossing_sum", "parameter_list": "(arr, left, mid, right)" }, { "docstring": "Returns the maximum sum of the subar...
[ 1, 1, 1, 1, 0, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def max_crossing_sum(arr, l, m, h):\n left_sum = float('-inf')\n sum = 0\n for i in range(m, l - 1, -1):\n sum += arr[i]\n if sum > left_sum:\n left_sum = su...
trial_gpt4o_9
{ "original_instruction": "Write a function to find the maximum subarray sum in a given array of integers. The function should use a divide and conquer approach.", "prompt_id": "00001296", "row_id": 1296, "seed_ids": "['magpie_prefill_1296']" }
0.703323
Prefill_1296
C
[ "max_crossing_sum", "max_subarray_sum", "find_maximum_subarray_sum" ]
3
[ [ "find_maximum_subarray_sum", "max_subarray_sum" ], [ "max_subarray_sum", "max_crossing_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3995f23bf6a2d7765c3de3b810f486d5d17db584
084c4db61618f1fefc0afbaa945595f080b05a85
v1.0
complete
Prefill
Prefill_1896_C
def circular_permutations(n): """ Returns the number of distinct ways to arrange 'n' distinct items in a circle. >>> circular_permutations(0) 0 >>> circular_permutations(1) 1 >>> circular_permutations(2) 1 >>> circular_permutations(3) 2 >>> circular_permutations(4) 6...
def circular_permutations(n): """ Returns the number of distinct ways to arrange 'n' distinct items in a circle. """ if n <= 0: return 0 elif n == 1: return 1 else: return factorial(n - 1) def factorial(num): """ Helper function to compute the factorial of a give...
from solution import circular_permutations def test_circular_permutations_zero(): assert circular_permutations(0) == 0 def test_circular_permutations_one(): assert circular_permutations(1) == 1 def test_circular_permutations_two(): assert circular_permutations(2) == 1 def test_circular_permutations_thre...
[ { "docstring": "Returns the number of distinct ways to arrange 'n' distinct items in a circle.", "function_declaration": "def circular_permutations(n):", "function_name": "circular_permutations", "parameter_list": "(n)" }, { "docstring": "Helper function to compute the factorial of a given 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 circular_permutations(n):\n \"\"\"\n Returns the number of ways to arrange n distinct items in a circle,\n considering two arrangements identical if one can be obtained from the ...
trial_gpt4o_9
{ "original_instruction": "Write a function to calculate the number of ways to arrange 'n' distinct items in a circle, considering two arrangements identical if one can be obtained from the other by rotation.", "prompt_id": "00001896", "row_id": 1896, "seed_ids": "['magpie_prefill_1896']" }
0.597106
Prefill_1896
C
[ "circular_permutations", "factorial" ]
2
[ [ "circular_permutations", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
05528ac1575480f9a913a6159b11872d8d7af735
3dc58a19fdcaac2ca88da8b019fdae0dc8386e79
v1.0
complete
Prefill
Prefill_2261_C
import time def factorial_iterative(n): """ Returns the factorial of a number using an iterative approach. >>> factorial_iterative(0) == 1 >>> factorial_iterative(5) == 120 """ pass def factorial_recursive(n): """ Returns the factorial of a number using a recursive approach. >>> fa...
import time def factorial_iterative(n): """ Returns the factorial of a number using an iterative approach. """ if n < 0: raise ValueError("Factorial is not defined for negative numbers") result = 1 for i in range(2, n + 1): result *= i return result def factorial_recursive(...
import pytest from solution import factorial_iterative, factorial_recursive, compare_performance def test_factorial_iterative(): assert factorial_iterative(0) == 1 assert factorial_iterative(1) == 1 assert factorial_iterative(5) == 120 assert factorial_iterative(10) == 3628800 def test_factorial_recur...
[ { "docstring": "Returns the factorial of a number using an iterative approach.", "function_declaration": "def factorial_iterative(n):", "function_name": "factorial_iterative", "parameter_list": "(n)" }, { "docstring": "Returns the factorial of a number using a recursive approach.", "func...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef factorial_iterative(n):\n \"\"\"\n Calculate factorial using iterative approach.\n \"\"\"\n result = 1\n for i in range(2, n + 1):\n result *= i\n ...
trial_gpt4o_9
{ "original_instruction": "Write a function to calculate the factorial of a number using both iterative and recursive approaches in Python. Compare their performance and speed for large numbers.", "prompt_id": "00002261", "row_id": 2261, "seed_ids": "['magpie_prefill_2261']" }
0.616615
Prefill_2261
C
[ "factorial_iterative", "factorial_recursive", "compare_performance" ]
3
[ [ "compare_performance", "factorial_iterative" ], [ "compare_performance", "factorial_recursive" ] ]
2
[]
false
[]
false
pytest
true
[]
true
891296a113430e1f19e8e8fce94891c12f2438e7
0bf37e7bd34f75df6927c363d968adb7d6e72695
v1.0
complete
Prefill
Prefill_2205_C
def fibonacci(n): """ Returns the nth Fibonacci number using recursion. >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(4) 3 >>> fibonacci(5) 5 >>> fibonacci(6) 8 >>> fibonacci(7) 13 >>> fibonacci(8) 21 >>> fibonacci(9) 34 >>> fib...
def fibonacci(n): """ Returns the nth Fibonacci number using recursion. """ if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def check_fibonacci(): """ Verify the correctness of the fibonacci function with provided da...
from solution import fibonacci, check_fibonacci def test_fibonacci_base_cases(): assert fibonacci(0) == 0 assert fibonacci(1) == 1 def test_fibonacci_recursive(): assert fibonacci(2) == 1 assert fibonacci(3) == 2 assert fibonacci(4) == 3 assert fibonacci(5) == 5 assert fibonacci(6) == 8 ...
[ { "docstring": "Returns the nth Fibonacci number using recursion.", "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": "Verify the correctness of the fibonacci function with provided data points.", "function_declaration": ...
[ 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 fibonacci(n):\n \"\"\"\n Returns the nth Fibonacci number using a recursive approach.\n \"\"\"\n if n <= 0:\n raise ValueError(\"Input must be a positive integer.\")\n ...
trial_gpt4o_9
{ "original_instruction": "Write a function to compute the nth Fibonacci number using a recursive approach. The function should also include a check function to verify the correctness of the solution with provided data points.", "prompt_id": "00002205", "row_id": 2205, "seed_ids": "['magpie_prefill_2205']" }
0.823837
Prefill_2205
C
[ "fibonacci", "check_fibonacci" ]
2
[ [ "check_fibonacci", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
debbbce3daca5e26e72c9542504815e06e05e4c7
e3a055751a253017927ed5da0a4902ac16753eb0
v1.0
complete
Prefill
Prefill_1695_C
import math from typing import Dict def is_mersenne_prime(n: int) -> Dict[str, bool]: """ Check if a number is Mersenne prime, a perfect square, or a perfect cube. Args: n (int): The number to check. Returns: Dict[str, bool]: A dictionary with keys "mersenne_prime", "perfect_square" a...
import math def is_prime(n): """ Returns True if n is prime, else False. """ if n <= 1: return False if n in (2, 3): return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False ...
from solution import is_mersenne_prime def test_is_mersenne_prime(): # Test Mersenne prime numbers assert is_mersenne_prime(3)["mersenne_prime"] == True assert is_mersenne_prime(7)["mersenne_prime"] == True assert is_mersenne_prime(31)["mersenne_prime"] == True # Test non-Mersenne prime number ...
[ { "docstring": "Returns True if n is prime, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns a dictionary with the results if n is a Mersenne prime,\na perfect square, or a perfect cube.", "function_...
[ 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Returns True if n is prime, else False.\n \"\"\"\n if n <= 1:\n return False\n if n in (2, 3):\n return True\n if n ...
trial_gpt4o_0
{ "original_instruction": "Write a function to check if a number is a Mersenne prime. A Mersenne prime is a prime number that can be written as 2^p - 1 for some integer p. The function should also identify whether the number is a perfect square or a perfect cube. Provide the code in Python.", "prompt_id": "00001695...
0.685903
Prefill_1695
C
[ "is_prime", "is_mersenne_prime" ]
2
[ [ "is_mersenne_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e3817091246fe8915ea31c23bc2941b735db3a12
f1d191118d87971d983ff6c98ff1c46227d4ee1a
v1.0
complete
Prefill
Prefill_1012_C
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def is_mirror_tree(root) -> bool: """ Returns True if the binary tree is a mirror of itself (i.e., a palindrome). >>> root = TreeNode(1) >>> root.left = TreeNode(2) >>> root.right = TreeNo...
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": "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.", "prompt_id": "00001012", "row_id": 1012, "seed_ids": "['mag...
0.609499
Prefill_1012
C
[ "is_mirror_tree", "is_mirror" ]
2
[ [ "is_mirror_tree", "is_mirror" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
ba1cfe615606e10c1133bc2a7ec51c7f73cbf0b5
e7bdfccdced99f0d82c8223f24b8ca3f381ebd96
v1.0
complete
Prefill
Prefill_1139_C
def radix_sort(arr: List[int]) -> List[int]: """ Sort an array of numbers in ascending order using the radix sort algorithm. Args: arr (List[int]): An array of integers to be sorted. Returns: List[int]: The sorted array. >>> radix_sort([]) [] >>> radix_sort([1]) [1] >>...
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": "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.", "prompt_id": "00001139", "row_id": 1139...
0.703762
Prefill_1139
C
[ "radix_sort", "counting_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
63882d33eea2bb21a7ddf21023e7487da868d2e7
0363483a8af7bd170e1a5037b5ef56a88673360e
v1.0
complete
Prefill
Prefill_1576_C
from typing import List def sort_array(arr: List[int]) -> List[int]: """ Sort an array of integers using the merge sort algorithm. The merge sort algorithm is a divide and conquer algorithm that divides the input array into two halves, calls itself for the two halves, and then merges the two ...
def merge(arr, l, m, r): """ Merges two sub-arrays of arr. First sub-array is arr[l..m] Second sub-array is arr[m+1..r] """ n1 = m - l + 1 n2 = r - m # Create temp arrays L = arr[l:l + n1] R = arr[m + 1:m + 1 + n2] # Merge the temp arrays back into arr[l..r] i = 0 j...
from solution import sort_array def test_sort_array(): assert sort_array([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82] assert sort_array([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13] assert sort_array([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert sort_array([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5...
[ { "docstring": "Merges two sub-arrays of arr.\nFirst sub-array is arr[l..m]\nSecond sub-array is arr[m+1..r]", "function_declaration": "def merge(arr, l, m, r):", "function_name": "merge", "parameter_list": "(arr, l, m, r)" }, { "docstring": "Sorts an array using merge sort algorithm", "...
[ 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 merge_sort(arr):\n \"\"\"\n Perform merge sort on an array.\n \"\"\"\n if len(arr) > 1:\n mid = len(arr) // 2 # Finding the middle of the array\n left_half = ar...
trial_gpt4o_9
{ "original_instruction": "Write a function to sort an array of integers using the merge sort algorithm. The function should return the sorted array. The merge sort algorithm is a divide and conquer algorithm that divides the input array into two halves, calls itself for the two halves, and then merges the two sorted...
0.700474
Prefill_1576
C
[ "merge", "merge_sort", "sort_array" ]
3
[ [ "merge_sort", "merge" ], [ "sort_array", "merge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e382daf2cee3fa150764d689a4e652dfa37ffa80
75fccf5b6db51174cd8db12a6716b04539722e4b
v1.0
complete
Prefill
Prefill_1826_C
def merge_sort_bottom_up(arr): """ Perform a bottom-up merge sort on an array of integers. :param arr: List of integers to sort :return: New list with sorted integers in ascending order >>> merge_sort_bottom_up([]) == [] >>> merge_sort_bottom_up([1]) == [1] >>> merge_sort_bottom_up...
def merge_sort_bottom_up(arr): """ Perform a bottom-up merge sort on an array of integers. :param arr: List of integers to sort :return: New list with sorted integers in ascending order """ if len(arr) <= 1: return arr width = 1 n = len(arr) while width < n: ...
from solution import merge_sort_bottom_up def test_merge_sort_bottom_up_empty_array(): assert merge_sort_bottom_up([]) == [] def test_merge_sort_bottom_up_single_element(): assert merge_sort_bottom_up([1]) == [1] def test_merge_sort_bottom_up_two_elements(): assert merge_sort_bottom_up([2, 1]) == [1, 2] ...
[ { "docstring": "Perform a bottom-up merge sort on an array of integers.\n\n:param arr: List of integers to sort\n:return: New list with sorted integers in ascending order", "function_declaration": "def merge_sort_bottom_up(arr):", "function_name": "merge_sort_bottom_up", "parameter_list": "(arr)" ...
[ 1, 1, 1, 1, 0, 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 merge_sort_bottom_up(arr):\n \"\"\"\n Perform a merge sort on an array of integers using a bottom-up approach.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n n = ...
trial_gpt4o_9
{ "original_instruction": "Write a function to perform a merge sort on an array of integers using a bottom-up approach. The function should take an array of integers as input and return a new array that is sorted in ascending order. Additionally, the function should be able to handle arrays with duplicate values.", ...
0.621688
Prefill_1826
C
[ "merge_sort_bottom_up", "merge" ]
2
[ [ "merge_sort_bottom_up", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff2c3c93d1838efde2a3d8b2f4c70858552d0161
f5435285ff44d3f3946e1d333ffbedf0a596ffdc
v1.0
complete
Prefill
Prefill_1583_C
class TreeNode: def __init__(self, key=0, left=None, right=None): self.key = key self.left = left self.right = right def delete_node(root, key): """ Deletes the node with the specified key from the binary tree rooted at root. Returns the new root of the tree. >>> root =...
class TreeNode: def __init__(self, key=0, left=None, right=None): self.key = key self.left = left self.right = right def delete_node(root, key): """ Deletes the node with the specified key from the binary tree rooted at root. Returns the new root of the tree. """ if root...
from solution import TreeNode, delete_node, get_min def tree_to_list(root): """ Utility function to convert binary search tree to sorted list. Useful for validation in tests. """ if root is None: return [] return tree_to_list(root.left) + [root.key] + tree_to_list(root.right) def test_...
[]
[ 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):\n self.left = None\n self.right = None\n self.value = key\n\ndef deleteNode(root, key):\n \"\"\"\n Deletes a node with...
trial_gpt4o_7
{ "original_instruction": "Write a function to delete a node from the binary tree. Given the root of the tree and the key to be deleted, delete the node and return the new root.", "prompt_id": "00001583", "row_id": 1583, "seed_ids": "['magpie_prefill_1583']" }
0.620113
Prefill_1583
C
[ "delete_node", "get_min" ]
2
[ [ "delete_node", "get_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
2ed868fb669b008900096c488df53da246798588
071f9fb3c5473f333a1dc97c333c8cb7ea88aad6
v1.0
complete
Prefill
Prefill_1921_C
def remove_consecutive_duplicates(s: str) -> str: """ Returns a string by removing consecutive duplicates from the input string. >>> remove_consecutive_duplicates("aabbcc") == "abc" >>> remove_consecutive_duplicates("aaaa") == "a" >>> remove_consecutive_duplicates("ab") == "ab" >>> remove_consec...
def remove_consecutive_duplicates(s): """ Returns a string by removing consecutive duplicates from the input string s. """ if not s: return s result = [s[0]] for char in s[1:]: if char != result[-1]: result.append(char) return ''.join(result) def all_s...
from solution import remove_consecutive_duplicates, all_subsequences def test_remove_consecutive_duplicates(): assert remove_consecutive_duplicates("aabbcc") == "abc" assert remove_consecutive_duplicates("aaaa") == "a" assert remove_consecutive_duplicates("ab") == "ab" assert remove_consecutive_duplica...
[ { "docstring": "Returns a string by removing consecutive duplicates from the input string s.", "function_declaration": "def remove_consecutive_duplicates(s):", "function_name": "remove_consecutive_duplicates", "parameter_list": "(s)" }, { "docstring": "Returns all unique subsequences of the ...
[ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_subsequences(s: str) -> list:\n \"\"\"\n Generates all subsequences of the given string 's' with removal of consecutive duplicates.\n \"\"\"\n subsequences = set()\n\...
trial_gpt4o_7
{ "original_instruction": "Write a function to generate all subsequences of a string with removal of consecutive duplicates.", "prompt_id": "00001921", "row_id": 1921, "seed_ids": "['magpie_prefill_1921']" }
0.663594
Prefill_1921
C
[ "remove_consecutive_duplicates", "all_subsequences" ]
2
[ [ "all_subsequences", "remove_consecutive_duplicates" ] ]
1
[]
false
[]
false
pytest
true
[]
true
82b8dad5610f8a6ace184b7dc71dc7cd5e7b0224
1117e06568a943c914dfc75bf802f38e6e81593f
v1.0
complete
Prefill
Prefill_2000_C
from typing import List def is_valid_isbn10(isbn: str) -> bool: """ Checks if an ISBN-10 number is valid. >>> is_valid_isbn10("0306406152") == True >>> is_valid_isbn10("0471117099") == True >>> is_valid_isbn10("123456789X") == True >>> is_valid_isbn10("030640615") == False >>> is_valid_isbn...
def is_valid_isbn10(isbn): """ Checks if an ISBN-10 number is valid. """ if len(isbn) != 10: return False if not isbn[:9].isdigit(): return False if not (isbn[9].isdigit() or isbn[9] == 'X'): return False # calculate the checksum using ISBN-10 validation me...
from solution import is_valid_isbn10, filter_valid_isbn10 def test_is_valid_isbn10_valid(): assert is_valid_isbn10("0306406152") == True assert is_valid_isbn10("0471117099") == True assert is_valid_isbn10("123456789X") == True def test_is_valid_isbn10_invalid_length(): assert is_valid_isbn10("03064061...
[ { "docstring": "Checks if an ISBN-10 number is valid.", "function_declaration": "def is_valid_isbn10(isbn):", "function_name": "is_valid_isbn10", "parameter_list": "(isbn)" }, { "docstring": "Filters out valid ISBN-10 numbers from a list of strings.", "function_declaration": "def filter_...
[ 1, 1, 0, 1, 1, 0, 0, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_valid_isbn10(isbn):\n \"\"\"\n Validate an ISBN-10 number.\n \"\"\"\n\n if len(isbn) != 10:\n return False\n\n # Check the first 9 characters are all digits\n ...
trial_gpt4o_4
{ "original_instruction": "Write a function to filter out invalid ISBN-10 numbers from a list of strings, where a valid ISBN-10 must consist of 10 characters long, with the first 9 characters being digits and the last character being either a digit or an 'X' representing the value 10. Also, the check digit must be va...
0.588341
Prefill_2000
C
[ "is_valid_isbn10", "filter_valid_isbn10" ]
2
[ [ "filter_valid_isbn10", "is_valid_isbn10" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7a7386792c57fc3abc20602da04818c5a16b15fb
08f88cabdb9cb7b8ce878cbb49d783423c6979bd
v1.0
complete
Prefill
Prefill_2159_C
def is_prime(n: int) -> bool: """ Check if a number is prime or not. >>> is_prime(11) True >>> is_prime(4) False """ pass def sum_of_primes_in_range(start: int, end: int) -> int: """ Returns the sum of all prime numbers between start and end, inclusive. If there are no prime numbers in ...
def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def sum_of_primes_in_range(start, end): """ Returns the sum of all prime numbers between start and end, inclusive. If there are no prime numbers in ...
from solution import sum_of_primes_in_range def test_sum_of_primes_within_small_range(): assert sum_of_primes_in_range(10, 20) == 60 # primes are 11, 13, 17, 19 def test_sum_of_primes_within_large_range(): assert sum_of_primes_in_range(1, 100) == 1060 def test_no_primes_in_range(): assert sum_of_primes_...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the sum of all prime numbers between start and end, inclusive.\nIf there are no prime numbers in the range, returns 0.", "function_declaration"...
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
6
medium
0.6
{ "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 is prime.\n \"\"\"\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i ==...
trial_gpt4o_4
{ "original_instruction": "Write a function to calculate the sum of all prime numbers within a given range. The range is specified using two integers, `start` and `end`. The function should return the sum of all prime numbers between `start` and `end`, inclusive. If there are no prime numbers in the range, the functi...
0.744044
Prefill_2159
C
[ "is_prime", "sum_of_primes_in_range" ]
2
[ [ "sum_of_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3fe50956e4827ce6a7c057e4dcaa8647193050a5
616f537b4262a382c48c189f951088282f561bdc
v1.0
complete
Prefill
Prefill_2658_C
def merge_sort(arr): """ Sorts an array in increasing order using the merge sort algorithm. :param arr: List of integers to be sorted :return: List of integers sorted in increasing order """
def merge_sort(arr): """ Sorts an array in increasing order using the merge sort algorithm. :param arr: List of integers to be sorted :return: List of integers sorted in increasing order """ if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) ...
from solution import merge_sort def test_merge_sort_empty(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_array(): assert me...
[ { "docstring": "Sorts an array in increasing order using the merge sort algorithm.\n\n:param arr: List of integers to be sorted\n:return: List of integers sorted in increasing order", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { ...
[ 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 merge_sort(arr):\n \"\"\"\n Sorts an array in increasing order using the merge sort algorithm.\n \"\"\"\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = ar...
trial_gpt4o_9
{ "original_instruction": "Write a function to sort an array in increasing order using the merge sort algorithm.", "prompt_id": "00002658", "row_id": 2658, "seed_ids": "['magpie_prefill_2658']" }
0.674567
Prefill_2658
C
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a432cb50ed7a138a4069b8da9c477aa5aa434103
055b27cfc773f7d3138ec513862c9844b6955478
v1.0
complete
Prefill
Prefill_971_C
from typing import List def sieve_of_eratosthenes(n: int) -> List[int]: """ Returns a list of all prime numbers up to n using the Sieve of Eratosthenes algorithm. >>> sieve_of_eratosthenes(1) [] >>> sieve_of_eratosthenes(2) [2] >>> sieve_of_eratosthenes(10) [2, 3, 5, 7] >>> sieve_of_era...
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": "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).", "prompt_id": "00000971", "row_id": 971, "seed_ids": "['magpie_prefill_971']" }
0.664322
Prefill_971
C
[ "sieve_of_eratosthenes", "primes_in_range" ]
2
[ [ "primes_in_range", "sieve_of_eratosthenes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
add3469f3057120910054e43941d406699c0b49b
4b6006186a51857f2d0c1e6e857f9aea90506926
v1.0
complete
Prefill
Prefill_2211_C
def longest_palindromic_substring(s: str) -> str: """ Returns the longest palindromic substring in the provided string. >>> longest_palindromic_substring("babad") in ["bab", "aba"] >>> longest_palindromic_substring("cbbd") == "bb" >>> longest_palindromic_substring("") == "" >>> longest_palindromic_s...
def longest_palindromic_substring(s): """ Returns the longest palindromic substring in the provided string. """ n = len(s) if n == 0: return "" start = 0 end = 0 for i in range(n): len1 = expand_from_center(s, i, i) len2 = expand_from_center(s, i, i + 1) ...
from solution import longest_palindromic_substring def test_longest_palindromic_substring(): assert longest_palindromic_substring("babad") in ["bab", "aba"] assert longest_palindromic_substring("cbbd") == "bb" assert longest_palindromic_substring("") == "" assert longest_palindromic_substring("a") == "...
[ { "docstring": "Returns the longest palindromic substring in the provided string.", "function_declaration": "def longest_palindromic_substring(s):", "function_name": "longest_palindromic_substring", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def expand_from_...
[ 0, 0, 1, 1, 1, 1, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def longest_palindromic_substring(s):\n \"\"\"\n Returns the longest palindromic substring in a given string.\n \"\"\"\n if len(s) <= 1:\n return s\n\n start, max_length...
trial_gpt4o_9
{ "original_instruction": "Write a function to generate the longest palindromic substring in a given string. For example, for input \"babad\", the function should return \"bab\" or \"aba\" since both are the longest palindromic substrings. The function should be efficient and work for strings of various lengths.", ...
0.785625
Prefill_2211
C
[ "longest_palindromic_substring", "expand_from_center" ]
2
[ [ "longest_palindromic_substring", "expand_from_center" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d9e59c72839d8f82e314c6f3b2c7713c9a31ecfc
a776c93565332771f6e3297685b914dbdd6dff5b
v1.0
complete
Prefill
Prefill_2412_C
def is_prime(num: int) -> bool: """ Check if a number is a prime number. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(5) True """ def sum_of_primes(n: int) -> int: """ Calculate the sum of all prime numbers up to a given number `n`. >>> sum_of_primes(10) ...
def is_prime(num): if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 return True def sum_of_primes(n): retu...
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(5) == True assert is_prime(10) == False assert is_prime(13) == True assert is_prime(17) == True assert is_prime(1) == False...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def sum_of_primes(n):", "function_name": "sum_of_primes", "parameter_list": "(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 is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i * i <= nu...
trial_gpt4o_0
{ "original_instruction": "Write a function to calculate the sum of all prime numbers up to a given number `n`. For example, if `n` is 10, the prime numbers up to 10 are 2, 3, 5, 7, so the function should return 17.", "prompt_id": "00002412", "row_id": 2412, "seed_ids": "['magpie_prefill_2412']" }
0.748968
Prefill_2412
C
[ "is_prime", "sum_of_primes" ]
2
[ [ "sum_of_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
32bb5b88560ab523d3bbe2cf20683a427f8b50d6
bcbf55d5f558fea2ee1c6476774a2a03eac7baa8
v1.0
complete
Prefill
Prefill_3346_C
def factorial(n): """ Returns the factorial of a given number n. >>> factorial(0) = 1 >>> factorial(1) = 1 >>> factorial(5) = 120 """ def factorials_up_to_10(): """ Returns a list of factorials for the numbers from 0 to 10. >>> factorials_up_to_10() = [1, 1, 2, 6, 24, 120, 720, ...
def factorial(n): """ Returns the factorial of a given number n. """ if n == 0: return 1 result = 1 for i in range(1, n + 1): result *= i return result def factorials_up_to_10(): """ Returns a list of factorials for the numbers from 0 to 10. """ return [facto...
from solution import factorial, factorials_up_to_10 def test_factorial_base_cases(): assert factorial(0) == 1 assert factorial(1) == 1 def test_factorial_small_numbers(): assert factorial(2) == 2 assert factorial(3) == 6 def test_factorial_larger_numbers(): assert factorial(5) == 120 assert f...
[ { "docstring": "Returns the factorial of a given number n.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Returns a list of factorials for the numbers from 0 to 10.", "function_declaration": "def factorials_up_to_10...
[ 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 factorial(n):\n \"\"\"\n Returns the factorial of the number n.\n \"\"\"\n if n == 0:\n return 1\n result = 1\n for i in range(1, n + 1):\n result *= i\n ...
trial_gpt4o_9
{ "original_instruction": "Write a function to calculate the factorial of a number in Java. The function should return the factorial values for the numbers from 0 to 10.", "prompt_id": "00003346", "row_id": 3346, "seed_ids": "['magpie_prefill_3346']" }
0.728614
Prefill_3346
C
[ "factorial", "factorials_up_to_10" ]
2
[ [ "factorials_up_to_10", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b3da1e71126741abd5463d4c52fa0fe1e21c00da
9822d262c299f4dbc1b29bd1c9a12699575fcbdf
v1.0
complete
Prefill
Prefill_2329_C
def palindromic_partition(s: str) -> List[List[str]]: """ Generate all possible palindromic partitions of a given string. A palindromic partition cuts the string into some substrings which are all palindromes. >>> palindromic_partition('') [[]] >>> palindromic_partition('a') [['a']] >>>...
def is_palindrome(s): return s == s[::-1] def palindromic_partition(s): def find_partitions(start, path): if start == len(s): result.append(path[:]) return for end in range(start + 1, len(s) + 1): if is_palindrome(s[start:end]): path.append(s[...
from solution import palindromic_partition def test_palindromic_partition_empty_string(): assert palindromic_partition('') == [[]] def test_palindromic_partition_single_character(): assert palindromic_partition('a') == [['a']] def test_palindromic_partition_two_characters(): assert palindromic_partition(...
[ { "docstring": null, "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def palindromic_partition(s):", "function_name": "palindromic_partition", "parameter_list": "(s)" }, ...
[ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(sub):\n \"\"\"\n Check if the provided substring is a palindrome.\n \"\"\"\n return sub == sub[::-1]\n\ndef palindromic_partitions(s):\n \"\"\"\n Generate ...
trial_gpt4o_9
{ "original_instruction": "Write a function to generate all possible palindromic partitions of a given string `s`. A palindromic partition cuts the string into some substrings which are all palindromes. Return a list of all possible partitions.", "prompt_id": "00002329", "row_id": 2329, "seed_ids": "['magpie_pr...
0.708439
Prefill_2329
C
[ "is_palindrome", "palindromic_partition" ]
2
[ [ "palindromic_partition", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f9541fb73ee9fffbbcecd315750939752281d5ed
8bb6f34d17559edb22cc2879314bb9971ec445ba
v1.0
complete
Prefill
Prefill_812_C
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. """ pass def com...
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": "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.", "prompt_id": "00000812", "row_id": 812, "seed_ids": "['ma...
0.62185
Prefill_812
C
[ "binary_search", "compare_arrays" ]
2
[ [ "compare_arrays", "binary_search" ] ]
1
[]
false
[]
false
pytest
true
[]
true
061c7444ffecc6825298ff6fdb02bd7dff6f5808
79b2cd0d822f97b8811c074f68112cc90618fc6c
v1.0
complete
Prefill
Prefill_1068_C
class TreeNode: def __init__(self, key=0, left=None, right=None): self.key = key self.left = left self.right = right def delete_node(root, key): """ Delete a node from a binary search tree. Parameters: root (TreeNode): The root of the BST. key (int): The key of the ...
class TreeNode: def __init__(self, key=0, left=None, right=None): self.key = key self.left = left self.right = right def delete_node(root, key): """ Delete a node from a binary search tree. Parameters: root (TreeNode): The root of the BST. key (int): The key of the ...
from solution import TreeNode, delete_node, find_min def inorder_traversal(root): return inorder_traversal(root.left) + [root.key] + inorder_traversal(root.right) if root else [] def test_delete_node_leaf(): root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(6) root = delete_nod...
[]
[ 1, 1, 0, 1, 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": "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 deleteNode(root, key):\n \"\"\"\...
trial_gpt4o_8
{ "original_instruction": "Write a function to delete a node from a binary search tree (BST) in C. The function should take the root of the BST and the key of the node to be deleted as parameters. The function should return the updated root of the BST.", "prompt_id": "00001068", "row_id": 1068, "seed_ids": "['m...
0.608679
Prefill_1068
C
[ "delete_node", "find_min" ]
2
[ [ "delete_node", "find_min" ] ]
1
[]
false
[ "TreeNode" ]
true
pytest
true
[]
true
456e41126dafff676488ba9b31644f5c0ed91edd
b8b5e1f7f89de511d8bbb3e397a32d3dfb25ee1c
v1.0
complete
Prefill
Prefill_3136_C
def is_palindrome(s): """ Check if a given string is a palindrome. """ pass def generate_palindrome_combinations(s): """ Generate all possible palindrome combinations of a given string. """ pass def test_single_letter(): assert generate_palindrome_combinations("a") == [["a"]] def ...
def is_palindrome(s): """ Check if a given string is a palindrome. """ return s == s[::-1] def generate_palindrome_combinations(s): """ Generate all possible palindrome combinations of a given string. """ def backtrack(start, path, result): if start == len(s): result...
from solution import generate_palindrome_combinations def test_single_letter(): assert generate_palindrome_combinations("a") == [["a"]] def test_two_letters_palindrome(): assert generate_palindrome_combinations("aa") == [["a", "a"], ["aa"]] def test_two_letters_non_palindrome(): assert generate_palindrom...
[ { "docstring": "Check if a given string is a palindrome.", "function_declaration": "def is_palindrome(s):", "function_name": "is_palindrome", "parameter_list": "(s)" }, { "docstring": "Generate all possible palindrome combinations of a given string.", "function_declaration": "def generat...
[ 1, 1, 0, 0, 0, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_palindrome_combinations(s):\n \"\"\"\n Function to generate all possible palindrome combinations from the given string.\n \n Parameters:\n s (str): The input strin...
trial_gpt4o_5
{ "original_instruction": "Write a function to generate all possible paliindrome combinations of a given string. A palindrome is a word, phrase, number, or other sequences of characters which reads the same forward and backward (ignoring spaces, punctuation, and capitalization).", "prompt_id": "00003136", "row_id...
0.782544
Prefill_3136
C
[ "is_palindrome", "generate_palindrome_combinations" ]
2
[ [ "generate_palindrome_combinations", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9a1dfe48639284eab1f4656e9dcfbbf05f0897ef
d31d159292bf777aefa2495b397b98523663e90e
v1.0
complete
Prefill
Prefill_870_C
def toggle(grid, r, c): """ Toggle the light at (r, c) and its neighbors. Args: grid (List[List[int]]): The grid representing the lights. r (int): The row index of the light to toggle. c (int): The column index of the light to toggle. """ directions = [(0, 0), (0, 1), (1, 0),...
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": "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.", "prompt_id": "00000870", "row_id": 870, "s...
0.46933
Prefill_870
C
[ "toggle", "solve_lights_out" ]
2
[ [ "solve_lights_out", "toggle" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d422160b9e09b0f39fb23753acf3acf3f0a39617
a8897c5c7b224493a7e5495e512587b454321b06
v1.0
complete
Prefill
Prefill_4422_C
def factorial(n: int) -> int: """ Returns the factorial of n using recursion and memoization. >>> factorial(0) 1 >>> factorial(1) 1 >>> factorial(5) 120 >>> factorial(6) 720 """ def sum_of_factorials(n: int) -> int: """ Returns the sum of the factorials of numbers from 1 to n. >>> s...
def factorial(n, memo={}): """ Returns the factorial of n using recursion and memoization. """ if n in memo: return memo[n] if n <= 1: return 1 else: memo[n] = n * factorial(n-1, memo) return memo[n] def sum_of_factorials(n): """ Returns the sum of the fa...
from solution import factorial, sum_of_factorials def test_factorial_base_cases(): assert factorial(0) == 1 assert factorial(1) == 1 def test_factorial_general_cases(): assert factorial(5) == 120 assert factorial(6) == 720 def test_sum_of_factorials(): assert sum_of_factorials(1) == 1 assert ...
[ { "docstring": "Returns the factorial of n using recursion and memoization.", "function_declaration": "def factorial(n, memo={}):", "function_name": "factorial", "parameter_list": "(n, memo={})" }, { "docstring": "Returns the sum of the factorials of numbers from 1 to n.", "function_decl...
[ 1, 1, 1, 1, 0, 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, memo={}):\n \"\"\"\n Recursively calculates the factorial of a given number n using memoization.\n \"\"\"\n if n == 0:\n return 1\n if n not in memo:\n ...
trial_gpt4o_9
{ "original_instruction": "Write a function to calculate the factorial of a given number using recursion. Then, write a function to calculate the sum of the factorial of numbers from 1 to n using memoization. Finally, create a test function to verify the correctness of the implementation.", "prompt_id": "00004422",...
0.754122
Prefill_4422
C
[ "factorial", "sum_of_factorials" ]
2
[ [ "sum_of_factorials", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d74a5f9aa3cbe8387f7273ff83cc675cf46e5563
dacc0bd5f8a2398e117241e025d131a655284f58
v1.0
complete
Prefill
Prefill_2903_C
import itertools from typing import List, Tuple def calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float: """Calculate the Euclidean distance between two points. Each point is represented as a tuple (x, y).""" pass def total_route_distance(route: List[Tuple[int, int]]) -> float: ...
import itertools def calculate_distance(point1, point2): """ Calculate the Euclidean distance between two points. Each point is represented as a tuple (x, y). """ return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5 def total_route_distance(route): """ Calculate the tota...
from solution import optimal_route def test_optimal_route_square(): delivery_points = [(0, 0), (0, 1), (1, 1), (1, 0)] route = optimal_route(delivery_points) assert route == ((0, 0), (0, 1), (1, 1), (1, 0)) or route == ((1, 0), (0, 0), (0, 1...
[ { "docstring": "Calculate the Euclidean distance between two points.\nEach point is represented as a tuple (x, y).", "function_declaration": "def calculate_distance(point1, point2):", "function_name": "calculate_distance", "parameter_list": "(point1, point2)" }, { "docstring": "Calculate the...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Returns the distance between two points.\n \"\"\"\n return ((point1[0] - point2[0])**2 + (...
trial_gpt4o_9
{ "original_instruction": "Write a function to select the optimal route for a delivery truck using a given set of delivery points in a city. The function should take a list of delivery points as input and return the shortest route that the delivery truck can follow to complete all deliveries.", "prompt_id": "000029...
0.630812
Prefill_2903
C
[ "calculate_distance", "total_route_distance", "optimal_route" ]
3
[ [ "total_route_distance", "calculate_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
56f414ff56d3e0abcb9a572a2bf9e33d0f4c1d07
d8f3d9ccfd67abe31a216a46466a6e45bc60e19d
v1.0
complete
Prefill
Prefill_4284_C
def is_prime(n: int) -> bool: """ Check if a number n is a prime number. >>> is_prime(2) True >>> is_prime(4) False >>> is_prime(29) True """ def sum_primes_upto_100(arr: List[int]) -> int: """ Calculate the sum of numbers in the array that are less than or equal to 100 and are prime. >...
def is_prime(n): """ Check if a number n is a prime number. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def sum_primes_upto_1...
from solution import is_prime, sum_primes_upto_100 def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-3) == False def test_sum_primes_upt...
[ { "docstring": "Check if a number n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculate the sum of numbers in the array that are less than or equal to 100 and are prime.", "function_declaration...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Returns True if n is a prime number, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n...
trial_gpt4o_8
{ "original_instruction": "Write a function to calculate the sum of numbers in an array, but only for those numbers that are less than or equal to 100 and are prime. How can we implement this in Python using a simple loop and a function to check if a number is prime?", "prompt_id": "00004284", "row_id": 4284, "...
0.738267
Prefill_4284
C
[ "is_prime", "sum_primes_upto_100" ]
2
[ [ "sum_primes_upto_100", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
02e8c9c9baac4a89ded134d4b0bf1347c7c051f2
ac0e132b790f3454391229d3b623d9baf2ccaf45
v1.0
complete
Prefill
Prefill_3247_C
def longest_palindromic_substrings(strings: List[str]) -> List[str]: """ Write a function to iterate through a list of strings, find the longest palindromic substring in each string, and return a list of these substrings. >>> longest_palindromic_substrings(["babad"]) ["bab"] >>> longest_palindromic_subs...
def longest_palindromic_substring(s): """ Returns the longest palindromic substring of s. """ def expand_around_center(s, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right] longest = "" ...
from solution import longest_palindromic_substrings def test_single_palindrome(): input_list = ["babad"] expected_output = ["bab"] assert longest_palindromic_substrings(input_list) == expected_output def test_multiple_palindromes(): input_list = ["babad", "cbbd"] expected_output = ["bab", "bb"] ...
[ { "docstring": "Returns the longest palindromic substring of s.", "function_declaration": "def longest_palindromic_substring(s):", "function_name": "longest_palindromic_substring", "parameter_list": "(s)" }, { "docstring": "Returns a list of the longest palindromic substrings from each input...
[ 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Prefill-43K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n This function returns the longest palindromic substring in s.\n \"\"\"\n def expand_around_center(left: int, right: in...
trial_gpt4o_9
{ "original_instruction": "Write a function to iterate through a list of strings, find the longest palindromic substring in each string, and return a list of these substrings.", "prompt_id": "00003247", "row_id": 3247, "seed_ids": "['magpie_prefill_3247']" }
0.76701
Prefill_3247
C
[ "longest_palindromic_substring", "longest_palindromic_substrings" ]
2
[ [ "longest_palindromic_substrings", "longest_palindromic_substring" ] ]
1
[]
false
[]
false
pytest
true
[]
true
933d34992c2d5f03103fb5a1d8b42eb8473a4f7a
6bf5cfee17624694c71b2ffa37020fbbfe82f88f
v1.0
complete
Prefill
Prefill_3712_C
def is_prime(num: int) -> bool: """Check if a number is prime. >>> is_prime(2) == True >>> is_prime(3) == True >>> is_prime(4) == False """ def smallest_prime_greater_than(n: int) -> int: """ Find the smallest prime number greater than a given integer n. >>> smallest_prime_greater_than(...
def is_prime(num): """Check if a number is prime.""" if num <= 1: return False if num == 2: return True if num % 2 == 0: return False max_divisor = int(num ** 0.5) + 1 for d in range(3, max_divisor, 2): if num % d == 0: return False return True de...
from solution import is_prime, smallest_prime_greater_than 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_smallest_prime_greater_than(): assert smallest_prime_greater_than(...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Find the smallest prime number greater than n.", "function_declaration": "def smallest_prime_greater_than(n):", "funct...
[ 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": "import math\n\ndef is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n wh...
trial_gpt4o_9
{ "original_instruction": "Write a function to find the smallest prime number greater than a given integer `n`. Your function should take an integer `n` as input and return the smallest prime number greater than `n`. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.", ...
0.777405
Prefill_3712
C
[ "is_prime", "smallest_prime_greater_than" ]
2
[ [ "smallest_prime_greater_than", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d51150b7ba867749d18d99204d71d7a59bcef145
0115a74bd85ae343c003da5b8e0818ca02897077