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_80840_I | Write a function to find the intersection of two linked lists. The intersection of two linked lists is a list that contains all the elements that are common to both lists. Assume that the linked lists do not contain duplicate elements. | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def linked_list_to_set(head):
current = head
elements = set()
while current:
elements.add(current.value)
current = current.next
return elements
def find_intersection(head1, h... | from solution import ListNode, find_intersection
def list_to_linked_list(lst):
dummy_head = ListNode()
current = dummy_head
for item in lst:
current.next = ListNode(item)
current = current.next
return dummy_head.next
def linked_list_to_list(head):
result = []
current = head
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\ndef find_intersection(headA, headB):\n \"\"\"\n This function finds ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00080840",
"row_id": 80840,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163898']"
} | 0.656042 | Filter_80840 | I | [
"linked_list_to_set",
"find_intersection"
] | 2 | [
[
"find_intersection",
"linked_list_to_set"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 09d04db1079b16630e196346ed97d61135124671 | 7cef0f9fde6409319ded119c26d4947b0456ad6c | |||
v1.0 | instruct | Filter | Filter_80868_I | Is there a way to use the `linalg` module in PyTorch with `numba` for acceleration? Specifically, I need to compute the inverse of a matrix, and I know that `numba` does not support `torch.inverse` directly. Is there a way to use `numba` with PyTorch for this purpose? | import torch
import numpy as np
from numba import jit
def invert_matrix_with_pytorch(matrix):
"""
Calculate the inverse of a given matrix using PyTorch.
Args:
- matrix (torch.Tensor): A square matrix to be inverted
Returns:
- torch.Tensor: Inverse of the input matrix
"""
return tor... | import torch
import numpy as np
from solution import invert_matrix_with_pytorch, process_data_with_numba, invert_and_process
def test_invert_matrix_with_pytorch():
matrix = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
inverse_matrix = invert_matrix_with_pytorch(matrix)
expected_inverse = torch.tensor([[-2.0, 1.0... | [
{
"docstring": "Calculate the inverse of a given matrix using PyTorch.\nArgs:\n- matrix (torch.Tensor): A square matrix to be inverted\n\nReturns:\n- torch.Tensor: Inverse of the input matrix",
"function_declaration": "def invert_matrix_with_pytorch(matrix):",
"function_name": "invert_matrix_with_pytorc... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport numba\nimport numpy as np\n\n@numba.jit(nopython=True)\ndef invert_matrix_numba(matrix):\n \"\"\"\n Compute the inverse of a matrix using Numba.\n \"\"\"\n try... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00080868",
"row_id": 80868,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163945']"
} | 0.265027 | Filter_80868 | I | [
"invert_matrix_with_pytorch",
"process_data_with_numba",
"invert_and_process"
] | 3 | [
[
"invert_and_process",
"invert_matrix_with_pytorch"
],
[
"invert_and_process",
"process_data_with_numba"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numba",
"numpy",
"torch"
] | false | 6f4889f48628a0fb1c65936e86d7cca896312bf7 | 27f146a631b2e7e3790e8665db3fa89472758631 | |||
v1.0 | instruct | Filter | Filter_80907_I | I am working on a project to recognize handwritten digits using a neural network. I have a dataset of 5000 handwritten digits, each digit is represented as a 20x20 image. I want to use the backpropagation algorithm to train a neural network with one hidden layer. The input layer will have 400 nodes (since 20x20 = 400),... | import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def sigmoid_gradient(z):
return sigmoid(z) * (1 - sigmoid(z))
def initialize_weights(l_in, l_out):
epsilon_init = 0.12
return np.random.rand(l_out, 1 + l_in) * 2 * epsilon_init - epsilon_init
def forward_propagate(X, theta1, theta2):
... | import numpy as np
from solution import initialize_weights, forward_propagate, cost_function, backpropagate, train_neural_network, sigmoid
# Generate dummy data
np.random.seed(42)
X_dummy = np.random.rand(5000, 400)
y_dummy = np.random.randint(0, 10, 5000)
y_onehot = np.eye(10)[y_dummy]
def test_initialize_weights():... | [
{
"docstring": null,
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},
{
"docstring": null,
"function_declaration": "def sigmoid_gradient(z):",
"function_name": "sigmoid_gradient",
"parameter_list": "(z)"
},
{
"docstring": n... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef sigmoid_gradient(z):\n return sigmoid(z) * (1 - sigmoid(z))\n\ndef initialize_weights(l_in, l_out):\n epsilo... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00080907",
"row_id": 80907,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_163998']"
} | 0.355308 | Filter_80907 | I | [
"sigmoid",
"sigmoid_gradient",
"initialize_weights",
"forward_propagate",
"cost_function",
"backpropagate",
"train_neural_network"
] | 7 | [
[
"backpropagate",
"sigmoid_gradient"
],
[
"forward_propagate",
"sigmoid"
],
[
"sigmoid_gradient",
"sigmoid"
],
[
"train_neural_network",
"backpropagate"
],
[
"train_neural_network",
"cost_function"
],
[
"train_neural_network",
"forward_propagate"
... | 7 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 7681d8f6fb589178beefb0384d54306e78e3d784 | 4691ff42a41694b6b15b792cdbdab96873af1523 | |||
v1.0 | instruct | Filter | Filter_80914_I | I'm working on a project that involves the Traveling Salesman Problem (TSP). I understand that TSP is an optimization problem where the goal is to find the shortest possible route that visits a set of cities and returns to the origin city. I'm particularly interested in using a Genetic Algorithm (GA) to solve TSP in Py... | import random
import numpy as np
def calculate_distance(route, distance_matrix):
"""
Calculate the total distance of a given route based on the distance matrix.
"""
return sum(distance_matrix[route[i], route[i + 1]] for i in range(len(route) - 1)) + distance_matrix[route[-1], route[0]]
def create_init... | import numpy as np
def test_calculate_distance():
distance_matrix = np.array([
[0, 1, 2],
[1, 0, 3],
[2, 3, 0]
])
route = [0, 1, 2]
assert calculate_distance(route, distance_matrix) == 6
def test_create_initial_population():
pop_size = 5
num_cities = 4
population = ... | [
{
"docstring": "Calculate the total distance of a given route based on the distance matrix.",
"function_declaration": "def calculate_distance(route, distance_matrix):",
"function_name": "calculate_distance",
"parameter_list": "(route, distance_matrix)"
},
{
"docstring": "Create an initial po... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\n\ndef calculate_distance(route, distance_matrix):\n \"\"\"\n Calculate the total distance of a given route based on the distance matrix.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00080914",
"row_id": 80914,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164011']"
} | 0.308484 | Filter_80914 | I | [
"calculate_distance",
"create_initial_population",
"rank_routes",
"selection",
"mating_pool",
"breed",
"breed_population",
"mutate",
"mutate_population",
"next_generation",
"genetic_algorithm"
] | 11 | [
[
"breed_population",
"breed"
],
[
"genetic_algorithm",
"create_initial_population"
],
[
"genetic_algorithm",
"next_generation"
],
[
"genetic_algorithm",
"rank_routes"
],
[
"mutate_population",
"mutate"
],
[
"next_generation",
"breed_population"
... | 11 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | 9c7af9462893c788bfe6b96b2c3f05ef9a314723 | 0821b93c1b9594916f1d4d898382cde3460a6148 | |||
v1.0 | instruct | Filter | Filter_80918_I | You are given a set of 2D points. Each point has a unique x-coordinate and a unique y-coordinate. Your task is to find the number of "inversions" in this set. An inversion is defined as a pair of points (x1, y1) and (x2, y2) such that x1 < x2 and y1 > y2. Write a function in Python that takes a list of points as input ... | def count_inversions(points):
"""
Returns the number of inversions in a set of 2D points.
Each inversion is a pair of points (x1, y1) and (x2, y2)
such that x1 < x2 and y1 > y2.
"""
if not points:
return 0
points.sort(key=lambda p: p[0])
ys = [p[1] for p in points]
return me... | from solution import count_inversions
def test_count_inversions_empty():
assert count_inversions([]) == 0
def test_count_inversions_single_point():
assert count_inversions([(1, 1)]) == 0
def test_count_inversions_no_inversions():
assert count_inversions([(1, 1), (2, 2), (3, 3)]) == 0
def test_count_inve... | [
{
"docstring": "Returns the number of inversions in a set of 2D points.\nEach inversion is a pair of points (x1, y1) and (x2, y2)\nsuch that x1 < x2 and y1 > y2.",
"function_declaration": "def count_inversions(points):",
"function_name": "count_inversions",
"parameter_list": "(points)"
},
{
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_and_count(arr, temp_arr, left, mid, right):\n i = left # Starting index for left subarray\n j = mid + 1 # Starting index for right subarray\n k = left # Starting index to... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00080918",
"row_id": 80918,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164017']"
} | 0.724708 | Filter_80918 | I | [
"count_inversions",
"merge_sort_and_count"
] | 2 | [
[
"count_inversions",
"merge_sort_and_count"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2ea56e7093bc1b79af564031ea2524da59432dd | 8dd5bd7f3922dff6ce2d2453752ef13fcb0acb37 | |||
v1.0 | instruct | Filter | Filter_80950_I | In the context of a programming problem, what is the definition of a "weird number," and how can I write a program to find the first n weird numbers? Specifically, what are the criteria for a number to be considered "weird"? | def proper_divisors(n):
"""
Returns a list of the proper divisors of n (excluding n itself).
"""
divisors = []
for i in range(1, n//2 + 1):
if n % i == 0:
divisors.append(i)
return divisors
def is_abundant(n):
"""
Check if a number is abundant.
"""
return sum... | from solution import first_n_weird_numbers, is_weird
def test_proper_divisors():
from solution import proper_divisors
assert proper_divisors(12) == [1, 2, 3, 4, 6]
assert proper_divisors(28) == [1, 2, 4, 7, 14]
def test_is_abundant():
from solution import is_abundant
assert is_abundant(12) == True... | [
{
"docstring": "Returns a list of the proper divisors of n (excluding n itself).",
"function_declaration": "def proper_divisors(n):",
"function_name": "proper_divisors",
"parameter_list": "(n)"
},
{
"docstring": "Check if a number is abundant.",
"function_declaration": "def is_abundant(n... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_proper_divisors(n):\n \"\"\"\n Return the proper divisors of n\n \"\"\"\n divisors = []\n for i in range(1, n//2 + 1):\n if n % i == 0:\n divisors.appe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00080950",
"row_id": 80950,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164064']"
} | 0.468183 | Filter_80950 | I | [
"proper_divisors",
"is_abundant",
"is_semiperfect",
"can_sum_to_n",
"is_weird",
"first_n_weird_numbers"
] | 6 | [
[
"first_n_weird_numbers",
"is_weird"
],
[
"is_abundant",
"proper_divisors"
],
[
"is_semiperfect",
"can_sum_to_n"
],
[
"is_semiperfect",
"proper_divisors"
],
[
"is_weird",
"is_abundant"
],
[
"is_weird",
"is_semiperfect"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 1281927536b33441158ab20b2bf364e12fe2adec | ca8230b4a0b281bb2e44820af6c3628eb7c8d442 | |||
v1.0 | instruct | Filter | Filter_80955_I | I am working on a project that involves solving the traveling salesman problem (TSP). I am interested in implementing the Lin-Kernighan algorithm in Python. Can you provide some guidance on how to approach this problem? | import random
import math
def distance(point1, point2):
"""
Computes the Euclidean distance between two points.
"""
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def total_distance(tour, cities):
"""
Computes the total distance of the tour.
"""
return su... | from solution import distance, total_distance, lin_kernighan
def test_distance():
assert distance((0, 0), (3, 4)) == 5.0
assert distance((1, 1), (4, 5)) == 5.0
assert distance((2, -1), (-2, 1)) == math.sqrt(20)
def test_total_distance():
tour = [0, 1, 2, 3]
cities = [(0, 0), (0, 1), (1, 1), (1, 0)... | [
{
"docstring": "Computes the Euclidean distance between two points.",
"function_declaration": "def distance(point1, point2):",
"function_name": "distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Computes the total distance of the tour.",
"function_declaration": "def tota... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport random\n\ndef calculate_total_distance(tour, distance_matrix):\n total_distance = 0\n for i in range(len(tour)):\n total_distance += distance_matrix[tour[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00080955",
"row_id": 80955,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164072']"
} | 0.318796 | Filter_80955 | I | [
"distance",
"total_distance",
"lin_kernighan"
] | 3 | [
[
"lin_kernighan",
"total_distance"
],
[
"total_distance",
"distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3d7ef80269e5e2d4bce798360e701d2f43f95b0b | 665557f754c6dbb50131755b4b5ce224b8764338 | |||
v1.0 | instruct | Filter | Filter_80971_I | In the context of a programming problem, what is a "BOOM number," and how can I determine the k-th BOOM number in a sequence? | def is_boom_number(num):
"""
Checks if the given number contains the substring '313'.
"""
return '313' in str(num)
def find_kth_boom_number(k):
"""
Finds the k-th BOOM number in the sequence of numbers containing '313' in their decimal representation.
"""
count = 0
num = 0
... | from solution import find_kth_boom_number, is_boom_number
def test_is_boom_number():
assert is_boom_number(313) == True
assert is_boom_number(1313) == True
assert is_boom_number(3130) == True
assert is_boom_number(12313) == True
assert is_boom_number(12312) == False
def test_find_kth_boom_numb... | [
{
"docstring": "Checks if the given number contains the substring '313'.",
"function_declaration": "def is_boom_number(num):",
"function_name": "is_boom_number",
"parameter_list": "(num)"
},
{
"docstring": "Finds the k-th BOOM number in the sequence of numbers containing '313' in their decim... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_boom_number(num):\n \"\"\"\n Checks if the given number contains the substring '313'.\n \"\"\"\n return '313' in str(num)\n\ndef find_kth_boom_number(k):\n \"\"\"\n Fi... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00080971",
"row_id": 80971,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164100']"
} | 0.464014 | Filter_80971 | I | [
"is_boom_number",
"find_kth_boom_number"
] | 2 | [
[
"find_kth_boom_number",
"is_boom_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c9a421af3a0346789696db38d9b34809a36a5829 | 654a68c1818f609dd42623dbca38c6d91c89fce8 | |||
v1.0 | instruct | Filter | Filter_80983_I | I am working on a project where I need to implement a function in Python that can calculate the determinant of a square matrix using recursion. The function should be able to handle matrices of any size. Can you guide me on how to approach this problem? | def get_matrix_minor(matrix, i, j):
"""
Returns the minor of the matrix obtained by removing the i-th row and j-th column.
"""
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def calculate_determinant(matrix):
"""
Recursively calculates the determinant of a square matrix.
... | from solution import calculate_determinant
def test_determinant_2x2():
matrix = [[4, 6], [3, 8]]
assert calculate_determinant(matrix) == 14
def test_determinant_3x3():
matrix = [[6, 1, 1], [4, -2, 5], [2, 8, 7]]
assert calculate_determinant(matrix) == -306
def test_determinant_singular_matrix():
... | [
{
"docstring": "Returns the minor of the matrix obtained by removing the i-th row and j-th column.",
"function_declaration": "def get_matrix_minor(matrix, i, j):",
"function_name": "get_matrix_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": "Recursively calculates the determinan... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_submatrix(matrix, row, col):\n \"\"\"\n Returns the submatrix after removing the specified row and column.\n \"\"\"\n return [r[:col] + r[col+1:] for i, r in enumerate(matr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00080983",
"row_id": 80983,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164123']"
} | 0.480098 | Filter_80983 | I | [
"get_matrix_minor",
"calculate_determinant"
] | 2 | [
[
"calculate_determinant",
"get_matrix_minor"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b394ae7ff736623e144231f1c8d3477ddaae006a | 39d6d0eeaff2ce2bb20e3c9e6730acf70b85c99e | |||
v1.0 | instruct | Filter | Filter_81001_I | Write a Python program that asks the user to input a number and then calculates the factorial of that number. The factorial of a number \( n \) is the product of all positive integers less than or equal to \( n \). For example, the factorial of 5 is \( 5 \times 4 \times 3 \times 2 \times 1 = 120 \). The factorial of 0 ... | def factorial(n):
"""
Returns the factorial of a non-negative integer n.
If n is 0, returns 1.
If n is negative, raises ValueError.
"""
if not isinstance(n, int):
raise ValueError("Input must be an integer.")
if n < 0:
raise ValueError("Input must be a non-negative integer.")... | from solution import factorial
def test_factorial_positive():
assert factorial(5) == 120
assert factorial(3) == 6
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_invalid_input():
try:
factorial(-1)
except ValueError as e:
assert str(e) == "Input must be a no... | [
{
"docstring": "Returns the factorial of a non-negative integer n.\nIf n is 0, returns 1.\nIf n is negative, raises ValueError.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Asks the user to input a number and returns ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n Returns the factorial of a non-negative integer n.\n Raises ValueError if n is a negative integer.\n \"\"\"\n if not isinstance(n, int) or n < 0:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081001",
"row_id": 81001,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164151']"
} | 0.712391 | Filter_81001 | I | [
"factorial",
"get_user_input"
] | 2 | [
[
"get_user_input",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1fd34d2848ba3378267a98659447b9ff4e905258 | a599ad16552038eddf6acb05d1cd0244490fdc9b | |||
v1.0 | instruct | Filter | Filter_81030_I | I am working on a project that involves solving a system of differential equations in Python. The system is quite complex, and I need to find a numerical solution. Can you guide me on how to approach this problem using Python libraries? | from scipy.integrate import solve_ivp
import numpy as np
def system_of_equations(t, y):
"""
Define the system of differential equations as dy/dt = f(t, y).
Example: A system of two equations
dy1/dt = y2
dy2/dt = -y1
"""
y1, y2 = y
dy1_dt = y2
dy2_dt = -y1
return [dy1_dt, dy2_dt]... | from solution import system_of_equations, solve_system
import numpy as np
def test_system_of_equations():
t = 0
y = [1.0, 0.0]
dy_dt = system_of_equations(t, y)
assert dy_dt == [0.0, -1.0]
def test_solve_system_basic():
initial_conditions = [1.0, 0.0]
t_span = (0, 10)
solution = solve_syst... | [
{
"docstring": "Define the system of differential equations as dy/dt = f(t, y).\nExample: A system of two equations\ndy1/dt = y2\ndy2/dt = -y1",
"function_declaration": "def system_of_equations(t, y):",
"function_name": "system_of_equations",
"parameter_list": "(t, y)"
},
{
"docstring": "Sol... | [
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 solve_ivp\n\ndef system_of_odes(t, z):\n \"\"\"\n Defines the system of ODEs.\n \n Args:\n t: float\n Independent variable... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081030",
"row_id": 81030,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164194']"
} | 0.296405 | Filter_81030 | I | [
"system_of_equations",
"solve_system"
] | 2 | [
[
"solve_system",
"system_of_equations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | ea0b78fdb592109064bf2fbfcc35188c548fad5d | a98030621e39cc9e9f8284aa9b591261e53b0683 | |||
v1.0 | instruct | Filter | Filter_81041_I | I want to create a dynamic plot using Python and matplotlib that updates in real-time. How can I do this? | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
def update(frame, line, data):
data.append(random.randint(0, 100))
line.set_data(range(len(data)), data)
plt.xlim(0, len(data))
if max(data) > plt.ylim()[1]:
plt.ylim(0, max(data) + 10)
return line,
def ... | from solution import update
def test_update_increases_data_length():
data = [1, 2, 3]
line = type('', (), {})() # Creating a mock object
line.set_data = lambda x, y: None
update(0, line, data)
# After update, data length should increase by 1
assert len(data) == 4
def test_update_cha... | [
{
"docstring": null,
"function_declaration": "def update(frame, line, data):",
"function_name": "update",
"parameter_list": "(frame, line, data)"
},
{
"docstring": null,
"function_declaration": "def dynamic_plot():",
"function_name": "dynamic_plot",
"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 matplotlib.pyplot as plt\nimport numpy as np\n\n# Create a figure and an axis\nfig, ax = plt.subplots()\n\n# Initial plot: two empty lists\nxdata, ydata = [], []\n\nln, = plt.plot([], [... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081041",
"row_id": 81041,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164209']"
} | 0.512112 | Filter_81041 | I | [
"update",
"dynamic_plot"
] | 2 | [
[
"dynamic_plot",
"update"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | a5aea68fc2cca82c5be90fed770e32b1dca38fc9 | 402b40281199731dcbc7941c5779e14e2a55206b | |||
v1.0 | instruct | Filter | Filter_81085_I | I am working on a project that requires me to use a genetic algorithm to solve a specific problem. Can you provide some guidance on how to get started with implementing a genetic algorithm in Python? | import random
def create_individual(length, min_value, max_value):
"""Create a member of the population."""
return [random.randint(min_value, max_value) for _ in range(length)]
def create_population(size, length, min_value, max_value):
"""Create a population."""
return [create_individual(length, min_v... | from solution import create_individual, create_population, fitness, select, crossover, mutate, genetic_algorithm
def test_create_individual():
individual = create_individual(5, 0, 10)
assert len(individual) == 5
assert all(0 <= gene <= 10 for gene in individual)
def test_create_population():
populatio... | [
{
"docstring": "Create a member of the population.",
"function_declaration": "def create_individual(length, min_value, max_value):",
"function_name": "create_individual",
"parameter_list": "(length, min_value, max_value)"
},
{
"docstring": "Create a population.",
"function_declaration": ... | [
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 individual(length, min_value, max_value):\n \"\"\"\n Create a member of the population.\n \"\"\"\n return [random.randint(min_value, max_value) for _ in range(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081085",
"row_id": 81085,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164279']"
} | 0.297179 | Filter_81085 | I | [
"create_individual",
"create_population",
"fitness",
"select",
"crossover",
"mutate",
"genetic_algorithm"
] | 7 | [
[
"create_population",
"create_individual"
],
[
"genetic_algorithm",
"create_population"
],
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 1675beae1637ee859c93385e958126e5eb0c9090 | 7accc7f19d809f84ef214698b59a8d8ae8865ffe | |||
v1.0 | instruct | Filter | Filter_81090_I | Write a Python function to determine if a given number is a prime number. The function should take an integer as input and return True if the number is prime, and False otherwise. Additionally, write a Python script that uses this function to find all prime numbers between 1 and 100. Print each prime number on a new li... | def is_prime(n):
"""
Determines if the given integer n is a prime number.
:param n: Integer to check for primality.
:return: True if n is prime, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = ... | from solution import is_prime
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(6) == False
assert is_prime(7) == True
assert is_prime(11) == True
assert is_prime(13) == True
assert is_pr... | [
{
"docstring": "Determines if the given integer n is a prime number.\n\n:param n: Integer to check for primality.\n:return: True if n is prime, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds and pri... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Determines if a given number n is a prime number.\n \n :param n: Integer to check for primality.\n :return: True if n is prime, False otherwise.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081090",
"row_id": 81090,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164287']"
} | 0.799452 | Filter_81090 | I | [
"is_prime",
"find_primes_between_1_and_100"
] | 2 | [
[
"find_primes_between_1_and_100",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b467ab0dc0663767f4d5494f476a9bc741cb70e4 | b6e6fca1683d61010616813bd5a50a60bda816aa | |||
v1.0 | instruct | Filter | Filter_81102_I | Write a Python function to find the next prime number after a given number. Use this function to find the next prime number after 100. | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | from solution import is_prime, next_prime
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(11)
assert not is_prime(15)
def test_next_prime():
assert next_prime(100) == ... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find the next prime number after a given number n.",
"function_declaration": "def next_prime(n):",
"function_name": "next_... | [
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 Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081102",
"row_id": 81102,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164302']"
} | 0.62917 | Filter_81102 | I | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15afe557792cba948674aab3c9c5b152ea932ba3 | 323f3eef684479d61db33b46899c1b5d00682713 | |||
v1.0 | instruct | Filter | Filter_81108_I | How can I write a Python program to find the sum of all prime numbers below a given number? | def is_prime(n):
"""
Helper function to check if a number is a prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import sum_of_primes_below
def test_sum_of_primes_below_ten():
assert sum_of_primes_below(10) == 17 # 2 + 3 + 5 + 7 = 17
def test_sum_of_primes_below_twenty():
assert sum_of_primes_below(20) == 77 # 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 = 77
def test_sum_of_primes_below_two():
assert sum_of_p... | [
{
"docstring": "Helper function to check if a number is a prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers below the given number n.",
"function_declaration": "def sum_of_prim... | [
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 Helper function to check if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081108",
"row_id": 81108,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164313']"
} | 0.767282 | Filter_81108 | I | [
"is_prime",
"sum_of_primes_below"
] | 2 | [
[
"sum_of_primes_below",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 983aa7cebc329b6490c4f96851fc087c9b6397a5 | 758915284b668eda4118c40186ee583bedd3c734 | |||
v1.0 | instruct | Filter | Filter_81115_I | Can you provide an example of how to use the `time` function in Python to measure the execution time of a function? Specifically, I want to measure the time it takes to compute the factorial of a number using a recursive function. | import time
def factorial(n):
"""
Recursive function to compute the factorial of a number.
"""
if n == 0:
return 1
else:
return n * factorial(n-1)
def measure_execution_time(n):
"""
Measures the execution time of the factorial function for a given n.
"""
start_time ... | from solution import factorial, measure_execution_time
def test_factorial_base_case():
assert factorial(0) == 1
def test_factorial_small_number():
assert factorial(5) == 120
assert factorial(3) == 6
def test_factorial_large_number():
assert factorial(10) == 3628800
assert factorial(12) == 4790016... | [
{
"docstring": "Recursive function to compute the factorial of a number.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Measures the execution time of the factorial function for a given n.",
"function_declaration": ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\n\ndef factorial(n):\n \"\"\"\n Returns the factorial of n using recursion.\n \"\"\"\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\ndef... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081115",
"row_id": 81115,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164328']"
} | 0.509563 | Filter_81115 | I | [
"factorial",
"measure_execution_time"
] | 2 | [
[
"measure_execution_time",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d4d03b11cc7e54b41145eff11c33383545fe18e | 9654c658f579992055ec24fe13e77a6b736a43cf | |||
v1.0 | instruct | Filter | Filter_81136_I | Is there a way to define a function in Python that can take a variable number of arguments and then pass them as a list to another function? For example, I want to define a function `my_function` that can take any number of arguments and then pass them as a list to another function `another_function`. How can I do this... | def another_function(arg_list):
"""
Takes a list of arguments and returns a string representing the arguments.
"""
return f"Received arguments: {', '.join(map(str, arg_list))}"
def my_function(*args):
"""
Takes a variable number of arguments and passes them as a list to another_function.
""... | from solution import another_function, my_function
def test_another_function():
assert another_function([1, 2, 3]) == "Received arguments: 1, 2, 3"
assert another_function(['a', 'b', 'c']) == "Received arguments: a, b, c"
assert another_function([]) == "Received arguments: "
def test_my_function_no_args()... | [
{
"docstring": "Takes a list of arguments and returns a string representing the arguments.",
"function_declaration": "def another_function(arg_list):",
"function_name": "another_function",
"parameter_list": "(arg_list)"
},
{
"docstring": "Takes a variable number of arguments and passes them ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def my_function(*args):\n \"\"\"\n This function takes any number of arguments and passes them as a list to another_function.\n \"\"\"\n return another_function(list(args))\n\ndef ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081136",
"row_id": 81136,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164364']"
} | 0.446878 | Filter_81136 | I | [
"another_function",
"my_function"
] | 2 | [
[
"my_function",
"another_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54b037771ac6a903eee2085352b8479697f95702 | 84f8ec55e03e950ddfa322d9c4ef5e1ad70c6d74 | |||
v1.0 | instruct | Filter | Filter_81141_I | Suppose you are given a set of 100 points in a plane, and you need to find the pair of points that are closest to each other. To do this, you can use the Divide and Conquer algorithm. The Divide step involves dividing the set of points into two equal subsets by a vertical line. The Conquer step involves finding the clo... | import math
def distance(p1, p2):
"""
Calculate the Euclidean distance between two points.
"""
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def closest_pair_of_points(points):
if len(points) < 2:
return float('inf'), ()
points.sort(key=lambda point: point[0])
... | from solution import closest_pair, distance
def test_closest_pair():
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_duplicate_points():
points = [(1, 1), (1, 1)]
asse... | [
{
"docstring": "Calculate the Euclidean distance between two points.",
"function_declaration": "def distance(p1, p2):",
"function_name": "distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def closest_pair_of_points(points):",
"function_name": "c... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(p1, p2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n\ndef... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081141",
"row_id": 81141,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164369']"
} | 0.588616 | Filter_81141 | I | [
"distance",
"closest_pair_of_points",
"closest_pair"
] | 3 | [
[
"closest_pair",
"closest_pair_of_points"
],
[
"closest_pair_of_points",
"distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 59f92035a65d1bfa50ebbde092722e1021b83024 | 7a80c0588ce4c402440539decd96f9189330eb69 | |||
v1.0 | instruct | Filter | Filter_81278_I | I am trying to find the roots of the polynomial equation \(x^3 - 2x^2 + 3x - 4 = 0\) using a numerical method in Python. Can you guide me on how to use the `fsolve` function from the `scipy.optimize` module to solve this equation? Also, I need to check the accuracy of the roots. How can I do that? | import numpy as np
from scipy.optimize import fsolve
def polynomial_eq(x):
"""
The polynomial equation x^3 - 2x^2 + 3x - 4.
"""
return x**3 - 2*x**2 + 3*x - 4
def find_roots():
"""
Finds the roots of the polynomial equation using fsolve.
"""
# Initial guess for the roots
initial_gu... | from solution import find_roots, check_root_accuracy
def test_find_roots():
roots = find_roots()
assert len(roots) == 3
# Validating the roots with some tolerance
tolerance = 1e-5
assert all(abs(polynomial_eq(r)) < tolerance for r in roots)
def polynomial_eq(x):
"""
The polynomial equation... | [
{
"docstring": "The polynomial equation x^3 - 2x^2 + 3x - 4.",
"function_declaration": "def polynomial_eq(x):",
"function_name": "polynomial_eq",
"parameter_list": "(x)"
},
{
"docstring": "Finds the roots of the polynomial equation using fsolve.",
"function_declaration": "def find_roots(... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from scipy.optimize import fsolve\n\ndef polynomial(x):\n \"\"\"\n Polynomial function x^3 - 2x^2 + 3x - 4 = 0\n \"\"\"\n return x**3 - 2*x**2 + 3*x - 4\n\ndef find_roots(initial_g... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081278",
"row_id": 81278,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164599']"
} | 0.500995 | Filter_81278 | I | [
"polynomial_eq",
"find_roots",
"check_root_accuracy"
] | 3 | [
[
"check_root_accuracy",
"polynomial_eq"
],
[
"find_roots",
"polynomial_eq"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | b1cd66d054fa5f22b26000f3e07e3e2397562e38 | 80cc3cdc21f1dd87164afa180e891154abbb743e | |||
v1.0 | instruct | Filter | Filter_81296_I | You are given a string s. We want to find the longest substring of s that is a palindrome. A palindrome is a string that reads the same forward and backward. For example, "racecar" is a palindrome. Write a function that returns the longest palindromic substring of s. If there are multiple palindromic substrings of the ... | def longest_palindromic_substring(s):
"""
Returns the longest palindromic substring of s.
"""
if not s:
return ""
start, end = 0, 0
for i in range(len(s)):
len1 = expand_around_center(s, i, i)
len2 = expand_around_center(s, i, i + 1)
max_len = max(len1, ... | from solution import longest_palindromic_substring
def test_longest_palindromic_substring():
assert longest_palindromic_substring("babad") == "bab" or longest_palindromic_substring("babad") == "aba"
assert longest_palindromic_substring("cbbd") == "bb"
assert longest_palindromic_substring("a") == "a"
as... | [
{
"docstring": "Returns the longest palindromic substring of s.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_list": "(s)"
},
{
"docstring": "Helper function to expand around the center and find the length of t... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n Finds the longest palindromic substring in s.\n A palindrome is a string that reads the same forward and backward.\n \n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081296",
"row_id": 81296,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164626']"
} | 0.852247 | Filter_81296 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed21e8ee11f0dd2a843243d138705fbb96eff8bd | 130aa8e52510234979678f964df0981c2b29d1f7 | |||
v1.0 | instruct | Filter | Filter_81318_I | I have a set of points in a 2D plane, and I need to find the shortest path that visits each point exactly once and returns to the starting point. This is known as the Traveling Salesman Problem (TSP). How can I solve this problem using Python? | import itertools
def calculate_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in the 2D plane.
"""
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
def total_path_distance(path, points):
"""
Calculate the total distance of the path ... | from solution import traveling_salesman
def test_traveling_salesman_single_point():
points = [(0, 0)]
result = traveling_salesman(points)
assert result['distance'] == 0
assert result['path'] == (0,)
def test_traveling_salesman_two_points():
points = [(0, 0), (1, 1)]
result = traveling_salesman... | [
{
"docstring": "Calculate the Euclidean distance between two points in the 2D plane.",
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Calculate the total distance of the path vi... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points in the 2D plane.\n \"\"\"\n return ((point1[0] - point2[0... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081318",
"row_id": 81318,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164661']"
} | 0.458737 | Filter_81318 | I | [
"calculate_distance",
"total_path_distance",
"traveling_salesman"
] | 3 | [
[
"total_path_distance",
"calculate_distance"
],
[
"traveling_salesman",
"total_path_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4d53b39e425018e09d15e91ddfd87c2f0f82ee0f | ad188f3c2f0d12e9a568de1337b736a08033319d | |||
v1.0 | instruct | Filter | Filter_81346_I | To verify the Goldbach Conjecture for a given even number `n`, we need to find two prime numbers that add up to `n`. Can you provide a Python function that does this, and explain how it works? | def is_prime(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
... | from solution import goldbach_conjecture, is_prime
def test_is_prime():
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(9)
assert is_prime(11)
def test_goldbach_conjecture_small_even_numbe... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns two prime numbers that add up to the given even number 'n'.\nThe function assumes n is an ... | [
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 for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n return True\n\ndef goldbach_conje... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081346",
"row_id": 81346,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164706']"
} | 0.583867 | Filter_81346 | I | [
"is_prime",
"goldbach_conjecture"
] | 2 | [
[
"goldbach_conjecture",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0644f4e19bc99c7f933d8b5077ca44692d27566f | 739883c6b4c76bd45d4ffa31b02c82bf1d0b3c60 | |||
v1.0 | instruct | Filter | Filter_81358_I | I want to create a plot of the function \(f(x) = x^3 - 3x + 1\) and its first derivative \(f'(x) = 3x^2 - 3\) using Python. How can I do this? | import matplotlib.pyplot as plt
import numpy as np
def f(x):
"""
Returns the value of the function f(x) = x^3 - 3x + 1.
"""
return x**3 - 3*x + 1
def f_prime(x):
"""
Returns the value of the first derivative f'(x) = 3x^2 - 3.
"""
return 3*x**2 - 3
def plot_function_and_derivative():
... | from solution import f, f_prime
def test_f_function():
assert f(0) == 1
assert f(1) == -1
assert f(-1) == 3
assert f(2) == 3
def test_f_prime_function():
assert f_prime(0) == -3
assert f_prime(1) == 0
assert f_prime(-1) == 0
assert f_prime(2) == 9 | [
{
"docstring": "Returns the value of the function f(x) = x^3 - 3x + 1.",
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": "Returns the value of the first derivative f'(x) = 3x^2 - 3.",
"function_declaration": "def f_prime(x):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n \"\"\"\n Returns the value of the function f(x) = x^3 - 3x + 1.\n \"\"\"\n return x**3 - 3*x + 1\n\ndef f_prime(x... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081358",
"row_id": 81358,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164732']"
} | 0.420758 | Filter_81358 | I | [
"f",
"f_prime",
"plot_function_and_derivative"
] | 3 | [
[
"plot_function_and_derivative",
"f"
],
[
"plot_function_and_derivative",
"f_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 94736a3f64ed1b9bca01133ec18c5bd0ee335a32 | 4fc128c2e2a46945b1898905447e7651b730c076 | |||
v1.0 | instruct | Filter | Filter_81364_I | I am trying to solve the differential equation \(y''(x) + 4y'(x) + 4y(x) = 0\) with initial conditions \(y(0) = 1\) and \(y'(0) = 0\) using the shooting method in Python. However, I am having trouble implementing it. Can you guide me through the process? | import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import root_scalar
# Define the system of first-order ODEs
def system(t, y):
return [y[1], -4*y[1] - 4*y[0]]
# Define the function to compute the shooting value
def shooting_function(shooting_value):
# Initial conditions for the IVP
... | import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import root_scalar
from solution import system, shooting_function
def test_system():
t = 0
y = [1, 0]
assert np.allclose(system(t, y), [0, -4])
y = [0, 1]
assert np.allclose(system(t, y), [1, -4])
def test_shooting_funct... | [
{
"docstring": null,
"function_declaration": "def system(t, y):",
"function_name": "system",
"parameter_list": "(t, y)"
},
{
"docstring": null,
"function_declaration": "def shooting_function(shooting_value):",
"function_name": "shooting_function",
"parameter_list": "(shooting_val... | [
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\nfrom scipy.integrate import solve_ivp\nfrom scipy.optimize import root_scalar\n\n# Define the system of first-order ODEs\ndef system(t, y):\n return [y[1], -4*y[1] - 4*y... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081364",
"row_id": 81364,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164745']"
} | 0.263129 | Filter_81364 | I | [
"system",
"shooting_function"
] | 2 | [
[
"shooting_function",
"system"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | a36988dbf8979fc655eb40db9713c3eb0a5b8929 | 2c934797aebb797f0c0d238276e04e05f3757da4 | |||
v1.0 | instruct | Filter | Filter_81393_I | I am working on a project that involves using the BFGS optimization method, and I need to implement it in Python. Can you provide me with some Python code examples for using the BFGS method for optimization problems? | from scipy.optimize import minimize
def rosenbrock(x):
"""
The Rosenbrock function.
The minimum value of this function is 0 which is located at (1,1).
"""
return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
def optimize_rosenbrock():
"""
Optimizes the Rosenbrock function using the... | from solution import optimize_rosenbrock
def test_optimization_result():
result = optimize_rosenbrock()
# Check if the optimizer has converged
assert result.success == True
# Check if the solution is close to the true minimum (1,1)
assert all(abs(x - 1) < 1e-3 for x in result.x)
# Check if the ... | [
{
"docstring": "The Rosenbrock function.\nThe minimum value of this function is 0 which is located at (1,1).",
"function_declaration": "def rosenbrock(x):",
"function_name": "rosenbrock",
"parameter_list": "(x)"
},
{
"docstring": "Optimizes the Rosenbrock function using the BFGS method.",
... | [
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.optimize import minimize\n\ndef rosenbrock(x):\n \"\"\"\n The Rosenbrock function.\n \"\"\"\n return sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081393",
"row_id": 81393,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164790']"
} | 0.355432 | Filter_81393 | I | [
"rosenbrock",
"optimize_rosenbrock"
] | 2 | [
[
"optimize_rosenbrock",
"rosenbrock"
]
] | 1 | [] | false | [] | false | pytest | true | [
"scipy"
] | false | e6404c37d6e463e8fec453c4241712e83e5f5b3d | cc893430f8234dd87f04ea9be0bedd6c897d6a8d | |||
v1.0 | instruct | Filter | Filter_81395_I | Write a Python function to find the sum of all the prime numbers in a given list of integers. Use the Sieve of Eratosthenes algorithm to determine if a number is prime. The function should take a list of integers as input and return the sum of all prime numbers in the list. | def sieve_of_eratosthenes(n):
"""
Returns a list of prime numbers up to n (inclusive) using the Sieve of Eratosthenes algorithm.
"""
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False # 0 and 1 are not primes
for start in range(2, int(n**0.5) + 1):
if sieve[start]:
for mul... | from solution import sum_of_primes
def test_empty_list():
assert sum_of_primes([]) == 0
def test_no_primes():
assert sum_of_primes([4, 6, 8, 10, 12]) == 0
def test_all_primes():
assert sum_of_primes([2, 3, 5, 7, 11]) == 28
def test_mixed_numbers():
assert sum_of_primes([4, 6, 7, 8, 10, 11]) == 18
d... | [
{
"docstring": "Returns a list of prime numbers up to n (inclusive) using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sum_of_primes(numbers):\n \"\"\"\n Returns the sum of all prime numbers in the given list of integers.\n \"\"\"\n def sieve_of_eratosthenes(max_num):\n is_prime = [True]... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081395",
"row_id": 81395,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164792']"
} | 0.691553 | Filter_81395 | I | [
"sieve_of_eratosthenes",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7cf0f8cabee5aee80797da8b2a0d2661c6d5dc50 | 0a5b5ae0cd36a0537c67ca7919ccbb6e94187a89 | |||
v1.0 | instruct | Filter | Filter_81400_I | Write a Python function that takes a positive integer \( n \) as input and returns the \( n \)-th prime number. You should use the Sieve of Eratosthenes algorithm to find the prime numbers. The function should be efficient and handle large values of \( n \) reasonably well. Test your function with \( n = 1000 \). | def sieve_of_eratosthenes(limit):
"""
Generates all prime numbers up to `limit` using the Sieve of Eratosthenes algorithm.
"""
is_prime = [True] * (limit + 1)
p = 2
while (p * p <= limit):
if (is_prime[p] == True):
for i in range(p * p, limit + 1, p):
is_prime... | from solution import nth_prime
def test_nth_prime_first_ten():
assert nth_prime(1) == 2
assert nth_prime(2) == 3
assert nth_prime(3) == 5
assert nth_prime(4) == 7
assert nth_prime(5) == 11
assert nth_prime(6) == 13
assert nth_prime(7) == 17
assert nth_prime(8) == 19
assert nth_prime... | [
{
"docstring": "Generates all prime numbers up to `limit` using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Returns the n-th prime number using the... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def nth_prime(n):\n \"\"\"\n Returns the n-th prime number using the Sieve of Eratosthenes algorithm.\n \"\"\"\n if n < 1:\n raise ValueError(\"n must be a positive integer\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081400",
"row_id": 81400,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164799']"
} | 0.64677 | Filter_81400 | I | [
"sieve_of_eratosthenes",
"nth_prime"
] | 2 | [
[
"nth_prime",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad1a77b2a0c5c145ba8fa967d26df286050595ff | fa542211c531b20025b3fb05b73050eff396eba1 | |||
v1.0 | instruct | Filter | Filter_81514_I | Write a Python program to find the first 10 prime numbers. | def is_prime(n):
"""
Determines if a given number n is a prime number.
"""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def find_first_n_primes(n):
"""
Finds the first n prime numbers and returns them a... | from solution import is_prime, find_first_n_primes, first_10_primes
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_prime(4) is False
assert is_prime(5) is True
assert is_prime(10) is False
assert is_prime(11) is True
def test_find_first_n_primes():
ass... | [
{
"docstring": "Determines if a given number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Finds the first n prime numbers and returns them as a list.",
"function_declaration": "def find_first_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(n):\n \"\"\"\n Determines if a given number n 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 %... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081514",
"row_id": 81514,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_164984']"
} | 0.630124 | Filter_81514 | I | [
"is_prime",
"find_first_n_primes",
"first_10_primes"
] | 3 | [
[
"find_first_n_primes",
"is_prime"
],
[
"first_10_primes",
"find_first_n_primes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6b37833028b4262222d93020ff0b1b3a021a8d73 | 015cf22628f73fadb7333896d9ebe8c88e00a1e8 | |||
v1.0 | instruct | Filter | Filter_81544_I | I am working on a project that involves simulating the behavior of a simple pendulum. I need a Python code that can numerically solve the equation of motion for a simple pendulum. Can you provide me with a sample code or guide me on how to write one? | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def pendulum_eq(y, t, g, L):
theta, omega = y
dydt = [omega, - (g / L) * np.sin(theta)]
return dydt
def solve_pendulum(theta0, omega0, L, g, t):
y0 = [theta0, omega0]
sol = odeint(pendulum_eq, y0, t, args=(g, L))... | from solution import solve_pendulum
import numpy as np
def test_pendulum_initial_conditions():
theta0 = np.pi / 4 # initial angle (45 degrees)
omega0 = 0.0 # initial angular velocity
L = 1.0 # length of pendulum (1 meter)
g = 9.81 # acceleration due to gravity (9.81 m/s^2... | [
{
"docstring": null,
"function_declaration": "def pendulum_eq(y, t, g, L):",
"function_name": "pendulum_eq",
"parameter_list": "(y, t, g, L)"
},
{
"docstring": null,
"function_declaration": "def solve_pendulum(theta0, omega0, L, g, t):",
"function_name": "solve_pendulum",
"parame... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef pendulum_rk4(theta0, omega0, length, g, dt, t_max):\n \"\"\"\n Simulates the motion of a simple pendulum using the Runge-Kutta method (RK4).\n \n Paramete... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081544",
"row_id": 81544,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165044']"
} | 0.313627 | Filter_81544 | I | [
"pendulum_eq",
"solve_pendulum"
] | 2 | [
[
"solve_pendulum",
"pendulum_eq"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | f0023b687913d0c711eab1a81076f305e022d91b | 532aeac5ca878d28524c021980d16e39f06cd331 | |||
v1.0 | instruct | Filter | Filter_81551_I | Write a Python function that takes two arguments: a list of integers and an integer `k`. The function should return the `k`th largest element in the list. Assume that the list contains at least `k` elements. Use the quicksort algorithm to solve this problem. | def quicksort(arr):
"""
Helper function that implements the quicksort algorithm.
"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(lef... | from solution import kth_largest_element
def test_kth_largest_single_element():
assert kth_largest_element([5], 1) == 5
def test_kth_largest_sorted_list():
assert kth_largest_element([1, 2, 3, 4, 5], 1) == 5
assert kth_largest_element([1, 2, 3, 4, 5], 2) == 4
assert kth_largest_element([1, 2, 3, 4, 5]... | [
{
"docstring": "Helper function that implements the quicksort algorithm.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": "Returns the k-th largest element in the list after sorting using quicksort.",
"function_dec... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quicksort(arr):\n \"\"\"\n Helper function to perform the quicksort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081551",
"row_id": 81551,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165054']"
} | 0.70297 | Filter_81551 | I | [
"quicksort",
"kth_largest_element"
] | 2 | [
[
"kth_largest_element",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cbfb21bba3c0939d073b79ac81efd2a52b3ea620 | 0d0780a77d68970ae5d202590a52a65cffe29d7e | |||
v1.0 | instruct | Filter | Filter_81601_I | I am working on a project that involves fitting a curve to a set of data points using the Levenberg-Marquardt method. Can you provide me with a Python code example to help me get started? | import numpy as np
from scipy.optimize import curve_fit
def model(x, a, b, c):
"""
Model function to fit, e.g., a quadratic function.
Parameters:
x : float or ndarray
The independent variable.
a: float
Coefficient of the quadratic term.
b: float
Coefficient of the linear... | from solution import model, fit_curve
import numpy as np
def test_model():
x = np.array([0, 1, 2, 3])
# Using specific known coefficients a=1, b=2, c=3 for testing
a, b, c = 1, 2, 3
expected = a * x**2 + b * x + c
result = model(x, a, b, c)
np.testing.assert_almost_equal(result, expected)
def ... | [
{
"docstring": "Model function to fit, e.g., a quadratic function.\nParameters:\nx : float or ndarray\n The independent variable.\na: float\n Coefficient of the quadratic term.\nb: float\n Coefficient of the linear term.\nc: float\n Constant term.\nReturns:\nfloat or ndarray\n The value of the mo... | [
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.optimize import least_squares\n\ndef model(params, x):\n \"\"\"\n The model function that describes the curve. In this example, we use \n a simple quadr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081601",
"row_id": 81601,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165150']"
} | 0.478908 | Filter_81601 | I | [
"model",
"fit_curve"
] | 2 | [
[
"fit_curve",
"model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 135437ce41884c5b54a0a0c7a21152774f90497e | e60b83195ec6198a1c474403dec8a22876101e9b | |||
v1.0 | instruct | Filter | Filter_81616_I | I am working on a project that involves using the k-Nearest Neighbors (k-NN) algorithm for regression. I have a dataset and I need to implement the k-NN regression algorithm from scratch in Python. Can you guide me through the process and provide some code examples? | import numpy as np
def euclidean_distance(a, b):
"""
Computes the Euclidean distance between two points.
"""
return np.sqrt(np.sum((a - b) ** 2))
def knn_regression(X_train, Y_train, X_test, k):
"""
Performs k-Nearest Neighbors regression on the test data.
Parameters:
X_train (num... | import numpy as np
from solution import euclidean_distance, knn_regression
def test_euclidean_distance():
point1 = np.array([1, 2])
point2 = np.array([4, 6])
assert np.isclose(euclidean_distance(point1, point2), 5.0)
def test_knn_regression():
X_train = np.array([[1, 2], [2, 3], [3, 4], [6, 7], [8, 9]... | [
{
"docstring": "Computes the Euclidean distance between two points.",
"function_declaration": "def euclidean_distance(a, b):",
"function_name": "euclidean_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Performs k-Nearest Neighbors regression on the test data.\n\nParameters:\nX_trai... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef euclidean_distance(x1, x2):\n return np.sqrt(np.sum((x1 - x2) ** 2))\n\ndef knn_regression(X_train, y_train, X_test, k):\n \"\"\"\n k-Nearest Neighbors regre... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081616",
"row_id": 81616,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165173']"
} | 0.538201 | Filter_81616 | I | [
"euclidean_distance",
"knn_regression"
] | 2 | [
[
"knn_regression",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 020495920950f87c89c4b81b2d88172dd1e88041 | 869c8da250b97a0c322be2776fe7f6b951bff15a | |||
v1.0 | instruct | Filter | Filter_81618_I | Is there a way to define a function in Python that can take a variable number of arguments, and then pass those arguments to another function as a list or tuple? For example, I want to write a function `my_function` that can take any number of arguments and then pass them to another function `other_function` as a list. | def other_function(args):
"""
A placeholder function that will receive the args from my_function and return them.
"""
return args
def my_function(*args):
"""
Takes variable number of arguments and passes them to other_function as a list.
"""
return other_function(list(args)) | from solution import other_function, my_function
def test_my_function_with_no_arguments():
assert my_function() == []
def test_my_function_with_single_argument():
assert my_function(1) == [1]
def test_my_function_with_multiple_arguments():
assert my_function(1, 2, 3) == [1, 2, 3]
def test_my_function_wi... | [
{
"docstring": "A placeholder function that will receive the args from my_function and return them.",
"function_declaration": "def other_function(args):",
"function_name": "other_function",
"parameter_list": "(args)"
},
{
"docstring": "Takes variable number of arguments and passes them to ot... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def other_function(args):\n \"\"\"\n A sample function that receives a list of arguments and returns it.\n \"\"\"\n return args\n\ndef my_function(*args):\n \"\"\"\n A functi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081618",
"row_id": 81618,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165176']"
} | 0.500807 | Filter_81618 | I | [
"other_function",
"my_function"
] | 2 | [
[
"my_function",
"other_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4cd4253647b34abab1993f7ff3089282ca0bcc4f | e18f39dc76a39d4a3006e2384c05e866591fbf9d | |||
v1.0 | instruct | Filter | Filter_81659_I | I am trying to implement the Perlin noise algorithm in Python, but I am having trouble understanding the code I found online. Specifically, I don't understand the part where the gradient vectors are generated and used to calculate the noise value. Can you explain this to me? | import numpy as np
def fade(t):
# Fade function as defined by Ken Perlin. This smooths the interpolation.
return t * t * t * (t * (t * 6 - 15) + 10)
def lerp(t, a, b):
# Linear interpolation function
return a + t * (b - a)
def gradient(h, x, y):
# Convert low 4 bits of hash into 12 gradient direc... | from solution import perlin
def test_perlin_same_point():
# Testing if the same point returns the same noise value
assert perlin(0.5, 0.5, seed=42) == perlin(0.5, 0.5, seed=42)
def test_perlin_different_points():
noise_value_1 = perlin(0.5, 0.5, seed=42)
noise_value_2 = perlin(0.6, 0.5, seed=42)
a... | [
{
"docstring": null,
"function_declaration": "def fade(t):",
"function_name": "fade",
"parameter_list": "(t)"
},
{
"docstring": null,
"function_declaration": "def lerp(t, a, b):",
"function_name": "lerp",
"parameter_list": "(t, a, b)"
},
{
"docstring": null,
"function... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef fade(t):\n # Fade function to smoothen the interpolation\n return t * t * t * (t * (t * 6 - 15) + 10)\n\ndef lerp(t, a, b):\n # Linear interpolation function\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081659",
"row_id": 81659,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165234']"
} | 0.32163 | Filter_81659 | I | [
"fade",
"lerp",
"gradient",
"perlin"
] | 4 | [
[
"perlin",
"fade"
],
[
"perlin",
"gradient"
],
[
"perlin",
"lerp"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 3ad7630bf6da81ffc2ae272c10c3ede4224afb8f | 5ec1dc6e98878d0a238d7c369491f64ccb629dab | |||
v1.0 | instruct | Filter | Filter_81685_I | I am working on a project where I need to implement a backtracking algorithm to solve a problem. Can you provide an example of a backtracking problem and explain how to solve it using Python? Specifically, I am interested in the N-Queens problem. | def is_safe(board, row, col, N):
"""
Check if it's safe to place a queen at board[row][col]
"""
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j i... | from solution import solve_nqueens
def test_solve_nqueens_4():
result = solve_nqueens(4)
assert result == [
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 1, 0, 0]
] or result == [
[0, 1, 0, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0]
]
d... | [
{
"docstring": "Check if it's safe to place a queen at board[row][col]",
"function_declaration": "def is_safe(board, row, col, N):",
"function_name": "is_safe",
"parameter_list": "(board, row, col, N)"
},
{
"docstring": "Utilizes backtracking to solve the N-Queens problem",
"function_dec... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def solve_n_queens(n):\n \"\"\"\n Solves the N-Queens problem and returns all distinct solutions.\n Each solution contains a list of strings where 'Q' represents a queen and '.' repre... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081685",
"row_id": 81685,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165278']"
} | 0.371679 | Filter_81685 | I | [
"is_safe",
"solve_nqueens_util",
"solve_nqueens"
] | 3 | [
[
"solve_nqueens",
"solve_nqueens_util"
],
[
"solve_nqueens_util",
"is_safe"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 684957b7d9924816d73f2422d173b33d8a9d8dbc | 0b2b5f3d8665bdbee596dbe91bb12e9b78f82250 | |||
v1.0 | instruct | Filter | Filter_81707_I | I want to create a Python function that asks the user for a number and then returns the factorial of that number. How can I do this? | def factorial(n):
"""
Calculate the factorial of a given positive integer n.
"""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
def get_facto... | from solution import factorial
def test_factorial_positive_numbers():
assert factorial(1) == 1
assert factorial(2) == 2
assert factorial(5) == 120
def test_factorial_zero():
assert factorial(0) == 1
def test_factorial_negative_number():
try:
factorial(-1)
except ValueError as e:
... | [
{
"docstring": "Calculate the factorial of a given positive integer n.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": "Asks the user for a number and returns the factorial of that number.",
"function_declaration": "d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n Calculate the factorial of a given positive integer n.\n \"\"\"\n if n < 0:\n raise ValueError(\"Factorial is not defined for negative numbers\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081707",
"row_id": 81707,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165322']"
} | 0.703907 | Filter_81707 | I | [
"factorial",
"get_factorial_from_user_input"
] | 2 | [
[
"get_factorial_from_user_input",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5873396d3570ff2491a5087075362897257f968a | d7332b023635ca371b06c7d5221ad8717cf259ae | |||
v1.0 | instruct | Filter | Filter_81731_I | Write a Python function that takes a list of integers as input and returns the sum of all the integers in the list. Use the provided `read_list` function to read the list of integers from the input. The `read_list` function reads a line of space-separated integers and returns them as a list. The input will be provided ... | def read_list():
"""
Read input from console and return a list of integers.
"""
import sys
input = sys.stdin.read
data = input().split()
n = int(data[0])
return list(map(int, data[1:1 + n]))
def sum_list():
"""
Reads a list of integers using read_list and returns their sum.
... | from io import StringIO
import sys
from solution import sum_list
def test_sum_list_basic():
"""
Test the sum_list function with a basic example.
"""
input_data = "5\n1 2 3 4 5\n"
expected_output = 15
sys.stdin = StringIO(input_data)
assert sum_list() == expected_output
def test_sum_list_em... | [
{
"docstring": "Read input from console and return a list of integers.",
"function_declaration": "def read_list():",
"function_name": "read_list",
"parameter_list": "()"
},
{
"docstring": "Reads a list of integers using read_list and returns their sum.",
"function_declaration": "def sum_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def read_list():\n \"\"\"\n Reads a space-separated line of integers from the standard input and returns them as a list.\n This function simulates reading from input.\n \n Retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081731",
"row_id": 81731,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165357']"
} | 0.730049 | Filter_81731 | I | [
"read_list",
"sum_list"
] | 2 | [
[
"sum_list",
"read_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 47b8f56908e5450cd84ba06bc6d0a5c0b53ad99b | 5b978acc73321a35b9a15a0ded7d08801a30af60 | |||
v1.0 | instruct | Filter | Filter_81735_I | I am working on a project to segment retinal blood vessels using Gabor filters. I understand the basic concept of Gabor filters, but I am having trouble implementing them in Python. Can you provide a step-by-step guide or some code examples to help me get started? | import numpy as np
import cv2
def create_gabor_filter(ksize, sigma, theta, lambd, gamma, psi):
"""
Generates a Gabor filter.
Args:
- ksize: Size of the filter (ksize x ksize)
- sigma: Standard deviation of the Gaussian envelope.
- theta: Orientation of the normal to the parallel stripes (in rad... | import pytest
import numpy as np
from solution import create_gabor_filter, apply_gabor_filter, apply_gabor_filters
def test_create_gabor_filter():
gabor_filter = create_gabor_filter(21, 5, 0, 10, 0.5, 0)
assert gabor_filter is not None
assert gabor_filter.shape == (21, 21)
def test_apply_gabor_filter():
... | [
{
"docstring": "Generates a Gabor filter.\nArgs:\n- ksize: Size of the filter (ksize x ksize)\n- sigma: Standard deviation of the Gaussian envelope.\n- theta: Orientation of the normal to the parallel stripes (in radians).\n- lambd: Wavelength of the sinusoidal factor.\n- gamma: Spatial aspect ratio.\n- psi: Ph... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef gabor_filter_processing(image_path):\n \"\"\"\n Process an image using Gabor filters to segment retinal blood ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081735",
"row_id": 81735,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165365']"
} | 0.381521 | Filter_81735 | I | [
"create_gabor_filter",
"apply_gabor_filter",
"apply_gabor_filters"
] | 3 | [
[
"apply_gabor_filters",
"apply_gabor_filter"
],
[
"apply_gabor_filters",
"create_gabor_filter"
]
] | 2 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 3e9a0ef93b18d94d277162a31ee6b34af0b1dae1 | f078048e6e70fd6dff821c31a7cf1385d5b81c14 | |||
v1.0 | instruct | Filter | Filter_81751_I | Define a function `f` that takes a single argument `x` and returns the value of `x` squared. Then, use the `map` function to apply `f` to the list `[1, 2, 3, 4, 5]` and print the resulting list. Finally, use the `reduce` function from the `functools` module to find the sum of the resulting list and print the sum. | from functools import reduce
def f(x):
"""
Returns the square of the given number x.
"""
return x * x
def compute_squares_and_sum(numbers):
"""
Applies the function f to the list of numbers and returns the sum of the results.
:param numbers: List of integers
:return: Sum of square... | from solution import f, compute_squares_and_sum
def test_f():
assert f(0) == 0
assert f(1) == 1
assert f(2) == 4
assert f(3) == 9
assert f(4) == 16
assert f(5) == 25
def test_compute_squares_and_sum():
assert compute_squares_and_sum([1, 2, 3, 4, 5]) == 55
assert compute_squares_and_sum... | [
{
"docstring": "Returns the square of the given number x.",
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": "Applies the function f to the list of numbers and returns the sum of the results.\n\n:param numbers: List of integers\n:return: Su... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import reduce\n\ndef f(x):\n \"\"\"\n Returns the value of x squared.\n \"\"\"\n return x * x\n\nsquared_list = list(map(f, [1, 2, 3, 4, 5]))\nprint(squared_list) # ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081751",
"row_id": 81751,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165388']"
} | 0.723041 | Filter_81751 | I | [
"f",
"compute_squares_and_sum"
] | 2 | [
[
"compute_squares_and_sum",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c58dd8bbc4afbfb1987fce53ddc598b4d85f1a4a | abd6dddb93cd437333bdd67c78fc211a5cff7401 | |||
v1.0 | instruct | Filter | Filter_81803_I | Define a function in Python that takes two arguments, `num` and `den`, representing the numerator and denominator of a fraction, respectively. The function should return the simplified form of the fraction as a tuple `(numerator, denominator)`. To simplify the fraction, find the greatest common divisor (GCD) of `num` a... | def gcd(a, b):
"""
Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm.
"""
while b != 0:
a, b = b, a % b
return a
def simplify_fraction(num, den):
"""
Returns the simplified form of the fraction (num/den) as a tuple (numerator, denominator).
The f... | from solution import gcd, simplify_fraction
def test_gcd():
assert gcd(15, 25) == 5
assert gcd(100, 10) == 10
assert gcd(81, 9) == 9
assert gcd(0, 10) == 10
assert gcd(17, 19) == 1
def test_simplify_fraction():
assert simplify_fraction(15, 25) == (3, 5)
assert simplify_fraction(100, 10) ==... | [
{
"docstring": "Returns the greatest common divisor (GCD) of a and b using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the simplified form of the fraction (num/den) as a tuple (numerator, d... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Compute the greatest common divisor using the Euclidean algorithm.\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\ndef simplify_fraction(num... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081803",
"row_id": 81803,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165469']"
} | 0.718005 | Filter_81803 | I | [
"gcd",
"simplify_fraction"
] | 2 | [
[
"simplify_fraction",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9006ba1464af92f7f71f276d0f38e88f65f0db8 | 95cff459e2fead728ed491ead81f7439d4dbfbd2 | |||
v1.0 | instruct | Filter | Filter_81818_I | Write a Python program that asks the user to enter a number and then prints out all the prime numbers less than that number. | def is_prime(n):
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
p = 3
while p * p <= n:
if n % p == 0:
return False
p += 2
return True
def primes_... | from solution import is_prime, primes_less_than
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(1) == False
assert is_prime(-5) == False
assert is_prime(17) == True
assert is_prime(18) == F... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers less than the given number.",
"function_declaration": "def primes_les... | [
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 Returns True if n is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00081818",
"row_id": 81818,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165488']"
} | 0.750033 | Filter_81818 | I | [
"is_prime",
"primes_less_than"
] | 2 | [
[
"primes_less_than",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 59c52cd3c65555973591bd381c3bb15597787df8 | b39266ae23ceb6507ae8aa020e5fc1e4b3eef59d | |||
v1.0 | instruct | Filter | Filter_81865_I | I am working on a project that involves using the Sine Cosine Algorithm (SCA) to optimize a function in Python. Can you provide me with a basic example of how to implement the SCA in Python? | import numpy as np
def initialize_population(pop_size, dim, bounds):
"""
Initialize the population within the given bounds.
Parameters:
- pop_size: int, number of individuals in the population
- dim: int, dimension of the problem
- bounds: tuple, bounds for each dimension (lower, upper)
... | from solution import initialize_population, fitness_function, update_position, sine_cosine_algorithm
import numpy as np
def test_initialize_population():
pop_size = 10
dim = 5
bounds = (-10, 10)
population = initialize_population(pop_size, dim, bounds)
assert population.shape == (10, 5)
as... | [
{
"docstring": "Initialize the population within the given bounds.\n\nParameters:\n- pop_size: int, number of individuals in the population\n- dim: int, dimension of the problem\n- bounds: tuple, bounds for each dimension (lower, upper)\n\nReturns:\n- population: 2D numpy array with shape (pop_size, dim)",
... | [
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 SCA(objective_function, dim, lb, ub, N=30, max_iter=100):\n \"\"\"\n Sine Cosine Algorithm (SCA) for optimization.\n\n Parameters:\n objective_function: F... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081865",
"row_id": 81865,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165571']"
} | 0.494841 | Filter_81865 | I | [
"initialize_population",
"fitness_function",
"update_position",
"sine_cosine_algorithm"
] | 4 | [
[
"sine_cosine_algorithm",
"fitness_function"
],
[
"sine_cosine_algorithm",
"initialize_population"
],
[
"sine_cosine_algorithm",
"update_position"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 3c8c77596811a2e28c22055818d101f6bcec5244 | f7bd9b1e997a57bc293ad2db9f31206abc450d7d | |||
v1.0 | instruct | Filter | Filter_81867_I | In the context of a programming problem, what is the definition of a "boring" number, and how can we identify the smallest "boring" number that is greater than or equal to a given positive integer \( n \)? Assume the programming language is Python. | def is_boring_number(number):
"""
Checks if a number is a "boring" number.
A "boring" number is defined as a number where all the digits are the same.
"""
digits = str(number)
return all(d == digits[0] for d in digits)
def smallest_boring_number(n):
"""
Finds the smallest "boring" numbe... | from solution import is_boring_number, smallest_boring_number
# Test for is_boring_number
def test_is_boring_number_true():
assert is_boring_number(111) == True
assert is_boring_number(2222) == True
assert is_boring_number(999999) == True
def test_is_boring_number_false():
assert is_boring_number(123)... | [
{
"docstring": "Checks if a number is a \"boring\" number.\nA \"boring\" number is defined as a number where all the digits are the same.",
"function_declaration": "def is_boring_number(number):",
"function_name": "is_boring_number",
"parameter_list": "(number)"
},
{
"docstring": "Finds the ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_boring(number):\n \"\"\"\n Check if the number is a boring number (all digits the same).\n \"\"\"\n num_str = str(number)\n return all(char == num_str[0] for char in num_... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00081867",
"row_id": 81867,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165574']"
} | 0.497994 | Filter_81867 | I | [
"is_boring_number",
"smallest_boring_number"
] | 2 | [
[
"smallest_boring_number",
"is_boring_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27f1a9194ac9be8085c66efa91ce2b1b65f79a2f | bc0f5ba1b608683d72c5ae9d09ae3e81ae216781 | |||
v1.0 | instruct | Filter | Filter_81874_I | I'm working on a project where I need to calculate the total surface area of a 3D model represented by a list of triangles. Each triangle is defined by its three vertices in 3D space. How can I write a Python function to calculate the total surface area of this model? | import math
def calculate_triangle_area(vertex1, vertex2, vertex3):
"""
Calculates the area of a single triangle given its three vertices.
Args:
vertex1, vertex2, vertex3: Tuples representing the (x, y, z) coordinates of the vertices.
Returns:
The area of the triangle.
"""
# Vectors f... | from solution import total_surface_area, calculate_triangle_area
def test_calculate_triangle_area():
assert math.isclose(calculate_triangle_area((0, 0, 0), (1, 0, 0), (0, 1, 0)), 0.5, rel_tol=1e-9)
assert math.isclose(calculate_triangle_area((0, 0, 0), (0, 3, 0), (0, 0, 4)), 6.0, rel_tol=1e-9)
def test_total_... | [
{
"docstring": "Calculates the area of a single triangle given its three vertices.\n\nArgs:\nvertex1, vertex2, vertex3: Tuples representing the (x, y, z) coordinates of the vertices.\n\nReturns:\nThe area of the triangle.",
"function_declaration": "def calculate_triangle_area(vertex1, vertex2, vertex3):",
... | [
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 vector_length(v):\n return math.sqrt(sum([coord ** 2 for coord in v]))\n\ndef vector_subtract(v1, v2):\n return [v1[i] - v2[i] for i in range(len(v1))]\n\ndef cross_pr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081874",
"row_id": 81874,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165591']"
} | 0.591045 | Filter_81874 | I | [
"calculate_triangle_area",
"total_surface_area"
] | 2 | [
[
"total_surface_area",
"calculate_triangle_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4d5be65aafe946ee3741a72d4d6830ec20b64aea | a699016dc26ed2c7905f305b47d0b8aeeabdf4cb | |||
v1.0 | instruct | Filter | Filter_81876_I | I need to find a Python function that can determine the number of days in a given month of a specific year, accounting for leap years. For example, if the user inputs February of the year 2000, the function should return 29 days, since 2000 is a leap year. Similarly, if the user inputs February of the year 2001, the fu... | def days_in_month(year, month):
"""
Returns the number of days in the given month of the given year.
"""
# List of days in each month for a non-leap year
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Check for leap year and if it's February, return 29 days
if month == ... | from solution import days_in_month
from solution import is_leap_year
def test_days_in_common_year():
assert days_in_month(2001, 1) == 31
assert days_in_month(2001, 2) == 28
assert days_in_month(2001, 3) == 31
assert days_in_month(2001, 4) == 30
assert days_in_month(2001, 5) == 31
assert days_in... | [
{
"docstring": "Returns the number of days in the given month of the given year.",
"function_declaration": "def days_in_month(year, month):",
"function_name": "days_in_month",
"parameter_list": "(year, month)"
},
{
"docstring": "Determines if a year is a leap year.",
"function_declaratio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def days_in_month(year, month):\n \"\"\"\n Returns the number of days in a given month of a specific year, accounting for leap years.\n \n :param year: int, the year (e.g. 2000)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081876",
"row_id": 81876,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165594']"
} | 0.667563 | Filter_81876 | I | [
"days_in_month",
"is_leap_year"
] | 2 | [
[
"days_in_month",
"is_leap_year"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ffc3bba3885c5ab7df437e005c665e018123ea5 | 7843d803d90661db8a24e14027c85e8ed588139d | |||
v1.0 | instruct | Filter | Filter_81891_I | Write a Python function to find the largest prime number in a given list of integers. The function should take a list as an argument and return the largest prime number in the list. If the list does not contain any prime numbers, the function should return None. | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def largest_prime... | from solution import largest_prime
def test_largest_prime_with_primes():
assert largest_prime([10, 3, 5, 7, 11, 13]) == 13
def test_largest_prime_no_primes():
assert largest_prime([4, 6, 8, 10]) == None
def test_largest_prime_with_empty_list():
assert largest_prime([]) == None
def test_largest_prime_wit... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the largest prime number in the given list.\nIf no prime number is found, returns None.",
"function... | [
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 Helper function to check whether a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081891",
"row_id": 81891,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165611']"
} | 0.750031 | Filter_81891 | I | [
"is_prime",
"largest_prime"
] | 2 | [
[
"largest_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6d395ea9cf28f46c658e80bc7406e2fede07725 | 33db7a3ca2063760ddb2c79054c363b03559337f | |||
v1.0 | instruct | Filter | Filter_81913_I | I am working on a project that involves using the BFGS algorithm for optimization. I am using Python and the `scipy.optimize` library. The function I am trying to minimize is a quadratic function, and I need to provide the gradient of the function to the BFGS algorithm. How do I write a function that computes the gradi... | from scipy.optimize import minimize
# Define the quadratic function to minimize
def quadratic_function(x):
"""
Quadratic function: f(x) = (x_0)^2 + (x_1)^2.
"""
return x[0]**2 + x[1]**2
# Define the gradient of the quadratic function
def gradient_quadratic_function(x):
"""
Gradient of the quad... | from solution import gradient_quadratic_function, optimize_quadratic_function
def test_gradient_quadratic_function():
assert gradient_quadratic_function([1, 1]) == [2, 2]
assert gradient_quadratic_function([2, 3]) == [4, 6]
assert gradient_quadratic_function([-1, -1]) == [-2, -2]
def test_optimize_quadrat... | [
{
"docstring": "Quadratic function: f(x) = (x_0)^2 + (x_1)^2.",
"function_declaration": "def quadratic_function(x):",
"function_name": "quadratic_function",
"parameter_list": "(x)"
},
{
"docstring": "Gradient of the quadratic function: ∇f(x) = [2*x_0, 2*x_1].",
"function_declaration": "d... | [
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.optimize import minimize\n\n# Define the quadratic function: f(x) = x^T * A * x + b^T * x + c\ndef quadratic_function(x, A, b, c):\n return 0.5 * np.dot(x.T, ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081913",
"row_id": 81913,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165638']"
} | 0.436929 | Filter_81913 | I | [
"quadratic_function",
"gradient_quadratic_function",
"optimize_quadratic_function"
] | 3 | [
[
"optimize_quadratic_function",
"quadratic_function"
]
] | 1 | [] | false | [] | false | pytest | true | [
"scipy"
] | false | 3b1a8e9031775b019b395bf8d2ebbd3e5b8ef0e1 | 53aae6331a2d2066272ef1d1e84dfb0766a1bac2 | |||
v1.0 | instruct | Filter | Filter_81922_I | I'm working on a project to find the largest palindrome made from the product of two 3-digit numbers. Can you provide a Python code snippet to help me with this? | def is_palindrome(n):
"""
Check if a number is a palindrome.
"""
return str(n) == str(n)[::-1]
def largest_palindrome_product():
"""
Find the largest palindrome made from the product of two 3-digit numbers.
"""
max_palindrome = 0
for i in range(100, 1000):
for j in range(100... | from solution import is_palindrome, largest_palindrome_product
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(12321) == True
assert is_palindrome(123) == False
assert is_palindrome(1221) == True
assert is_palindrome(1234321) == True
def test_largest_palindrome_pro... | [
{
"docstring": "Check if a number is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Find the largest palindrome made from the product of two 3-digit numbers.",
"function_declaration": "def larg... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(number):\n \"\"\"\n Check if a given number is a palindrome.\n \"\"\"\n return str(number) == str(number)[::-1]\n\ndef largest_palindrome_product():\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081922",
"row_id": 81922,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165653']"
} | 0.652004 | Filter_81922 | I | [
"is_palindrome",
"largest_palindrome_product"
] | 2 | [
[
"largest_palindrome_product",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b32595506b9678641a5a26bfc39cfca74da1c6b5 | a31cd4dabd2cc4e8214e66523af1606269e0d227 | |||
v1.0 | instruct | Filter | Filter_81924_I | Write a Python function to find the sum of all the prime numbers in a given list of integers. Use the Sieve of Eratosthenes algorithm to identify the prime numbers. | def sieve_of_eratosthenes(n):
"""
Returns a list of prime numbers up to n using the Sieve of Eratosthenes algorithm.
"""
prime = [True] * (n + 1)
p = 2
while (p * p <= n):
if prime[p] == True:
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
... | from solution import sieve_of_eratosthenes, sum_of_primes_in_list
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(1) == []
assert sieve_of_eratosthenes(2) == [2]
assert s... | [
{
"docstring": "Returns a list of prime numbers up to n using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of all prime numbers in the given... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sieve_of_eratosthenes(n):\n \"\"\"\n Returns a list of prime numbers up to n.\n \"\"\"\n is_prime = [True] * (n + 1)\n p = 2\n while p * p <= n:\n if is_prime[p]:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00081924",
"row_id": 81924,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165655']"
} | 0.609816 | Filter_81924 | I | [
"sieve_of_eratosthenes",
"sum_of_primes_in_list"
] | 2 | [
[
"sum_of_primes_in_list",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 060746261354e2bc73754f980dbc40df11dec6ac | dc320f870003f8652998756f03e636a2172f9de3 | |||
v1.0 | instruct | Filter | Filter_82020_I | I am working on a project where I need to find the optimal parameters for a machine learning model using a genetic algorithm. Can you provide some guidance on how to implement this in Python? | import random
# Define a simple mock fitness function
def fitness_function(params):
"""
Mock fitness function that we aim to optimize.
This function is used to evaluate the parameters.
For simplicity, let's use a quadratic function.
"""
return -sum((x - 5) ** 2 for x in params) # Optimal solut... | from solution import fitness_function, generate_population, select, crossover, mutate, genetic_algorithm
def test_fitness_function():
params = [5, 5, 5]
assert fitness_function(params) == 0
def test_generate_population():
population = generate_population(10, 3)
assert len(population) == 10
assert ... | [
{
"docstring": "Mock fitness function that we aim to optimize.\nThis function is used to evaluate the parameters.\nFor simplicity, let's use a quadratic function.",
"function_declaration": "def fitness_function(params):",
"function_name": "fitness_function",
"parameter_list": "(params)"
},
{
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom deap import base, creator, tools, algorithms\n\n# Example: Optimizing parameters for a simple linear regression model\n# We'll use mean squared error as the fitness measure... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082020",
"row_id": 82020,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165848']"
} | 0.363437 | Filter_82020 | I | [
"fitness_function",
"generate_population",
"select",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness_function"
],
[
"genetic_algorithm",
"generate_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select"
],
[
"select",
"fitness_function"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | f5ff3dd425107cb20c3c5266f27e586046e85840 | 67ce9ac01a1ab4d1bdcde75a6023841ae60008c2 | |||
v1.0 | instruct | Filter | Filter_82027_I | Is it possible to implement a genetic algorithm using only Python's built-in functions and classes, without any third-party libraries or frameworks? If so, could you provide a simple example or outline the steps to do so? | import random
def initialize_population(size, gene_length):
return [[random.randint(0, 1) for _ in range(gene_length)] for _ in range(size)]
def fitness(individual):
# Example fitness function: count the number of 1s
return sum(individual)
def select_parents(population, fitness_fn):
population_fitnes... | from solution import initialize_population, fitness, select_parents, crossover, mutate, genetic_algorithm
def test_initialize_population():
population = initialize_population(10, 5)
assert len(population) == 10
assert all(len(individual) == 5 for individual in population)
def test_fitness():
assert fi... | [
{
"docstring": null,
"function_declaration": "def initialize_population(size, gene_length):",
"function_name": "initialize_population",
"parameter_list": "(size, gene_length)"
},
{
"docstring": null,
"function_declaration": "def fitness(individual):",
"function_name": "fitness",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef initialize_population(size, gene_length):\n return [[random.randint(0, 1) for _ in range(gene_length)] for _ in range(size)]\n\ndef fitness(individual):\n # Example ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082027",
"row_id": 82027,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165862']"
} | 0.286608 | Filter_82027 | I | [
"initialize_population",
"fitness",
"select_parents",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"select_parents"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 14d871f378c82ac68d223c24cc106f3915ff61b4 | 3fb3a326d984f4934aca5fa536056cc0648eea57 | |||
v1.0 | instruct | Filter | Filter_82036_I | Write a Python program that asks the user for a number and then prints out all the prime numbers up to that number. | def is_prime(n):
"""
Checks if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return T... | from solution import is_prime, primes_up_to
def test_is_prime():
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(11) == True
assert is_prime(15) == False
def test_primes_up_to():
as... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers up to n (inclusive).",
"function_declaration": "def primes_up_to(n):",
"function_name... | [
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 \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082036",
"row_id": 82036,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165878']"
} | 0.683297 | Filter_82036 | I | [
"is_prime",
"primes_up_to",
"main"
] | 3 | [
[
"primes_up_to",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eefe09c11ccfadb7058ba8d907e4b007ace660b1 | d940ecb9f261c439707343cc4f9964d087adcbe6 | |||
v1.0 | instruct | Filter | Filter_82038_I | I want to create a Python function that returns a list of the first n prime numbers. How can I do this? | def is_prime(num):
"""
Helper function to determine if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while (i * i) <= num:
if num % i == 0 or num % (i + 2) == 0:
re... | from solution import first_n_primes
def test_first_prime():
assert first_n_primes(1) == [2]
def test_first_five_primes():
assert first_n_primes(5) == [2, 3, 5, 7, 11]
def test_first_ten_primes():
assert first_n_primes(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_empty_prime_list():
assert fi... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of the first n prime numbers.",
"function_declaration": "def first_n_primes(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 \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082038",
"row_id": 82038,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165880']"
} | 0.679438 | Filter_82038 | I | [
"is_prime",
"first_n_primes"
] | 2 | [
[
"first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f24d949e5ba7aa28962a775152450cdb4ea0fd0f | 0d1fcc7cbeac9e47bc43f1ae1dddbb029ec2b9d4 | |||
v1.0 | instruct | Filter | Filter_82053_I | I am working on a project that involves using the BFGS optimization algorithm to find the minimum of a function. Can you provide me with a basic example of how to implement the BFGS algorithm in Python using the `scipy.optimize` library? | import numpy as np
from scipy.optimize import minimize
def rosenbrock(x):
"""
The Rosenbrock function.
"""
return sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
def minimize_rosenbrock_bfgs(x0):
"""
Minimizes the Rosenbrock function using the BFGS algorithm.
:param x0: In... | from solution import minimize_rosenbrock_bfgs
import numpy as np
def test_minimize_rosenbrock_bfgs_initial_guess():
initial_guess = np.array([1.3, 0.7])
result = minimize_rosenbrock_bfgs(initial_guess)
assert result.success
assert np.allclose(result.x, np.ones_like(initial_guess), atol=1e-3)
def test_... | [
{
"docstring": "The Rosenbrock function.",
"function_declaration": "def rosenbrock(x):",
"function_name": "rosenbrock",
"parameter_list": "(x)"
},
{
"docstring": "Minimizes the Rosenbrock function using the BFGS algorithm.\n\n:param x0: Initial guess for the variables.\n\n:returns: The resul... | [
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.optimize import minimize\n\ndef rosenbrock(x):\n \"\"\"\n The Rosenbrock function.\n \"\"\"\n return sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082053",
"row_id": 82053,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_165904']"
} | 0.395088 | Filter_82053 | I | [
"rosenbrock",
"minimize_rosenbrock_bfgs"
] | 2 | [
[
"minimize_rosenbrock_bfgs",
"rosenbrock"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 48918cc007c1f4bd0b83fa6da612235987954b78 | 810b4fd8342f377c43f36cf1b2c7117d933af1c8 | |||
v1.0 | instruct | Filter | Filter_82125_I | Write a Python function to check if a given number is a prime number. Use this function to find the first 10 prime numbers. Display the prime numbers in a list. | def is_prime(n):
"""
Returns True if n is a prime number, else returns False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import is_prime, find_first_n_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(13) == True
assert is_prime(1) == False
assert is_prime(0) ==... | [
{
"docstring": "Returns True if n is a prime number, else returns False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list containing the first n prime numbers.",
"function_declaration": "def find_first_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(n):\n \"\"\"\n Checks if a number n is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082125",
"row_id": 82125,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166033']"
} | 0.734114 | Filter_82125 | I | [
"is_prime",
"find_first_n_primes"
] | 2 | [
[
"find_first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 485df281b541b2bd4064e83434fdfd1f04adce7b | e169663835170c4b02b22c8fa3445d367d9f198e | |||
v1.0 | instruct | Filter | Filter_82158_I | I am a teacher in a primary school and I want to create a simple Python program that can help my students practice their multiplication tables. The program should generate random multiplication questions and provide immediate feedback. Can you help me with this? | import random
def generate_question():
"""
Generates a random multiplication question and its correct answer.
Returns a tuple containing the question string and the correct answer.
"""
a = random.randint(1, 10)
b = random.randint(1, 10)
question = f"What is {a} x {b}?"
answer = a * b
... | from solution import generate_question, ask_question
def test_generate_question():
question, answer = generate_question()
assert isinstance(question, str)
assert "x" in question
assert isinstance(answer, int)
assert 1 <= answer <= 100
def test_ask_question(monkeypatch):
# test when the user's ... | [
{
"docstring": "Generates a random multiplication question and its correct answer.\nReturns a tuple containing the question string and the correct answer.",
"function_declaration": "def generate_question():",
"function_name": "generate_question",
"parameter_list": "()"
},
{
"docstring": "Ask... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_multiplication_question():\n \"\"\"\n Generates a random multiplication question with factors between 1 and 10 inclusive.\n Returns a tuple containing th... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082158",
"row_id": 82158,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166094']"
} | 0.478939 | Filter_82158 | I | [
"generate_question",
"ask_question"
] | 2 | [
[
"ask_question",
"generate_question"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ffe05f44ad2191bd45edca51ca31b7e2cb35fdb3 | 80c439f5673b7f536a097b3bf32c644bf17a08ff | |||
v1.0 | instruct | Filter | Filter_82162_I | I'm working on a project to implement a simple deep learning model in Python using PyTorch. Can you provide some guidance or tips on how to get started? | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Define the neural network architecture
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(i... | import torch
import torch.nn as nn
import pytest
from solution import SimpleNN, train_model
def test_model_initialization():
model = SimpleNN(input_size=10, hidden_size=5, output_size=2)
assert model is not None
assert isinstance(model.fc1, nn.Linear)
assert isinstance(model.fc2, nn.Linear)
def test_f... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nclass SimpleNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082162",
"row_id": 82162,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166103']"
} | 0.25304 | Filter_82162 | I | [
"train_model",
"example_train_model"
] | 2 | [
[
"example_train_model",
"train_model"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 9534a08d898ec8d79c94cf528ed83c3c62db3364 | 68a7d7491f922df5f0ea031881693eff8ad1849a | |||
v1.0 | instruct | Filter | Filter_82167_I | I am working on a project where I need to find the minimum value of a function using the Nelder-Mead method. Can you provide an example of how to implement this method in Python using the `scipy.optimize` library? | from scipy.optimize import minimize
def function_to_minimize(x):
"""
The function we want to minimize.
For example, let's use a simple quadratic function: f(x) = (x-3)^2 + 4.
"""
return (x[0] - 3)**2 + 4
def find_minimum():
"""
Uses the Nelder-Mead method to find the minimum of the functio... | from solution import find_minimum
def test_find_minimum():
x_min, f_min = find_minimum()
assert abs(x_min - 3) < 0.001 # x_min should be close to 3
assert abs(f_min - 4) < 0.001 # The minimum value of the function should be close to 4 | [
{
"docstring": "The function we want to minimize.\nFor example, let's use a simple quadratic function: f(x) = (x-3)^2 + 4.",
"function_declaration": "def function_to_minimize(x):",
"function_name": "function_to_minimize",
"parameter_list": "(x)"
},
{
"docstring": "Uses the Nelder-Mead method... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from scipy.optimize import minimize\n\ndef objective_function(x):\n \"\"\"\n Objective function to be minimized. This is an example using\n a simple quadratic function.\n \"\"\"\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082167",
"row_id": 82167,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166110']"
} | 0.404469 | Filter_82167 | I | [
"function_to_minimize",
"find_minimum"
] | 2 | [
[
"find_minimum",
"function_to_minimize"
]
] | 1 | [] | false | [] | false | pytest | true | [
"scipy"
] | false | db7fa11d2049445b0e6e9c47598f5300ce779c2a | 347148d0461d0954af6d7f5c1be5ff406818d177 | |||
v1.0 | instruct | Filter | Filter_82225_I | Write a Python function to find the sum of all the prime numbers in a given list of integers. If there are no prime numbers in the list, the function should return 0. Use the Sieve of Eratosthenes to generate a list of prime numbers up to the maximum number in the given list. | def sieve_of_eratosthenes(max_num):
"""
Generates a list of prime numbers up to the maximum number using the Sieve of Eratosthenes algorithm.
"""
sieve = [True] * (max_num + 1)
sieve[0] = sieve[1] = False # 0 and 1 are not prime numbers
for start in range(2, int(max_num ** 0.5) + 1):
... | from solution import sum_of_primes
def test_sum_of_primes_with_primes():
assert sum_of_primes([2, 3, 5, 7, 11]) == 28
def test_sum_of_primes_with_no_primes():
assert sum_of_primes([4, 6, 8, 10, 12]) == 0
def test_sum_of_primes_with_mixed_numbers():
assert sum_of_primes([2, 4, 6, 3, 7]) == 12
def test_su... | [
{
"docstring": "Generates a list of prime numbers up to the maximum number using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(max_num):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(max_num)"
},
{
"docstring": "Returns the sum of... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sieve_of_eratosthenes(n):\n \"\"\"\n Generate a list of prime numbers up to n using the Sieve of Eratosthenes.\n \"\"\"\n is_prime = [True] * (n + 1)\n p = 2\n while p **... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082225",
"row_id": 82225,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166219']"
} | 0.662761 | Filter_82225 | I | [
"sieve_of_eratosthenes",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 18c724d4e039954bffd7c2397c2c7b12f3b68007 | 22a85799121d9ad1d0ff69abfc22f5134cd7f632 | |||
v1.0 | instruct | Filter | Filter_82232_I | I am working on a project to implement a simple feedforward neural network in Python using NumPy. Can you provide me with a basic code example to get started? | import numpy as np
def sigmoid(x):
"""
Sigmoid activation function.
"""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
"""
Derivative of the sigmoid function.
"""
return x * (1 - x)
def initialize_weights(input_size, hidden_size, output_size):
"""
Initialize weights an... | from solution import sigmoid, sigmoid_derivative, initialize_weights, feedforward
def test_sigmoid():
assert sigmoid(0) == 0.5
assert sigmoid(-np.inf) == 0
assert sigmoid(np.inf) == 1
def test_sigmoid_derivative():
assert sigmoid_derivative(0.5) == 0.25
assert sigmoid_derivative(1) == 0
assert... | [
{
"docstring": "Sigmoid activation function.",
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": "Derivative of the sigmoid function.",
"function_declaration": "def sigmoid_derivative(x):",
"function_name": "sigmoid_deriv... | [
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 \"\"\"\n Sigmoid activation function.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n \"\"\"\n Derivative of th... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082232",
"row_id": 82232,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166233']"
} | 0.33491 | Filter_82232 | I | [
"sigmoid",
"sigmoid_derivative",
"initialize_weights",
"feedforward"
] | 4 | [
[
"feedforward",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 1a98709443d5a496536ecbc8694d827ca6927809 | d91bd153ee969a47f1b9ff952fed54682627600b | |||
v1.0 | instruct | Filter | Filter_82272_I | I am working on a project that involves solving the Traveling Salesman Problem (TSP). Can you provide me with some Python code examples or suggest where I can find them? | import itertools
def calculate_total_distance(tour, distance_matrix):
"""
Calculate the total distance of the given tour using the provided distance matrix.
"""
total_distance = 0
for i in range(len(tour)):
total_distance += distance_matrix[tour[i - 1]][tour[i]]
return total_distance
d... | from solution import calculate_total_distance, brute_force_tsp
def test_calculate_total_distance():
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
tour = [0, 1, 2, 3]
assert calculate_total_distance(tour, distance_matrix) == 95
... | [
{
"docstring": "Calculate the total distance of the given tour using the provided distance matrix.",
"function_declaration": "def calculate_total_distance(tour, distance_matrix):",
"function_name": "calculate_total_distance",
"parameter_list": "(tour, distance_matrix)"
},
{
"docstring": "Sol... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef calculate_distance(matrix, route):\n \"\"\"\n Calculate the total distance of a given route based on the distance matrix.\n \"\"\"\n distance = 0\n num_c... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082272",
"row_id": 82272,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166307']"
} | 0.357486 | Filter_82272 | I | [
"calculate_total_distance",
"brute_force_tsp"
] | 2 | [
[
"brute_force_tsp",
"calculate_total_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6698c49e6eece07031349f0dd3918e5a4b9a7bcb | 5c0a6267e5c8ae35b2bb3978346651df45f4b35a | |||
v1.0 | instruct | Filter | Filter_82299_I | I am working on a project that involves image classification using the K Nearest Neighbors (KNN) algorithm in Python. I have a dataset of images, and I need to implement the KNN algorithm to classify new images based on the training set. Can you provide a step-by-step guide or some code examples to help me get started? | import numpy as np
from sklearn.neighbors import KNeighborsClassifier
def flatten_image(image):
"""
Flattens a 2D image into a 1D array.
"""
return image.flatten()
def prepare_dataset(images, labels):
"""
Prepare the dataset by flattening the images and returning the feature matrix and labels.... | import numpy as np
from solution import flatten_image, prepare_dataset, train_knn_classifier, classify_image
def test_flatten_image():
image = np.array([[1, 2], [3, 4]])
result = flatten_image(image)
assert np.array_equal(result, np.array([1, 2, 3, 4]))
def test_prepare_dataset():
images = [np.array([... | [
{
"docstring": "Flattens a 2D image into a 1D array.",
"function_declaration": "def flatten_image(image):",
"function_name": "flatten_image",
"parameter_list": "(image)"
},
{
"docstring": "Prepare the dataset by flattening the images and returning the feature matrix and labels.",
"functi... | [
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 sklearn.neighbors import KNeighborsClassifier\n\ndef flatten_image(image):\n \"\"\"\n Flattens a 2D image into a 1D array.\n \"\"\"\n return image.flatten(... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082299",
"row_id": 82299,
"seed_ids": "['Qwen2.5-Math-72B-Instruct_166350']"
} | 0.47503 | Filter_82299 | I | [
"flatten_image",
"prepare_dataset",
"train_knn_classifier",
"classify_image"
] | 4 | [
[
"classify_image",
"flatten_image"
],
[
"prepare_dataset",
"flatten_image"
],
[
"train_knn_classifier",
"prepare_dataset"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | c0ccd21a8a6271161d1307203d5cc3ba75dd10b0 | cc0f64bd2ead258b01bdeed84537fad5dd612885 | |||
v1.0 | instruct | Filter | Filter_82393_I | I'm trying to create a program that can solve Sudoku puzzles.
I'm thinking of using a recursive backtracking algorithm.
Could you explain the concept and provide a Python implementation? | def is_valid(board, row, col, num):
"""
Check if num can be placed at board[row][col] without
violating Sudoku rules.
"""
# Check row
for x in range(9):
if board[row][x] == num:
return False
# Check column
for x in range(9):
if board[x][col] == num:
... | from solution import solve_sudoku, is_valid, find_empty_location
def test_find_empty_location():
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,... | [
{
"docstring": "Check if num can be placed at board[row][col] without\nviolating Sudoku rules.",
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list": "(board, row, col, num)"
},
{
"docstring": "Solve the Sudoku puzzle using recursive b... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid(board, row, col, num):\n \"\"\"\n Check if placing the num at board[row][col] is valid.\n \"\"\"\n # Check if num is in the current row\n for x in range(9):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082393",
"row_id": 82393,
"seed_ids": "['gemma-2-27b-it_166595']"
} | 0.408483 | Filter_82393 | I | [
"is_valid",
"solve_sudoku",
"find_empty_location"
] | 3 | [
[
"solve_sudoku",
"find_empty_location"
],
[
"solve_sudoku",
"is_valid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f6f94c4953b9e94545444fe6e3cbb0357bb8bfa7 | 2e964ea1b3f9a4af73c8b837c3e6d42eb0e90379 | |||
v1.0 | instruct | Filter | Filter_82405_I | This problem is about **finding the smallest prime number that is greater than a given number**.
**Example:**
If the given number is 10, the smallest prime number greater than 10 is 11.
**Can you explain how to write a Python code to solve this problem? | def is_prime(n):
"""
Checks if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return T... | from solution import smallest_prime_greater_than, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_smallest_prime_greater_than():
assert smallest_prime_greater_than(... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the smallest prime number that is greater than the given number n.",
"function_declaration": "def smallest_prime_grea... | [
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 provided number n is a prime number.\n\n Args:\n n (int): The number to check.\n\n Returns:\n bool: True if n is a prime number, Fals... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082405",
"row_id": 82405,
"seed_ids": "['gemma-2-27b-it_166635']"
} | 0.598942 | Filter_82405 | I | [
"is_prime",
"smallest_prime_greater_than"
] | 2 | [
[
"smallest_prime_greater_than",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 338aa607404dd7c77234aa427ed0b3af2135b233 | 074c415726f59301d7e24305cf4564f0449ba1fb | |||
v1.0 | instruct | Filter | Filter_82459_I | This is a game about guessing a secret number. The game should ask the user to guess a number between 1 and 100. If the guess is incorrect, the game should tell the user whether their guess was too high or too low. The game should continue until the user guesses the correct number.
Here is the Python code for the game... | import random
def choose_difficulty():
"""Allows user to choose difficulty level."""
print("Choose a difficulty level:")
print("1. Easy (Range: 1 to 50)")
print("2. Medium (Range: 1 to 100)")
print("3. Hard (Range: 1 to 200)")
while True:
try:
level = int(input("Enter the n... | import pytest
from unittest.mock import patch
from solution import choose_difficulty
def test_choose_difficulty_easy():
with patch('builtins.input', return_value='1'):
assert choose_difficulty() == 50
def test_choose_difficulty_medium():
with patch('builtins.input', return_value='2'):
assert c... | [
{
"docstring": "Allows user to choose difficulty level.",
"function_declaration": "def choose_difficulty():",
"function_name": "choose_difficulty",
"parameter_list": "()"
},
{
"docstring": "Plays a guessing game with the user.",
"function_declaration": "def guess_the_number():",
"fun... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef choose_difficulty():\n \"\"\"Allows user to choose difficulty level.\"\"\"\n print(\"Choose a difficulty level:\")\n print(\"1. Easy (Range: 1 to 50)\")\n prin... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082459",
"row_id": 82459,
"seed_ids": "['gemma-2-27b-it_166815']"
} | 0.50486 | Filter_82459 | I | [
"choose_difficulty",
"guess_the_number"
] | 2 | [
[
"guess_the_number",
"choose_difficulty"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f826a6d8f55118a54f2a61a4580f357892006fa5 | 3bbebdedf6023381904fe7fbdba03025bdcdaff7 | |||
v1.0 | instruct | Filter | Filter_82485_I | This is the code I'm trying to use.
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Get input from the user
num = int(input("Enter a non-negative integer: "))
# Check if the input is non-negative
if num < 0:
print("Factorial is not defined for negative numbers.")
els... | def factorial(n):
"""
This function calculates the factorial of a non-negative integer.
For negative integers, it returns a message indicating factorial is not defined.
"""
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0:
return 1
else:
r... | from solution import factorial
def test_factorial_positive_numbers():
assert factorial(5) == 120
assert factorial(0) == 1
def test_factorial_negative_numbers():
assert factorial(-1) == "Factorial is not defined for negative numbers."
assert factorial(-10) == "Factorial is not defined for negative numb... | [
{
"docstring": "This function calculates the factorial of a non-negative integer.\nFor negative integers, it returns a message indicating factorial is not defined.",
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n This function calculates the factorial of a non-negative integer.\n For negative integers, it returns a message indicating factorial is not defined.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082485",
"row_id": 82485,
"seed_ids": "['gemma-2-27b-it_166884']"
} | 0.621277 | Filter_82485 | I | [
"factorial",
"calculate_factorial"
] | 2 | [
[
"calculate_factorial",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 23127a0203050ec552a0dc208cfaa46789c9a6e8 | 4e9cb6cb2631e4b9029bc2382ba8069011e114da | |||
v1.0 | instruct | Filter | Filter_82496_I | Here is a problem statement:
Given an array of integers `nums`, write a function to find the maximum possible sum of a contiguous subarray within the array.
**Example:**
```
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The contiguous subarray [4,-1,2,1] has the largest sum = 6.
```
**Constraints:**
*... | def max_crossing_sum(nums, left, mid, right):
left_sum = float('-inf')
sum = 0
for i in range(mid, left - 1, -1):
sum += nums[i]
if sum > left_sum:
left_sum = sum
right_sum = float('-inf')
sum = 0
for i in range(mid + 1, right + 1):
sum += nums[i]
... | from solution import max_sub_array
def test_example_case():
assert max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
def test_single_element_positive():
assert max_sub_array([2]) == 2
def test_single_element_negative():
assert max_sub_array([-2]) == -2
def test_all_positive_numbers():
assert max_s... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(nums, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(nums, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_sub_array_divide_and_conquer(nums, left, right):",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_crossing_sum(nums, left, middle, right):\n sum_left = float('-inf')\n sum_temp = 0\n for i in range(middle, left - 1, -1):\n sum_temp += nums[i]\n if sum_temp > ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082496",
"row_id": 82496,
"seed_ids": "['gemma-2-27b-it_166923']"
} | 0.70892 | Filter_82496 | I | [
"max_crossing_sum",
"max_sub_array_divide_and_conquer",
"max_sub_array"
] | 3 | [
[
"max_sub_array",
"max_sub_array_divide_and_conquer"
],
[
"max_sub_array_divide_and_conquer",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9ceb89698089cb88f680b95e0d1728db63251113 | e0e3fbd3836d5bd0e76e3c85400ee6b010261a19 | |||
v1.0 | instruct | Filter | Filter_82497_I | Design a program that simulates a simple lottery game.
Requirements:
The program should generate six random numbers between 1 and 49 (inclusive).
The user should be able to input six numbers of their choice.
The program should compare the user's numbers with the randomly generated numbers and count ho... | import random
def generate_lottery_numbers():
"""Generates six random numbers between 1 and 49."""
return random.sample(range(1, 50), 6)
def compare_numbers(lottery_numbers, user_numbers):
"""Compares the lottery numbers with the user's numbers and returns the number of matches."""
matches = 0
for... | from solution import generate_lottery_numbers, compare_numbers, play_lottery_round
def test_generate_lottery_numbers():
lottery_numbers = generate_lottery_numbers()
assert len(lottery_numbers) == 6
assert all(1 <= num <= 49 for num in lottery_numbers)
assert len(set(lottery_numbers)) == 6
def test_com... | [
{
"docstring": "Generates six random numbers between 1 and 49.",
"function_declaration": "def generate_lottery_numbers():",
"function_name": "generate_lottery_numbers",
"parameter_list": "()"
},
{
"docstring": "Compares the lottery numbers with the user's numbers and returns the number of ma... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_lottery_numbers():\n \"\"\"Generates six random numbers between 1 and 49.\"\"\"\n return random.sample(range(1, 50), 6)\n\ndef get_user_numbers(user_input):... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082497",
"row_id": 82497,
"seed_ids": "['gemma-2-27b-it_166929']"
} | 0.584821 | Filter_82497 | I | [
"generate_lottery_numbers",
"compare_numbers",
"play_lottery_round"
] | 3 | [
[
"play_lottery_round",
"compare_numbers"
],
[
"play_lottery_round",
"generate_lottery_numbers"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7a43eb76a4f89535d18adfe7b97336d5cfd996aa | c9fbee74633e7ac7d6c9442ae888ff7ebfef87e2 | |||
v1.0 | instruct | Filter | Filter_82506_I | This is the task:
Write a Python program that takes a list of strings as input and returns a new list containing only the strings that are palindromes.
Here's what I've come up with:
```python
def is_palindrome(word):
return word == word[::-1]
def find_palindromes(words):
palindromes = []
for word in words:
... | def is_palindrome(word):
"""
Check if a word is a palindrome.
Parameters:
word (str): The word to check.
Returns:
bool: True if the word is a palindrome, False otherwise.
"""
return word == word[::-1]
def find_palindromes(words):
"""
Finds all palindromes in a list of ... | from solution import is_palindrome, find_palindromes
def test_is_palindrome():
assert is_palindrome("racecar") == True
assert is_palindrome("python") == False
assert is_palindrome("madam") == True
assert is_palindrome("hello") == False
assert is_palindrome("a") == True
assert is_palindrome("") ... | [
{
"docstring": "Check if a word is a palindrome.\n\nParameters:\nword (str): The word to check.\n\nReturns:\nbool: True if the word is a palindrome, False otherwise.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docst... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(word):\n \"\"\"\n Checks if a given word is a palindrome.\n A palindrome is a word that reads the same backward as forward.\n \"\"\"\n return word == word[::-1... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082506",
"row_id": 82506,
"seed_ids": "['gemma-2-27b-it_166947']"
} | 0.755772 | Filter_82506 | I | [
"is_palindrome",
"find_palindromes"
] | 2 | [
[
"find_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9946aaae94711ab7f1b1fb5902f2b711c23d1cb3 | 8be0d0101a91dd6a53f689900d5864f027915ffe | |||
v1.0 | instruct | Filter | Filter_82516_I | Here are the rules for a game called "Word Search Mania":
* **Objective:** To find all the hidden words in a grid of letters.
* **Grid:** A rectangular grid of letters.
* **Word List:** A list of words that are hidden in the grid.
* **Directions:** Words can be hidden horizontally, vertically, diagonally, forwards, or... | import random
# Directions for searching the grid
DIRECTIONS = [
(0, 1), # Horizontal Right
(0, -1), # Horizontal Left
(1, 0), # Vertical Down
(-1, 0), # Vertical Up
(1, 1), # Diagonal Right Down
(1, -1), # Diagonal Left Down
(-1, 1), # Diagonal Right Up
(-1, -1) # Diagonal L... | from solution import generate_grid, display_grid, create_empty_grid, place_word
def test_create_empty_grid():
grid = create_empty_grid(5, 5)
assert len(grid) == 5
assert len(grid[0]) == 5
assert all(cell == '_' for row in grid for cell in row)
def test_place_word_horizontally():
grid = create_empt... | [
{
"docstring": "Creates an empty grid of specified size filled with underscores.",
"function_declaration": "def create_empty_grid(rows, cols):",
"function_name": "create_empty_grid",
"parameter_list": "(rows, cols)"
},
{
"docstring": "Attempts to place a word in the grid starting from (row, ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\ndef generate_empty_grid(rows, cols):\n \"\"\"Generates an empty grid filled with spaces.\"\"\"\n return [[' ' for _ in range(cols)] for _ in range(rows)]\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082516",
"row_id": 82516,
"seed_ids": "['gemma-2-27b-it_166969']"
} | 0.522095 | Filter_82516 | I | [
"create_empty_grid",
"place_word",
"generate_grid",
"display_grid"
] | 4 | [
[
"generate_grid",
"create_empty_grid"
],
[
"generate_grid",
"place_word"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b2acc8427ac750662f395b75f4d49e69416fbb00 | bcb30c1973b962388606ea7203316f11bc6e4e33 | |||
v1.0 | instruct | Filter | Filter_82558_I | Please provide a detailed explanation of how to create a simple chatbot using Python.
Let's keep it basic and focus on:
Core components:
User Input: Handling user text input.
Text Processing: Basic techniques for understanding user input.
Response Generation: Creating simple, rule-based responses.
... | def get_response(user_input):
"""
Generates a simple response based on user input.
"""
user_input = user_input.lower()
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I assist you today?"
elif "how are you" in user_input:
return "I'm just a bot, but I'... | from solution import get_response
def test_greeting():
assert get_response("hello") == "Hello! How can I assist you today?"
assert get_response("hi there") == "Hello! How can I assist you today?"
def test_how_are_you():
assert get_response("How are you?") == "I'm just a bot, but I'm doing great! How can I... | [
{
"docstring": "Generates a simple response based on user input.",
"function_declaration": "def get_response(user_input):",
"function_name": "get_response",
"parameter_list": "(user_input)"
},
{
"docstring": "A simple chatbot interaction loop.",
"function_declaration": "def chatbot():",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def chatbot_response(user_input):\n \"\"\"\n Generates a simple response for the chatbot based on user input.\n\n Args:\n user_input (str): The text input from the user.\n\n Ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082558",
"row_id": 82558,
"seed_ids": "['gemma-2-27b-it_167093']"
} | 0.371745 | Filter_82558 | I | [
"get_response",
"chatbot"
] | 2 | [
[
"chatbot",
"get_response"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2e8fe930030da543604da4781e372552b5776773 | c07ebcf6e7928dc816925a5291b684f70b4cd8c7 | |||
v1.0 | instruct | Filter | Filter_82576_I | Here's a problem I'm having with my code:
I'm trying to write a program that takes an integer input from the user and then prints all the prime numbers up to that integer.
Here's my code:
```python
def is_prime(num):
"""Checks if a number is prime."""
if num <= 1:
return False
for i in range(2, int(num**0.... | def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def primes_up_to(n):
"""
Returns a list of all prime numbers up to n (inclusive).
"""
pri... | from solution import is_prime, primes_up_to
# Tests for is_prime function
def test_is_prime_with_prime_numbers():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(11) == True
assert is_prime(13) == True
def test_is_prime_with_non_prime_numbers():
assert is_prime(1) == False
... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all prime numbers up to n (inclusive).",
"function_declaration": "def primes_up_to(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_prime(num):\n \"\"\"\n Checks if a number is prime.\n\n Parameters:\n num (int): The number to check.\n\n Returns:\n bool: True if num is prime, False otherwise.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082576",
"row_id": 82576,
"seed_ids": "['gemma-2-27b-it_167156']"
} | 0.720256 | Filter_82576 | I | [
"is_prime",
"primes_up_to"
] | 2 | [
[
"primes_up_to",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6e8b13d0fdd7389af1410b723d17615516e7bc92 | 0259dc959634b8c22ed02b21ecf7d33cfc406cbe | |||
v1.0 | instruct | Filter | Filter_82577_I | The Challenge:
Create a Python program that allows users to play a simple text-based adventure game.
Game Overview:
The game will take place in a dark forest. The player starts at a crossroads and must choose which path to take. Each path leads to a different encounter or outcome.
Features:
Multiple Paths: The pl... | def adventure_game():
print("You find yourself at a crossroads in a dark forest. Which path do you choose?")
print("1. Take the left path")
print("2. Take the middle path")
print("3. Take the right path")
choice = input("Enter the number of your choice: ")
if choice == '1':
left_path()... | import pytest
from io import StringIO
from contextlib import redirect_stdout
from unittest.mock import patch
from solution import adventure_game, left_path, middle_path, right_path
def test_adventure_game_left_path_accept_help():
user_input = ['1', '1']
expected_output = (
"You find yourself at a cross... | [
{
"docstring": null,
"function_declaration": "def adventure_game():",
"function_name": "adventure_game",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def left_path():",
"function_name": "left_path",
"parameter_list": "()"
},
{
"docstring": null,... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def play_game():\n print(\"You find yourself at a crossroads in a dark forest. Which path do you choose?\")\n print(\"1. Path to the left\")\n print(\"2. Path straight ahead\")\n p... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082577",
"row_id": 82577,
"seed_ids": "['gemma-2-27b-it_167158']"
} | 0.489678 | Filter_82577 | I | [
"adventure_game",
"left_path",
"middle_path",
"right_path"
] | 4 | [
[
"adventure_game",
"left_path"
],
[
"adventure_game",
"middle_path"
],
[
"adventure_game",
"right_path"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 28bcadb5ea6c076a136f0214650cac553933034d | 78f8d75b6b154d665aba0de6719f0fec50021a95 | |||
v1.0 | instruct | Filter | Filter_82593_I | Please help me understand how to use a recursive function to solve this problem:
Given an array of integers, find the maximum sum of a contiguous subarray within the array.
For example:
```
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Explanation: The contiguous subarray [4, -1, 2, 1] has the largest sum = 6.
... | def max_subarray_cross_sum(nums, left, mid, right):
left_sum = float('-inf')
right_sum = float('-inf')
sum_temp = 0
for i in range(mid, left - 1, -1):
sum_temp += nums[i]
if sum_temp > left_sum:
left_sum = sum_temp
sum_temp = 0
for i in range(mid + 1, right ... | from solution import max_subarray
def test_single_element():
assert max_subarray([1]) == 1
def test_all_negative():
assert max_subarray([-1, -2, -3, -4]) == -1
def test_mixed_numbers():
assert max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
def test_all_zeros():
assert max_subarray([0, 0, 0, 0]) ... | [
{
"docstring": null,
"function_declaration": "def max_subarray_cross_sum(nums, left, mid, right):",
"function_name": "max_subarray_cross_sum",
"parameter_list": "(nums, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_recursive(nums, left, right):",
... | [
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(nums, left, mid, right):\n \"\"\"\n Helper function to find the maximum sum of subarray which crosses the midpoint.\n \"\"\"\n # Include at least one element f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082593",
"row_id": 82593,
"seed_ids": "['gemma-2-27b-it_167226']"
} | 0.660159 | Filter_82593 | I | [
"max_subarray_cross_sum",
"max_subarray_recursive",
"max_subarray"
] | 3 | [
[
"max_subarray",
"max_subarray_recursive"
],
[
"max_subarray_recursive",
"max_subarray_cross_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0baa05dfd3ffd9f47d54caefe4ae425f20d50538 | d6395f29a4a19aa5897f81a7d123d7e7ae2f32f6 | |||
v1.0 | instruct | Filter | Filter_82660_I | This is a coding challenge:
You are given an array of integers, `nums`. Find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
**Example 1:**
```
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
```
**Example 2:**
``... | def maxCrossingSum(nums, left, mid, right):
left_sum = float('-inf')
sum = 0
for i in range(mid, left - 1, -1):
sum += nums[i]
if sum > left_sum:
left_sum = sum
right_sum = float('-inf')
sum = 0
for i in range(mid + 1, right + 1):
sum += nums[i]
if su... | from solution import maxSubArray
def test_example_1():
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
assert maxSubArray(nums) == 6
def test_example_2():
nums = [1]
assert maxSubArray(nums) == 1
def test_example_3():
nums = [5, 4, -1, 7, 8]
assert maxSubArray(nums) == 23
def test_all_negative():
... | [
{
"docstring": null,
"function_declaration": "def maxCrossingSum(nums, left, mid, right):",
"function_name": "maxCrossingSum",
"parameter_list": "(nums, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def maxSubArrayDivideAndConquer(nums, left, right):",
"function... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maxSubArray(nums):\n def maxCrossingSum(arr, left, mid, right):\n # Include elements on the left of mid\n sm = 0\n left_sum = float('-inf')\n for i in range(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082660",
"row_id": 82660,
"seed_ids": "['gemma-2-27b-it_167403']"
} | 0.757207 | Filter_82660 | I | [
"maxCrossingSum",
"maxSubArrayDivideAndConquer",
"maxSubArray"
] | 3 | [
[
"maxSubArray",
"maxSubArrayDivideAndConquer"
],
[
"maxSubArrayDivideAndConquer",
"maxCrossingSum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 58ca22b2cd761a559f785cb9d3b785590bea0c46 | 7dfcdff37220f184a42438bae32219bdf67a491f | |||
v1.0 | instruct | Filter | Filter_82683_I | Here's what I want to achieve:
**Goal:**
I want to create a simple text-based adventure game in Python. The game should allow the player to explore a few locations, interact with simple objects, and make choices that affect the story's outcome.
**Features:**
* **Locations:** The game should have at least three dist... | def start_game():
"""
Starts the text-based adventure game.
"""
print("Welcome to the Adventure Game!")
print("You find yourself at a crossroad with three paths.")
print("1: Go to the forest.")
print("2: Enter the cave.")
print("3: Take the path to the house.")
choice = input("W... | from solution import forest, cave, house, add_to_inventory, show_inventory, inventory
def test_forest_open_chest(monkeypatch):
inventory.clear()
monkeypatch.setattr('builtins.input', lambda _: '1')
forest()
assert inventory == ["treasure"]
def test_cave_take_lantern(monkeypatch):
inventory.clear()... | [
{
"docstring": "Starts the text-based adventure game.",
"function_declaration": "def start_game():",
"function_name": "start_game",
"parameter_list": "()"
},
{
"docstring": "Defines the forest location.",
"function_declaration": "def forest():",
"function_name": "forest",
"parame... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_game():\n \"\"\"\n Starts the text-based adventure game.\n \"\"\"\n print(\"Welcome to the Adventure Game!\")\n print(\"You find yourself at a crossroad with three pat... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082683",
"row_id": 82683,
"seed_ids": "['gemma-2-27b-it_167465']"
} | 0.382534 | Filter_82683 | I | [
"start_game",
"forest",
"cave",
"house",
"add_to_inventory",
"show_inventory"
] | 6 | [
[
"cave",
"add_to_inventory"
],
[
"cave",
"start_game"
],
[
"forest",
"add_to_inventory"
],
[
"forest",
"start_game"
],
[
"house",
"add_to_inventory"
],
[
"house",
"start_game"
],
[
"start_game",
"cave"
],
[
"start_game",
"f... | 9 | [] | false | [] | false | pytest | true | [] | true | b4f5f4b3af53161a6fba7a797948dc7f89fa57b2 | bbc9a1777d2e12f01b6fffcb50d69e26ff8b5566 | |||
v1.0 | instruct | Filter | Filter_82708_I | The following text describes a problem that I have to solve:
**Problem:**
Design a program that identifies prime numbers within a given range.
**Input:**
Two positive integers, representing the lower and upper bounds of the range.
**Output:**
A list of all prime numbers within the specified range.
Can you help ... | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True... | from solution import is_prime, find_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(0) == False
assert is_prime(1) == False
assert is_prime(-5) == False
def test_find_primes_i... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers within the given range [lower, upper].",
"function_declaration": "def find_primes_in_range(low... | [
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 \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082708",
"row_id": 82708,
"seed_ids": "['gemma-2-27b-it_167547']"
} | 0.635797 | Filter_82708 | I | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a8677f9c5c6e5558c9d0f2664950b7f20704f16 | 4af6716b229431c3c0ad15573800b6778bc655fa | |||
v1.0 | instruct | Filter | Filter_82723_I | A
Apple
Apricot
B
Banana
Blueberry
C
Cherry
Clementine
D
Dragon Fruit
Date
E
Elderberry
F
Fig
Fruit cocktail
G
Grapefruit
H
Honeydew Melon
I
Indian Plum
J
Jackfruit
K
Kiwi
L
Lemon
Lime
M
Mango
Mandarin
N
Nectarine
O
Orange
P
Peach
Pear
Plum
Q
Quince
R
Raspbe... | import random
# Dictionary of fruits by their starting letter
fruits_dict = {
"A": ["Apple", "Apricot"],
"B": ["Banana", "Blueberry"],
"C": ["Cherry", "Clementine"],
"D": ["Dragon Fruit", "Date"],
"E": ["Elderberry"],
"F": ["Fig", "Fruit cocktail"],
"G": ["Grapefruit"],
"H": ["Honeydew ... | from solution import get_random_fruit, display_current_state
def test_get_random_fruit():
fruit = get_random_fruit()
assert isinstance(fruit, str)
assert fruit[0] in fruits_dict
assert fruit in [fruit.upper() for sublist in fruits_dict.values() for fruit in sublist]
def test_display_current_state_init... | [
{
"docstring": null,
"function_declaration": "def get_random_fruit():",
"function_name": "get_random_fruit",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def display_current_state(fruit, guessed_letters):",
"function_name": "display_current_state",
"par... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\n# Dictionary of fruits categorized by their starting letters\nfruits = {\n 'A': [\"Apple\", \"Apricot\"],\n 'B': [\"Banana\", \"Blueberry\"],\n 'C': [\"Cherry\", \"Cl... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082723",
"row_id": 82723,
"seed_ids": "['gemma-2-27b-it_167595']"
} | 0.53379 | Filter_82723 | I | [
"get_random_fruit",
"display_current_state",
"guess_the_fruit_game"
] | 3 | [
[
"guess_the_fruit_game",
"display_current_state"
],
[
"guess_the_fruit_game",
"get_random_fruit"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4aefb78e4978196aeed5c350088d0f710504eba0 | f3a0c0c20924b8374f78cedc5d72f55e33f68ecd | |||
v1.0 | instruct | Filter | Filter_82742_I | This is my code:
```python
import random
def roll_dice(sides):
"""Rolls a single die with the given number of sides."""
return random.randint(1, sides)
def roll_multiple_dice(num_dice, sides):
"""Rolls multiple dice with the given number of sides and returns the total."""
total = 0
for _ in range... | import random
def roll_dice(sides):
"""
Rolls a single die with the given number of sides.
Args:
sides (int): The number of sides on the die.
Returns:
int: A random number between 1 and the number of sides (inclusive).
"""
return random.randint(1, sides)
def roll_multiple_dic... | import pytest
import random
from solution import roll_dice, roll_multiple_dice
def test_roll_dice():
sides = 6
results = [roll_dice(sides) for _ in range(100)]
for result in results:
assert 1 <= result <= sides
def test_roll_multiple_dice():
num_dice = 3
sides = 6
total = roll_multiple... | [
{
"docstring": "Rolls a single die with the given number of sides.\n\nArgs:\nsides (int): The number of sides on the die.\n\nReturns:\nint: A random number between 1 and the number of sides (inclusive).",
"function_declaration": "def roll_dice(sides):",
"function_name": "roll_dice",
"parameter_list"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice(sides):\n \"\"\"\n Rolls a single die with the given number of sides.\n \n Args:\n sides (int): The number of sides on the die.\n \n Returns... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082742",
"row_id": 82742,
"seed_ids": "['gemma-2-27b-it_167635']"
} | 0.65087 | Filter_82742 | I | [
"roll_dice",
"roll_multiple_dice"
] | 2 | [
[
"roll_multiple_dice",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2521cf487e5a8561058f860604f56f387f36a6d3 | 8dec0942b9c3c9978a3292127e9c7f22e90e735d | |||
v1.0 | instruct | Filter | Filter_82772_I | I want to create a python script that will automate the process of sending emails.
I need to use Gmail SMTP server.
Here's what I want the script to do:
1. **Read email credentials from a file:** Instead of hardcoding the username and password, I want the script to read them from a separate file called "credentials.... | import smtplib
from email.mime.text import MIMEText
def read_credentials(cred_file="credentials.txt"):
try:
with open(cred_file, "r") as f:
username = f.readline().strip()
password = f.readline().strip()
return username, password
except FileNotFoundError:
print(f... | import pytest
from unittest.mock import patch, mock_open
from solution import read_credentials, read_recipients, create_email
def test_read_credentials():
mock_data = "user@example.com\npassword\n"
with patch("builtins.open", mock_open(read_data=mock_data)):
username, password = read_credentials("dummy... | [
{
"docstring": null,
"function_declaration": "def read_credentials(cred_file='credentials.txt'):",
"function_name": "read_credentials",
"parameter_list": "(cred_file='credentials.txt')"
},
{
"docstring": null,
"function_declaration": "def read_recipients(recipients_file='recipients.txt')... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.text import MIMEText\nimport os\n\n\ndef read_credentials(file_path=\"credentials.txt\"):\n \"\"\"\n Function to read email crede... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082772",
"row_id": 82772,
"seed_ids": "['gemma-2-27b-it_167717']"
} | 0.76055 | Filter_82772 | I | [
"read_credentials",
"read_recipients",
"create_email",
"send_email"
] | 4 | [
[
"send_email",
"create_email"
],
[
"send_email",
"read_credentials"
],
[
"send_email",
"read_recipients"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 58eca81ae2315a7c66a09cce14788e1b10976849 | 08c9fc0b41a6ed48a46d1d81bb3a1b0e0147f306 | |||
v1.0 | instruct | Filter | Filter_82822_I | Project:
Create a simple chatbot using Python that can respond to basic greetings and farewells.
Instructions:
1. Define Functions:
Create separate functions to handle greetings, farewells, and default responses.
2. User Input:
Get user input using the `input()` function.
3. Response Logic:
Use ... | def handle_greetings(user_input):
"""
Returns a response for a greeting.
"""
greetings = ['hello', 'hi', 'hey']
if user_input.lower() in greetings:
return "Hi there!"
else:
return None
def handle_farewells(user_input):
"""
Returns a response for a farewell.
"""
... | from solution import handle_greetings, handle_farewells, default_response, chatbot_response
def test_handle_greetings():
assert handle_greetings('Hello') == "Hi there!"
assert handle_greetings('Hi') == "Hi there!"
assert handle_greetings('Hey') == "Hi there!"
assert handle_greetings('Hola') is None
de... | [
{
"docstring": "Returns a response for a greeting.",
"function_declaration": "def handle_greetings(user_input):",
"function_name": "handle_greetings",
"parameter_list": "(user_input)"
},
{
"docstring": "Returns a response for a farewell.",
"function_declaration": "def handle_farewells(us... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def handle_greetings(user_input):\n \"\"\"\n Returns a response for a greeting.\n \"\"\"\n greetings = ['hello', 'hi', 'hey']\n if user_input.lower() in greetings:\n retu... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00082822",
"row_id": 82822,
"seed_ids": "['gemma-2-27b-it_167881']"
} | 0.439794 | Filter_82822 | I | [
"handle_greetings",
"handle_farewells",
"default_response",
"chatbot_response"
] | 4 | [
[
"chatbot_response",
"default_response"
],
[
"chatbot_response",
"handle_farewells"
],
[
"chatbot_response",
"handle_greetings"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e176696ea2fad34b1d4b479961c026e4be6bf5d6 | c17bfd6ad500acbbd2eabbad1f524f74b818fc96 | |||
v1.0 | instruct | Filter | Filter_82824_I | This is a very difficult problem.
I need to generate a Python script that can solve the Traveling Salesperson Problem (TSP) using a genetic algorithm.
The goal of the TSP is to find the shortest possible route that visits a set of cities exactly once and returns to the original city.
**Here's a breakdown of the step... | import random
import math
from itertools import permutations
def calculate_distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
def total_route_distance(route, cities):
distance = 0
for i in range(len(route)):
city1 = cities[route[i % len(route)]]
... | from solution import calculate_distance, total_route_distance, generate_initial_population, selection, ordered_crossover, mutate, genetic_algorithm
def test_calculate_distance():
assert calculate_distance((0, 0), (3, 4)) == 5.0
assert calculate_distance((1, 1), (4, 5)) == 5.0
def test_total_route_distance():
... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(city1, city2):",
"function_name": "calculate_distance",
"parameter_list": "(city1, city2)"
},
{
"docstring": null,
"function_declaration": "def total_route_distance(route, cities):",
"function_name": "total_route_di... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\n\ndef calculate_distance(city1, city2):\n return np.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)\n\ndef total_route_distance(route, citie... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082824",
"row_id": 82824,
"seed_ids": "['gemma-2-27b-it_167884']"
} | 0.475882 | Filter_82824 | I | [
"calculate_distance",
"total_route_distance",
"generate_initial_population",
"selection",
"ordered_crossover",
"mutate",
"genetic_algorithm"
] | 7 | [
[
"genetic_algorithm",
"generate_initial_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"ordered_crossover"
],
[
"genetic_algorithm",
"selection"
],
[
"genetic_algorithm",
"total_route_distance"
],
[
"total_route_distance",
... | 6 | [] | false | [] | false | pytest | true | [] | true | d168936793f4b7d86eb0660032d89c2e5d7afd54 | e78aa2a84894a1a30f56abe511cc1359a5951080 | |||
v1.0 | instruct | Filter | Filter_82840_I | The goal is to create a text-based adventure game in Python.
Here's a basic outline and some code to get started:
**Outline:**
1. **Introduction:**
- Welcome the player.
- Briefly describe the game's setting and premise.
2. **Rooms:**
- Define rooms as a dictionary with descriptions and possible exits.
3. *... | class Player:
def __init__(self, starting_location):
self.location = starting_location
self.inventory = []
def move(self, direction, rooms):
if direction in rooms[self.location]["exits"]:
self.location = rooms[self.location]["exits"][direction]
return True
... | import pytest
from solution import Player, describe_room, show_inventory, process_command
def test_player_movement():
rooms = {
"hall": {"description": "You are in a dark hallway.", "exits": {"north": "bedroom"}},
"bedroom": {"description": "You are in a dusty bedroom.", "exits": {"south": "hall"}}... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Player:\n def __init__(self, start_location):\n self.location = start_location\n self.inventory = []\n\n def move(self, direction, rooms):\n if direction in ro... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082840",
"row_id": 82840,
"seed_ids": "['gemma-2-27b-it_167928']"
} | 0.485773 | Filter_82840 | I | [
"describe_room",
"show_inventory",
"process_command",
"game"
] | 4 | [
[
"game",
"describe_room"
],
[
"game",
"process_command"
],
[
"process_command",
"describe_room"
],
[
"process_command",
"show_inventory"
]
] | 4 | [] | false | [
"Player"
] | true | pytest | true | [] | true | 50263a8231028f1c85240495c4aa9e8b947d1547 | 26ec8f8cf8472549836e549f526a57b469e9a5b9 | |||
v1.0 | instruct | Filter | Filter_82854_I | My son is learning to code in Python. He's excited about creating his own games. He's just starting out and needs a simple game to practice with.
Here's what we're looking for:
* **Simple logic:** Easy for a beginner to understand.
* **Text-based:** No need for graphics yet.
* **Interactive:** The player makes choice... | def welcome_message():
"""
Prints the welcome message for the game.
"""
print("Welcome to the Adventure Game!")
print("You are standing in a dark forest.")
print("There are two paths in front of you.")
print("One path leads to a village, the other to a castle.")
def get_choice():
""... | from io import StringIO
from unittest.mock import patch
from solution import welcome_message, get_choice, village_path, castle_path, adventure_game
def test_welcome_message():
with patch('sys.stdout', new=StringIO()) as fake_out:
welcome_message()
output = fake_out.getvalue().strip().split("\n")
... | [
{
"docstring": "Prints the welcome message for the game.",
"function_declaration": "def welcome_message():",
"function_name": "welcome_message",
"parameter_list": "()"
},
{
"docstring": "Prompts the player to make a choice between two paths.",
"function_declaration": "def get_choice():",... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def text_adventure_game():\n \"\"\"\n A simple text-based adventure game where the player makes choices\n that affect the outcome.\n \"\"\"\n print(\"Welcome to the adventure ga... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082854",
"row_id": 82854,
"seed_ids": "['gemma-2-27b-it_167970']"
} | 0.371935 | Filter_82854 | I | [
"welcome_message",
"get_choice",
"village_path",
"castle_path",
"adventure_game"
] | 5 | [
[
"adventure_game",
"castle_path"
],
[
"adventure_game",
"get_choice"
],
[
"adventure_game",
"village_path"
],
[
"adventure_game",
"welcome_message"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 41149eca2bb674e89c2b937bbf3ecddc3fcf4b04 | c39dc1018b8a33eaacef694b43a07df1a77f416c | |||
v1.0 | instruct | Filter | Filter_82865_I | This problem concerns a game played with a standard deck of 52 playing cards.
Here are the rules:
* **Dealing:** The dealer deals 5 cards face down to each player.
* **Hand Ranking:** Hands are ranked according to standard poker hand rankings (see below for a quick reference).
**Poker Hand Rankings (Best to Worst):*... | import random
from collections import defaultdict
# Define card ranks and suits
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
def create_deck():
"""Creates a standard deck of 52 playing cards."""
return [(rank, suit) for suit in SU... | from solution import create_deck, deal_hands, classify_hand, poker_winner, play_poker_game
def test_deck_creation():
deck = create_deck()
assert len(deck) == 52
assert len(set(deck)) == 52
def test_deal_hands():
deck = create_deck()
hands = deal_hands(deck)
assert len(hands) == 2
assert le... | [
{
"docstring": "Creates a standard deck of 52 playing cards.",
"function_declaration": "def create_deck():",
"function_name": "create_deck",
"parameter_list": "()"
},
{
"docstring": "Deals hands to the specified number of players from the deck.",
"function_declaration": "def deal_hands(d... | [
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# Ranks and suits for a standard deck of cards\nRANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nSUITS = ['H', 'D', 'C', 'S']\n\ndef create_deck():\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082865",
"row_id": 82865,
"seed_ids": "['gemma-2-27b-it_168000']"
} | 0.595215 | Filter_82865 | I | [
"create_deck",
"deal_hands",
"classify_hand",
"poker_winner",
"play_poker_game"
] | 5 | [
[
"play_poker_game",
"create_deck"
],
[
"play_poker_game",
"deal_hands"
],
[
"play_poker_game",
"poker_winner"
],
[
"poker_winner",
"classify_hand"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 0f5b900e644ad83a8a9c25d455cb52edbf688b6b | bff8a5f0f728137176a7e31db5ca270eb1f31312 | |||
v1.0 | instruct | Filter | Filter_82898_I | This is the code I am working on. I need to figure out how to
```python
import random
# Function to generate a random number between 1 and 100
def generate_random_number():
return random.randint(1, 100)
# Function to get the user's guess
def get_user_guess():
while True:
try:
guess = int(input("Guess a... | import random
# Function to generate a random number between 1 and 100
def generate_random_number():
return random.randint(1, 100)
# Function to get the user's guess
def get_user_guess(input_func=input):
while True:
try:
guess = int(input_func("Guess a number between 1 and 100: "))
... | from solution import generate_random_number, get_user_guess, play_game
import pytest
def test_generate_random_number(monkeypatch):
random_numbers = []
def fake_randint(start, end):
num = random_numbers.pop()
return num
monkeypatch.setattr('random.randint', fake_randint)
random_numb... | [
{
"docstring": null,
"function_declaration": "def generate_random_number():",
"function_name": "generate_random_number",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_user_guess(input_func=input):",
"function_name": "get_user_guess",
"parameter_l... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_random_number():\n \"\"\"\n Returns a random number between 1 and 100.\n \"\"\"\n return random.randint(1, 100)\n\ndef get_user_guess(input_function=i... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082898",
"row_id": 82898,
"seed_ids": "['gemma-2-27b-it_168104']"
} | 0.61292 | Filter_82898 | I | [
"generate_random_number",
"get_user_guess",
"play_game"
] | 3 | [
[
"play_game",
"generate_random_number"
],
[
"play_game",
"get_user_guess"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 335419e2ea1b6ec055f05a5d860da9555cc504c0 | e17bc57a11f286693fdc9631800c851f406df98e | |||
v1.0 | instruct | Filter | Filter_82903_I | This is a coding question:
**Given an array of integers, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.**
**Example:**
```
Input: [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
```
**Follow up:**
* If you have figured ... | # 1. O(n) Solution (Kadane's Algorithm)
def max_subarray_sum_kadane(nums):
"""
Returns the maximum sum of a contiguous subarray using Kadane's algorithm.
"""
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
if max_current > max_global... | from solution import max_subarray_sum_kadane, max_subarray_sum
def test_max_subarray_sum_kadane():
assert max_subarray_sum_kadane([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
assert max_subarray_sum_kadane([1, 2, 3, 4]) == 10
assert max_subarray_sum_kadane([-1, -2, -3, -4]) == -1
assert max_subarray_sum_kadan... | [
{
"docstring": "Returns the maximum sum of a contiguous subarray using Kadane's algorithm.",
"function_declaration": "def max_subarray_sum_kadane(nums):",
"function_name": "max_subarray_sum_kadane",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def max_cross... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_subarray_kadane(nums: List[int]) -> int:\n \"\"\"\n Finds the largest sum of a contiguous subarray using Kadane's Algorithm.\n Time complexity: O(n)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082903",
"row_id": 82903,
"seed_ids": "['gemma-2-27b-it_168125']"
} | 0.730533 | Filter_82903 | I | [
"max_subarray_sum_kadane",
"max_crossing_sum",
"max_subarray_sum_divide_and_conquer",
"max_subarray_sum"
] | 4 | [
[
"max_subarray_sum",
"max_subarray_sum_divide_and_conquer"
],
[
"max_subarray_sum_divide_and_conquer",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2bc8db512afe128d821729947c1e0537376fc4b3 | f81f21d03feb672d7d6b87d509d55417ef45b9fd | |||
v1.0 | instruct | Filter | Filter_82920_I | These are the rules of a game:
* Players roll two six-sided dice.
* The sum of the two dice is the player's score for that turn.
* Players continue rolling until they choose to stop or their score exceeds 21.
* If a player exceeds 21, they "bust" and their score for that turn is 0.
* The player with the highest sc... | import random
def roll_dice():
"""Rolls two dice and returns the sum."""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def play_turn(player_name):
"""Simulates a single player's turn."""
score = 0
while score <= 21:
roll = roll_dice()
print(f"{p... | from solution import roll_dice, play_turn, play_game
def test_roll_dice():
roll = roll_dice()
assert 2 <= roll <= 12
def test_play_turn(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: 'n')
assert play_turn("Player") <= 21
monkeypatch.setattr('builtins.input', lambda _: 'y')
monke... | [
{
"docstring": "Rolls two dice and returns the sum.",
"function_declaration": "def roll_dice():",
"function_name": "roll_dice",
"parameter_list": "()"
},
{
"docstring": "Simulates a single player's turn.",
"function_declaration": "def play_turn(player_name):",
"function_name": "play_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef roll_dice():\n \"\"\"Rolls two dice and returns the sum.\"\"\"\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n return die1 + die2\n\ndef play_tur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082920",
"row_id": 82920,
"seed_ids": "['gemma-2-27b-it_168198']"
} | 0.606129 | Filter_82920 | I | [
"roll_dice",
"play_turn",
"play_game"
] | 3 | [
[
"play_game",
"play_turn"
],
[
"play_turn",
"roll_dice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 299942b9bb1f60a5c149bc923927144c7dcce31d | 775d8c32d8fdeace359a0ef5d2afa27174f6a558 | |||
v1.0 | instruct | Filter | Filter_82922_I | Design a program that simulates the game of Rock, Paper, Scissors against a computer opponent.
Requirements:
1. The program should randomly choose rock, paper, or scissors for the computer.
2. The player should input their choice.
3. The program should determine the winner based on the rules of Rock, Paper, Scissors... | import random
def get_player_choice():
# This function is for interaction with user, for testing we will mock this input
pass
def get_computer_choice():
return random.choice(["rock", "paper", "scissors"])
def determine_winner(player_choice, computer_choice):
if player_choice == computer_choice:
... | import pytest
from unittest.mock import patch
from solution import get_computer_choice, determine_winner, play_round, play_game
def test_get_computer_choice():
choices = ["rock", "paper", "scissors"]
for _ in range(100):
assert get_computer_choice() in choices
@patch('solution.get_player_choice', retu... | [
{
"docstring": null,
"function_declaration": "def get_player_choice():",
"function_name": "get_player_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef get_player_choice():\n # This function would get input from the user in an interactive setting.\n # For testing purposes, we'll assume it returns a valid choice.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00082922",
"row_id": 82922,
"seed_ids": "['gemma-2-27b-it_168203']"
} | 0.578416 | Filter_82922 | I | [
"get_player_choice",
"get_computer_choice",
"determine_winner",
"play_round",
"play_game"
] | 5 | [
[
"play_game",
"play_round"
],
[
"play_round",
"determine_winner"
],
[
"play_round",
"get_computer_choice"
],
[
"play_round",
"get_player_choice"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9c317bb0b8db8c80cc92d2b7765fe02eb9c120b4 | 46049fa350476d58b8182704227d71f8b0555da8 | |||
v1.0 | instruct | Filter | Filter_82931_I | We need to write a program that takes a list of words and determines if any two words in the list are anagrams of each other. | def are_anagrams(word1, word2):
"""
Returns True if word1 and word2 are anagrams, False otherwise.
"""
return sorted(word1) == sorted(word2)
def contains_anagrams(words):
"""
Returns True if any two words in the list are anagrams of each other, False otherwise.
"""
for i in range(len(wo... | from solution import contains_anagrams
def test_contains_anagrams_true():
assert contains_anagrams(["listen", "silent", "enlist"]) == True
assert contains_anagrams(["rat", "tar", "art"]) == True
assert contains_anagrams(["evil", "vile", "live", "veil"]) == True
def test_contains_anagrams_false():
asse... | [
{
"docstring": "Returns True if word1 and word2 are anagrams, False otherwise.",
"function_declaration": "def are_anagrams(word1, word2):",
"function_name": "are_anagrams",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Returns True if any two words in the list are anagrams of each ot... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def are_anagrams(word1, word2):\n \"\"\"\n Checks if two given words are anagrams of each other.\n \"\"\"\n return sorted(word1) == sorted(word2)\n\ndef any_anagrams(word_list):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082931",
"row_id": 82931,
"seed_ids": "['gemma-2-27b-it_168223']"
} | 0.551918 | Filter_82931 | I | [
"are_anagrams",
"contains_anagrams"
] | 2 | [
[
"contains_anagrams",
"are_anagrams"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a1c53a7b1fbfb2b286c965721f628d9ec691831 | 7cbe0fd64f8fd0a5607c1d5f9d1e65a78d9eee1f | |||
v1.0 | instruct | Filter | Filter_82934_I | Purpose: To create a Python function that can identify and return a list of all prime numbers within a given range. | def is_prime(n):
"""
Helper function to determine if n is a prime number.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def prime... | from solution import prime_numbers_in_range
def test_prime_numbers_in_small_range():
assert prime_numbers_in_range(1, 10) == [2, 3, 5, 7]
def test_prime_numbers_in_medium_range():
assert prime_numbers_in_range(10, 20) == [11, 13, 17, 19]
def test_prime_numbers_with_no_primes():
assert prime_numbers_i... | [
{
"docstring": "Helper function to determine if n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all prime numbers between start and end (inclusive).",
"function_declaration": "def... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \n :param n: An integer to check for prime status\n :return: True if n is a prime number, False otherwise\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00082934",
"row_id": 82934,
"seed_ids": "['gemma-2-27b-it_168239']"
} | 0.728521 | Filter_82934 | I | [
"is_prime",
"prime_numbers_in_range"
] | 2 | [
[
"prime_numbers_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a3b2f84d1e39e16ef16fbe43ed909535ee6412a3 | 05480d9ae97bd30c7f819d9b6630cfb12fe94f0c | |||
v1.0 | instruct | Filter | Filter_83006_I | This is the code for a text adventure game.
```python
inventory = []
def show_inventory():
if inventory:
print("You have:")
for item in inventory:
print(f"- {item}")
else:
print("Your inventory is empty.")
def take_item(item):
inventory.append(item)
print(f"You took the {item}.")
def drop_... | inventory = []
def show_inventory():
if inventory:
print("You have:")
for item in inventory:
print(f"- {item}")
else:
print("Your inventory is empty.")
def take_item(item):
inventory.append(item)
print(f"You took the {item}.")
def drop_item(item):
if item in in... | from solution import inventory, take_item, drop_item, show_inventory, process_command
def test_take_item():
inventory.clear()
take_item("shield")
assert "shield" in inventory
def test_drop_item():
inventory.clear()
take_item("shield")
drop_item("shield")
assert "shield" not in inventory
d... | [
{
"docstring": null,
"function_declaration": "def show_inventory():",
"function_name": "show_inventory",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def take_item(item):",
"function_name": "take_item",
"parameter_list": "(item)"
},
{
"docstring... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "inventory = []\n\ndef show_inventory():\n if inventory:\n print(\"You have:\")\n for item in inventory:\n print(f\"- {item}\")\n else:\n print(\"Your inve... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00083006",
"row_id": 83006,
"seed_ids": "['gemma-2-27b-it_168431']"
} | 0.323569 | Filter_83006 | I | [
"show_inventory",
"take_item",
"drop_item",
"process_command",
"game_loop"
] | 5 | [
[
"game_loop",
"process_command"
],
[
"game_loop",
"show_inventory"
],
[
"process_command",
"drop_item"
],
[
"process_command",
"take_item"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 53a5f71ce53872482cb2cc0eabeab5079734aeb2 | 3a43b71fc06a3ba469756252e71a3998a0b9ee10 | |||
v1.0 | instruct | Filter | Filter_83024_I | The challenge: Implement a simple text-based adventure game in Python where the player explores a forest, encounters obstacles, and makes choices that affect the outcome.
Key Features:
Text-based interaction: The game will use text prompts and descriptions to guide the player.
Choice-driven narrative: The ... | def start_game():
print("You are a lone traveler exploring a dense forest. The path forks ahead, leading to a rushing river and a dark cave.")
choice = input("Which path will you take? (river/cave): ").strip().lower()
if choice == 'river':
river_path()
elif choice == 'cave':
cave_path()
... | from solution import river_path, cave_path
def test_river_path_build_raft(monkeypatch, capsys):
monkeypatch.setattr('builtins.input', lambda _: 'build a raft')
river_path()
captured = capsys.readouterr()
assert "successfully built a raft" in captured.out
def test_river_path_search_for_bridge(monkeypat... | [
{
"docstring": null,
"function_declaration": "def start_game():",
"function_name": "start_game",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def river_path():",
"function_name": "river_path",
"parameter_list": "()"
},
{
"docstring": null,
"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_game():\n print(\"You are a lone traveler exploring a dense forest.\")\n print(\"The path forks ahead, leading to a rushing river and a dark cave.\")\n choice = input(\"Whic... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00083024",
"row_id": 83024,
"seed_ids": "['gemma-2-27b-it_168492']"
} | 0.473183 | Filter_83024 | I | [
"start_game",
"river_path",
"cave_path"
] | 3 | [
[
"start_game",
"cave_path"
],
[
"start_game",
"river_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 36365373ba73b4794b97d52e62ea4d92f47a02cb | d2a05bcbed4e4af5a68b88863739df08a0d80741 | |||
v1.0 | instruct | Filter | Filter_83025_I | These are the rules for a game:
* There are 52 cards in a deck.
* The game uses only the number cards (2 through 10)
* The goal is to get as close to 21 as possible without going over.
* Each player is dealt two cards face up.
* The dealer is dealt one card face up and one card face down.
* Players can choose to "h... | import random
def draw_card():
"""
Returns a random card from a standard deck of cards.
"""
return random.randint(2, 10)
def calculate_hand_value(hand):
"""
Returns the sum of the values of the cards in the hand.
"""
return sum(hand)
def dealer_turn(dealer_hand):
"""
Simulates... | from solution import draw_card, calculate_hand_value, dealer_turn, player_turn, game_simulation, example_player_choice_func
def test_draw_card():
card = draw_card()
assert 2 <= card <= 10
def test_calculate_hand_value():
hand = [5, 7, 9]
assert calculate_hand_value(hand) == sum(hand)
def test_dealer_... | [
{
"docstring": "Returns a random card from a standard deck of cards.",
"function_declaration": "def draw_card():",
"function_name": "draw_card",
"parameter_list": "()"
},
{
"docstring": "Returns the sum of the values of the cards in the hand.",
"function_declaration": "def calculate_hand... | [
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\nclass Blackjack:\n def __init__(self):\n self.deck = [2, 3, 4, 5, 6, 7, 8, 9, 10] * 4\n random.shuffle(self.deck)\n self.player_hand = []\n self... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00083025",
"row_id": 83025,
"seed_ids": "['gemma-2-27b-it_168494']"
} | 0.61078 | Filter_83025 | I | [
"draw_card",
"calculate_hand_value",
"dealer_turn",
"player_turn",
"game_simulation",
"example_player_choice_func"
] | 6 | [
[
"dealer_turn",
"calculate_hand_value"
],
[
"dealer_turn",
"draw_card"
],
[
"example_player_choice_func",
"calculate_hand_value"
],
[
"game_simulation",
"dealer_turn"
],
[
"game_simulation",
"draw_card"
],
[
"game_simulation",
"player_turn"
],
... | 8 | [] | false | [] | false | pytest | true | [] | true | a0ab787db6d86ceeaf6946d275e7b0411781ca59 | eb1782997a48631ef306effd429059cf11b5cd9a | |||
v1.0 | instruct | Filter | Filter_83031_I | Objective:
To create a Python program that simulates a dice rolling simulator.
Features:
The program should allow the user to choose the number of dice to roll.
The program should allow the user to choose the number of sides on each die.
The program should display the results of each roll.
The program sh... | import random
def roll_dice(num_dice, num_sides):
"""
Rolls a specified number of dice with a specified number of sides.
Parameters:
num_dice (int): Number of dice to roll.
num_sides (int): Number of sides on each die.
Returns:
list: A list of results from each roll.
"""
r... | from solution import roll_dice, simulate_dice_rolls
def test_roll_dice_single_die():
rolls = roll_dice(1, 6)
assert len(rolls) == 1
assert 1 <= rolls[0] <= 6
def test_roll_dice_multiple_dice():
rolls = roll_dice(5, 6)
assert len(rolls) == 5
for roll in rolls:
assert 1 <= roll <= 6
def... | [
{
"docstring": "Rolls a specified number of dice with a specified number of sides.\n\nParameters:\nnum_dice (int): Number of dice to roll.\nnum_sides (int): Number of sides on each die.\n\nReturns:\nlist: A list of results from each roll.",
"function_declaration": "def roll_dice(num_dice, num_sides):",
... | [
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 roll_dice(num_dice, num_sides):\n \"\"\"\n Rolls a specified number of dice with a specified number of sides.\n \n Parameters:\n num_dice (int): Number of d... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00083031",
"row_id": 83031,
"seed_ids": "['gemma-2-27b-it_168515']"
} | 0.661638 | Filter_83031 | I | [
"roll_dice",
"simulate_dice_rolls"
] | 2 | [
[
"simulate_dice_rolls",
"roll_dice"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a6f20d376aac16b853ac934b917538333dda16ab | 7c2df7ebf215f96678e711f7e4c8d7949725423e | |||
v1.0 | instruct | Filter | Filter_83063_I | This is a question for a coding interview.
**Problem:**
Given a string `s`, find the longest palindromic substring in `s`.
**Example:**
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
**Follow Up:**
Can you solve it in O(n) time complexity? | def longest_palindromic_substring(s):
"""
Returns the longest palindromic substring in the given string s.
:param s: A string input.
:return: The longest palindromic substring in s.
"""
if not s:
return ""
n = len(s)
start = end = 0
for i in range(n):
l... | from solution import longest_palindromic_substring
def test_palindrome_in_middle():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
def test_single_character():
assert longest_palindromic_substring("a") == "a"
def test_all_characters_same():
assert longest_palindromic_substring("aaaa") ==... | [
{
"docstring": "Returns the longest palindromic substring in the given string s.\n\n:param s: A string input.\n:return: The longest palindromic substring in s.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_list": "(s)"... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s):\n \"\"\"\n Returns the longest palindromic substring in the given string s.\n\n :param s: A string input.\n :return: The longest palindromic s... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00083063",
"row_id": 83063,
"seed_ids": "['gemma-2-27b-it_168612']"
} | 0.796762 | Filter_83063 | I | [
"longest_palindromic_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c5308bfe30e19ca20097ce25a99b76e911a653a | bc7f4a3aa7098cd5056aa946906e9f79a8fa07b6 | |||
v1.0 | instruct | Filter | Filter_83088_I | The purpose of this code is to implement a simple AI that can play tic-tac-toe. The code uses a minimax algorithm with alpha-beta pruning to determine the best move for the AI. | import math
def is_winner(board, player):
"""
Check if the player has won the game.
"""
win_conditions = [
[board[0], board[1], board[2]],
[board[3], board[4], board[5]],
[board[6], board[7], board[8]],
[board[0], board[3], board[6]],
[board[1], board[4], board[7... | from solution import is_winner, is_board_full, get_available_moves, minimax, find_best_move
def test_is_winner():
board = ['X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
assert is_winner(board, 'X') == True
board = ['O', ' ', ' ', ' ', 'O', ' ', ' ', ' ', 'O']
assert is_winner(board, 'O') == True
b... | [
{
"docstring": "Check if the player has won the game.",
"function_declaration": "def is_winner(board, player):",
"function_name": "is_winner",
"parameter_list": "(board, player)"
},
{
"docstring": "Check if the board is full.",
"function_declaration": "def is_board_full(board):",
"fu... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimax(board, depth, is_maximizing, alpha, beta):\n winner = check_winner(board)\n if winner is not None:\n return scores[winner]\n \n if is_maximizing:\n max_ev... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00083088",
"row_id": 83088,
"seed_ids": "['gemma-2-27b-it_168694']"
} | 0.466761 | Filter_83088 | I | [
"is_winner",
"is_board_full",
"get_available_moves",
"minimax",
"find_best_move"
] | 5 | [
[
"find_best_move",
"get_available_moves"
],
[
"find_best_move",
"minimax"
],
[
"minimax",
"get_available_moves"
],
[
"minimax",
"is_board_full"
],
[
"minimax",
"is_winner"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 5267f691bd7c1f4991742755460e5188d8c0ca7d | 0b856fb127bfc297b4a6acb513d2ccf643b3eb27 | |||
v1.0 | instruct | Filter | Filter_83090_I | This is a Python code snippet:
```python
def add_one(x):
return x + 1
numbers = [1, 2, 3, 4, 5]
mapped_numbers = list(map(add_one, numbers))
print(mapped_numbers)
```
This code uses the `map()` function to apply the `add_one` function to each element in the `numbers` list.
**Can you explain how this code works... | def add_one(x):
"""
Returns the value of x incremented by 1.
"""
return x + 1
def map_add_one(numbers):
"""
Applies the add_one function to each element in the list of numbers.
Parameters:
numbers (list): A list of integers.
Returns:
list: A new list with each element ... | from solution import add_one, map_add_one
def test_add_one():
assert add_one(1) == 2
assert add_one(0) == 1
assert add_one(-1) == 0
def test_map_add_one():
assert map_add_one([1, 2, 3, 4, 5]) == [2, 3, 4, 5, 6]
assert map_add_one([-1, 0, 1]) == [0, 1, 2]
assert map_add_one([0]) == [1]
asse... | [
{
"docstring": "Returns the value of x incremented by 1.",
"function_declaration": "def add_one(x):",
"function_name": "add_one",
"parameter_list": "(x)"
},
{
"docstring": "Applies the add_one function to each element in the list of numbers.\n\nParameters:\nnumbers (list): A list of integers... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add_one(x):\n \"\"\"\n Returns x incremented by 1.\n \"\"\"\n return x + 1\n\ndef apply_map_add_one(numbers):\n \"\"\"\n Applies the add_one function to each element in t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00083090",
"row_id": 83090,
"seed_ids": "['gemma-2-27b-it_168696']"
} | 0.506702 | Filter_83090 | I | [
"add_one",
"map_add_one"
] | 2 | [
[
"map_add_one",
"add_one"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b89e6a1a70a7a2e6cc51f61e4f83e4ed326807bb | cbafd9e0c5bba9d8f94f2a1693d3211bcb2e22de | |||
v1.0 | instruct | Filter | Filter_83103_I | This problem asks you to create a text-based adventure game, using Python. You should use functions to organize your code, and allow the player to make choices that affect the outcome of the game.**
```python
def start_game():
"""Prints the game introduction and gets player name."""
print("Welcome to the Text ... | def start_game():
"""Prints the game introduction and gets the player's name."""
print("Welcome to the Text Adventure!")
name = input("What is your name, adventurer? ")
print(f"Hello, {name}! Your adventure begins now.")
return name
def choose_path():
"""Allows the player to choose a path in th... | import pytest
from solution import start_game, choose_path, dark_forest, sunny_fields, play_game
def test_dark_forest(monkeypatch):
monkeypatch.setattr('builtins.input', lambda _: "1")
result = dark_forest()
assert result == "forest"
def test_sunny_fields(monkeypatch):
monkeypatch.setattr('builtins.in... | [
{
"docstring": "Prints the game introduction and gets the player's name.",
"function_declaration": "def start_game():",
"function_name": "start_game",
"parameter_list": "()"
},
{
"docstring": "Allows the player to choose a path in the adventure.",
"function_declaration": "def choose_path... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_game():\n \"\"\"\n Prints the game introduction and gets player name.\n The player then makes choices that affect the outcome.\n \"\"\"\n print(\"Welcome to the Text A... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00083103",
"row_id": 83103,
"seed_ids": "['gemma-2-27b-it_168740']"
} | 0.445203 | Filter_83103 | I | [
"start_game",
"choose_path",
"dark_forest",
"sunny_fields",
"play_game"
] | 5 | [
[
"play_game",
"choose_path"
],
[
"play_game",
"dark_forest"
],
[
"play_game",
"start_game"
],
[
"play_game",
"sunny_fields"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b2a0b23b145a290eb6c5ff63cab15fbaff6e1267 | 2d311520ea763942beb38c9783783a43fd5d048f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.