version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Filter | Filter_19732_I | Given the following script:
```python
def greet(name):
print(f"Hello, {name}!")
```
Can we use this function within another function? Yes, we can! Here's an example:
```python
def process_info(name, age):
greet(name)
print(f"You are {age} years old.")
```
In the `process_info` function, we call `greet` and ... | def greet(name):
print(f"Hello, {name}!")
def show_address(address):
print(f"Your address is: {address}")
def process_info(name, age=None, address=None):
greet(name)
if age is None:
print("Your age is unknown.")
else:
print(f"You are {age} years old.")
if address:
show_... | from solution import greet, show_address, process_info
def test_greet(capsys):
greet("Alice")
captured = capsys.readouterr()
assert captured.out == "Hello, Alice!\n"
def test_show_address(capsys):
show_address("123 Main St, Anytown")
captured = capsys.readouterr()
assert captured.out == "Your ... | [
{
"docstring": null,
"function_declaration": "def greet(name):",
"function_name": "greet",
"parameter_list": "(name)"
},
{
"docstring": null,
"function_declaration": "def show_address(address):",
"function_name": "show_address",
"parameter_list": "(address)"
},
{
"docstri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greet(name):\n print(f\"Hello, {name}!\")\n\ndef show_address(address):\n print(f\"Your address is: {address}\")\n\ndef process_info(name, age=None, address=None):\n greet(name)\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019732",
"row_id": 19732,
"seed_ids": "['Llama-3.3-70B-Instruct_49788']"
} | 0.42453 | Filter_19732 | I | [
"greet",
"show_address",
"process_info"
] | 3 | [
[
"process_info",
"greet"
],
[
"process_info",
"show_address"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4dc967b0193105a91024d47a3a960a0cb1243d3c | 5d7a4e6d0e15e8a0d184000ed5d529639df4ccda | |||
v1.0 | instruct | Filter | Filter_19739_I | The time-dependent Schrodinger equation describes how a quantum state of a quantum system changes over time. When studying the vibrational motion of molecules, chemists commonly use the harmonic oscillator as a useful approximation to model molecular vibrations. In the context of the one-dimensional harmonic oscillator... | import numpy as np
import matplotlib.pyplot as plt
from scipy.special import hermite
from scipy.constants import hbar
def hermite_poly(n, x):
"""Compute the n-th Hermite polynomial."""
Hn = hermite(n)
return Hn(x)
def harmonic_oscillator_wavefunction(n, x, m, omega):
"""Compute the n-th wavefunction o... | import numpy as np
from solution import harmonic_oscillator_wavefunction, probability_density
def test_hermite_poly():
from scipy.special import hermite
x = np.linspace(-5, 5, 1000)
assert np.allclose(hermite_poly(0, x), hermite(0)(x))
assert np.allclose(hermite_poly(1, x), hermite(1)(x))
assert np... | [
{
"docstring": "Compute the n-th Hermite polynomial.",
"function_declaration": "def hermite_poly(n, x):",
"function_name": "hermite_poly",
"parameter_list": "(n, x)"
},
{
"docstring": "Compute the n-th wavefunction of a quantum harmonic oscillator.",
"function_declaration": "def harmonic... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.special import hermite\nfrom scipy.constants import hbar\n\ndef harmonic_oscillator_wavefunction(n, x, m, ω):\n \"\"\"\n C... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019739",
"row_id": 19739,
"seed_ids": "['Llama-3.3-70B-Instruct_49813']"
} | 0.321359 | Filter_19739 | I | [
"hermite_poly",
"harmonic_oscillator_wavefunction",
"probability_density",
"plot_wavefunctions"
] | 4 | [
[
"harmonic_oscillator_wavefunction",
"hermite_poly"
],
[
"plot_wavefunctions",
"harmonic_oscillator_wavefunction"
],
[
"plot_wavefunctions",
"probability_density"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 6506cf334c36bac36d02f928acd2ef5526c6f483 | 0edff0f922ec3dc09f5e991485ade4d93489f369 | |||
v1.0 | instruct | Filter | Filter_19740_I | I've taken Calculus 1 & 2 (Multivariable). I'm just beginning to learn Differential Equations and I want to write some simple python code to visualize the behavior of the spring-mass system, which is governed by the equation: m*x''(t) + c*x'(t) + k*x(t) = F(t). Can you guide me through how to solve and visualize this s... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def spring_mass_system(state, t, m, c, k, F):
"""
Defines the differential equations for the coupled spring-mass system.
Arguments:
state : vector of the state variables [x, x'] (position and velocity)
t... | import numpy as np
from solution import spring_mass_system, solve_spring_mass
def test_spring_mass_system_no_damping_no_force():
# No damping and no external force
m = 1.0
c = 0.0
k = 1.0
F = lambda t: 0.0
state = [1.0, 0.0] # initial conditions (x = 1.0, x' = 0.0)
t = 0.0
result... | [
{
"docstring": "Defines the differential equations for the coupled spring-mass system.\n\nArguments:\n state : vector of the state variables [x, x'] (position and velocity)\n t : time\n m : mass\n c : damping coefficient\n k : spring constant\n F : external force as f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\ndef spring_mass_system(y, t, m, c, k, F):\n \"\"\"\n Defines the differential equation for the ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019740",
"row_id": 19740,
"seed_ids": "['Llama-3.3-70B-Instruct_49814']"
} | 0.341687 | Filter_19740 | I | [
"spring_mass_system",
"solve_spring_mass",
"visualize_solution"
] | 3 | [
[
"solve_spring_mass",
"spring_mass_system"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | c4d5495db55d763de812eb82a88143b6bbd40301 | 9844550374edf14dc8e43839eb5daee8248fd142 | |||
v1.0 | instruct | Filter | Filter_19755_I | I wrote a Python solution to a Project Euler problem that calculates the sum of all the odd numbers in a Fibonacci sequence until a specified number. The code is below:
```python
def fibonacci():
"""Return a generator that generates Fibonacci sequence."""
a, b = 0, 1
while True:
yield a
a, b... | def fibonacci():
"""Return a generator that generates Fibonacci sequence."""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def sum_of_odd_fibonacci(sequence_max):
"""Return the sum of all the odd numbers in the Fibonacci sequence up to sequence_max."""
fib_gen = fibonacci()
su... | from solution import fibonacci, sum_of_odd_fibonacci
def test_sum_of_odd_fibonacci_up_to_10():
assert sum_of_odd_fibonacci(10) == 10 # Odd Fibonacci numbers: 1, 1, 3, 5, sum is 10
def test_sum_of_odd_fibonacci_up_to_1():
assert sum_of_odd_fibonacci(1) == 2 # Odd Fibonacci numbers: 1, 1, sum is 2
def test_s... | [
{
"docstring": "Return a generator that generates Fibonacci sequence.",
"function_declaration": "def fibonacci():",
"function_name": "fibonacci",
"parameter_list": "()"
},
{
"docstring": "Return the sum of all the odd numbers in the Fibonacci sequence up to sequence_max.",
"function_decl... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci():\n \"\"\"Return a generator that generates Fibonacci sequence.\"\"\"\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a + b\n\ndef sum_of_odd_fibonacci(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019755",
"row_id": 19755,
"seed_ids": "['Llama-3.3-70B-Instruct_49849']"
} | 0.611464 | Filter_19755 | I | [
"fibonacci",
"sum_of_odd_fibonacci"
] | 2 | [
[
"sum_of_odd_fibonacci",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9276d419215581634e04bbf040414d4b800586a | b5f2587eb7c135e122194d7911b19d6191742220 | |||
v1.0 | instruct | Filter | Filter_19778_I | Here are the rules for the FizzBuzz problem:
1. If the number is divisible by 3, print "Fizz".
2. If the number is divisible by 5, print "Buzz".
3. If the number is divisible by both 3 and 5, print "FizzBuzz".
4. If the number is not divisible by either 3 or 5, print the number.
Write the code that implements the Fi... | def fizz_buzz(n):
"""
Returns the FizzBuzz result for an input number n.
"""
if n % 3 == 0 and n % 5 == 0:
return "FizzBuzz"
elif n % 3 == 0:
return "Fizz"
elif n % 5 == 0:
return "Buzz"
else:
return str(n)
def fizz_buzz_range(start, end):
"""
Returns... | from solution import fizz_buzz, fizz_buzz_range
def test_fizz_buzz():
assert fizz_buzz(1) == "1"
assert fizz_buzz(3) == "Fizz"
assert fizz_buzz(5) == "Buzz"
assert fizz_buzz(15) == "FizzBuzz"
assert fizz_buzz(30) == "FizzBuzz"
assert fizz_buzz(7) == "7"
assert fizz_buzz(9) == "Fizz"
ass... | [
{
"docstring": "Returns the FizzBuzz result for an input number n.",
"function_declaration": "def fizz_buzz(n):",
"function_name": "fizz_buzz",
"parameter_list": "(n)"
},
{
"docstring": "Returns the list of FizzBuzz results for a range of numbers from start to end (inclusive).",
"functio... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fizzbuzz():\n \"\"\"\n Prints the FizzBuzz sequence from 1 to 100.\n \"\"\"\n for i in range(1, 101):\n if i % 3 == 0 and i % 5 == 0:\n print(\"FizzBuzz\")\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019778",
"row_id": 19778,
"seed_ids": "['Llama-3.3-70B-Instruct_49903']"
} | 0.739867 | Filter_19778 | I | [
"fizz_buzz",
"fizz_buzz_range"
] | 2 | [
[
"fizz_buzz_range",
"fizz_buzz"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0e38a2b4d3a3dbce0c19b35a2a47e8061d846986 | b57fa523be09c132ee540637cf29345a831b53af | |||
v1.0 | instruct | Filter | Filter_19822_I | I've been learning about the basics of neural networks and how to implement them using common libraries. I'm looking to take my knowledge to the next level by incorporating genetic algorithms into my project. Can you provide a tutorial on how to use genetic algorithms for neural network optimization? | import numpy as np
# Define the neural network
class SimpleNN:
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.weights_input_hidden = np.random.randn(input_size, hidden_size)
... | from solution import SimpleNN, genetic_algorithm
import numpy as np
def test_nn_structure():
nn = SimpleNN(2, 2, 1)
assert nn.input_size == 2
assert nn.hidden_size == 2
assert nn.output_size == 1
assert nn.weights_input_hidden.shape == (2, 2)
assert nn.weights_hidden_output.shape == (2, 1)
def... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\n# Define the neural network\nclass SimpleNN:\n def __init__(self, input_size, hidden_size, output_size):\n self.input_size = input_size\n self.hidden_siz... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019822",
"row_id": 19822,
"seed_ids": "['Llama-3.3-70B-Instruct_49997']"
} | 0.209485 | Filter_19822 | I | [
"fitness_function",
"crossover",
"mutate",
"genetic_algorithm",
"main"
] | 5 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness_function"
],
[
"genetic_algorithm",
"mutate"
]
] | 3 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"numpy"
] | false | 4ec495adc3b4b393006f81af01c741b262a0a2c3 | 5c87cc636ebed1ecd44d48b5ce08c77ffe69f858 | |||
v1.0 | instruct | Filter | Filter_19834_I | You've been tasked with writing a recursive function to produce the next smallest palindrome number from the input number. A palindrome is a number that reads the same forwards and backwards, for example 121, 12321, etc. If the input number is negative or not an integer, the function should raise a ValueError. | def is_palindrome(num):
return str(num) == str(num)[::-1]
def next_palindrome_recursive(n):
"""
Returns the next smallest palindrome number greater than n.
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Input number must be a non-negative integer.")
def helper(k):
... | from solution import next_palindrome_recursive
import pytest
def test_next_palindrome_regular_case():
assert next_palindrome_recursive(123) == 131
def test_next_palindrome_single_digit():
assert next_palindrome_recursive(7) == 8
def test_next_palindrome_already_palindrome():
assert next_palindrome_recurs... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": "Returns the next smallest palindrome number greater than n.",
"function_declaration": "def next_palindrome_recursive(n):",
"function_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(n):\n s = str(n)\n return s == s[::-1]\n\ndef next_smallest_palindrome(n):\n if not isinstance(n, int) or n < 0:\n raise ValueError(\"Input must be a non-nega... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019834",
"row_id": 19834,
"seed_ids": "['Llama-3.3-70B-Instruct_50041']"
} | 0.812958 | Filter_19834 | I | [
"is_palindrome",
"next_palindrome_recursive"
] | 2 | [
[
"next_palindrome_recursive",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c2d04fb2e4e748a425cbc552a1816be7ac1f157f | ef771130524d949af9697310f881a9a763b51218 | |||
v1.0 | instruct | Filter | Filter_19875_I | ### Lesson Plan: Random Number Generation and Simulation
#### Topic: Random Number Generation
##### Objective:
- Write Python code to generate truly random numbers
- Simulate a random experiment to estimate probabilities
#### Introduction (10 minutes)
Introduce the concept of random number generation and its importanc... | import secrets
def generate_random_number(min_val, max_val):
"""
Generate a random number between min_val and max_val inclusive.
"""
return secrets.randbelow(max_val - min_val + 1) + min_val
def simulate_coin_toss(num_tosses):
"""
Simulate a coin toss num_tosses times.
Returns a tuple (hea... | from solution import generate_random_number, simulate_coin_toss
def test_generate_random_number_range():
min_val = 1
max_val = 10
for _ in range(1000):
result = generate_random_number(min_val, max_val)
assert min_val <= result <= max_val
def test_simulate_coin_toss_counts():
num_tosses... | [
{
"docstring": "Generate a random number between min_val and max_val inclusive.",
"function_declaration": "def generate_random_number(min_val, max_val):",
"function_name": "generate_random_number",
"parameter_list": "(min_val, max_val)"
},
{
"docstring": "Simulate a coin toss num_tosses time... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import secrets\n\ndef generate_random_number(min_val, max_val):\n \"\"\"Generate a random number between min_val and max_val inclusive\"\"\"\n if min_val > max_val:\n raise ValueE... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019875",
"row_id": 19875,
"seed_ids": "['Llama-3.3-70B-Instruct_50127']"
} | 0.568625 | Filter_19875 | I | [
"generate_random_number",
"simulate_coin_toss"
] | 2 | [
[
"simulate_coin_toss",
"generate_random_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c44428d8f601a977a012ff353be223ed3c632cd | 9244dd2d7171b55ec29535b442847a7903fccffe | |||
v1.0 | instruct | Filter | Filter_19880_I | ### Situation:
We have a project where we need to compare two sets of data, the original data and the new data. Each data point is a JSON document and we are comparing them to see if they have been updated.
Our current code is:
```python
import json
from collections import Counter
def json_DIFF(original_data, new_da... | import json
from collections import Counter
def compare_json(orig_json, new_json, path=""):
if orig_json == new_json:
return {}
changes = {}
if isinstance(orig_json, dict) and isinstance(new_json, dict):
all_keys = set(orig_json.keys()).union(set(new_json.keys()))
for key ... | from solution import json_DIFF, compare_json
import pytest
def test_no_changes(tmp_path):
orig_data = {"key1": "value1", "key2": "value2"}
new_data = {"key1": "value1", "key2": "value2"}
orig_file = tmp_path / "orig.json"
new_file = tmp_path / "new.json"
orig_file.write_text(json.dumps(o... | [
{
"docstring": null,
"function_declaration": "def compare_json(orig_json, new_json, path=''):",
"function_name": "compare_json",
"parameter_list": "(orig_json, new_json, path='')"
},
{
"docstring": null,
"function_declaration": "def json_DIFF(original_data, new_data):",
"function_nam... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nfrom collections import Counter\n\ndef json_diff(original_data, new_data):\n def compare_json(orig, new, path=\"\"):\n \"\"\"Compares two JSON objects and returns a list... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019880",
"row_id": 19880,
"seed_ids": "['Llama-3.3-70B-Instruct_50137']"
} | 0.600838 | Filter_19880 | I | [
"compare_json",
"json_DIFF"
] | 2 | [
[
"json_DIFF",
"compare_json"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4de7eeb3ebe4fb84c31a413a9cd103093ec2807b | 4cb82580c7c6018f96ed5ad8f59f7cdd094888a7 | |||
v1.0 | instruct | Filter | Filter_19902_I | Here's my encoding algo for text compression: Main string is broken down into continous substrings of either alphanumeric(a-z, A-Z, 0-9) characters, non-alphanumeric characters(like space, symbol), or both together. Then encode each substring by adding a certain integer 'X' to the ASCII value of each character in the s... | import random
import string
def encode_substring(substr, shift):
encoded_chars = []
for i, char in enumerate(substr):
encoded_chars.append(chr(((ord(char) + shift + i) % 256))) # Shift can be dynamic per character
return ''.join(encoded_chars)
def encode_text(text, base_shift):
alphanumeric =... | from solution import encode_text
def test_encode_text_alphanumeric():
original = "abc123"
encoded = encode_text(original, 4)
assert encoded == ''.join([chr((ord(char) + 4 + i) % 256) for i, char in enumerate(original)])
def test_encode_text_non_alphanumeric():
original = "!@# $%^"
encoded = e... | [
{
"docstring": null,
"function_declaration": "def encode_substring(substr, shift):",
"function_name": "encode_substring",
"parameter_list": "(substr, shift)"
},
{
"docstring": null,
"function_declaration": "def encode_text(text, base_shift):",
"function_name": "encode_text",
"par... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def encode_text_with_variable_shift(text, base_shift, salt, seed):\n \"\"\"\n Encode the input text with a variable shift value.\n \n Args:\n text (str): Input text to be en... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019902",
"row_id": 19902,
"seed_ids": "['Llama-3.3-70B-Instruct_50202']"
} | 0.586898 | Filter_19902 | I | [
"encode_substring",
"encode_text"
] | 2 | [
[
"encode_text",
"encode_substring"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f7d31176acbf036844f8b216e90b30ded2c80f2a | b7aec0c66f68e800fc9119be9536e7a72d8750c9 | |||
v1.0 | instruct | Filter | Filter_19910_I | Can you help me write a Python 3 solution to a Project Euler problem?
Here is the problem:
145: How many reversible numbers are there below one-million that only have an even number of 0's?
My first guess is that there are around 10,000 reversible numbers. So to start with I will create a program that checks each n... | def is_reversible(n):
"""
Returns True if the number 'n' is reversible.
A number is considered reversible if reversing the digits results in a different number,
and the sum of the number and its reverse has all odd digits.
"""
str_n = str(n)
reversed_str = str_n[::-1]
reversed_n = int(re... | from solution import is_reversible, count_reversible_numbers
def test_is_reversible():
assert is_reversible(12) == True # 12 + 21 = 33, all odd digits
assert is_reversible(21) == True # 21 + 12 = 33, all odd digits
assert is_reversible(10) == False # ends in 0
assert is_reversible(11) == False # 11... | [
{
"docstring": "Returns True if the number 'n' is reversible.\nA number is considered reversible if reversing the digits results in a different number,\nand the sum of the number and its reverse has all odd digits.",
"function_declaration": "def is_reversible(n):",
"function_name": "is_reversible",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_reversible(n):\n \"\"\"\n Check if a number is reversible.\n \n A number is reversible if:\n - Reversing the digits results in a different number.\n - It does not cont... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019910",
"row_id": 19910,
"seed_ids": "['Llama-3.3-70B-Instruct_50218']"
} | 0.626534 | Filter_19910 | I | [
"is_reversible",
"count_reversible_numbers"
] | 2 | [
[
"count_reversible_numbers",
"is_reversible"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4699d32ce78cc7976e77a5c932ecb1f443b281a4 | e3ce0527ae2385d18e449bbca13bd2c5a2d1da3a | |||
v1.0 | instruct | Filter | Filter_19913_I | Based on your analysis of the massive dataset comprised of functions, algorithms, and comments, I'd like you to provide an optimized algorithm to solve the following problem:
**Problem: Generate Prime Number (5)**
Let's assume for simplicity and without loss of generality that we are interested in generating the 5th p... | def is_prime(num):
"""
Checks whether a number is a prime.
Args:
num (int): The number to be checked.
Returns:
bool: True if the number is prime, False otherwise.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return Fals... | 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(1) == False
assert is_prime(0) == False
assert is_prime(-1) == False
def test_nt... | [
{
"docstring": "Checks whether a number is a prime.\n\nArgs:\nnum (int): The number to be checked.\n\nReturns:\nbool: True if the number is prime, False otherwise.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Find t... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Checks whether a number is a prime.\n \n Args:\n num (int): The number to be checked.\n \n Returns:\n bool: True if the number is prime, F... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019913",
"row_id": 19913,
"seed_ids": "['Llama-3.3-70B-Instruct_50222']"
} | 0.615651 | Filter_19913 | I | [
"is_prime",
"nth_prime"
] | 2 | [
[
"nth_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d5dff815a32650ae9ffb19d3787cfb9a0f1c608a | c7405586a0b6ef73e00d1c5c9e6944dc49e39063 | |||
v1.0 | instruct | Filter | Filter_19932_I | I have 1000 runner ids and want to assign a unique 2 character code to each runner based on their id. What is the most efficient and best way to do this? | import itertools
import string
def generate_runner_codes():
"""
Generate a list of unique 2-character codes.
"""
characters = string.digits + string.ascii_uppercase
codes = [''.join(code) for code in itertools.product(characters, repeat=2)]
return codes
def assign_codes_to_runners(runner_ids):... | from solution import generate_runner_codes, assign_codes_to_runners
def test_generate_runner_codes_length():
codes = generate_runner_codes()
assert len(codes) == 36 * 36 # 1296 unique codes
def test_generate_runner_codes_uniqueness():
codes = generate_runner_codes()
assert len(codes) == len(set(codes... | [
{
"docstring": "Generate a list of unique 2-character codes.",
"function_declaration": "def generate_runner_codes():",
"function_name": "generate_runner_codes",
"parameter_list": "()"
},
{
"docstring": "Assigns unique 2-character codes to runners based on given runner ids.\n\nArgs:\n- runner... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def to_base36(num):\n \"\"\"\n Convert a number to a base36 string.\n \n Parameters:\n num (int): The number to convert to base36.\n\n Returns:\n str: The base36 represent... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019932",
"row_id": 19932,
"seed_ids": "['Llama-3.3-70B-Instruct_50257']"
} | 0.401422 | Filter_19932 | I | [
"generate_runner_codes",
"assign_codes_to_runners"
] | 2 | [
[
"assign_codes_to_runners",
"generate_runner_codes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6507196d4c2bdadda0d58f1e3ba5ec4c32f9be7c | 2d3815a0382d46bec01cd227502e66f484606910 | |||
v1.0 | instruct | Filter | Filter_19937_I | I have a list of image paths that are in my local machine, which I want to upload to a server. The list of paths is too long and the server gets timeout if I try to upload all at once. I need to split the list and upload images in chunks.
Here is my approach:
```python
def upload_images_to_server():
image_paths =... | def upload_chunk_to_server(chunk):
"""
Simulate uploading images to the server. This function should actually
contain code to upload the images to the server.
"""
# Simulating a network issue for demonstration (this should be your actual upload code)
if chunk[0] == 'bad_image_path':
rais... | from solution import upload_images_to_server
def test_upload_images_to_server_success():
image_paths = [f'image_{i}.jpg' for i in range(30)]
result = upload_images_to_server(image_paths, chunk_size=10)
expected_result = [
(0, [f'image_{i}.jpg' for i in range(10)]),
(10, [f'image_{i}.jpg' fo... | [
{
"docstring": "Simulate uploading images to the server. This function should actually\ncontain code to upload the images to the server.",
"function_declaration": "def upload_chunk_to_server(chunk):",
"function_name": "upload_chunk_to_server",
"parameter_list": "(chunk)"
},
{
"docstring": "U... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def upload_images_to_server(image_paths, chunk_size=10):\n \"\"\"\n Uploads images to the server in chunks, ensuring the order and keeping\n track of successfully uploaded chunks.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019937",
"row_id": 19937,
"seed_ids": "['Llama-3.3-70B-Instruct_50270']"
} | 0.450286 | Filter_19937 | I | [
"upload_chunk_to_server",
"upload_images_to_server"
] | 2 | [
[
"upload_images_to_server",
"upload_chunk_to_server"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 690ca49d2037347e06f48f3557a895e52821c75c | fe175521913c883f7fe1ce3f37c094546bba809a | |||
v1.0 | instruct | Filter | Filter_19940_I | Here is the problem:
Suppose that a country's economy is growing at a rate proportional to its current size. When we model this using a differential equation (using separation of variables), we get an equation for the population P(t) = P0 * e^(kt), where P0 is the initial population and k is the growth rate (k can be... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Exponential growth model
def exponential_growth_model(P0, k, t):
"""
Calculate population P(t) for the exponential growth model.
Parameters:
P0 (float): Initial population at time t=0.
k (float): Growth rat... | # Unit Tests
import numpy as np
from solution import exponential_growth_model, logistic_growth_model
def test_exponential_growth_model():
P0 = 100
k = 0.1
t = np.array([0, 10, 20])
expected = P0 * np.exp(k * t)
assert np.allclose(exponential_growth_model(P0, k, t), expected)
def test_logistic_grow... | [
{
"docstring": "Calculate population P(t) for the exponential growth model.\n\nParameters:\nP0 (float): Initial population at time t=0.\nk (float): Growth rate.\nt (array_like): Time points to evaluate the population.\n\nReturns:\narray_like: Population at each time point t.",
"function_declaration": "def e... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\ndef exponential_growth(P0, k, t):\n \"\"\"\n Computes the population at time t using the expone... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019940",
"row_id": 19940,
"seed_ids": "['Llama-3.3-70B-Instruct_50275']"
} | 0.356172 | Filter_19940 | I | [
"exponential_growth_model",
"logistic_growth_ode",
"logistic_growth_model",
"plot_population_growth"
] | 4 | [
[
"logistic_growth_model",
"logistic_growth_ode"
],
[
"plot_population_growth",
"exponential_growth_model"
],
[
"plot_population_growth",
"logistic_growth_model"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | aa027c8b77cbcc76470cfb56c51c47940d45bc20 | 9e0aea993c00a1421f6ac4f3799f0a836ab658de | |||
v1.0 | instruct | Filter | Filter_19951_I | I hope you can assist me with this specific task. I'm working on developing a 3D graphics tutorial, and I'm having trouble with a particular part. I want to create a 3D rotating cube, but I'm getting stuck with the rotation part.
Here's a general idea of what I've done so far:
1. I created a 3D cube with vertices at... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Line3DCollection
import math
def rotate_y(point, angle):
"""
Rotates a point around the Y-axis by the given angle.
:param point: Tuple (x, y, z) representing the point coordinates.
:param angle: The angle in radia... | from solution import rotate_y, rotate_cube
def test_rotate_y_90_degrees():
point = (1, 0, 0)
angle = np.pi / 2 # 90 degrees
rotated_point = rotate_y(point, angle)
assert np.isclose(rotated_point[0], 0)
assert rotated_point[1] == 0
assert np.isclose(rotated_point[2], 1)
def test_rotate_y_180_d... | [
{
"docstring": "Rotates a point around the Y-axis by the given angle.\n:param point: Tuple (x, y, z) representing the point coordinates.\n:param angle: The angle in radians by which to rotate the point.\n:return: The new point coordinates after rotation.",
"function_declaration": "def rotate_y(point, angle)... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\nimport math\n\ndef rotate_y(point, angle):\n \"\"\"\n Rotates a point around... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019951",
"row_id": 19951,
"seed_ids": "['Llama-3.3-70B-Instruct_50306']"
} | 0.443543 | Filter_19951 | I | [
"rotate_y",
"rotate_cube",
"plot_cube",
"animate_cube"
] | 4 | [
[
"animate_cube",
"plot_cube"
],
[
"animate_cube",
"rotate_cube"
],
[
"rotate_cube",
"rotate_y"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"mpl_toolkits",
"numpy"
] | false | db3a22ebf8ae2d1b994bb7ba9c353484437fcc80 | 1a99abf53b58ad2aca7fef93ab73fb81dc3b5ea9 | |||
v1.0 | instruct | Filter | Filter_19996_I | I've been given an assignment in my Algorithms class to find the closest pair of points from two different lists of points. I was given the implementation of a brute force approach and was asked to improve upon it.
Here's what I have so far:
```python
import math
from typing import List, Tuple
import numpy as np
def ... | import math
from typing import List, Tuple
def distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float:
return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def closest_pair_recursive(points1: List[Tuple[float, float]], points2: List[Tuple[float, float]]) -> Tuple[Tuple[float, float], Tuple[float... | from solution import closest_pair_recursive, closest_pair_brute_force
def test_closest_pair_basic():
points1 = [(0, 0), (2, 2)]
points2 = [(1, 1), (3, 3)]
assert closest_pair_recursive(points1, points2) == ((0, 0), (1, 1))
def test_closest_pair_mixed():
points1 = [(1, 2), (4, 4), (6, 3)]
points2 =... | [
{
"docstring": null,
"function_declaration": "def distance(p1, p2):",
"function_name": "distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def closest_pair_recursive(points1, points2):",
"function_name": "closest_pair_recursive",
"parameter_l... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import List, Tuple\n\ndef distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float:\n return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)\n\ndef cl... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019996",
"row_id": 19996,
"seed_ids": "['Llama-3.3-70B-Instruct_50399']"
} | 0.669727 | Filter_19996 | I | [
"distance",
"closest_pair_recursive",
"closest_pair_brute_force"
] | 3 | [
[
"closest_pair_brute_force",
"distance"
],
[
"closest_pair_recursive",
"closest_pair_brute_force"
],
[
"closest_pair_recursive",
"distance"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 5427cc6754b2bacbc054cd50a9fe3abd413302e9 | f861fa9bdf6daad9177a6092af91d0269406e182 | |||
v1.0 | instruct | Filter | Filter_20005_I | I have text, I need a program to read and write the file in plain text
Here's how it works
I run the program, enter the name of the file, then I can write to the file or read the file.
Here is an example of what the file would look like after I'm done running the program
let's say the file is called "test.txt" and... | def read_file(file_name):
"""
Reads the content of the specified file and returns it as a string with '\\n' representing new lines.
"""
try:
with open(file_name, 'r') as file:
content = file.read()
return repr(content)
except FileNotFoundError:
return f"File {... | import os
import pytest
from solution import read_file, write_file
def test_read_file():
test_file = 'test_read.txt'
with open(test_file, 'w') as file:
file.write("hello world\n goodbye")
expected_output = "'hello world\\n goodbye'"
assert read_file(test_file) == expected_output
o... | [
{
"docstring": "Reads the content of the specified file and returns it as a string with '\\n' representing new lines.",
"function_declaration": "def read_file(file_name):",
"function_name": "read_file",
"parameter_list": "(file_name)"
},
{
"docstring": "Writes the provided content to the spe... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_file(file_name):\n \"\"\"\n Reads the content of the specified file and returns it as a string with '\\\\n' representing new lines.\n \"\"\"\n try:\n with open(file... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020005",
"row_id": 20005,
"seed_ids": "['Llama-3.3-70B-Instruct_50423']"
} | 0.388469 | Filter_20005 | I | [
"read_file",
"write_file",
"file_manager"
] | 3 | [
[
"file_manager",
"read_file"
],
[
"file_manager",
"write_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a7ddeca6769eea545e4b593c7b9ae2f5e3e9a1f5 | c763d0eafd24c7a2f6e7176edea9ecfc74665adf | |||
v1.0 | instruct | Filter | Filter_20007_I | ### Engineer Modified Koch Curve Implementation using Python Turtle | import turtle
def koch_curve(t, order, size):
"""
Draws a modified Koch curve with the given turtle, order, and size.
Parameters:
t (turtle.Turtle): The turtle instance used for drawing.
order (int): The recursion depth.
size (float): The length of each side of the Koch curve.
"""
... | def test_koch_curve():
# This test is a placeholder -- running this script will open a Turtle graphics window
# and must be manually verified for visual correctness by the user.
# In practice, one could mock the turtle module or verify by saving output to a file.
assert True # This would be replaced wi... | [
{
"docstring": "Draws a modified Koch curve with the given turtle, order, and size.\n\nParameters:\nt (turtle.Turtle): The turtle instance used for drawing.\norder (int): The recursion depth.\nsize (float): The length of each side of the Koch curve.",
"function_declaration": "def koch_curve(t, order, size):... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef koch_curve(t, length, depth):\n \"\"\"\n Draws a Koch curve with the given length and depth using Turtle.\n \n Parameters:\n t (turtle.Turtle): A turtle obj... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020007",
"row_id": 20007,
"seed_ids": "['Llama-3.3-70B-Instruct_50437']"
} | 0.436297 | Filter_20007 | I | [
"koch_curve",
"draw_koch_snowflake",
"main"
] | 3 | [
[
"draw_koch_snowflake",
"koch_curve"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 7ec99ae51a12894d4f4b196aaf524a4a786da49f | 576fd01cb4678d594dc33b711d8bd09ffd5c005d | |||
v1.0 | instruct | Filter | Filter_20055_I | Given a binary tree, find the height of the deepest subtree rooted at each node and return it as a list. For example, given the following binary tree:
```
1
/ \
2 3
/ \ / \
4 5 6 7
```
The function should return [1, 2, 2, 1, 1, 1, 1] which are the heights of the deepest subtrees rooted at each no... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def get_heights(root):
def height(node):
if not node:
return 0
left_height = height(node.left)
right_height = height(node.right)
current_height = max(left_h... | from solution import TreeNode, get_heights
def test_full_tree():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
assert get_heights(root) == [2, 1,... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef get_heights(root):\n def height(n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020055",
"row_id": 20055,
"seed_ids": "['Llama-3.3-70B-Instruct_50547']"
} | 0.480896 | Filter_20055 | I | [
"get_heights",
"find_max_node_value"
] | 2 | [
[
"get_heights",
"find_max_node_value"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 51284551c960ea1bf23cade59e6783bf3fd4d2ff | ed6af1451fef8e6881ec9ce21bf8b01b30756d44 | |||
v1.0 | instruct | Filter | Filter_20064_I | ### Task 2: Removing Duplicates and Ungrouping Lists
For this task you will need to remove duplicates from the result of task 1 and flatten the list. The original list had the following structure: `[ [Integer] , [Integer] ]`. By ungrouping we get an Integer list like [ Integer , Integer ].
### Task 1 Result
```json
[... | def task_1():
result = [
[1, 2, 3],
[2, 3, 4],
[1, 2, 3],
[1, 2, 3, 4],
[2, 3, 4],
[1, 2]
]
return result
def task_2():
# Flatten the list and remove duplicates
task_1_result = task_1()
flat_list = [item for sublist in task_1_result for item in su... | from solution import task_1, task_2
def test_task_1():
assert task_1() == [
[1, 2, 3],
[2, 3, 4],
[1, 2, 3],
[1, 2, 3, 4],
[2, 3, 4],
[1, 2]
]
def test_task_2():
assert task_2() == [1, 2, 3, 4]
def test_task_2_order():
# Ensure the order is sorted a... | [
{
"docstring": null,
"function_declaration": "def task_1():",
"function_name": "task_1",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def task_2():",
"function_name": "task_2",
"parameter_list": "()"
}
] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def task_2():\n \"\"\"\n Implements task 2 based on the result of task 1.\n 1. Takes the result of task 1 as input.\n 2. Removes duplicates from the input.\n 3. Ungroups the inp... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020064",
"row_id": 20064,
"seed_ids": "['Llama-3.3-70B-Instruct_50567']"
} | 0.610289 | Filter_20064 | I | [
"task_1",
"task_2"
] | 2 | [
[
"task_2",
"task_1"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50d6fabf20f2fa6d595b92e0a054d1fdee309be4 | a49658bbe694b4a8ed8bf9ad79b8d1acb0ad7ab3 | |||
v1.0 | instruct | Filter | Filter_20069_I | Given a function that returns the sum of its two integer arguments, how can we implement a function that uses the provided function to calculate the sum of three integers, with one of the calls using an intermediate variable? | def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def sum_three_integers(x, y, z):
"""
Returns the sum of three integers x, y, and z using the add function.
"""
intermediate_result = add(x, y)
return add(intermediate_result, z) | from solution import add, sum_three_integers
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_with_zero():
assert add(0, 5) == 5
assert add(5, 0) == 5
def test_add_negative_numbers():
assert add(-2, -3) == -5
def test_add_mixed_sign_numbers():
assert add(-1, 3) == 2
def test_... | [
{
"docstring": "Returns the sum of a and b.",
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the sum of three integers x, y, and z using the add function.",
"function_declaration": "def sum_three_integers(x, y, z):"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b.\n \"\"\"\n return a + b\n\ndef add_three_numbers(x, y, z):\n \"\"\"\n Returns the sum of three integers x, y, and z usin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020069",
"row_id": 20069,
"seed_ids": "['Llama-3.3-70B-Instruct_50578']"
} | 0.566755 | Filter_20069 | I | [
"add",
"sum_three_integers"
] | 2 | [
[
"sum_three_integers",
"add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cb17cc0ae581c87bf42491cd88366b88b91b67ac | 5613adfcbec49d6885efa47a20fd95af516ca3ea | |||
v1.0 | instruct | Filter | Filter_20076_I | ### Overview
Here is a basic implementation of a rock-paper-scissors game in Python. However, I need to enhance the functionality of this game by adding more features. Here are the requirements:
1. The game should allow players to register themselves and store their information in a file.
2. The game should allow pla... | import random
import json
import os
DATA_FILE = 'players_data.json'
def load_data():
if not os.path.exists(DATA_FILE):
return {}
with open(DATA_FILE, 'r') as file:
return json.load(file)
def save_data(data):
with open(DATA_FILE, 'w') as file:
json.dump(data, file)
def reg... | import os
import json
import pytest
from solution import register_player, update_scoreboard, load_data, save_data, display_scoreboard, DATA_FILE
def setup_module(module):
# Backup the existing data
if os.path.exists(DATA_FILE):
os.rename(DATA_FILE, DATA_FILE + '.bak')
def teardown_module(module):
... | [
{
"docstring": null,
"function_declaration": "def load_data():",
"function_name": "load_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def save_data(data):",
"function_name": "save_data",
"parameter_list": "(data)"
},
{
"docstring": null,
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport json\nimport os\n\ndef register_player():\n players = load_players()\n \n username = input(\"Enter a unique username: \")\n while username in players:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020076",
"row_id": 20076,
"seed_ids": "['Llama-3.3-70B-Instruct_50590']"
} | 0.493187 | Filter_20076 | I | [
"load_data",
"save_data",
"register_player",
"update_scoreboard",
"display_scoreboard",
"game"
] | 6 | [
[
"display_scoreboard",
"load_data"
],
[
"game",
"display_scoreboard"
],
[
"game",
"register_player"
],
[
"game",
"update_scoreboard"
],
[
"register_player",
"load_data"
],
[
"register_player",
"save_data"
],
[
"update_scoreboard",
"loa... | 8 | [] | false | [] | false | pytest | true | [] | true | aeceed983fb567320a6f9cd94780de63ed84770a | 811c6139031c3e3f1f1bc75c75cae8f3ffb988dd | |||
v1.0 | instruct | Filter | Filter_20079_I | We are given a utility function (utility function can take any form, as long as it is increasing and concave, some examples include: \(x^{0.5}\), \(ln(x)\), \(\frac{x}{1+x}\)). The task is to write code that evaluates a Nash Equilibrium for a penny auction with two players using the utility function to find bids.
Not... | import math
from random import choice
def utility_function(x):
"""
Utility function using natural logarithm.
"""
return math.log(x)
def find_nash_equilibrium():
"""
Find the Nash Equilibrium for a penny auction with two players
using the natural logarithm utility function.
"""
best... | from solution import find_nash_equilibrium, utility_function
def test_find_nash_equilibrium():
best_bid_for_player_1, best_bid_for_player_2 = find_nash_equilibrium()
assert 1 <= best_bid_for_player_1 <= 100
assert 1 <= best_bid_for_player_2 <= 100
def test_utility_function():
assert utility_function(1... | [
{
"docstring": "Utility function using natural logarithm.",
"function_declaration": "def utility_function(x):",
"function_name": "utility_function",
"parameter_list": "(x)"
},
{
"docstring": "Find the Nash Equilibrium for a penny auction with two players\nusing the natural logarithm utility ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nimport random\n\ndef utility_function(x):\n \"\"\"\n Utility function ln(x).\n \"\"\"\n return math.log(x)\n\ndef nash_equilibrium_penny_auction():\n \"\"\"\n Ev... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020079",
"row_id": 20079,
"seed_ids": "['Llama-3.3-70B-Instruct_50596']"
} | 0.482773 | Filter_20079 | I | [
"utility_function",
"find_nash_equilibrium"
] | 2 | [
[
"find_nash_equilibrium",
"utility_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fb2e75763f7773547ffe055494bc1cdecb2bced6 | d1a364e9006eab7fb6b0ab40de16b5429b8971df | |||
v1.0 | instruct | Filter | Filter_20120_I | I've been tasked with writing a Python script that needs to convert an integer to a roman numeral. This needs to be done in a two-step process:
1. Write a function that can map the integer values to their corresponding roman numerals.
2. Use this function to convert the integer to roman numeral.
Here's a basic outli... | def create_mapping(values, roman_numerals):
"""
Creates a mapping from integer values to roman numerals.
"""
mapping = {}
for i in range(len(values)):
mapping[values[i]] = roman_numerals[i]
return mapping
def integer_to_roman(n):
"""
Converts an integer to a Roman numeral using ... | from solution import create_mapping, integer_to_roman
def test_create_mapping():
values = [1000, 500, 100]
roman_numerals = ['M', 'D', 'C']
mapping = create_mapping(values, roman_numerals)
assert mapping == {1000: 'M', 500: 'D', 100: 'C'}
def test_integer_to_roman():
assert integer_to_roman(1)... | [
{
"docstring": "Creates a mapping from integer values to roman numerals.",
"function_declaration": "def create_mapping(values, roman_numerals):",
"function_name": "create_mapping",
"parameter_list": "(values, roman_numerals)"
},
{
"docstring": "Converts an integer to a Roman numeral using th... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_mapping(values, roman_numerals):\n \"\"\"\n Creates a mapping dictionary from integer values to their corresponding roman numerals.\n \n Parameters:\n values (list): ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020120",
"row_id": 20120,
"seed_ids": "['Llama-3.3-70B-Instruct_50668']"
} | 0.618469 | Filter_20120 | I | [
"create_mapping",
"integer_to_roman"
] | 2 | [
[
"integer_to_roman",
"create_mapping"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 76f72cf98de626816c6375d63df1edebd8141055 | d0fb55afa48dbc7842251f15f976c7883503d5f7 | |||
v1.0 | instruct | Filter | Filter_20143_I | I've made a Python script to help me with some tasks. Below is the script:
```python
def thing1():
print('Thing 1')
def thing2():
print('Thing 2')
def thing3():
print('Thing 3')
thing1()
thing2()
thing3()
```
This script currently just runs these three functions in order and does not provide any option... | def thing1():
print('Thing 1')
def thing2():
print('Thing 2')
def thing3():
print('Thing 3')
def menu():
while True:
print("\nMenu:")
print("1. Thing 1")
print("2. Thing 2")
print("3. Thing 3")
print("4. Exit")
choice = input("Enter your choice: ")
... | from solution import thing1, thing2, thing3, menu
def test_thing1(capsys):
thing1()
captured = capsys.readouterr()
assert captured.out == "Thing 1\n"
def test_thing2(capsys):
thing2()
captured = capsys.readouterr()
assert captured.out == "Thing 2\n"
def test_thing3(capsys):
thing3()
c... | [
{
"docstring": null,
"function_declaration": "def thing1():",
"function_name": "thing1",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def thing2():",
"function_name": "thing2",
"parameter_list": "()"
},
{
"docstring": null,
"function_declara... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def thing1():\n print('Thing 1')\n\ndef thing2():\n print('Thing 2')\n\ndef thing3():\n print('Thing 3')\n\ndef menu():\n while True:\n print(\"\\nMenu:\")\n print(\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020143",
"row_id": 20143,
"seed_ids": "['Llama-3.3-70B-Instruct_50722']"
} | 0.424977 | Filter_20143 | I | [
"thing1",
"thing2",
"thing3",
"menu"
] | 4 | [
[
"menu",
"thing1"
],
[
"menu",
"thing2"
],
[
"menu",
"thing3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ca9159ddd28d6bfac8b1759a2bd0f44b76f76d01 | 2eaf56155da965ab4698731cde7a10108a2d0f0e | |||
v1.0 | instruct | Filter | Filter_20172_I | I have a CSV file containing a list of names, addresses, phone numbers, and email addresses. I want to use Python to create a program that reads this CSV file, stores the data in a dictionary, and then allows me to add, delete, and update entries.
Here are the requirements:
- The dictionary keys should be unique iden... | import csv
import os
# Initialize an empty dictionary to store the contacts
contacts = {}
# Initialize a counter for the unique identifier
id_counter = 1
# Function to read the CSV file and populate the dictionary
def read_csv():
global id_counter
global contacts
try:
with open('contacts.csv', 'r... | import os
import csv
import pytest
from solution import read_csv, add_contact, delete_contact, update_contact, view_contacts, write_csv
# Test data for contacts
test_contacts = {
1: {'name': 'John Doe', 'address': '123 Elm St', 'phone': '555-555-5555', 'email': 'john@example.com'},
2: {'name': 'Jane Smith', 'a... | [
{
"docstring": null,
"function_declaration": "def read_csv():",
"function_name": "read_csv",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def write_csv():",
"function_name": "write_csv",
"parameter_list": "()"
},
{
"docstring": null,
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport os\n\n# Dictionary to store contacts\ncontacts = {}\n\n# Initialize ID counter\nid_counter = 1\n\n# Read CSV file and populate dictionary\ndef read_csv(filename='contacts.cs... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020172",
"row_id": 20172,
"seed_ids": "['Llama-3.3-70B-Instruct_50801']"
} | 0.562412 | Filter_20172 | I | [
"read_csv",
"write_csv",
"add_contact",
"delete_contact",
"update_contact",
"view_contacts",
"main"
] | 7 | [
[
"add_contact",
"write_csv"
],
[
"delete_contact",
"write_csv"
],
[
"update_contact",
"write_csv"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 955d0006bb8f47c57ca16003a5be1fa6881c3271 | 01d82f8a4705a3fb78d980d1735eb4653ba7d52c | |||
v1.0 | instruct | Filter | Filter_20181_I | I am considering creating a Python script to help me with account preparation for my business. The goals of the script are as follows:
1. **User Input:** To take in user input for account number, account name, and an initial balance.
2. **Data Validation:** Validate the user input to ensure it conforms to the business... | class Account:
def __init__(self, account_number, account_name, initial_balance):
self.account_number = account_number
self.account_name = account_name
self.initial_balance = initial_balance
def __repr__(self):
return f'Account({self.account_number}, {self.account_name}, {self.i... | from solution import Account, create_account, view_all_accounts, search_account_by_number
def test_create_account_success():
account = create_account(12345, "John Doe", 1000)
assert account.account_number == 12345
assert account.account_name == "John Doe"
assert account.initial_balance == 1000
def tes... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Account:\n def __init__(self, account_number, account_name, initial_balance):\n self.account_number = account_number\n self.account_name = account_name\n self.ini... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020181",
"row_id": 20181,
"seed_ids": "['Llama-3.3-70B-Instruct_50826']"
} | 0.473849 | Filter_20181 | I | [
"is_valid_account_number",
"is_valid_account_name",
"is_valid_initial_balance",
"create_account",
"view_all_accounts",
"search_account_by_number"
] | 6 | [
[
"create_account",
"is_valid_account_name"
],
[
"create_account",
"is_valid_account_number"
],
[
"create_account",
"is_valid_initial_balance"
]
] | 3 | [] | false | [
"Account"
] | true | pytest | true | [] | true | db1aa0d3842225b397478be5b2d5ed904e125da0 | 4f4825589c29df906868d669b63f4833d38e89f9 | |||
v1.0 | instruct | Filter | Filter_20187_I | ### Triggering Qurban for Poor Farmers
The government has launched an initiative to provide financial aid through qurban (livestock) to poor farmers. The initiative targets farmers who have suffered from crop failures or livestock diseases, and are in dire need of assistance. The government has allocated a budget of $1... | def calculate_assistance(dependents):
"""
Calculate assistance based on the number of dependents.
"""
if dependents == 4:
return 100
elif dependents == 5:
return 150
elif dependents == 6:
return 200
elif dependents > 6:
return 250
else:
return 0 #... | from solution import calculate_assistance, check_eligibility, determine_qurban_eligibility
def test_calculate_assistance():
assert calculate_assistance(4) == 100
assert calculate_assistance(5) == 150
assert calculate_assistance(6) == 200
assert calculate_assistance(7) == 250
assert calculate_assist... | [
{
"docstring": "Calculate assistance based on the number of dependents.",
"function_declaration": "def calculate_assistance(dependents):",
"function_name": "calculate_assistance",
"parameter_list": "(dependents)"
},
{
"docstring": "Check eligibility based on income and number of dependents."... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def qurban_assistance(income, dependents):\n \"\"\"\n Determines if the farmer is eligible for qurban assistance and calculates the amount of assistance.\n \n Parameters:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020187",
"row_id": 20187,
"seed_ids": "['Llama-3.3-70B-Instruct_50842']"
} | 0.522012 | Filter_20187 | I | [
"calculate_assistance",
"check_eligibility",
"determine_qurban_eligibility"
] | 3 | [
[
"determine_qurban_eligibility",
"calculate_assistance"
],
[
"determine_qurban_eligibility",
"check_eligibility"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8416942d04b701f80272dda110bcaca2328beaa7 | 29ecee19cfb7eb732704b95cae2938ab045b24a0 | |||
v1.0 | instruct | Filter | Filter_20198_I | Can you write a Python code snippet to find the prime factors of a number and then calculate the greatest common divisor (GCD) of the prime factors? | import math
from functools import reduce
from math import gcd
def prime_factors(n):
"""
Returns a list of prime factors of a given number n.
"""
factors = []
# Check for number of 2s
while n % 2 == 0:
factors.append(2)
n //= 2
# Check for odd factors from 3 onwards
for i... | from solution import prime_factors, gcd_of_prime_factors
def test_prime_factors():
assert prime_factors(28) == [2, 2, 7]
assert prime_factors(45) == [3, 3, 5]
assert prime_factors(13) == [13]
assert prime_factors(1) == []
assert prime_factors(2) == [2]
def test_gcd_of_prime_factors():
assert g... | [
{
"docstring": "Returns a list of prime factors of a given number n.",
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": "Returns the greatest common divisor (GCD) of the prime factors of n.",
"function_declaratio... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\nfrom functools import reduce\n\ndef prime_factors(n):\n i = 2\n factors = set()\n while i * i <= n:\n if n % i:\n i += 1\n else:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020198",
"row_id": 20198,
"seed_ids": "['Llama-3.3-70B-Instruct_50870']"
} | 0.751157 | Filter_20198 | I | [
"prime_factors",
"gcd_of_prime_factors"
] | 2 | [
[
"gcd_of_prime_factors",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 094990eff2a390f1dc2df4aa7edbe249f8a879f8 | 651fff45b7d065f0dec600f736a52f16d49ce175 | |||
v1.0 | instruct | Filter | Filter_20205_I | I'm looking to generate realistic ambient noises for my game development project. I'm specifically looking to generate noise with Python to create various environments. Can you guide me through generating ambient noise with Python?
### Requirements
* I need to generate ambient noise files in WAV format.
* The pro... | # First, ensure you have the required libraries installed:
# pip install pydub numpy scipy
import numpy as np
from scipy.io.wavfile import write
from pydub import AudioSegment
# Define the sample rate and duration of the noise
SAMPLE_RATE = 44100 # Sample rate in Hertz
DURATION = 60 # Duration in seconds
def gener... | import os
from solution import generate_ambient_noise
def test_generate_rain_noise():
output_file = 'test_rain_noise.wav'
generate_ambient_noise('rain', 1.0, output_file)
assert os.path.exists(output_file)
os.remove(output_file)
def test_generate_wind_noise():
output_file = 'test_wind_noise.wav'
... | [
{
"docstring": null,
"function_declaration": "def generate_white_noise(duration, intensity):",
"function_name": "generate_white_noise",
"parameter_list": "(duration, intensity)"
},
{
"docstring": null,
"function_declaration": "def generate_rain_noise(duration, intensity):",
"function... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport wave\nimport struct\nfrom scipy.io.wavfile import write\n\ndef generate_white_noise(duration, sample_rate, intensity):\n \"\"\"\n Generates white noise with th... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020205",
"row_id": 20205,
"seed_ids": "['Llama-3.3-70B-Instruct_50885']"
} | 0.378234 | Filter_20205 | I | [
"generate_white_noise",
"generate_rain_noise",
"generate_wind_noise",
"generate_ocean_noise",
"generate_forest_noise",
"save_wave_file",
"generate_ambient_noise"
] | 7 | [
[
"generate_ambient_noise",
"generate_forest_noise"
],
[
"generate_ambient_noise",
"generate_ocean_noise"
],
[
"generate_ambient_noise",
"generate_rain_noise"
],
[
"generate_ambient_noise",
"generate_wind_noise"
],
[
"generate_ambient_noise",
"save_wave_file"
... | 9 | [] | false | [] | false | pytest | true | [
"numpy",
"pydub",
"scipy"
] | false | 5f8731a22d2e873788bf804865ac45c9b218d212 | 086ee19a391c7f5b2d1580bf17774aa5e3c4f349 | |||
v1.0 | instruct | Filter | Filter_20214_I | What is k-NN algorithm and how do you implement it in Python? | import numpy as np
from collections import Counter
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
"""
return np.sqrt(np.sum((point1 - point2) ** 2))
def knn_classify(X_train, y_train, X_test, k):
"""
k-Nearest Neighbors classification.
Par... | import numpy as np
from solution import knn_classify
def test_knn_simple_case():
X_train = np.array([[1, 2], [2, 3], [3, 4]])
y_train = np.array([0, 1, 0])
X_test = np.array([[1, 2], [2, 2]])
k = 1
assert np.array_equal(knn_classify(X_train, y_train, X_test, k), np.array([0, 0]))
def test_knn_mult... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return np.... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020214",
"row_id": 20214,
"seed_ids": "['Llama-3.3-70B-Instruct_50906']"
} | 0.494698 | Filter_20214 | I | [
"euclidean_distance",
"knn_classify"
] | 2 | [
[
"knn_classify",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 3893052002c82d28dec7d990831d685c9fd95db2 | 27975c8e688dff28632210c0fec949584bc7ca0d | |||
v1.0 | instruct | Filter | Filter_20215_I | I wrote an autocorrect spell checker feature for a touchscreen keyboard. It is implemented as a 2D grid-based trie structure with a cost computation. The issue I am concerned about is that the smoothening factor α in the cost computation can significantly impact the suggestion quality.
I'd like to explore the possibil... | import numpy as np
def cost_function(word1, word2, alpha):
"""Compute the cost between two words using the Levenshtein distance with a smoothening factor alpha."""
m, n = len(word1), len(word2)
dp = np.zeros((m+1, n+1))
for i in range(m+1):
dp[i, 0] = i * alpha
for j in range(n+1):
... | from solution import cost_function, tune_alpha
def test_cost_function():
assert cost_function("kitten", "sitting", 1) == 3
assert cost_function("flaw", "lawn", 1) == 2
assert cost_function("intention", "execution", 1) == 5
assert cost_function("abc", "abc", 1) == 0
def test_tune_alpha():
word_pair... | [
{
"docstring": "Compute the cost between two words using the Levenshtein distance with a smoothening factor alpha.",
"function_declaration": "def cost_function(word1, word2, alpha):",
"function_name": "cost_function",
"parameter_list": "(word1, word2, alpha)"
},
{
"docstring": "Tune the alph... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.model_selection import ParameterGrid\n\ndef cost_function(word1, word2, alpha):\n \"\"\"\n Compute the cost between two words using the Levenshtein dista... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020215",
"row_id": 20215,
"seed_ids": "['Llama-3.3-70B-Instruct_50910']"
} | 0.359467 | Filter_20215 | I | [
"cost_function",
"tune_alpha"
] | 2 | [
[
"tune_alpha",
"cost_function"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 7bc8dd32a04b260a0793fe83b9f7883c392efeb1 | df48421c862e4500aa0ee8061c6c060966f240d2 | |||
v1.0 | instruct | Filter | Filter_20216_I | Design an algorithm to find the shortest path in a graph when one-way roads are involved. For simplicity purposes, assume the graph is made of nodes (intersections) connected by directed edges (roads) with weights (distances).
The algorithm should output the shortest distance to all nodes from a given starting point ... | class Graph:
def __init__(self, num_nodes):
self.num_nodes = num_nodes
self.edges = [[] for _ in range(num_nodes)]
def add_edge(self, from_node, to_node, weight):
self.edges[from_node].append((to_node, weight))
def print_graph(self):
for i in range(self.num_nodes):
... | from solution import Graph, find_shortest_paths
def create_sample_graph():
g = Graph(5)
g.add_edge(0, 1, -1)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 3)
g.add_edge(1, 3, 2)
g.add_edge(1, 4, 2)
g.add_edge(3, 2, 5)
g.add_edge(3, 1, 1)
g.add_edge(4, 3, -3)
return g
def test_bellman_fo... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Graph:\n def __init__(self, num_nodes):\n self.num_nodes = num_nodes\n self.edges = [[] for _ in range(num_nodes)]\n\n def add_edge(self, from_node, to_node, weight):... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020216",
"row_id": 20216,
"seed_ids": "['Llama-3.3-70B-Instruct_50912']"
} | 0.589692 | Filter_20216 | I | [
"bellman_ford",
"reconstruct_path",
"find_shortest_paths"
] | 3 | [
[
"find_shortest_paths",
"bellman_ford"
],
[
"find_shortest_paths",
"reconstruct_path"
]
] | 2 | [] | false | [
"Graph"
] | true | pytest | true | [] | true | 6c6b607124f1a0804417daa85b1438e5c8c1ba17 | c2f68adc96951800053c9e6cf79e3b047f99c767 | |||
v1.0 | instruct | Filter | Filter_20232_I | I have a doubt on implementing Neural Network from scratch in Python. Let's consider a simple feedforward network. My question is about implementing the sigmoid activation function and its derivative in Python. How can I implement these functions? | import numpy as np
def sigmoid(x):
"""
Implements the sigmoid activation function.
Parameters:
x (numpy array or scalar): Input value or array of input values.
Returns:
numpy array or scalar: The sigmoid of the input.
"""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):... | import numpy as np
from solution import sigmoid, sigmoid_derivative
def test_sigmoid_scalar():
assert np.isclose(sigmoid(0), 0.5)
assert np.isclose(sigmoid(2), 1 / (1 + np.exp(-2)))
assert np.isclose(sigmoid(-2), 1 / (1 + np.exp(2)))
def test_sigmoid_array():
inputs = np.array([0, 2, -2])
expected... | [
{
"docstring": "Implements the sigmoid activation function.\n\nParameters:\nx (numpy array or scalar): Input value or array of input values.\n\nReturns:\nnumpy array or scalar: The sigmoid of the input.",
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Compute the sigmoid of x.\n \n Arguments:\n x -- A scalar or numpy array of any size.\n \n Returns:\n s -- sigmoid(x)\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020232",
"row_id": 20232,
"seed_ids": "['Llama-3.3-70B-Instruct_50939']"
} | 0.358904 | Filter_20232 | I | [
"sigmoid",
"sigmoid_derivative"
] | 2 | [
[
"sigmoid_derivative",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 87e1d8e4508b9bfaca000c5c8fd86bb5fbc7f7b6 | c10333a66e07e72b15c93e14fb16a806b9fb08d3 | |||
v1.0 | instruct | Filter | Filter_20240_I | I have a situation where I need to extract the width and height of a shape from a JSON file where the shape is encoded in a string. The string is essentially a simplified SVG path definition.
Here is an example of what the JSON might look like:
```json
{
"shape": "M 10 10 L 20 10 L 20 20 L 10 20 Z"
}
```
And here i... | import json
def calculate_dimensions(shape_string):
commands = shape_string.split()
# Initialize min and max x and y coordinates
min_x, max_x, min_y, max_y = float('inf'), float('-inf'), float('inf'), float('-inf')
# We expect coordinates in pairs: x y
is_coordinate = False
for comman... | import pytest
from solution import calculate_dimensions, parse_json
def test_calculate_dimensions_square():
shape_string = "M 10 10 L 20 10 L 20 20 L 10 20 Z"
result = calculate_dimensions(shape_string)
assert result['width'] == 10
assert result['height'] == 10
def test_calculate_dimensions_rectangle(... | [
{
"docstring": null,
"function_declaration": "def calculate_dimensions(shape_string):",
"function_name": "calculate_dimensions",
"parameter_list": "(shape_string)"
},
{
"docstring": null,
"function_declaration": "def parse_json(json_string):",
"function_name": "parse_json",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef calculate_dimensions(shape_string):\n commands = shape_string.split()\n \n # Initialize min and max x and y coordinates\n min_x, max_x, min_y, max_y = float('inf... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020240",
"row_id": 20240,
"seed_ids": "['Llama-3.3-70B-Instruct_50953']"
} | 0.511318 | Filter_20240 | I | [
"calculate_dimensions",
"parse_json"
] | 2 | [
[
"parse_json",
"calculate_dimensions"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf2e94ce3f780048cd32d11e33014a6703e1595d | 2ceed311f57d5a11c29cc655eb2d01bfac61277a | |||
v1.0 | instruct | Filter | Filter_20242_I | Here's my Python list of dictionaries, where each dictionary represents information about a store:
```python
stores = [
{"name": "Store A", "open_time": "9:00 AM", "close_time": "6:00 PM", "address": "123 Main St"},
{"name": "Store B", "open_time": "8:00 AM", "close_time": "7:00 PM", "address": "456 Elm St"},
... | from datetime import datetime
def parse_time(time_str):
"""
Parse a 12-hour format time string into a datetime object.
"""
return datetime.strptime(time_str, "%I:%M %p")
def is_open(store, target_time):
"""
Check if a store is open at the target time.
"""
open_time = parse_time(store["... | import pytest
from solution import parse_time, is_open, find_open_stores
def test_parse_time():
assert parse_time("9:00 AM") == datetime.strptime("9:00 AM", "%I:%M %p")
assert parse_time("5:00 PM") == datetime.strptime("5:00 PM", "%I:%M %p")
def test_is_open():
store = {"name": "Store A", "open_time": "9:... | [
{
"docstring": "Parse a 12-hour format time string into a datetime object.",
"function_declaration": "def parse_time(time_str):",
"function_name": "parse_time",
"parameter_list": "(time_str)"
},
{
"docstring": "Check if a store is open at the target time.",
"function_declaration": "def i... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef parse_time(time_str):\n return datetime.strptime(time_str, \"%I:%M %p\")\n\ndef is_open(store, target_time):\n open_time = parse_time(store[\"open_ti... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020242",
"row_id": 20242,
"seed_ids": "['Llama-3.3-70B-Instruct_50958']"
} | 0.581648 | Filter_20242 | I | [
"parse_time",
"is_open",
"find_open_stores"
] | 3 | [
[
"find_open_stores",
"is_open"
],
[
"find_open_stores",
"parse_time"
],
[
"is_open",
"parse_time"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7442dd561bdf28e74659b272997d11f45ebd39f0 | 310fe1843f280e40c421f3b557ba4dda7dcb562a | |||
v1.0 | instruct | Filter | Filter_20246_I | Here's a specific problem:
A complete binary tree is a tree where every level, except possibly the last, is completely filled, and all nodes are as far left as possible. A "*" denotes a missing node.
Given the following complete binary tree:
1
/ \
2 3
/ \ / \
4 5 6 *
Consider the num... | from collections import deque
class Node:
"""Represents a node in a binary tree."""
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def sorted_array_to_bst(arr):
"""
Given a sorted array, generate a balanced binary search tree.
"""
if no... | from solution import max_width_of_complete_binary_tree
def test_single_node_tree():
assert max_width_of_complete_binary_tree([1]) == 1
def test_two_level_tree():
assert max_width_of_complete_binary_tree([3, 1, 7]) == 2
def test_three_level_tree_missing_node():
assert max_width_of_complete_binary_tree([1,... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\nclass Node:\n \"\"\"Represents a node in a binary tree.\"\"\"\n def __init__(self, value):\n self.value = value\n self.left = None\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020246",
"row_id": 20246,
"seed_ids": "['Llama-3.3-70B-Instruct_50970']"
} | 0.55698 | Filter_20246 | I | [
"sorted_array_to_bst",
"max_level_width",
"max_width_of_complete_binary_tree"
] | 3 | [
[
"max_width_of_complete_binary_tree",
"max_level_width"
],
[
"max_width_of_complete_binary_tree",
"sorted_array_to_bst"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | dc7f9cda28de859afd283883c4aae7799ad016ee | 55391f689d42403437b4909e2071d6b9afc6f0b3 | |||
v1.0 | instruct | Filter | Filter_20249_I | Here's the problem I'm trying to solve:
Create a function called `num_coins` that takes no arguments, but uses two other functions, `penny`, `nickel`, `dime`, `quarter`, each producing a random number between `1` and `100`, to calculate the total number of coins. Each coin type has a different value: penny is 1 cent, ... | import random
def penny():
return random.randint(1, 100)
def nickel():
return random.randint(1, 100)
def dime():
return random.randint(1, 100)
def quarter():
return random.randint(1, 100)
def num_coins():
p = penny()
n = nickel()
d = dime()
q = quarter()
total_amount = p * 0.01 ... | import pytest
from solution import num_coins, penny, nickel, dime, quarter
# Mock the penny, nickel, dime, and quarter functions to return fixed values
def test_num_coins_fixed_values(monkeypatch):
monkeypatch.setattr('solution.penny', lambda: 10)
monkeypatch.setattr('solution.nickel', lambda: 10)
monkeypa... | [
{
"docstring": null,
"function_declaration": "def penny():",
"function_name": "penny",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def nickel():",
"function_name": "nickel",
"parameter_list": "()"
},
{
"docstring": null,
"function_declarati... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef penny():\n return random.randint(1, 100)\n\ndef nickel():\n return random.randint(1, 100)\n\ndef dime():\n return random.randint(1, 100)\n\ndef quarter():\n re... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020249",
"row_id": 20249,
"seed_ids": "['Llama-3.3-70B-Instruct_50974']"
} | 0.534125 | Filter_20249 | I | [
"penny",
"nickel",
"dime",
"quarter",
"num_coins"
] | 5 | [
[
"num_coins",
"dime"
],
[
"num_coins",
"nickel"
],
[
"num_coins",
"penny"
],
[
"num_coins",
"quarter"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 10db842a26ac46c7fad15dde54e8017f30fbfb23 | 4a894235d553ae8e71fe8726378a2b567fece7de | |||
v1.0 | instruct | Filter | Filter_20263_I | ### Pricing System Overview
A company wants to design a pricing system for its products. The system will have different pricing tiers with discounts based on the quantity of products purchased.
### Task Overview
Your task is to create a Python program that will calculate the prices of products based on the pricing sys... | def calculate_price(quantity):
"""
Calculates the total price based on the quantity of products.
Args:
quantity (int): The number of products.
Returns:
int: The total price.
"""
if quantity <= 0:
return 0
elif 1 <= quantity <= 5:
return quantity * 5
elif... | from solution import calculate_price, calculate_total_price
def test_calculate_price():
assert calculate_price(0) == 0
assert calculate_price(3) == 15
assert calculate_price(7) == 28
assert calculate_price(12) == 36
assert calculate_price(30) == 60
assert calculate_price(51) == 51
def test... | [
{
"docstring": "Calculates the total price based on the quantity of products.\n\nArgs:\nquantity (int): The number of products.\n\nReturns:\nint: The total price.",
"function_declaration": "def calculate_price(quantity):",
"function_name": "calculate_price",
"parameter_list": "(quantity)"
},
{
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_price(quantity):\n \"\"\"\n Calculates the total price based on the quantity of products.\n \n Args:\n quantity (int): The number of products.\n \n Returns:\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020263",
"row_id": 20263,
"seed_ids": "['Llama-3.3-70B-Instruct_51010']"
} | 0.5856 | Filter_20263 | I | [
"calculate_price",
"calculate_total_price"
] | 2 | [
[
"calculate_total_price",
"calculate_price"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f5b9f3d69ef12550e11045a75f8125fa9a7803e | 970ef740d8136988548d95d94c373aadc7b2a685 | |||
v1.0 | instruct | Filter | Filter_20295_I | ### Description of the Project
We need to write a program that implements a simple game of BlackJack. The objective of this game is to have a hand value that is closer to 21 than that of the dealer's hand without exceeding 21. The cards 2 through 10 are worth their face value. Jacks, queens, and kings are worth 10 poin... | import random
# Define the ranks and suits of a deck of cards
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
# Define the values of the cards
values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': ... | from solution import create_deck, deal_card, calculate_hand_value
def test_create_deck_length():
deck = create_deck()
assert len(deck) == 52
def test_deal_card():
deck = create_deck()
card = deal_card(deck)
assert len(deck) == 51
assert card['rank'] in ranks
assert card['suit'] in suits
d... | [
{
"docstring": null,
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def deal_card(deck):",
"function_name": "deal_card",
"parameter_list": "(deck)"
},
{
"docstring": nul... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Define the ranks and suits of a deck of cards\nranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nsuits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020295",
"row_id": 20295,
"seed_ids": "['Llama-3.3-70B-Instruct_51083']"
} | 0.586153 | Filter_20295 | I | [
"create_deck",
"deal_card",
"calculate_hand_value",
"play_blackjack"
] | 4 | [
[
"play_blackjack",
"calculate_hand_value"
],
[
"play_blackjack",
"deal_card"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ccd3f0e8a223b98bca6ace446b1f058bd91365a6 | 069404d2d41509e7c7ba20994b3791eb0a1b7111 | |||
v1.0 | instruct | Filter | Filter_20298_I | I'll give you a simplified example that illustrates what I need to do in my program. Suppose I have four switches A, B, C, D. Each of them can be either ON or OFF. Then I have a rule that defines how the outputs are calculated from the inputs. For example, the rule could be:
- The output is ON if A and B are ON or C ... | import itertools
def generate_input_combinations(num_inputs):
"""
Generates all possible combinations of inputs where each can be 0 (OFF) or 1 (ON).
Args:
- num_inputs (int): The number of inputs/switches.
Returns:
- List of tuples, where each tuple represents a combination of inputs.
... | from solution import generate_input_combinations, apply_rule, generate_outputs_for_combinations
def test_generate_input_combinations():
combinations_3 = generate_input_combinations(3)
expected_combinations_3 = [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
assert c... | [
{
"docstring": "Generates all possible combinations of inputs where each can be 0 (OFF) or 1 (ON).\n\nArgs:\n- num_inputs (int): The number of inputs/switches.\n\nReturns:\n- List of tuples, where each tuple represents a combination of inputs.",
"function_declaration": "def generate_input_combinations(num_i... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef generate_input_combinations(n):\n \"\"\"\n Generates all possible input combinations for n switches.\n Each switch can be either ON(1) or OFF(0).\n\n Args:\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020298",
"row_id": 20298,
"seed_ids": "['Llama-3.3-70B-Instruct_51089']"
} | 0.510966 | Filter_20298 | I | [
"generate_input_combinations",
"apply_rule",
"generate_outputs_for_combinations"
] | 3 | [
[
"generate_outputs_for_combinations",
"apply_rule"
],
[
"generate_outputs_for_combinations",
"generate_input_combinations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0bea56dbcde55579e95d1ed7e456ad633e924866 | e47c47eff9fb9fd4e40316c2acb6dc441cefbfe4 | |||
v1.0 | instruct | Filter | Filter_20318_I | ### Combining MDFS and BFS to Find the Shortest Path in a Social Network
In a social network represented as a graph, finding the shortest path between two individuals can be done using either Breadth-First Search (BFS) or Depth-First Search (DFS) algorithms. While DFS (or its variant, Modified DFS (MDFS)) excels at de... | from collections import deque
def mdfs(graph, source, target, path, visited):
"""
A helper function to perform modified DFS to find a path (not necessarily the shortest) from source to target.
Args:
graph (dict): A dictionary representing the adjacency list of the graph.
source (node): The ID ... | def test_mdfs_simple_path():
graph = {
1: [2, 3],
2: [4],
3: [4],
4: []
}
assert shortest_path(graph, 1, 4) == [1, 2, 4] or shortest_path(graph, 1, 4) == [1, 3, 4]
def test_mdfs_no_path():
graph = {
1: [2],
2: [3],
3: [],
4: []
}
a... | [
{
"docstring": "A helper function to perform modified DFS to find a path (not necessarily the shortest) from source to target.\n\nArgs:\ngraph (dict): A dictionary representing the adjacency list of the graph.\nsource (node): The ID of the source node.\ntarget (node): The ID of the target node.\npath (list): Th... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef modified_dfs(graph, source, target, visited=None):\n \"\"\"\n Helper function to perform a modified DFS to find a path from source to target.\n \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020318",
"row_id": 20318,
"seed_ids": "['Llama-3.3-70B-Instruct_51126']"
} | 0.530989 | Filter_20318 | I | [
"mdfs",
"shortest_path"
] | 2 | [
[
"shortest_path",
"mdfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bfe987010aded08d37c137364beb08c5fa4130a2 | dae0725d7e60b2598a8ba235ae6151a092beeebf | |||
v1.0 | instruct | Filter | Filter_20323_I | This is a real valid Python script where I want to check all surveillance cameras available on my raspberry PI and get the results.
Theoretically, this Python should be able to find all video capture devices.
```python
import cv2
# Create a list to store video capture devices
devices = []
# Iterate through possible ... | import cv2
import os
def find_available_cameras(max_devices=20):
"""
Finds available cameras using OpenCV.
:param max_devices: Maximum number of devices to be checked
:return: A list of indices of the available cameras
"""
devices = []
for i in range(max_devices):
cap = cv2.VideoCap... | from solution import find_available_cameras, find_available_v4l2_devices
def test_find_available_cameras():
# This test requires actual hardware to validate, so we'll assume at least one camera is available in many setups
devices = find_available_cameras()
assert type(devices) == list, "Should return a lis... | [
{
"docstring": "Finds available cameras using OpenCV.\n:param max_devices: Maximum number of devices to be checked\n:return: A list of indices of the available cameras",
"function_declaration": "def find_available_cameras(max_devices=20):",
"function_name": "find_available_cameras",
"parameter_list"... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport os\n\ndef find_available_cameras(max_devices=20):\n \"\"\"\n Finds available cameras using OpenCV.\n :param max_devices: Maximum number of devices to be checked\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020323",
"row_id": 20323,
"seed_ids": "['Llama-3.3-70B-Instruct_51131']"
} | 0.393716 | Filter_20323 | I | [
"find_available_cameras",
"find_available_v4l2_devices",
"list_cameras"
] | 3 | [
[
"list_cameras",
"find_available_cameras"
],
[
"list_cameras",
"find_available_v4l2_devices"
]
] | 2 | [] | false | [] | false | pytest | true | [
"cv2"
] | false | 422251475a6682e8422b698b2fb6bde2f7b403b8 | a44daf3680c8bbf218768fa4c43e1fc06771a645 | |||
v1.0 | instruct | Filter | Filter_20326_I | Here is a recursive function `numbers` that takes no arguments and returns a series of objects.
```python
def numbers():
x = 0
def inner():
nonlocal x
x += 1
return x
return inner
```
How should I rewrite `numbers` so that it works with the `map()` function? | def number_generator():
"""
Generator function that yields an increasing sequence of numbers.
"""
x = 0
while True:
x += 1
yield x
def number_mapper(iterable):
"""
Function to be used with map that gets the next number from number_generator for each item in the iterable.
... | from solution import number_generator, number_mapper
def test_number_generator():
gen = number_generator()
assert next(gen) == 1
assert next(gen) == 2
assert next(gen) == 3
assert next(gen) == 4
def test_number_mapper():
seq = [None, None, None, None]
result = list(number_mapper(seq))
... | [
{
"docstring": "Generator function that yields an increasing sequence of numbers.",
"function_declaration": "def number_generator():",
"function_name": "number_generator",
"parameter_list": "()"
},
{
"docstring": "Function to be used with map that gets the next number from number_generator f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def numbers():\n x = 0\n while True:\n x += 1\n yield x",
"test_code": "def test_numbers_generator():\n gen = numbers()\n assert next(gen) == 1\n assert next(g... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020326",
"row_id": 20326,
"seed_ids": "['Llama-3.3-70B-Instruct_51134']"
} | 0.485568 | Filter_20326 | I | [
"number_generator",
"number_mapper"
] | 2 | [
[
"number_mapper",
"number_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a78b9f3e82cedf20470a77c9c46ab09b3f345af0 | ecd7addf0b83652f894667afc45202acad65e94b | |||
v1.0 | instruct | Filter | Filter_20367_I | Here is the minimax algorithm in pseudocode. How can I implement recursive algorithms in python?
```python
function minimax(state, depth, maximizingPlayer)
if depth == 0 or gameover(state):
return evaluate(state)
if maximizingPlayer:
value = -inf
for child in generateChildren(state):
... | import math
def minimax(state, depth, maximizingPlayer):
if depth == 0 or gameover(state):
return evaluate(state)
if maximizingPlayer:
value = -math.inf
for child in generateChildren(state, 1):
value = max(value, minimax(child, depth-1, False))
return value
else... | import pytest
from solution import minimax, gameover, evaluate, generateChildren, bestMove
def test_gameover():
assert not gameover([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
assert gameover([[1, 1, 1], [0, 0, 0], [0, 0, 0]])
assert gameover([[0, 0, 0], [1, 1, 1], [0, 0, 0]])
assert gameover([[0, 0, 0], [0, 0,... | [
{
"docstring": null,
"function_declaration": "def minimax(state, depth, maximizingPlayer):",
"function_name": "minimax",
"parameter_list": "(state, depth, maximizingPlayer)"
},
{
"docstring": null,
"function_declaration": "def gameover(state):",
"function_name": "gameover",
"para... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef minimax(state, depth, maximizingPlayer):\n if depth == 0 or gameover(state):\n return evaluate(state)\n\n if maximizingPlayer:\n value = -math.inf\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020367",
"row_id": 20367,
"seed_ids": "['Llama-3.3-70B-Instruct_51198']"
} | 0.431978 | Filter_20367 | I | [
"minimax",
"gameover",
"evaluate",
"generateChildren",
"bestMove"
] | 5 | [
[
"bestMove",
"generateChildren"
],
[
"bestMove",
"minimax"
],
[
"minimax",
"evaluate"
],
[
"minimax",
"gameover"
],
[
"minimax",
"generateChildren"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 4c42ed1184eb12145c06262330ac43a04f15b02d | 5a1fd273a054125a78986bbe672456668b4c31f8 | |||
v1.0 | instruct | Filter | Filter_20398_I | I have a compelling reason to write a very short bit of code to locate duplicate files in a folder. I've chosen Python because it's known for its excellent data processing capabilities and easy file operations.
Can you provide me with a quick snippet to get me started? | import os
import hashlib
def get_file_hash(file_path):
"""
Computes the MD5 hash of the given file.
"""
hasher = hashlib.md5()
with open(file_path, 'rb') as file:
buf = file.read()
hasher.update(buf)
return hasher.hexdigest()
def find_duplicate_files(directory):
"""
Fin... | import os
import hashlib
from solution import get_file_hash, find_duplicate_files
def test_get_file_hash(tmpdir):
# Set up a temporary file with known contents
file_path = tmpdir.join("testfile.txt")
file_content = b"Hello, world!"
with open(file_path, 'wb') as file:
file.write(file_conten... | [
{
"docstring": "Computes the MD5 hash of the given file.",
"function_declaration": "def get_file_hash(file_path):",
"function_name": "get_file_hash",
"parameter_list": "(file_path)"
},
{
"docstring": "Finds and returns a list of duplicate files in the given directory based on their content h... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\n\ndef get_file_hash(file_path):\n \"\"\"\n Computes the MD5 hash of the given file.\n \"\"\"\n hasher = hashlib.md5()\n with open(file_path, 'rb') as ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020398",
"row_id": 20398,
"seed_ids": "['Llama-3.3-70B-Instruct_51258']"
} | 0.590964 | Filter_20398 | I | [
"get_file_hash",
"find_duplicate_files"
] | 2 | [
[
"find_duplicate_files",
"get_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f51da9dbd9a47b7cd11374fa33b98d54d258ddb | e2e777161f414b6f667633234a6aab21a57499b7 | |||
v1.0 | instruct | Filter | Filter_20401_I | I have a list of words, and I want to find the longest word that has ONLY vowels, but I want to do it in a separate function. Checking if a word is a vowel word and finding the longest vowel word should be in separate functions.
Here's my current attempt, which returns an empty list for some reason:
```python
def has... | def has_only_vowels(word):
"""
Returns True if the word contains only vowels, False otherwise.
"""
return all(letter in 'aeiouAEIOU' for letter in word)
def find_longest_vowel_word(words):
"""
Finds the longest word that contains only vowels from the list of words.
"""
vowel_words = [wo... | from solution import has_only_vowels, find_longest_vowel_word
def test_has_only_vowels():
assert has_only_vowels('aeiou') == True
assert has_only_vowels('aEiou') == True
assert has_only_vowels('hello') == False
assert has_only_vowels('bcd') == False
assert has_only_vowels('') == True
def test_find... | [
{
"docstring": "Returns True if the word contains only vowels, False otherwise.",
"function_declaration": "def has_only_vowels(word):",
"function_name": "has_only_vowels",
"parameter_list": "(word)"
},
{
"docstring": "Finds the longest word that contains only vowels from the list of words.",... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def has_only_vowels(word):\n \"\"\"\n Check if a word has only vowels.\n \"\"\"\n return all(letter in 'aeiouAEIOU' for letter in word)\n\ndef find_longest_vowel_word(words):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020401",
"row_id": 20401,
"seed_ids": "['Llama-3.3-70B-Instruct_51265']"
} | 0.643369 | Filter_20401 | I | [
"has_only_vowels",
"find_longest_vowel_word"
] | 2 | [
[
"find_longest_vowel_word",
"has_only_vowels"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7cc30df43858bf07eb99212c6446daf915eb41bb | 80db34285525c1b552dc44f1f9ece6677dafcba0 | |||
v1.0 | instruct | Filter | Filter_20425_I | Here's the code for a simple pendulum simulation. The code also includes a section for a slider to select the length of the pendulum.
```python
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from matplotlib import animation, rcParams
from matplotlib.widgets import Slider
from sc... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from matplotlib import animation, rcParams
from matplotlib.widgets import Slider, Button
from scipy.constants import g
# constants
M = 1.0 # mass of pendulum
A = 0.1 # initial angular displacement
L_max = 1.0
L_min = 0.1
# time po... | from solution import equations_of_motion
import numpy as np
def test_equations_of_motion():
g = 9.81
L = 1.0
state = [0.1, 0.0]
t = 0
result = equations_of_motion(state, t, g, L)
expected = [0.0, -0.9793658173053844] # Hand-calculated expected result
assert np.allclose(result, expected, at... | [
{
"docstring": null,
"function_declaration": "def equations_of_motion(state, t, g, L):",
"function_name": "equations_of_motion",
"parameter_list": "(state, t, g, L)"
},
{
"docstring": null,
"function_declaration": "def update(val):",
"function_name": "update",
"parameter_list": "... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation, rcParams\nfrom matplotlib.widgets import Slider, Button\nfrom scipy.c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020425",
"row_id": 20425,
"seed_ids": "['Llama-3.3-70B-Instruct_51312']"
} | 0.493681 | Filter_20425 | I | [
"equations_of_motion",
"update",
"reset"
] | 3 | [
[
"update",
"equations_of_motion"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 5704329d3f59010c9c650c536afb5e80aab0c409 | d06cf6076da5e47c413d1ed615eeacc49fc74a13 | |||
v1.0 | instruct | Filter | Filter_20441_I | In the following code, how can I implement a radix sort algorithm to sort an array of integers? | def counting_sort(arr, exp):
"""
A counting sort based on the digit represented by `exp`.
"""
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i -... | from solution import radix_sort
def test_radix_sort_sorted_array():
sorted_array = [1, 2, 3, 4, 5]
assert radix_sort(sorted_array) == sorted_array
def test_radix_sort_reverse_sorted_array():
reverse_sorted_array = [5, 4, 3, 2, 1]
assert radix_sort(reverse_sorted_array) == [1, 2, 3, 4, 5]
def test_rad... | [
{
"docstring": "A counting sort based on the digit represented by `exp`.",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "A radix sort implementation to sort an array of integers.",
"function_dec... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n \n # Store count of occurrences in count[]\n for i in range(n):\n index = (arr[i] /... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020441",
"row_id": 20441,
"seed_ids": "['Llama-3.3-70B-Instruct_51360']"
} | 0.616933 | Filter_20441 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | be598387cf6351d9e7315741b86128d4218ac6ed | bc7435ad38b7abcdbcce5c9423c7bd4f1fc9de60 | |||
v1.0 | instruct | Filter | Filter_20452_I | Here is the problem I'm trying to solve:
Consider a binary tree with n nodes. Each node has a value, and we want to use these nodes to construct the largest possible BST (Binary Search Tree) using the numbers in the given tree.
The goal is to create the largest possible BST from the given nodes, meaning that for any ... | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder_traversal(root):
if root is None:
return []
return inorder_traversal(root.left) + [root.value] + inorder_traversal(root.right)
def sorted_l... | from solution import TreeNode, largest_bst_from_binary_tree, print_tree_inorder
def test_largest_bst_from_binary_tree_case1():
# Construct binary tree from example
root = TreeNode(10)
root.left = TreeNode(30, TreeNode(1), TreeNode(20))
root.right = TreeNode(15, TreeNode(5), TreeNode(10))
bst_r... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef inorder_traversal(root, nodes)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020452",
"row_id": 20452,
"seed_ids": "['Llama-3.3-70B-Instruct_51390']"
} | 0.448701 | Filter_20452 | I | [
"inorder_traversal",
"sorted_list_to_bst",
"largest_bst_from_binary_tree",
"print_tree_inorder"
] | 4 | [
[
"largest_bst_from_binary_tree",
"inorder_traversal"
],
[
"largest_bst_from_binary_tree",
"sorted_list_to_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | cd6a7bc7049761635735fdeab3d0ef0decf04fe7 | 2f981bbe34dcbe07b9f9a749885ae6bacc8eaec0 | |||
v1.0 | instruct | Filter | Filter_20473_I | I have a procedure that converts strings to base64 and another procedure that converts base64 to string. Now I want to create a new procedure that calls these two procedures and converts the input string to uppercase in between.
Here are the procedure definitions in Python:
```python
import base64
def string_to_bas... | import base64
def string_to_base64(input_string: str) -> str:
# Convert string to bytes
bytes_string = input_string.encode('utf-8')
# Convert bytes to base64
base64_bytes = base64.b64encode(bytes_string)
# Convert base64 bytes to string
base64_string = base64_bytes.decode('utf-8')
... | from solution import string_to_base64, base64_to_string, string_to_uppercase_base64_string
def test_string_to_base64():
assert string_to_base64("hello") == "aGVsbG8="
assert string_to_base64("world") == "d29ybGQ="
def test_base64_to_string():
assert base64_to_string("aGVsbG8=") == "hello"
assert base6... | [
{
"docstring": null,
"function_declaration": "def string_to_base64(input_string):",
"function_name": "string_to_base64",
"parameter_list": "(input_string)"
},
{
"docstring": null,
"function_declaration": "def base64_to_string(input_string):",
"function_name": "base64_to_string",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import base64\n\ndef string_to_base64(input_string: str) -> str:\n # Convert string to bytes\n bytes_string = input_string.encode('utf-8')\n \n # Convert bytes to base64\n base6... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020473",
"row_id": 20473,
"seed_ids": "['Llama-3.3-70B-Instruct_51449']"
} | 0.524493 | Filter_20473 | I | [
"string_to_base64",
"base64_to_string",
"string_to_uppercase_base64_string"
] | 3 | [
[
"string_to_uppercase_base64_string",
"string_to_base64"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 52422de162985c888ae8f0ab83bc848ca2938794 | 19c9aafe3628137c422d376b374eca53d504e6e3 | |||
v1.0 | instruct | Filter | Filter_20486_I | This exercise guides you through building a phase-contrast X-ray computed tomography (CT) reconstruction algorithm that uses the Transport of Intensity Equation (TIE) method to retrieve phase information from X-ray attenuation images. The TIE method involves one or more of the following steps:
- Forward propagation of... | import numpy as np
def propagate_forward(wavefield, wavelength, z):
"""
This function propagates the given wavefield forward by a distance z using the
Angular Spectrum Method (ASM).
Parameters:
wavefield (numpy array): The input wavefield to be propagated.
wavelength (float): The wavelength o... | import numpy as np
from solution import propagate_forward, retrieve_phase_optimization, propagate_backward, compensate_beam_hardening
def test_propagate_forward():
wavefield = np.array([[1, 2], [3, 4]])
wavelength = 0.5
z = 10
propagated = propagate_forward(wavefield, wavelength, z)
assert propagat... | [
{
"docstring": "This function propagates the given wavefield forward by a distance z using the \nAngular Spectrum Method (ASM).\n\nParameters:\nwavefield (numpy array): The input wavefield to be propagated.\nwavelength (float): The wavelength of the X-ray beam.\nz (float): The distance to propagate the wavefiel... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef propagate_forward(wavefield, wavelength, z):\n \"\"\"\n This function propagates the given wavefield forward by a distance z using the \n Angular Spectrum Me... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020486",
"row_id": 20486,
"seed_ids": "['Llama-3.3-70B-Instruct_51489']"
} | 0.471496 | Filter_20486 | I | [
"propagate_forward",
"retrieve_phase_optimization",
"propagate_backward",
"compensate_beam_hardening"
] | 4 | [
[
"propagate_backward",
"propagate_forward"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 878c9ac80b406a3c3c86e87f2ee0d1452d04a41a | 65e651b870e240d874fb956e26b761915396531c | |||
v1.0 | instruct | Filter | Filter_20487_I | Here is a basic add and subtract program that does
not support negative numbers:
def add(x, y):
while(y):
x += 1
y -= 1
return x
def subtract(x, y):
while(y):
x -= 1
y -= 1
return x
What would be a simple way to support negative numbers using
the... | def add(x, y):
if y < 0:
return subtract(x, -y)
while y:
x += 1
y -= 1
return x
def subtract(x, y):
if y < 0:
return add(x, -y)
while y:
x -= 1
y -= 1
return x | def test_add_positive_numbers():
assert add(3, 2) == 5
def test_add_negative_and_positive_numbers():
assert add(-3, 2) == -1
assert add(2, -3) == -1
def test_add_zero():
assert add(0, 0) == 0
assert add(5, 0) == 5
assert add(0, 5) == 5
def test_add_negative_numbers():
assert add(-3, -2) =... | [
{
"docstring": null,
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def subtract(x, y):",
"function_name": "subtract",
"parameter_list": "(x, y)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(x, y):\n if y < 0:\n while y:\n x -= 1\n y += 1\n else:\n while y:\n x += 1\n y -= 1\n return x\n \n\ndef subtract... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020487",
"row_id": 20487,
"seed_ids": "['Llama-3.3-70B-Instruct_51495']"
} | 0.645049 | Filter_20487 | I | [
"add",
"subtract"
] | 2 | [
[
"add",
"subtract"
],
[
"subtract",
"add"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 07ddb5b621711a488633beb26ee4b9ee60d5619a | afe7c6a7d288db238facfaad4de41a9c88f77b99 | |||
v1.0 | instruct | Filter | Filter_20490_I | I want to implement mergesort on a list of strings. I would like to know the step-by-step process of mergesort.
Here is a basic implementation of mergesort for integers:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid... | def merge_sort(arr):
"""
Function to perform mergesort on a list of strings.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
return merge(merge_sort(left_half), merge_sort(right_half))
def merge(left, right):
"""
Merge... | from solution import merge_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort(["apple"]) == ["apple"]
def test_merge_sort_sorted_list():
assert merge_sort(["apple", "banana", "grape", "orange", "pear"]) == ["apple", "banana", "grape", "or... | [
{
"docstring": "Function to perform mergesort on a list of strings.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge two sorted lists of strings into one sorted list.",
"function_declaration": "def merge(l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_strings(arr):\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n\n return merge_strings(merge_sort... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020490",
"row_id": 20490,
"seed_ids": "['Llama-3.3-70B-Instruct_51498']"
} | 0.535582 | Filter_20490 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bb3bef1228d90d2129f296eb3075c4545eedced | 1ba1dcd92e3a3e01dfce03cc0a8b5355466b9b8a | |||
v1.0 | instruct | Filter | Filter_20534_I | I've written a basic neural network from scratch in Python to classify handwritten digits using the MNIST dataset. My model currently uses the sigmoid activation function for both hidden and output layers. I'd like to replace the sigmoid function in the hidden layers with ReLU (Rectified Linear Unit). | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
sig = sigmoid(x)
return sig * (1 - sig)
def relu(x):
return np.maximum(0, x)
def relu_derivative(x):
return np.where(x > 0, 1, 0)
class SimpleNeuralNetwork:
def __init__(self, input_layer_size, hidden_... | import numpy as np
from solution import SimpleNeuralNetwork, relu, relu_derivative
def test_relu():
X = np.array([[-1, 2, -3, 4]])
Y = np.array([[0, 2, 0, 4]])
assert np.array_equal(relu(X), Y)
def test_relu_derivative():
X = np.array([[-1, 2, -3, 4]])
Y = np.array([[0, 1, 0, 1]])
assert np.ar... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef relu(x):\n return np.maximum(0, x)\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\ndef relu_derivative... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020534",
"row_id": 20534,
"seed_ids": "['Llama-3.3-70B-Instruct_51586']"
} | 0.353369 | Filter_20534 | I | [
"sigmoid",
"sigmoid_derivative",
"relu",
"relu_derivative"
] | 4 | [
[
"sigmoid_derivative",
"sigmoid"
]
] | 1 | [] | false | [
"SimpleNeuralNetwork"
] | true | pytest | true | [
"numpy"
] | false | 2378c4a4294cf368593b59f236c549ac5650c197 | 357574a6469340d480011c33c3722b4cebe27bd6 | |||
v1.0 | instruct | Filter | Filter_20537_I | Here is a Python code I'm working on, which takes in a list of lists of integers and returns a new list of integers where each integer is increased by a certain value.
```python
def increase_value(lst, value):
new_lst = []
for sub_lst in lst:
new_sub_lst = []
for num in sub_lst:
ne... | import itertools
def flatten(it):
for x in it:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
def increase_value(lst, value):
new_lst = []
flat_list = list(flatten(lst))
for num in flat_list:
new_lst.append(num + value)
return new_lst
n... | from solution import increase_value
def test_increase_value_standard():
assert increase_value([[1,2,3], [4,5,6]], 2) == [3, 4, 5, 6, 7, 8]
def test_increase_value_empty():
assert increase_value([], 2) == []
def test_increase_value_single_element_lists():
assert increase_value([[1], [2], [3]], 1) == [2, 3... | [
{
"docstring": null,
"function_declaration": "def flatten(it):",
"function_name": "flatten",
"parameter_list": "(it)"
},
{
"docstring": null,
"function_declaration": "def increase_value(lst, value):",
"function_name": "increase_value",
"parameter_list": "(lst, value)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef flatten(it):\n \"\"\"\n Flattens a nested list into a flat list.\n \"\"\"\n for x in it:\n if isinstance(x, list):\n yield from flatten(x)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020537",
"row_id": 20537,
"seed_ids": "['Llama-3.3-70B-Instruct_51592']"
} | 0.573023 | Filter_20537 | I | [
"flatten",
"increase_value"
] | 2 | [
[
"increase_value",
"flatten"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bb391b7a1dc96872a677a2ed64f65425eeda74fe | 309eea78bd858dd3c2101948b44bd914593cc7b1 | |||
v1.0 | instruct | Filter | Filter_20539_I | ### Application: Make a Simple Calculator
# Now that you've seen a complete example, let's write a simple application
# called Calc that performs addition, subtraction, multiplication, and division
# based on user input.
## Step-by-step analysis of the problem:
1. **Define the user interface**: The user interface sh... | def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def calculator(operation, a, b):
if operation == 'add':
return add(a, b)
elif operation == 'su... | from solution import add, subtract, multiply, divide, calculator
def test_add():
assert add(3, 4) == 7
assert add(-1, 1) == 0
assert add(0, 0) == 0
assert add(-5, -5) == -10
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(0, 0) == 0
assert subtract(5, 10) == -5
assert ... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divid... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020539",
"row_id": 20539,
"seed_ids": "['Llama-3.3-70B-Instruct_51602']"
} | 0.518287 | Filter_20539 | I | [
"add",
"subtract",
"multiply",
"divide",
"calculator"
] | 5 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | ef4604750c400e7eb9d69b6ff2620bdd30a1bec6 | 75b588c853a4f058770d565729939453784c3ce0 | |||
v1.0 | instruct | Filter | Filter_20555_I | I've got a large json file with the following structure:
{
"map": {
"width": 50,
"height": 50
},
"cell_size": 10,
"cells": [
{
"id": 1,
"x": 10,
"y": 10,
"agents": [
{
"id": 1,
... | import json
def generate_possible_steps(agent):
"""
Generates all possible steps for an agent.
Parameters:
agent (dict): A dictionary representing an agent.
Returns:
list: A list of possible steps dictionaries.
"""
possible_steps = []
for dx in range(-1, 2):
... | import json
from solution import generate_possible_steps, generate_steps
def test_generate_possible_steps():
agent = {"id": 1, "steps": []}
expected_steps = [
{"step_id": 1, "action": "move", "dx": -1, "dy": -1},
{"step_id": 2, "action": "move", "dx": -1, "dy": 0},
{"step_id": 3, "actio... | [
{
"docstring": "Generates all possible steps for an agent.\n\nParameters:\n agent (dict): A dictionary representing an agent.\n \nReturns:\n list: A list of possible steps dictionaries.",
"function_declaration": "def generate_possible_steps(agent):",
"function_name": "generate_possible_steps",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef generate_possible_steps(agent):\n possible_steps = []\n for dx in range(-1, 2):\n for dy in range(-1, 2):\n if dx == 0 and dy == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020555",
"row_id": 20555,
"seed_ids": "['Llama-3.3-70B-Instruct_51635']"
} | 0.643157 | Filter_20555 | I | [
"generate_possible_steps",
"generate_steps"
] | 2 | [
[
"generate_steps",
"generate_possible_steps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cc6b82d8ddb42f19a7ea2b3225220a626fdb1a59 | a13739e689bca1b37c80ca57ed35362b6637c311 | |||
v1.0 | instruct | Filter | Filter_20565_I | Given two strings, determine if they are valid parentheses strings. A string of parentheses is valid if:
- Every open bracket has a corresponding closing bracket of the same type.
- Every closing bracket has a corresponding open bracket of the same type.
- The string is properly nested.
Example:
Input: s = "()", t = "... | def isValid(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if stack:
stack.pop()
else:
return False
return not stack
def checkValidString(s, t):
return isValid(s) and isValid(t) | from solution import checkValidString
def test_both_valid():
assert checkValidString("()", "()") == True
def test_first_valid_second_invalid():
assert checkValidString("()", "())") == False
def test_both_invalid_open_brackets():
assert checkValidString("(", "(") == False
def test_open_and_closed_invalid... | [
{
"docstring": null,
"function_declaration": "def isValid(s):",
"function_name": "isValid",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def checkValidString(s, t):",
"function_name": "checkValidString",
"parameter_list": "(s, t)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def isValid(s):\n \"\"\"\n Determine if a single string of parentheses is valid.\n A string of parentheses is valid if:\n - Every open bracket has a corresponding closing bracket o... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020565",
"row_id": 20565,
"seed_ids": "['Llama-3.3-70B-Instruct_51667']"
} | 0.75593 | Filter_20565 | I | [
"isValid",
"checkValidString"
] | 2 | [
[
"checkValidString",
"isValid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b88577e1494857cdcd67e138e12ba3436a55b099 | 986c92b07211bc917894b89b635e64ac5c8c8b73 | |||
v1.0 | instruct | Filter | Filter_20610_I | Create a code that solves the Towers of Hanoi problem. The code should also have an input validation for the number of disks. | def towers_of_hanoi(n, source, destination, auxiliary):
"""
Solve the Towers of Hanoi problem and print the moves.
Parameters:
n : int
Number of disks
source : str
The source peg
destination : str
The destination peg
auxiliary : str
The auxiliary peg
"""
... | import pytest
from solution import solve_hanoi
def test_solve_hanoi_basic():
solve_hanoi(1)
def test_solve_hanoi_medium():
solve_hanoi(3)
def test_invalid_zero_disks():
with pytest.raises(ValueError):
solve_hanoi(0)
def test_invalid_negative_disks():
with pytest.raises(ValueError):
s... | [
{
"docstring": "Solve the Towers of Hanoi problem and print the moves.\n\nParameters:\nn : int\n Number of disks\nsource : str\n The source peg\ndestination : str\n The destination peg\nauxiliary : str\n The auxiliary peg",
"function_declaration": "def towers_of_hanoi(n, source, destination, aux... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def towers_of_hanoi(n, source, destination, auxiliary):\n \"\"\"\n Solve the Towers of Hanoi problem and print the moves.\n\n Parameters:\n n : int\n Number of disks\n so... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020610",
"row_id": 20610,
"seed_ids": "['Llama-3.3-70B-Instruct_51769']"
} | 0.485607 | Filter_20610 | I | [
"towers_of_hanoi",
"solve_hanoi"
] | 2 | [
[
"solve_hanoi",
"towers_of_hanoi"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a73a27bd7a79a2be2f747f972d06ae55a3101449 | 8ae9adefedac5e000a11598c63df54332da9dc83 | |||
v1.0 | instruct | Filter | Filter_20621_I | ### Left Rotation of Binary Tree
#### Problem Statement
Given the root of a binary tree and an integer k, rotate the binary tree to the left by k steps.
#### Example
```
4
/ \
2 6
/ \ / \
1 3 5 7
```
After rotating left by 1 step, the tree becomes:
```
2
/ \
1 4
/ \
3 6
/ \
5 ... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def left_rotate_tree_once(root):
if not root or not root.left:
return root
new_root = root.left
root.left = new_root.right
new_root.right = root
return new_root
def left_... | import pytest
def test_left_rotation():
# Construct the original tree
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(5)
root.right.right = TreeNode(7)
# Expected tree afte... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef left_rotate_tree_once(root):\n if not root or not root.left:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020621",
"row_id": 20621,
"seed_ids": "['Llama-3.3-70B-Instruct_51792']"
} | 0.518261 | Filter_20621 | I | [
"left_rotate_tree_once",
"left_rotation",
"print_tree"
] | 3 | [
[
"left_rotation",
"left_rotate_tree_once"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | faaf16165499d5deaff4f3ee4a07b529b586e946 | c2faf97e354db5da6ad24c68d07954f7d8e6d0ad | |||
v1.0 | instruct | Filter | Filter_20631_I | I have the formula for the least common multiple (LCM) of three numbers, which is:
lcm(a, b, c) = lcm(lcm(a, b), c)
I want to write a function that will calculate the LCM of any number of input values.
How can I do this using recursive programming in Python? | from math import gcd
from functools import reduce
def lcm(a, b):
"""
Returns the least common multiple (LCM) of two numbers a and b.
"""
return a * b // gcd(a, b)
def lcm_multiple(*numbers):
"""
Returns the least common multiple (LCM) of any number of input values.
Uses a recursive approac... | from solution import lcm_multiple
def test_lcm_of_two_numbers():
assert lcm_multiple(4, 5) == 20
assert lcm_multiple(6, 8) == 24
def test_lcm_of_three_numbers():
assert lcm_multiple(3, 4, 5) == 60
assert lcm_multiple(4, 5, 10) == 20
def test_lcm_with_prime_numbers():
assert lcm_multiple(2, 3, 5, ... | [
{
"docstring": "Returns the least common multiple (LCM) of two numbers a and b.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the least common multiple (LCM) of any number of input values.\nUses a recursive approach ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef lcm(a, b):\n \"\"\"\n Calculate the least common multiple of two numbers a and b.\n \"\"\"\n return abs(a * b) // math.gcd(a, b)\n\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020631",
"row_id": 20631,
"seed_ids": "['Llama-3.3-70B-Instruct_51811']"
} | 0.605951 | Filter_20631 | I | [
"lcm",
"lcm_multiple"
] | 2 | [
[
"lcm_multiple",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbfc12573957bbe44072c3fbb9abcd93fe11e555 | 7f5860a4ea48bf34264c86596982ba83df4d831d | |||
v1.0 | instruct | Filter | Filter_20643_I | ### Visualizing rt-PCR Data
To better understand the results of rt-PCR (reverse transcription polymerase chain reaction) experiments, researchers often visualize the data using graphs. One common type of graph is the amplification curve, which shows the fluorescence intensity (a measure of the amount of amplified DNA) ... | import matplotlib.pyplot as plt
import numpy as np
import random
def generate_amplification_curve(num_cycles):
"""
Simulate the amplification curve by generating random fluorescence intensity values.
Parameters:
num_cycles (int): The number of PCR cycles.
Returns:
list: A list of fluo... | from solution import generate_amplification_curve, plot_amplification_curves
import matplotlib.pyplot as plt
import numpy as np
def test_generate_amplification_curve_length():
num_cycles = 30
curve = generate_amplification_curve(num_cycles)
assert len(curve) == num_cycles
def test_generate_amplification_c... | [
{
"docstring": "Simulate the amplification curve by generating random fluorescence intensity values.\n\nParameters:\nnum_cycles (int): The number of PCR cycles.\n\nReturns:\nlist: A list of fluorescence intensity values representing the amplification curve.",
"function_declaration": "def generate_amplificat... | [
1
] | 1 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\ndef generate_amplification_curve(num_cycles):\n \"\"\"\n Simulate the amplification curve b... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020643",
"row_id": 20643,
"seed_ids": "['Llama-3.3-70B-Instruct_51837']"
} | 0.559857 | Filter_20643 | I | [
"generate_amplification_curve",
"plot_amplification_curves",
"main"
] | 3 | [
[
"plot_amplification_curves",
"generate_amplification_curve"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 6551f9d82622b3f17e639754ae756a0025fecce0 | ea0ffd3826e4582652a3c5c45bab10a95ce072d8 | |||
v1.0 | instruct | Filter | Filter_20700_I | I have tried following the whitepaper to implement a simplified version of the Lightning Network for my academic project. However, I am having trouble getting it working.
Describing the problem with your own words so that the other devs can understand it and contribute to finding the solution.
I've been trying to s... | import hashlib
import logging
class Node:
def __init__(self, public_key):
self.public_key = public_key
self.channels = []
def create_channel(self, other_node, capacity):
channel = Channel(self, other_node, capacity)
self.channels.append(channel)
other_node.channels.appe... | import hashlib
from solution import Node, Channel, HTLC, handle_routing
def test_create_and_resolve_htlc():
alice = Node("alice_public_key")
bob = Node("bob_public_key")
channel = alice.create_channel(bob, 10)
secret = "secret"
hash_lock = hashlib.sha256(secret.encode()).hexdigest()
htlc = chan... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport logging\n\nclass Node:\n def __init__(self, public_key):\n self.public_key = public_key\n self.channels = []\n\n def create_channel(self, other_node,... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020700",
"row_id": 20700,
"seed_ids": "['Llama-3.3-70B-Instruct_51972']"
} | 0.288752 | Filter_20700 | I | [
"onion_routing",
"handle_routing"
] | 2 | [
[
"handle_routing",
"onion_routing"
]
] | 1 | [] | false | [
"Node",
"Channel",
"HTLC"
] | true | pytest | true | [] | true | 5d4954bac69b6289c039220bc34276abd431279b | b162f7e46eb4588ff8e18d1c90af580b5e6457bb | |||
v1.0 | instruct | Filter | Filter_20727_I | You've been given the task to sort a list of elements using the merge sort algorithm. Unfortunately, your code is missing the merge step. Can you implement the merge step and complete the code? | def merge_sort(arr):
"""
Sorts an array using the merge sort algorithm.
"""
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
merge(arr, left_half, right_half)
return arr
... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elements():
assert merge_sort([2, 1]) == [1, 2]
def test_merge_sort_multiple_elements():
assert merge_sort([4, 1, ... | [
{
"docstring": "Sorts an array using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two halves of an array in sorted order.",
"function_declaration": "def merge(arr, left_half,... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge(left, right):\n \"\"\"\n Merges two sorted lists into one sorted list.\n \"\"\"\n merged_list = []\n left_index, right_index = 0, 0\n\n # Compare and merge elements... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020727",
"row_id": 20727,
"seed_ids": "['Llama-3.3-70B-Instruct_52031']"
} | 0.664933 | Filter_20727 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 794e9bf40488582924d363118aade1680369b580 | 0226e881465004cbe3439a047b10d8deb86a42d3 | |||
v1.0 | instruct | Filter | Filter_20735_I | Please help me debug an issue with my Python code intended to determine the nearest prime number to a given number `n`. The provided function should return both the nearest prime and the distance from `n`. | def is_prime(num):
if num <= 1:
return False
if num == 2 or 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 nearest_prime(... | from solution import nearest_prime
def test_nearest_prime_below_n():
assert nearest_prime(10) == (11, 1)
assert nearest_prime(14) == (13, 1)
def test_nearest_prime_above_n():
assert nearest_prime(20) == (19, 1)
assert nearest_prime(25) == (23, 2)
def test_nearest_prime_equal_n():
assert n... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def nearest_prime(n):",
"function_name": "nearest_prime",
"parameter_list": "(n)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_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 <= num... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020735",
"row_id": 20735,
"seed_ids": "['Llama-3.3-70B-Instruct_52042']"
} | 0.568656 | Filter_20735 | I | [
"is_prime",
"nearest_prime"
] | 2 | [
[
"nearest_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3666e0642d05dfc2c8ba97ccc2d105efa1e8fbb | 6258e23d945fdf5891339e5f9dedb1f5b6d6a43d | |||
v1.0 | instruct | Filter | Filter_20786_I | Write a code in python to add all the prime numbers between 10 and 20 | def is_prime(num):
"""
Helper function to check if 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
def s... | from solution import is_prime, sum_primes_in_range, sum_primes_between_10_and_20
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(11) == True
assert is_prime(12) == False
assert is_prime(19) == True
def test_sum_primes_in_ra... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Sum all prime numbers in the range [start, end].",
"function_declaration": "def sum_primes_in_range(sta... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 ==... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020786",
"row_id": 20786,
"seed_ids": "['Llama-3.3-70B-Instruct_52158']"
} | 0.63696 | Filter_20786 | I | [
"is_prime",
"sum_primes_in_range",
"sum_primes_between_10_and_20"
] | 3 | [
[
"sum_primes_between_10_and_20",
"sum_primes_in_range"
],
[
"sum_primes_in_range",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 601300e4858e4e196c69b15cdc8a2715df39de9e | 72638376e88c826d20db284807f60bc3bce5ec7f | |||
v1.0 | instruct | Filter | Filter_20788_I | I have a list of lists, a 2D array that is actually a text representation of a Sudoku grid where each inner list represents a row. The Sudoku grid may contain zeros representing blank spaces. The zeros should be replaced with numbers that make the Sudoku grid valid.
Here is a code snippet in Python for solving the Sud... | def is_valid(board, row, col, value):
"""
Checks if placing 'value' in 'board' at 'row', 'col' is valid.
"""
# check if the value is already in the row or column
if value in board[row] or value in [board[i][col] for i in range(9)]:
return False
# check the 3x3 subgrid
start_row = 3 ... | from solution import is_valid, solve_sudoku, print_board
def test_is_valid():
test_board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
... | [
{
"docstring": "Checks if placing 'value' in 'board' at 'row', 'col' is valid.",
"function_declaration": "def is_valid(board, row, col, value):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, value)"
},
{
"docstring": "Solves the Sudoku board in place",
"function_decl... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid(board, row, col, value):\n # Check if the value is already in the row or column\n if value in board[row] or value in [board[i][col] for i in range(9)]:\n return False... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020788",
"row_id": 20788,
"seed_ids": "['Llama-3.3-70B-Instruct_52164']"
} | 0.563481 | Filter_20788 | I | [
"is_valid",
"solve_sudoku",
"print_board"
] | 3 | [
[
"solve_sudoku",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f7db7c449f4b04711fa9fcca8717ed2fdce4eb3 | 0ef7bb04224c71209cd81370d4e98d0b530b09bc | |||
v1.0 | instruct | Filter | Filter_20793_I | ### Word Scramble Game
# Description
Create a word scramble game. The game should randomly choose a word from a predefined list, scramble the letters,
# and then ask the user to unscramble the word. The user should have a limited number of attempts to unscramble the word.
# If the user uses up all their attempts, the g... | import random
def scramble_word(word):
scrambled = ''.join(random.sample(word, len(word)))
return scrambled
def word_scramble_game(word_list, max_attempts=3):
chosen_word = random.choice(word_list)
scrambled_word = scramble_word(chosen_word)
print(f"I'm thinking of a word: {scrambled_word}")
... | from solution import scramble_word, word_scramble_game
def test_scramble_word():
word = "example"
scrambled = scramble_word(word)
assert scrambled != word
assert sorted(scrambled) == sorted(word)
def test_word_scramble_game(monkeypatch):
word_list = ["example"]
inputs = iter(["examlpe", "examl... | [
{
"docstring": null,
"function_declaration": "def scramble_word(word):",
"function_name": "scramble_word",
"parameter_list": "(word)"
},
{
"docstring": null,
"function_declaration": "def word_scramble_game(word_list, max_attempts=3):",
"function_name": "word_scramble_game",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\nclass WordScrambleGame:\n def __init__(self, word_list, attempts=3):\n self.word_list = word_list\n self.attempts = attempts\n self.selected_word = ran... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020793",
"row_id": 20793,
"seed_ids": "['Llama-3.3-70B-Instruct_52174']"
} | 0.597801 | Filter_20793 | I | [
"scramble_word",
"word_scramble_game"
] | 2 | [
[
"word_scramble_game",
"scramble_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ef00787ebbb6539e38554315d38db13dffee5f6c | 3ad366030dd180722f548582fb6ab2508a81e06b | |||
v1.0 | instruct | Filter | Filter_20794_I | I've created a barebones version of Tic Tac Toe on the command line and I want to add basic AI to my existing game.
Here's how it looks so far:
```python
import random
def print_board(board):
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---+---+---")
print(f" {board[3]} | {board[4]} | {board[5]... | import random
def print_board(board):
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---+---+---")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("---+---+---")
print(f" {board[6]} | {board[7]} | {board[8]} ")
def check_winner(board):
win_conditions = [(0, 1, 2), (3, 4, 5), (6... | from solution import ai_move
def test_ai_winning_move():
board = ["X", "X", " ", "O", "O", " ", " ", " ", " "]
assert ai_move(board) == 2
def test_ai_blocking_move():
board = ["X", " ", " ", "O", "O", " ", "X", " ", " "]
assert ai_move(board) == 5
def test_ai_random_move():
board = ["X", " ", "X"... | [
{
"docstring": null,
"function_declaration": "def print_board(board):",
"function_name": "print_board",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def check_winner(board):",
"function_name": "check_winner",
"parameter_list": "(board)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def ai_move(board):\n \"\"\"\n Determines AI's move and updates the board.\n \"\"\"\n def find_winning_move(player):\n win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0,... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020794",
"row_id": 20794,
"seed_ids": "['Llama-3.3-70B-Instruct_52175']"
} | 0.516104 | Filter_20794 | I | [
"print_board",
"check_winner",
"ai_move",
"main"
] | 4 | [
[
"ai_move",
"check_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 01db78541333b1e8c367f623d0f98efbba2698d8 | 59f87fff1619d84bcdcd1b03d8050e1f24fa1897 | |||
v1.0 | instruct | Filter | Filter_20839_I | In this problem, we are given an array of integers and we need to find the maximum subarray sum. This is a classic problem in algorithm design, and it can be solved using Kadane's algorithm.
However, I want to implement this using a divide and conquer strategy.
Could you help me? | def max_crossing_sum(arr, left, mid, right):
"""
Helper function to find the maximum sum that crosses the midpoint.
"""
# Include elements on the left of mid
left_sum = float('-inf')
total = 0
for i in range(mid, left - 1, -1):
total += arr[i]
if total > left_sum:
... | from solution import find_max_subarray
def test_find_max_subarray_single_element():
assert find_max_subarray([1]) == 1
assert find_max_subarray([-1]) == -1
def test_find_max_subarray_all_positive():
assert find_max_subarray([1, 2, 3, 4, 5]) == 15
def test_find_max_subarray_all_negative():
assert find... | [
{
"docstring": "Helper function to find the maximum sum that crosses the midpoint.",
"function_declaration": "def max_crossing_sum(arr, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(arr, left, mid, right)"
},
{
"docstring": "Function to find the maximum subarr... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(arr, low, mid, high):\n left_sum = float('-inf')\n sum = 0\n for i in range(mid, low - 1, -1):\n sum += arr[i]\n if sum > left_sum:\n lef... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020839",
"row_id": 20839,
"seed_ids": "['Llama-3.3-70B-Instruct_52285']"
} | 0.730681 | Filter_20839 | I | [
"max_crossing_sum",
"max_subarray_sum",
"find_max_subarray"
] | 3 | [
[
"find_max_subarray",
"max_subarray_sum"
],
[
"max_subarray_sum",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7a170eef9dae01c19a5281bf6b59cfcafacaaafa | 260a0b27ecc86a315fb1b83aca68fcf48dd7e38d | |||
v1.0 | instruct | Filter | Filter_20849_I | I've got a giveaway for 15 users that will be selected at random. I want to display the number of available spots remaining in real-time, so users can see how many spots are left. How would I do this using Python and possibly a GUI library like Tkinter? | import tkinter as tk
class Giveaway:
def __init__(self, total_spots):
self.total_spots = total_spots
self.available_spots = total_spots
def reserve_spot(self):
if self.available_spots > 0:
self.available_spots -= 1
return True
return False
def update_di... | import pytest
from solution import Giveaway
def test_initial_spots():
giveaway = Giveaway(total_spots=15)
assert giveaway.total_spots == 15
assert giveaway.available_spots == 15
def test_reserve_spot():
giveaway = Giveaway(total_spots=15)
giveaway.reserve_spot()
assert giveaway.available_spots... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\n\nclass Giveaway:\n def __init__(self, total_spots):\n self.total_spots = total_spots\n self.available_spots = total_spots\n\n def reserve_spot(self):... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020849",
"row_id": 20849,
"seed_ids": "['Llama-3.3-70B-Instruct_52306']"
} | 0.37555 | Filter_20849 | I | [
"update_display",
"reserve_spot_button_clicked"
] | 2 | [
[
"reserve_spot_button_clicked",
"update_display"
]
] | 1 | [] | false | [
"Giveaway"
] | true | pytest | true | [] | true | 44cc785ddd279f4f4b422e563333df6fce4c7c56 | 4e4c9af2567cbf2db078de2fa9edc250e46879d4 | |||
v1.0 | instruct | Filter | Filter_20855_I | Here is a Python code snippet that finds the maximum subarray sum in a given list of numbers:
```
MAX_SIZE = 1000000
def maxCrossingSum(arr, l, m, h):
sm = 0
left_sum = -MAX_SIZE
for i in range(m, l-1, -1):
sm = sm + arr[i]
if (sm > left_sum):
left_sum = sm
sm = 0
right_... | MAX_SIZE = 1000000
def maxCrossingSum(arr, l, m, h):
sm = 0
left_sum = -MAX_SIZE
for i in range(m, l-1, -1):
sm = sm + arr[i]
if sm > left_sum:
left_sum = sm
sm = 0
right_sum = -MAX_SIZE
for i in range(m+1, h+1):
sm = sm + arr[i]
if sm > right_sum:
... | from solution import maxSubArraySum
def test_single_element():
assert maxSubArraySum([1]) == 1
assert maxSubArraySum([-1]) == -1
def test_all_positive_elements():
assert maxSubArraySum([1, 2, 3, 4, 5]) == 15
def test_all_negative_elements():
assert maxSubArraySum([-1, -2, -3, -4, -5]) == -1
def test... | [
{
"docstring": null,
"function_declaration": "def maxCrossingSum(arr, l, m, h):",
"function_name": "maxCrossingSum",
"parameter_list": "(arr, l, m, h)"
},
{
"docstring": null,
"function_declaration": "def maxSubArraySum(arr):",
"function_name": "maxSubArraySum",
"parameter_list":... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "MAX_SIZE = 1000000\n\ndef maxCrossingSum(arr, l, m, h):\n sm = 0\n left_sum = -MAX_SIZE\n for i in range(m, l-1, -1):\n sm = sm + arr[i]\n if (sm > left_sum):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020855",
"row_id": 20855,
"seed_ids": "['Llama-3.3-70B-Instruct_52318']"
} | 0.648286 | Filter_20855 | I | [
"maxCrossingSum",
"maxSubArraySum",
"max_crossing_sum_util"
] | 3 | [
[
"maxSubArraySum",
"max_crossing_sum_util"
],
[
"max_crossing_sum_util",
"maxCrossingSum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 91dcb133765e73fd4d85b82bff76904bc3cae3b1 | 0f38b7ba63926884356839f590653f2f4d574d04 | |||
v1.0 | instruct | Filter | Filter_20857_I | Can you create an AI that can be used to control a robot, using Natural Language Processing (NLP)? | import re
class Robot:
def __init__(self):
self.position = [0, 0]
def move_forward(self, steps):
self.position[1] += steps
def move_backward(self, steps):
self.position[1] -= steps
def move_left(self, steps):
self.position[0] -= steps
def move_right(self, steps):... | from solution import Robot, execute_command, parse_command
def test_parse_command_valid():
assert parse_command("move forward 3 steps") == ("forward", 3)
assert parse_command("move backward 2 steps") == ("backward", 2)
assert parse_command("move left 5 steps") == ("left", 5)
assert parse_command("move ... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef parse_command(command):\n \"\"\"\n Parses the given natural language command and translates it into robot instructions.\n \n :param command: str, natural language ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020857",
"row_id": 20857,
"seed_ids": "['Llama-3.3-70B-Instruct_52321']"
} | 0.304579 | Filter_20857 | I | [
"parse_command",
"execute_command"
] | 2 | [
[
"execute_command",
"parse_command"
]
] | 1 | [] | false | [
"Robot"
] | true | pytest | true | [] | true | fec13f0674eaae941a3be69b3ff45615dc8b6653 | 4596ef21bfbb5178c23078e48dd759dd487d29b9 | |||
v1.0 | instruct | Filter | Filter_20858_I | ### В Sparse Color Image Compression Using Adaptive Recursive Interpolation
The goal of this project was to implement a lossy image compression algorithm using Adaptive Recursive Interpolation (ARI) for sparse color images. ARI is a method of reconstructing missing pixel values in an image by iteratively applying a set... | import numpy as np
def get_sparse_colors(image, num_sparse_colors):
"""
Find the sparse colors in the image.
Parameters:
image (numpy.ndarray): The input image.
num_sparse_colors (int): The number of sparse colors to find.
Returns:
numpy.ndarray: An array of sparse colors.
"""... | import numpy as np
from solution import get_sparse_colors, adaptive_recursive_interpolation, compress_image
def test_get_sparse_colors():
image = np.array([[[0, 0, 0], [255, 255, 255]],
[[128, 128, 128], [0, 0, 0]]])
sparse_colors = get_sparse_colors(image, 1)
assert sparse_colors.sha... | [
{
"docstring": "Find the sparse colors in the image.\n\nParameters:\nimage (numpy.ndarray): The input image.\nnum_sparse_colors (int): The number of sparse colors to find.\n\nReturns:\nnumpy.ndarray: An array of sparse colors.",
"function_declaration": "def get_sparse_colors(image, num_sparse_colors):",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef get_sparse_colors(image, num_sparse_colors):\n \"\"\"\n Returns the `num_sparse_colors` least frequent colors in the image.\n \n Args:\n image: np.ndar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020858",
"row_id": 20858,
"seed_ids": "['Llama-3.3-70B-Instruct_52323']"
} | 0.448197 | Filter_20858 | I | [
"get_sparse_colors",
"adaptive_recursive_interpolation",
"compress_image"
] | 3 | [
[
"compress_image",
"adaptive_recursive_interpolation"
],
[
"compress_image",
"get_sparse_colors"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | a9e3e72b947293420f036b6c883e74911e6f9d51 | c607c223942f042feb9a647e94d803508c271442 | |||
v1.0 | instruct | Filter | Filter_20872_I | I have a python script that uses scipy.integrate.odeint to solve a system of differential equations. Now I would like to implement the equivalent of a 'step input' in the system. In a step input, the input switches from 0 to a particular value at a particular time. I am thinking of modifying the derivative function tha... | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def step_input(t, t_step, value):
"""Returns the step input value, which switches from 0 to 'value' at t_step."""
return value if t >= t_step else 0
def system_dynamics(y, t, t_step, input_value):
"""Derivative function ... | from solution import step_input, system_dynamics
import numpy as np
from scipy.integrate import odeint
def test_step_input_before_step():
assert step_input(1, 3, 5) == 0
def test_step_input_at_step():
assert step_input(3, 3, 5) == 5
def test_step_input_after_step():
assert step_input(5, 3, 5) == 5
def t... | [
{
"docstring": "Returns the step input value, which switches from 0 to 'value' at t_step.",
"function_declaration": "def step_input(t, t_step, value):",
"function_name": "step_input",
"parameter_list": "(t, t_step, value)"
},
{
"docstring": "Derivative function that includes a step input.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from scipy.integrate import odeint\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef derivative(y, t, step_time, step_value):\n \"\"\"\n Compute the derivative of y at time t, ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020872",
"row_id": 20872,
"seed_ids": "['Llama-3.3-70B-Instruct_52361']"
} | 0.286629 | Filter_20872 | I | [
"step_input",
"system_dynamics"
] | 2 | [
[
"system_dynamics",
"step_input"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | b6426013dda5292f0405d7be62837dbfc36f43c5 | 7d18033de8b5ee5404ca0630bc05fbe98bdda152 | |||
v1.0 | instruct | Filter | Filter_20875_I | In this task, I will describe a scenario and you will write a code that meets the requirements. The code should be written in python and should be clear and easy to understand.
The input to the function will be a list of integers and the output should be the sum of all the prime numbers in the list.
Have you underst... | 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(lst):
"""
Returns the sum of all prime numbers in the provided list of integers.
"""
return sum(filter(is_prime, lst)) | from solution import sum_of_primes
def test_sum_of_primes_all_primes():
assert sum_of_primes([2, 3, 5, 7, 11]) == 28
def test_sum_of_primes_mixed_numbers():
assert sum_of_primes([4, 6, 8, 9, 10, 11, 13]) == 24
def test_sum_of_primes_no_primes():
assert sum_of_primes([4, 6, 8, 9, 10]) == 0
def test_sum_o... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers in the provided list of integers.",
"function_declaration": "def sum_of_primes(lst):",
"function_name": "sum_o... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if the input number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020875",
"row_id": 20875,
"seed_ids": "['Llama-3.3-70B-Instruct_52366']"
} | 0.671777 | Filter_20875 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3074686dd257c37b263dd6c49ea0cb98867d684 | c6891cfa19cd18a2954fe9c5c204da81f641abf3 | |||
v1.0 | instruct | Filter | Filter_20931_I | I've just created a simple function that calculates the gcd (greatest common divisor) of two numbers using the Euclidean algorithm and returns the result. I would like to, also, append it to a .txt file.
Here is my code:
```python
def calculate_gcd(num1, num2):
while num2 != 0:
num1, num2 = num2, num1 % n... | def calculate_gcd(num1, num2):
while num2 != 0:
num1, num2 = num2, num1 % num2
return num1
def append_gcd_to_file(num1, num2, filename="gcd_results.txt"):
gcd_result = calculate_gcd(num1, num2)
with open(filename, "a") as file:
file.write(f"GCD of {num1} and {num2} is {gcd_result}\n")
... | from solution import calculate_gcd, append_gcd_to_file
def test_calculate_gcd():
assert calculate_gcd(48, 18) == 6
assert calculate_gcd(100, 25) == 25
assert calculate_gcd(25, 100) == 25
assert calculate_gcd(17, 13) == 1
def test_append_gcd_to_file(tmpdir):
# Use a temporary file to avoid creating... | [
{
"docstring": null,
"function_declaration": "def calculate_gcd(num1, num2):",
"function_name": "calculate_gcd",
"parameter_list": "(num1, num2)"
},
{
"docstring": null,
"function_declaration": "def append_gcd_to_file(num1, num2, filename='gcd_results.txt'):",
"function_name": "appen... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_gcd(num1, num2):\n \"\"\"\n Returns the greatest common divisor of num1 and num2 using the Euclidean algorithm.\n \"\"\"\n while num2 != 0:\n num1, num2 = num2... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020931",
"row_id": 20931,
"seed_ids": "['Llama-3.3-70B-Instruct_52501']"
} | 0.461803 | Filter_20931 | I | [
"calculate_gcd",
"append_gcd_to_file"
] | 2 | [
[
"append_gcd_to_file",
"calculate_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a65fb86b2fd9c73bfac55ceccdfbf35e0d50e59f | 8a59e6f0612c4b2ee5c5151fc4859eeb44cf52b9 | |||
v1.0 | instruct | Filter | Filter_20951_I | ###Using Python,write a program that counts all the prime numbers between 1 and 100
Here is how it should work:
- The program should have a function called `is_prime() ` that checks if a number is prime. This function should return `True` if the number is prime and `False` otherwise.
- The function should be called i... | def is_prime(n):
"""
Determine if the number n is prime.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
"""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return T... | from solution import is_prime, count_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(29) == True
assert is_prime(49) == False
assert is_prime(97) == True
def test_count_primes():
co... | [
{
"docstring": "Determine if the number n is prime.\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Count and return... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Checks if a number is prime.\n Returns True if the number is prime, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020951",
"row_id": 20951,
"seed_ids": "['Llama-3.3-70B-Instruct_52549']"
} | 0.679901 | Filter_20951 | I | [
"is_prime",
"count_primes"
] | 2 | [
[
"count_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4730b6e0e6b5a85d7f9df564ba32fab1312e1a73 | af6aa04243ef32b17727beda0b04c59f3bcc4513 | |||
v1.0 | instruct | Filter | Filter_20952_I | I know a Python function that checks if a date is valid. It throws a `ValueError` if the date is not valid. The function is called `validate_date`. I want to create another function that filters a list of dictionaries where each dictionary contains a date string in the key named `"date"`. I want to filter out the dicti... | def validate_date(date_string):
"""
Validates if the date_string is in the format YYYY-MM-DD.
Throws a ValueError if the date is not valid.
"""
from datetime import datetime
try:
datetime.strptime(date_string, '%Y-%m-%d')
except ValueError:
raise ValueError(f"Invalid date: {d... | from solution import validate_date, filter_dicts_by_date
def test_filter_dicts_by_date_all_valid():
dict_list = [
{"name": "John", "date": "2022-01-01"},
{"name": "Jane", "date": "2022-02-01"},
{"name": "Bob", "date": "2022-02-28"},
]
result = filter_dicts_by_date(dict_list)
ass... | [
{
"docstring": "Validates if the date_string is in the format YYYY-MM-DD.\nThrows a ValueError if the date is not valid.",
"function_declaration": "def validate_date(date_string):",
"function_name": "validate_date",
"parameter_list": "(date_string)"
},
{
"docstring": "Filters out the diction... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def validate_date(date_string):\n \"\"\"\n Validates the date string. Raises a ValueError if the date is invalid.\n :param date_string: Date string in 'YYYY-MM-DD' format\n \"\"\"\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020952",
"row_id": 20952,
"seed_ids": "['Llama-3.3-70B-Instruct_52550']"
} | 0.672379 | Filter_20952 | I | [
"validate_date",
"filter_dicts_by_date"
] | 2 | [
[
"filter_dicts_by_date",
"validate_date"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a3bb1938d479359d51d1b74ec92bbdd3e7d334b | 5bf7cc7e1b09790d85b7311ec1be9e6a8927ec61 | |||
v1.0 | instruct | Filter | Filter_20985_I | Here is the Python script that creates a node class to be used in a singly linked list:
```
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
```
Now I want to implement an `insert_numbers` module, that will take a connected list of numbers as input and return a... | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def create_linked_list(lst):
if not lst:
return None
head = Node(lst[0])
current = head
for data in lst[1:]:
current.next = Node(data)
current = current.next
return he... | from solution import Node, create_linked_list, insert_numbers
def linked_list_to_list(node):
"""Helper function to convert linked list to list."""
result = []
while node:
result.append(node.data)
node = node.next
return result
def test_create_linked_list_empty():
assert create_link... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\ndef create_linked_list(lst):\n if not lst:\n return None\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020985",
"row_id": 20985,
"seed_ids": "['Llama-3.3-70B-Instruct_52627']"
} | 0.514248 | Filter_20985 | I | [
"create_linked_list",
"insert_numbers"
] | 2 | [
[
"insert_numbers",
"create_linked_list"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 6ae63cf51a0d452c072c14a493b5577cb5a4c35b | f6d618cf4081139824b6085045065411a11463f2 | |||
v1.0 | instruct | Filter | Filter_20986_I | Here's a code snippet that generates prime numbers using the Sieve of Eratosthenes algorithm and then uses NumPy to find the average, median, and mode of a specified subset of these prime numbers:
```python
import numpy as np
def sieve_of_eratosthenes(n):
"""Returns a list of prime numbers up to n"""
sieve = ... | import numpy as np
from collections import Counter
def sieve_of_eratosthenes(n):
""" Returns a list of prime numbers up to n """
sieve = [True] * (n + 1)
sieve[0:2] = [False, False] # 0 and 1 are not prime numbers
for start in range(2, int(n**0.5) + 1):
if sieve[start]:
for i in ra... | def test_sieve_of_eratosthenes():
assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]
assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]
assert sieve_of_eratosthenes(2) == [2]
assert sieve_of_eratosthenes(1) == []
assert sieve_of_eratosthenes(0) == []
def test_prime_statistics():
ave... | [
{
"docstring": "Returns a list of prime numbers up to n ",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the average, median, and mode of prime numbers up to n ",
"function_declarati... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy import stats\n\ndef sieve_of_eratosthenes(n):\n \"\"\"\n Returns a list of prime numbers up to n.\n \"\"\"\n sieve = [True] * (n + 1)\n sieve[0:2]... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020986",
"row_id": 20986,
"seed_ids": "['Llama-3.3-70B-Instruct_52628']"
} | 0.598846 | Filter_20986 | I | [
"sieve_of_eratosthenes",
"prime_statistics"
] | 2 | [
[
"prime_statistics",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | 781a440b15aa425e9ac001fe7afa2629b0b7e12e | 4050713fc591cc645c958d8a72182ae05683f0c8 | |||
v1.0 | instruct | Filter | Filter_20988_I | Here are the counts of each letter used in the given grid using a dictionary format.
Here is the grid:
2 6 4
3 8 5
8 4 9
letter_count = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0,... | def grid_row_map(word, grid, letter_count, row_number):
"""
Map each word to the corresponding numerical values of its letters and update the grid and letter_count
"""
# Convert word letters to their numerical values
numbers = [ord(c.upper()) - 64 for c in word]
grid[row_number] = numbers
#... | def test_grid_row_map_correct_grid_and_count():
words = ['FIND', 'RANE', 'TOPS']
grid_size = 3
expected_grid = [[6, 9, 14, 4], [18, 1, 14, 5], [20, 15, 16, 19]]
expected_letter_count = {
'A': 1, 'B': 0, 'C': 0, 'D': 1, 'E': 1, 'F': 1, 'G': 0, 'H': 0, 'I': 1, 'J': 0, 'K': 0, 'L': 0,
'M':... | [
{
"docstring": "Map each word to the corresponding numerical values of its letters and update the grid and letter_count",
"function_declaration": "def grid_row_map(word, grid, letter_count, row_number):",
"function_name": "grid_row_map",
"parameter_list": "(word, grid, letter_count, row_number)"
}... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def grid_row_map(word, grid, letter_count, row_number):\n \"\"\"\n Maps the given word to the grid based on alphabetical position,\n and updates the letter count dictionary with occur... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020988",
"row_id": 20988,
"seed_ids": "['Llama-3.3-70B-Instruct_52630']"
} | 0.649599 | Filter_20988 | I | [
"grid_row_map",
"update_letter_count"
] | 2 | [
[
"update_letter_count",
"grid_row_map"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8150e27d59fdb578857750d5285295615984993d | a189ce3c3cd24d262cb390a9b85c5a4ddbff9d8b | |||
v1.0 | instruct | Filter | Filter_21029_I | You have been tasked with writing a Python program that computes and prints the first N perfect numbers, a perfect number being a positive integer that is equal to the sum of its proper divisors, excluding the number itself. Write your code in the following steps:
Create a function to check if a number is perfect.
Im... | def is_perfect(num):
"""
Checks if a given number is perfect.
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself.
"""
if num < 2:
return False
divisors_sum = sum(i for i in range(1, num) if num % i == 0)
return divisors_sum == num... | from solution import is_perfect, find_first_n_perfect_numbers
def test_is_perfect():
assert is_perfect(6) == True
assert is_perfect(28) == True
assert is_perfect(496) == True
assert is_perfect(8128) == True
assert is_perfect(7) == False
assert is_perfect(12) == False
def test_find_first_n_perf... | [
{
"docstring": "Checks if a given number is perfect.\nA perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself.",
"function_declaration": "def is_perfect(num):",
"function_name": "is_perfect",
"parameter_list": "(num)"
},
{
"docstring": "Finds ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_perfect_number(num):\n \"\"\"\n Determines if a number is a perfect number.\n \n A perfect number is a positive integer that is equal to the sum of its proper \n divisors... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021029",
"row_id": 21029,
"seed_ids": "['Llama-3.3-70B-Instruct_52729']"
} | 0.654471 | Filter_21029 | I | [
"is_perfect",
"find_first_n_perfect_numbers"
] | 2 | [
[
"find_first_n_perfect_numbers",
"is_perfect"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ca82ae08ad65d2d2fa7d5a66042d0b72beea327 | e69be80b60795ef4f0f4e00f77b6b4601ad3ba37 | |||
v1.0 | instruct | Filter | Filter_21034_I | I have a function `snake_to_camel` with the following signature:
```python
def snake_to_camel(snake_case: str) -> str:
"""
Converts a snake_case string to camelCase.
:param snake_case: a string in snake_case
:return: a camelCase version of the input string
"""
```
How would I use this function to... | def snake_to_camel(snake_case: str) -> str:
"""
Converts a snake_case string to camelCase.
:param snake_case: a string in snake_case
:return: a camelCase version of the input string
"""
components = snake_case.split('_')
if not components:
return snake_case
return components[0] ... | from solution import snake_to_camel, convert_dict_keys_to_camel_case
def test_snake_to_camel_basic():
assert snake_to_camel('hello_world') == 'helloWorld'
assert snake_to_camel('foo_bar_baz') == 'fooBarBaz'
assert snake_to_camel('python_is_awesome') == 'pythonIsAwesome'
def test_snake_to_camel_empty():
... | [
{
"docstring": "Converts a snake_case string to camelCase.\n\n:param snake_case: a string in snake_case\n:return: a camelCase version of the input string",
"function_declaration": "def snake_to_camel(snake_case):",
"function_name": "snake_to_camel",
"parameter_list": "(snake_case)"
},
{
"doc... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def snake_to_camel(snake_case: str) -> str:\n \"\"\"\n Converts a snake_case string to camelCase.\n\n :param snake_case: a string in snake_case\n :return: a camelCase version of th... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021034",
"row_id": 21034,
"seed_ids": "['Llama-3.3-70B-Instruct_52740']"
} | 0.640491 | Filter_21034 | I | [
"snake_to_camel",
"convert_dict_keys_to_camel_case"
] | 2 | [
[
"convert_dict_keys_to_camel_case",
"snake_to_camel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5a4abfe08a563e239a34a913a6c08b1a9cd8e2c5 | c684ed4e55dfd72649df7b714c905e3ec885aab4 | |||
v1.0 | instruct | Filter | Filter_21076_I | I have an array of JSON objects with nested arrays of objects, and I want to apply a function to each object at the deepest level, i.e., the object itself and also the objects within the nested arrays.
Here is my array of JSON objects:
```json
[
{
"id": 1,
"name": "John",
"scores": [
... | def convert_keys_to_uppercase(obj):
"""
Recursively converts all keys of a JSON object to uppercase.
"""
if isinstance(obj, list):
return [convert_keys_to_uppercase(item) for item in obj]
elif isinstance(obj, dict):
return {key.upper(): convert_keys_to_uppercase(value) for key, value... | from solution import transform_json_array
def test_transform_simple_objects():
input_data = [
{"id": 1,
"name": "John"},
{"id": 2,
"name": "Alice"}
]
expected_output = [
{"ID": 1,
"NAME": "John"},
{"ID": 2,
"NAME": "Alice"}
]
asser... | [
{
"docstring": "Recursively converts all keys of a JSON object to uppercase.",
"function_declaration": "def convert_keys_to_uppercase(obj):",
"function_name": "convert_keys_to_uppercase",
"parameter_list": "(obj)"
},
{
"docstring": "Apply the key conversion for each object in the array.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def convert_keys_to_uppercase(obj):\n \"\"\"\n Recursively converts all keys in the object to uppercase.\n \"\"\"\n if isinstance(obj, dict):\n uppercased_dict = {}\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021076",
"row_id": 21076,
"seed_ids": "['Llama-3.3-70B-Instruct_52843']"
} | 0.425704 | Filter_21076 | I | [
"convert_keys_to_uppercase",
"transform_json_array"
] | 2 | [
[
"transform_json_array",
"convert_keys_to_uppercase"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 860636c02708b50565ac7ddab05d963ce4ba3560 | 4388f226744d8bc0d7fab637f6a63cf88a403748 | |||
v1.0 | instruct | Filter | Filter_21080_I | Hi, I'm new to Python and I've run into a few problems with my code. It's supposed to be a game where you roll a dice, and it randomly selects a number between 1 and 6. Then it selects a random enemy with a strength from 1 to 10. Then the dice roll is compared to the enemy strength and depending on the results, you get... | import random
# List of enemies and their strengths
enemies = [
{"name": "Goblin", "strength": 3},
{"name": "Orc", "strength": 6},
{"name": "Troll", "strength": 8},
{"name": "Dragon", "strength": 10},
{"name": "Wolf", "strength": 2},
{"name": "Bandit", "strength": 4},
{"name": "Skeleton", "... | from unittest.mock import patch
import pytest
from solution import roll_dice, select_enemy
def test_roll_dice():
for _ in range(100): # Run multiple times to check range
roll = roll_dice()
assert 1 <= roll <= 6
def test_select_enemy():
for _ in range(100): # Run multiple times to ensure rand... | [
{
"docstring": null,
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def select_enemy():",
"function_name": "select_enemy",
"parameter_list": "()"
},
{
"docstring": null,
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# List of enemies and their strengths\nenemies = [\n {\"name\": \"Goblin\", \"strength\": 3},\n {\"name\": \"Orc\", \"strength\": 6},\n {\"name\": \"Troll\", \"streng... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021080",
"row_id": 21080,
"seed_ids": "['Llama-3.3-70B-Instruct_52847']"
} | 0.478701 | Filter_21080 | I | [
"roll_dice",
"select_enemy",
"game"
] | 3 | [
[
"game",
"roll_dice"
],
[
"game",
"select_enemy"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2677361774b923fe95da33c002ae94f7eb195c06 | bf7e0110f93ebf0b776e787cfe9ce5de0f54f6a5 | |||
v1.0 | instruct | Filter | Filter_21086_I | Here is the code to find the closest pair of points in a plane.
```python
def distance(p1, p2):
"""
Calculate the Euclidean distance between two points.
Args:
p1 (tuple): First point
p2 (tuple): Second point
Returns:
float: Euclidean distance between p1 and p2
"""
retu... | from math import inf
def distance(p1, p2):
"""
Calculate the Euclidean distance between two points.
Args:
p1 (tuple): First point
p2 (tuple): Second point
Returns:
float: Euclidean distance between p1 and p2
"""
return ((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) ** 0... | from solution import closest_pair, distance
def test_closest_pair_with_small_set():
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
assert closest_pair(points) == ((2, 3), (3, 4)) or closest_pair(points) == ((3, 4), (2, 3))
def test_closest_pair_with_duplicates():
points = [(0, 0), (1, 1),... | [
{
"docstring": "Calculate the Euclidean distance between two points.\n\nArgs:\n p1 (tuple): First point\n p2 (tuple): Second point\n\nReturns:\n float: Euclidean distance between p1 and p2",
"function_declaration": "def distance(p1, p2):",
"function_name": "distance",
"parameter_list": "(p1... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import inf\n\ndef distance(p1, p2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n\n Args:\n p1 (tuple): First point\n p2 (tuple): Second po... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021086",
"row_id": 21086,
"seed_ids": "['Llama-3.3-70B-Instruct_52857']"
} | 0.655966 | Filter_21086 | I | [
"distance",
"closest_pair_recursive",
"closest_pair",
"brute_force_closest_pair"
] | 4 | [
[
"brute_force_closest_pair",
"distance"
],
[
"closest_pair",
"closest_pair_recursive"
],
[
"closest_pair_recursive",
"brute_force_closest_pair"
],
[
"closest_pair_recursive",
"distance"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 99f0ac776efa2a8e2944ed5da5d52c63d7a538db | e9d61f99d08b97bf25435c102b1367ecb86372b7 | |||
v1.0 | instruct | Filter | Filter_21093_I | I have a code that keeps track of the stock price of a number of different stocks. The price is updated at different intervals, but I want to be able to create a summary report of all the current stock prices and print it out. The current code uses a dictionary where the keys are the stock symbols and the values are th... | def generate_report(current_prices):
report = ""
for stock, price in current_prices.items():
report += f"{stock}: ${price:.2f}\n"
return report
def print_report(current_prices):
report = generate_report(current_prices)
print(report) | from solution import generate_report
def test_generate_report_empty():
assert generate_report({}) == ""
def test_generate_report_single_stock():
assert generate_report({"AAPL": 150.0}) == "AAPL: $150.00\n"
def test_generate_report_multiple_stocks():
stock_prices = {"AAPL": 150.0, "GOOGL": 2800.5, "AMZN":... | [
{
"docstring": null,
"function_declaration": "def generate_report(current_prices):",
"function_name": "generate_report",
"parameter_list": "(current_prices)"
},
{
"docstring": null,
"function_declaration": "def print_report(current_prices):",
"function_name": "print_report",
"par... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_report(current_prices):\n \"\"\"\n Generates a summary report of the current stock prices.\n \n Args:\n current_prices (dict): A dictionary where keys are stock... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021093",
"row_id": 21093,
"seed_ids": "['Llama-3.3-70B-Instruct_52870']"
} | 0.556314 | Filter_21093 | I | [
"generate_report",
"print_report"
] | 2 | [
[
"print_report",
"generate_report"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0cabe3d2756317c422138dc0d64e28573721a31b | 5de5f1c624bb954775e3201d16e7b9f94f142eea | |||
v1.0 | instruct | Filter | Filter_21097_I | The problem asks to write an executable code to share an example use case for a customer service chat system. The code should follow the specific style described below.
Here is the code template that needs to follow:
```python
"""
Example for:
Title: Customer Service Chat System
Description: A brief description about ... | """
Example for:
Title: Customer Service Chat System
Description: A brief description about the customer service chat system.
"""
# pylint: disable=missing-module-docstring,missing-function-docstring
# Add required imports
from datetime import datetime
# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
WELCOME_MESSAGE = ... | from solution import get_current_timestamp, generate_welcome_message, reply_to_customer_message
from datetime import datetime
def test_get_current_timestamp():
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
assert get_current_timestamp() == now
def test_generate_welcome_message():
timestamp = datetime... | [
{
"docstring": null,
"function_declaration": "def get_current_timestamp():",
"function_name": "get_current_timestamp",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_welcome_message():",
"function_name": "generate_welcome_message",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "\"\"\"\nExample for:\nTitle: Customer Service Chat System\nDescription: A brief description about the customer service chat system\n\"\"\"\n\n# pylint: disable=missing-module-docstring,missing... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021097",
"row_id": 21097,
"seed_ids": "['Llama-3.3-70B-Instruct_52879']"
} | 0.389217 | Filter_21097 | I | [
"get_current_timestamp",
"generate_welcome_message",
"reply_to_customer_message"
] | 3 | [
[
"generate_welcome_message",
"get_current_timestamp"
],
[
"reply_to_customer_message",
"get_current_timestamp"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3d9f421f13e16e4f0dace3d4d9cff4406ac0ccfe | 52c95d5c8f1176b351806efddb1c973ec8c1a01e | |||
v1.0 | instruct | Filter | Filter_21121_I | I have a list of ordered pairs that represents the edges of a graph, where the pairs are of the form (u, v). The edges are directed. I want to detect cycles in the graph.
I would like to have an algorithm that can detect whether a given vertex is part of a cycle.
I can make use of depth-first search to perform this ... | def create_adjacency_list(edges):
"""
Creates an adjacency list from a list of edges.
Args:
edges (list of tuple): List of directed edges where each edge is a tuple (u, v).
Returns:
dict: Adjacency list representation of the graph.
"""
adjacency_list = {}
for u, v in edges:
... | from solution import create_adjacency_list, is_vertex_in_cycle
def test_create_adjacency_list():
edges = [(1, 2), (2, 3), (3, 1), (3, 4)]
adjacency_list = create_adjacency_list(edges)
assert adjacency_list == {1: [2], 2: [3], 3: [1, 4]}
def test_is_vertex_in_cycle():
edges = [(1, 2), (2, 3), (3, 1), (... | [
{
"docstring": "Creates an adjacency list from a list of edges.\n\nArgs:\nedges (list of tuple): List of directed edges where each edge is a tuple (u, v).\n\nReturns:\ndict: Adjacency list representation of the graph.",
"function_declaration": "def create_adjacency_list(edges):",
"function_name": "creat... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\n\ndef create_adjacency_list(edges):\n \"\"\"\n Creates an adjacency list from a list of edges.\n \n Parameters:\n edges (list of tuples): Ea... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021121",
"row_id": 21121,
"seed_ids": "['Llama-3.3-70B-Instruct_52933']"
} | 0.466916 | Filter_21121 | I | [
"create_adjacency_list",
"is_cyclic_dfs",
"is_vertex_in_cycle"
] | 3 | [
[
"is_vertex_in_cycle",
"create_adjacency_list"
],
[
"is_vertex_in_cycle",
"is_cyclic_dfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 37f3aa9c447a2d881446eee430ca31235c1ab9e8 | bbd9e88fcf918a40b1a59cc8e02d33d2d26f0a16 | |||
v1.0 | instruct | Filter | Filter_21126_I | I know that the trim command (`trim.py`) in Python provides the following functionality:
- Trims whitespace characters from both the beginning and end of text files.
- Deletes files that are completely empty.
- Takes two optional arguments: `--verbose` and `--recursive`.
- When `--verbose` is provided, prints the n... | import os
import argparse
def trim_file(file_path, verbose=False):
with open(file_path, 'r+') as f:
content = f.read()
trimmed_content = content.strip()
if verbose:
print(f'Processing file: {file_path}')
if trimmed_content != content:
if ver... | import os
import tempfile
import pytest
from solution import trim_file, delete_empty_file, trim_directory
# Helper to create a temporary file
def create_temp_file(content=''):
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(content.encode())
temp_file.close()
return temp_file.name... | [
{
"docstring": null,
"function_declaration": "def trim_file(file_path, verbose=False):",
"function_name": "trim_file",
"parameter_list": "(file_path, verbose=False)"
},
{
"docstring": null,
"function_declaration": "def delete_empty_file(file_path, verbose=False):",
"function_name": "... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport argparse\n\ndef trim_file(filepath, verbose=False):\n \"\"\"\n Trims whitespace characters from beginning and end of the file's content.\n Deletes the file if it is ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021126",
"row_id": 21126,
"seed_ids": "['Llama-3.3-70B-Instruct_52941']"
} | 0.443151 | Filter_21126 | I | [
"trim_file",
"delete_empty_file",
"trim_directory",
"main"
] | 4 | [
[
"trim_directory",
"delete_empty_file"
],
[
"trim_directory",
"trim_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 99dbcde879d9162aa39139e1f4ca5e4bb4040747 | 0312b599911a6051edea12fc3590030a873ab32d | |||
v1.0 | instruct | Filter | Filter_21187_I | Here is a basic implementation of the merge sort algorithm in Python:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i, j = 0,... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def merge_sort_linked_list(head):
if not head or not head.next:
return head
middle = get_middle(head)
next_to_middle = middle.next
middle.next = None
left = merge_sort_linked_list(head)
right =... | from solution import Node, merge_sort_linked_list
def list_to_linked_list(arr):
if not arr:
return None
head = Node(arr[0])
current = head
for value in arr[1:]:
current.next = Node(value)
current = current.next
return head
def linked_list_to_list(head):
arr = []
whi... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n# Helper function to find the middle of the linked list\ndef get_middle(head):\n if head is... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021187",
"row_id": 21187,
"seed_ids": "['Llama-3.3-70B-Instruct_53082']"
} | 0.512756 | Filter_21187 | I | [
"merge_sort_linked_list",
"get_middle",
"merge"
] | 3 | [
[
"merge_sort_linked_list",
"get_middle"
],
[
"merge_sort_linked_list",
"merge"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 669c8f368e72ebb1104bccf286219d98c6fca07f | 9bc87770eb1ffcfb17f71a211dd4ee55ddeb83db | |||
v1.0 | instruct | Filter | Filter_21207_I | I have a CRM system that has a data structure that stores customer details. The data is a list of dictionaries where each dictionary represents a customer and contains their id, name, customerType (either 'A' or 'B'), and contact details. The list contains 1000000 customers.
I need to write a script that takes the li... | import threading
from queue import Queue
def send_promotional_email(customer):
# Simulate sending a promotional email
print(f"Sending promotional email to {customer['name']}")
def send_survey(customer):
# Simulate sending a survey
print(f"Sending survey to {customer['name']}")
def process_customer(cu... | from solution import process_customers
def test_process_customers():
from io import StringIO
import sys
# Prepare a list of example customers
customers = [
{'id': 1, 'name': 'Customer A', 'customerType': 'A', 'contact': 'a@example.com'},
{'id': 2, 'name': 'Customer B', 'customerType': ... | [
{
"docstring": null,
"function_declaration": "def send_promotional_email(customer):",
"function_name": "send_promotional_email",
"parameter_list": "(customer)"
},
{
"docstring": null,
"function_declaration": "def send_survey(customer):",
"function_name": "send_survey",
"parameter... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing as mp\n\ndef process_customers(customer_chunk):\n \"\"\"\n Process a chunk of customers. Sends promotional email for customerType 'A' \n and survey for customer... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021207",
"row_id": 21207,
"seed_ids": "['Llama-3.3-70B-Instruct_53135']"
} | 0.422601 | Filter_21207 | I | [
"send_promotional_email",
"send_survey",
"process_customer",
"worker",
"process_customers"
] | 5 | [
[
"process_customer",
"send_promotional_email"
],
[
"process_customer",
"send_survey"
],
[
"worker",
"process_customer"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 433b82b33104355885fa746b6eea1ddd6cbc18b6 | 9f9d46805b5353b477ccfef060faa2b6a0da30ba | |||
v1.0 | instruct | Filter | Filter_21213_I | Once you have two functions `int square(int x)` and `int cube(int x)` that take an integer `x` as input and respectively return `x` squared and `x` cubed, how can I use the higher order function `map()` to use these functions with map() like `map(square, [1, 2, 3])`? | def square(x):
"""
Returns the square of x.
"""
return x * x
def cube(x):
"""
Returns the cube of x.
"""
return x * x * x
# Example usage with map functions
def apply_square(input_list):
"""
Applies the square function to a list using map.
"""
return list(map(square, in... | from solution import square, cube, apply_square, apply_cube
def test_square_function():
assert square(2) == 4
assert square(-3) == 9
assert square(0) == 0
def test_cube_function():
assert cube(2) == 8
assert cube(-3) == -27
assert cube(0) == 0
def test_apply_square():
assert apply_square(... | [
{
"docstring": "Returns the square of x.",
"function_declaration": "def square(x):",
"function_name": "square",
"parameter_list": "(x)"
},
{
"docstring": "Returns the cube of x.",
"function_declaration": "def cube(x):",
"function_name": "cube",
"parameter_list": "(x)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def square(x):\n \"\"\"\n Returns the square of x.\n \"\"\"\n return x * x\n\ndef cube(x):\n \"\"\"\n Returns the cube of x.\n \"\"\"\n return x * x * x\n\n# Example us... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021213",
"row_id": 21213,
"seed_ids": "['Llama-3.3-70B-Instruct_53145']"
} | 0.433624 | Filter_21213 | I | [
"square",
"cube",
"apply_square",
"apply_cube"
] | 4 | [
[
"apply_cube",
"cube"
],
[
"apply_square",
"square"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3b8c07f404560cf1cbd5f7bd47e173d3d2247b91 | f2670ba3942f9b14ffdfe2f0748d42160876365e | |||
v1.0 | instruct | Filter | Filter_21218_I | I'd like you to write a code that generates a specified number of random points within a rectangular region. These points should then be connected in a way that minimizes the total distance between them, and the distance between each consecutive pair of points should be calculated. | import random
import math
from scipy.spatial import distance_matrix
from scipy.spatial import Delaunay
import numpy as np
def generate_random_points(num_points, width, height):
"""
Generates a specified number of random points within a rectangular region.
Parameters:
num_points (int): Number of po... | from solution import generate_random_points, calculate_distances, minimum_spanning_tree
def test_generate_random_points():
points = generate_random_points(5, 100, 100)
assert len(points) == 5
for x, y in points:
assert 0 <= x <= 100
assert 0 <= y <= 100
def test_calculate_distances():
... | [
{
"docstring": "Generates a specified number of random points within a rectangular region.\n\nParameters:\nnum_points (int): Number of points to generate.\nwidth (int): Width of the rectangular region.\nheight (int): Height of the rectangular region.\n\nReturns:\nlist of tuple: List containing the generated poi... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport math\nfrom scipy.spatial import distance_matrix\nfrom scipy.spatial.distance import euclidean\nfrom itertools import permutations\n\ndef generate_random_points(n, x_range... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021218",
"row_id": 21218,
"seed_ids": "['Llama-3.3-70B-Instruct_53153']"
} | 0.680631 | Filter_21218 | I | [
"generate_random_points",
"calculate_distances",
"minimum_spanning_tree"
] | 3 | [
[
"minimum_spanning_tree",
"calculate_distances"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 53e82ee940cd845ac85fc951bced32e7d2e16519 | cd77116f31d6f029cdd11ca64b03210314b639d3 | |||
v1.0 | instruct | Filter | Filter_21222_I | I have a set of 9 phrases, each consisting of 5 words. I would like to generate all possible combinations of these phrases such that for each combination of 3 phrases, at least one of the phrases is the same. For instance, in the combination ("this is a test", "that is a test", "this is a test"), the phrase "this is a ... | import itertools
phrases = [
"the dog is very happy",
"the cat is very happy",
"the dog is very sad",
"the dog is very angry",
"the cat is very angry",
"the cat is very sad",
"the dog is very tired",
"the dog is very hungry",
"the dog is very happy"
]
def intersection_size(lists):
... | from solution import filter_valid_combinations
def test_filter_valid_combinations():
phrases = [
"the dog is very happy",
"the cat is very happy",
"the dog is very sad",
"the dog is very angry",
"the cat is very angry",
"the cat is very sad",
"the dog is very... | [
{
"docstring": null,
"function_declaration": "def intersection_size(lists):",
"function_name": "intersection_size",
"parameter_list": "(lists)"
},
{
"docstring": null,
"function_declaration": "def filter_valid_combinations(phrases, num_words):",
"function_name": "filter_valid_combina... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\nphrases = [\n \"the dog is very happy\",\n \"the cat is very happy\",\n \"the dog is very sad\",\n \"the dog is very angry\",\n \"the cat is very angry\",\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021222",
"row_id": 21222,
"seed_ids": "['Llama-3.3-70B-Instruct_53157']"
} | 0.563145 | Filter_21222 | I | [
"intersection_size",
"filter_valid_combinations"
] | 2 | [
[
"filter_valid_combinations",
"intersection_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4fb7ddb56707fd2fffcbac06d6e0f1a4cea278d | 3a8e84ec2d0076167331d12362f9a2ac19a09953 | |||
v1.0 | instruct | Filter | Filter_21250_I | I am attempting to create an accurate simulation of the balls in a Galton Board, which is a triangular board with pegs that the balls fall through. I do not understand where to start with approximating the bounces and simulating the behavior.
To begin with, I will be using Python for the implementation.
Before lookin... | import random
def drop_ball(num_levels):
"""
Simulates dropping a single ball through the Galton Board with a given number of levels.
Returns the final position of the ball.
"""
position = 0
for level in range(num_levels):
# Randomly decide to move left or right
if random.random... | from solution import drop_ball, simulate_galton_board, count_bins
def test_drop_ball_randomness():
num_levels = 10
positions = [drop_ball(num_levels) for _ in range(100)]
assert min(positions) >= -num_levels
assert max(positions) <= num_levels
def test_simulate_galton_board_distribution():
num_lev... | [
{
"docstring": "Simulates dropping a single ball through the Galton Board with a given number of levels.\nReturns the final position of the ball.",
"function_declaration": "def drop_ball(num_levels):",
"function_name": "drop_ball",
"parameter_list": "(num_levels)"
},
{
"docstring": "Simulate... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef simulate_galton_board(rows, num_balls):\n \"\"\"\n Simulates a Galton Board with a specified number of rows and balls.\n \n Parameters:\n rows (int): The nu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021250",
"row_id": 21250,
"seed_ids": "['Llama-3.3-70B-Instruct_53218']"
} | 0.267665 | Filter_21250 | I | [
"drop_ball",
"simulate_galton_board",
"count_bins"
] | 3 | [
[
"simulate_galton_board",
"drop_ball"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 23b4184ee98ef6bd0f318c48123946eeaac1707e | 64101bed907e0d669791fb75583456b5446c0e85 | |||
v1.0 | instruct | Filter | Filter_21280_I | I have a simulation that operates over a large range of time (years, decades, etc), and would like to add some non-recurring events that can occur at arbitrary times within the simulation. These events are often specific to a particular type of entity (e.g., company, person, etc.) and can have different effects dependi... | import functools
def event_decorator(event_type):
"""
A decorator to define events with a certain type.
"""
def decorator_event(func):
@functools.wraps(func)
def wrapper_event(*args, **kwargs):
result = func(*args, **kwargs)
# Here you can add additional logging ... | from solution import company_event, person_event, custom_event
def test_company_event():
result = company_event("Annual shareholders meeting")
assert result == "Company event: Annual shareholders meeting"
def test_person_event():
result = person_event("Birthday celebration")
assert result == "Person e... | [
{
"docstring": "A decorator to define events with a certain type.",
"function_declaration": "def event_decorator(event_type):",
"function_name": "event_decorator",
"parameter_list": "(event_type)"
},
{
"docstring": null,
"function_declaration": "def company_event(description):",
"fun... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import datetime\nfrom functools import wraps\n\n# Dictionary to store event handlers by entity type\nevent_handlers = {}\n\n\ndef register_event(entity_type):\n \"\"\"\n Decorator to reg... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021280",
"row_id": 21280,
"seed_ids": "['Llama-3.3-70B-Instruct_53284']"
} | 0.369159 | Filter_21280 | I | [
"event_decorator",
"company_event",
"person_event",
"custom_event"
] | 4 | [
[
"company_event",
"event_decorator"
],
[
"custom_event",
"event_decorator"
],
[
"person_event",
"event_decorator"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 71486b5ba46d59909bd097216ea28051ed6ee521 | 24f8e9b297f9d3c328664191acd99f482c2c6109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.