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_40840_I | Program a function to remove all prime numbers from an array of integers. The function should also return the sum of the remaining numbers in the array after the prime numbers have been removed. | def is_prime(num):
"""
Checks if a number is prime.
"""
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def remove_primes_and_sum(arr):
"""
Removes prime numbers from the array and returns the sum of ... | from solution import remove_primes_and_sum
def test_remove_primes_and_sum_all_primes():
assert remove_primes_and_sum([2, 3, 5, 7, 11]) == ([], 0)
def test_remove_primes_and_sum_mixed_numbers():
assert remove_primes_and_sum([2, 4, 6, 7, 9]) == ([4, 6, 9], 19)
def test_remove_primes_and_sum_no_primes():
as... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Removes prime numbers from the array and returns the sum of the remaining numbers.",
"function_declaration": "def remove_... | [
1,
0,
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 Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040840",
"row_id": 40840,
"seed_ids": "['Qwen2-72B-Instruct_89130']"
} | 0.616505 | Filter_40840 | I | [
"is_prime",
"remove_primes_and_sum"
] | 2 | [
[
"remove_primes_and_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9b55b6ee217e43ffdbd1de1dd2b7fdd2dce5b6c | ca12f3f4c6936c17ecc0bd93fb77ebfadacef9c2 | |||
v1.0 | instruct | Filter | Filter_40844_I | Find the longest common substring between two given strings. The substring should contain only alphabetic characters. The solution should have a time complexity of O(n), where n is the length of the longer string. Additionally, the solution should not use any built-in functions or libraries for string manipulation. | def is_alpha(c):
"""
Returns True if the character c is an alphabetic character.
"""
return 'A' <= c <= 'Z' or 'a' <= c <= 'z'
def longest_common_substring_alpha(s1, s2):
"""
Returns the longest common substring of s1 and s2 that contains only alphabetic characters.
"""
max_len = 0
... | from solution import is_alpha, longest_common_substring_alpha
def test_is_alpha():
assert is_alpha('a') == True
assert is_alpha('Z') == True
assert is_alpha('1') == False
assert is_alpha('!') == False
assert is_alpha(' ') == False
def test_longest_common_substring_alpha_basic():
assert longest... | [
{
"docstring": "Returns True if the character c is an alphabetic character.",
"function_declaration": "def is_alpha(c):",
"function_name": "is_alpha",
"parameter_list": "(c)"
},
{
"docstring": "Returns the longest common substring of s1 and s2 that contains only alphabetic characters.",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_common_substring(s1, s2):\n \"\"\"\n Finds the longest common substring between two given strings that contains only alphabetic characters.\n \"\"\"\n # Function to che... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040844",
"row_id": 40844,
"seed_ids": "['Qwen2-72B-Instruct_89137']"
} | 0.664804 | Filter_40844 | I | [
"is_alpha",
"longest_common_substring_alpha"
] | 2 | [
[
"longest_common_substring_alpha",
"is_alpha"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a07d87d79b002b054a77fe2bf8e4c583479e1e3e | 425dd78eeec79672b144c3def9038b17c5b479f7 | |||
v1.0 | instruct | Filter | Filter_40864_I | Given an array of integers that includes positive and negative values, write a program that replaces all prime numbers in the array with their squares. | import math
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
... | from solution import is_prime, replace_primes_with_squares
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(-3) == False
assert is_prime(0) == False
assert is_prime(1) == False
def test_replace... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Replace all prime numbers in the array with their squares.",
"function_declaration": "def replace_primes_with_squares(arr):",
... | [
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, otherwise False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040864",
"row_id": 40864,
"seed_ids": "['Qwen2-72B-Instruct_89177']"
} | 0.504568 | Filter_40864 | I | [
"is_prime",
"replace_primes_with_squares"
] | 2 | [
[
"replace_primes_with_squares",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf0499279bbbba9c4a53b16161806738bc7ec2c0 | ff74d88b85da824a7f03aaafe0ece0a7d13736e0 | |||
v1.0 | instruct | Filter | Filter_40884_I | Write a recursive Python function to calculate the factorial of a number. Additionally, include error handling to verify if the input is a non-negative integer. Also, write a wrapper function that limits the maximum input value due to potential stack overflow from recursion. The wrapper function should politely inform ... | MAX_INPUT = 1000 # maximum limit for input to prevent stack overflow
def factorial_recursive(n):
"""
Recursively calculates the factorial of a number.
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Input must be a non-negative integer.")
if n == 0 or n == 1:
return 1
... | from solution import factorial, factorial_recursive, MAX_INPUT
def test_factorial_base_cases():
assert factorial(0) == 1
assert factorial(1) == 1
def test_factorial_small_numbers():
assert factorial(5) == 120
assert factorial(3) == 6
def test_factorial_large_numbers():
assert factorial(10) == 362... | [
{
"docstring": "Recursively calculates the factorial of a number.",
"function_declaration": "def factorial_recursive(n):",
"function_name": "factorial_recursive",
"parameter_list": "(n)"
},
{
"docstring": "Wrapper function that checks for maximum input value and calls the recursive factorial... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def factorial(n):\n \"\"\"\n Recursive function to calculate factorial of a non-negative integer n.\n \"\"\"\n if n < 0:\n raise ValueError(\"Input must be a non-negative in... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040884",
"row_id": 40884,
"seed_ids": "['Qwen2-72B-Instruct_89210']"
} | 0.672309 | Filter_40884 | I | [
"factorial_recursive",
"factorial"
] | 2 | [
[
"factorial",
"factorial_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1107658410cf1dd6b2782cc0f879fe6ed25669ad | 885bb58b2d473835bfc2d9f758bcdc4f2a8857ef | |||
v1.0 | instruct | Filter | Filter_40885_I | Write a code to generate an array of prime numbers from 1 to 10,000. However, you are only allowed to use the Sieve of Eratosthenes algorithm to generate the prime numbers. Additionally, optimize your code to have a time complexity of O(n log(log n)). | def sieve_of_eratosthenes(n):
"""
Returns a list of prime numbers from 1 to n using the Sieve of Eratosthenes algorithm.
"""
is_prime = [True] * (n + 1)
p = 2
while p * p <= n:
if is_prime[p]:
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1... | from solution import prime_numbers_up_to_10000
def test_prime_numbers_up_to_10000_length():
primes = prime_numbers_up_to_10000()
assert len(primes) == 1229
def test_prime_numbers_up_to_10000_contains_primes():
primes = prime_numbers_up_to_10000()
known_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
... | [
{
"docstring": "Returns a list of prime numbers from 1 to n using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers from 1 to 10,... | [
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(limit):\n \"\"\"\n Generate an array of prime numbers from 1 to 'limit' using the Sieve of Eratosthenes algorithm.\n \"\"\"\n if limit < 2:\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040885",
"row_id": 40885,
"seed_ids": "['Qwen2-72B-Instruct_89211']"
} | 0.591622 | Filter_40885 | I | [
"sieve_of_eratosthenes",
"prime_numbers_up_to_10000"
] | 2 | [
[
"prime_numbers_up_to_10000",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ea3003a5d4e8cbb924a68ab415d87e7878a9286d | 8244dca44e9aaa90b03ded4135dc7d6ae68acffb | |||
v1.0 | instruct | Filter | Filter_40888_I | Initialize a new array to 0 of size 10 and implement a function that updates the array with factorial of index as the value at every point. The function to calculate the factorial should be implemented recursively and your solution should also handle overflow situations. | def initialize_array(size=10):
"""
Initializes an array of the given size with all elements set to 0.
"""
return [0] * size
def factorial(n):
"""
Computes the factorial of a given non-negative integer n using recursion.
"""
if n < 0:
raise ValueError("Factorial is not defined fo... | from solution import initialize_array, factorial, update_array_with_factorials
def test_initialize_array():
assert initialize_array(10) == [0] * 10
assert initialize_array(5) == [0] * 5
def test_factorial():
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(2) == 2
assert fact... | [
{
"docstring": "Initializes an array of the given size with all elements set to 0.",
"function_declaration": "def initialize_array(size=10):",
"function_name": "initialize_array",
"parameter_list": "(size=10)"
},
{
"docstring": "Computes the factorial of a given non-negative integer n using ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def initialize_array(size=10):\n \"\"\"\n Initializes an array of the given size with all elements set to 0.\n \"\"\"\n return [0] * size\n\ndef factorial(n):\n \"\"\"\n Comp... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00040888",
"row_id": 40888,
"seed_ids": "['Qwen2-72B-Instruct_89214']"
} | 0.521116 | Filter_40888 | I | [
"initialize_array",
"factorial",
"update_array_with_factorials"
] | 3 | [
[
"update_array_with_factorials",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6536a2b024df2ee8cf4d06220a3b34f81592853 | ffbc908b953c527cf2a1999982b3d8b2af98f472 | |||
v1.0 | instruct | Filter | Filter_40892_I | Write a code that sorts an array in descending order, but do not use any built-in sorting functions or methods. You can only use basic operations such as loops, conditional statements, and variable assignments. The input array will contain integers ranging from -1000 to 1000, and its length will be between 1 and 1000. ... | def merge_sort_desc(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort_desc(arr[:mid])
right = merge_sort_desc(arr[mid:])
return merge_desc(left, right)
def merge_desc(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if... | from solution import sort_descending
def test_sort_descending_with_positive_numbers():
assert sort_descending([1, 4, 2, 3]) == [4, 3, 2, 1]
def test_sort_descending_with_negative_numbers():
assert sort_descending([-1, -3, -2, -4]) == [-1, -2, -3, -4]
def test_sort_descending_with_mixed_numbers():
assert ... | [
{
"docstring": null,
"function_declaration": "def merge_sort_desc(arr):",
"function_name": "merge_sort_desc",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_desc(left, right):",
"function_name": "merge_desc",
"parameter_list": "(left, right)"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort_desc(arr):\n \"\"\"\n Sorts an array in descending order using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n # Split the arra... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040892",
"row_id": 40892,
"seed_ids": "['Qwen2-72B-Instruct_89225']"
} | 0.617671 | Filter_40892 | I | [
"merge_sort_desc",
"merge_desc",
"sort_descending"
] | 3 | [
[
"merge_sort_desc",
"merge_desc"
],
[
"sort_descending",
"merge_sort_desc"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 101ac467938d4862c2d0554779e8e20198791eec | 7543ca8010e5e78085c9ca579ae6fd28ac3eb87a | |||
v1.0 | instruct | Filter | Filter_40895_I | Write a Python program that can handle multiple addresses and print the city name, along with the country, only if the postal code is valid according to the given conditions. The program must support postal codes in the format of NNNN and NNN NNN. If the postal code is not in one of those formats, the program should pr... | import re
def validate_postal_code(postal_code):
"""Returns True if the postal code is in the format NNNN or NNN NNN."""
pattern = re.compile(r'^\d{4}$|^\d{3} \d{3}$')
return bool(pattern.match(postal_code))
def process_addresses(addresses):
"""
Takes a list of addresses and returns a list consist... | from solution import validate_postal_code, process_addresses
def test_validate_postal_code():
assert validate_postal_code("1234") == True
assert validate_postal_code("123 456") == True
assert validate_postal_code("123") == False
assert validate_postal_code("12345") == False
assert validate_postal_c... | [
{
"docstring": "Returns True if the postal code is in the format NNNN or NNN NNN.",
"function_declaration": "def validate_postal_code(postal_code):",
"function_name": "validate_postal_code",
"parameter_list": "(postal_code)"
},
{
"docstring": "Takes a list of addresses and returns a list con... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_postal_code(postal_code):\n \"\"\"\n Checks if the given postal code is valid.\n A valid postal code is either in the format of NNNN or NNN NNN.\n \"\"\"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040895",
"row_id": 40895,
"seed_ids": "['Qwen2-72B-Instruct_89228']"
} | 0.518394 | Filter_40895 | I | [
"validate_postal_code",
"process_addresses"
] | 2 | [
[
"process_addresses",
"validate_postal_code"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f211b9cffbd2bf0ded8da3c2eb087fd6a540d09 | ec881ee04a4aaa5f84c2effeb80d0a16d172878b | |||
v1.0 | instruct | Filter | Filter_40937_I | How do you return 'Documents and Settings' if current Operating System is Windows XP else return 'Home' on Python? | import platform
def get_special_directory():
"""
Returns 'Documents and Settings' if the current Operating System is Windows XP,
otherwise returns 'Home'.
"""
if is_windows_xp():
return 'Documents and Settings'
else:
return 'Home'
def is_windows_xp():
"""
Check if the c... | from unittest.mock import patch
from solution import get_special_directory, is_windows_xp
def test_get_special_directory_windows_xp():
with patch('platform.system', return_value='Windows'):
with patch('platform.version', return_value='5.1.2600'):
assert get_special_directory() == 'Documents and... | [
{
"docstring": "Returns 'Documents and Settings' if the current Operating System is Windows XP,\notherwise returns 'Home'.",
"function_declaration": "def get_special_directory():",
"function_name": "get_special_directory",
"parameter_list": "()"
},
{
"docstring": "Check if the current Operat... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import platform\n\ndef get_directory():\n \"\"\"\n Returns 'Documents and Settings' if the current Operating System is Windows XP,\n else returns 'Home'.\n \"\"\"\n os_version =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040937",
"row_id": 40937,
"seed_ids": "['Qwen2-72B-Instruct_89310']"
} | 0.472032 | Filter_40937 | I | [
"get_special_directory",
"is_windows_xp"
] | 2 | [
[
"get_special_directory",
"is_windows_xp"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cdb16d4a31a9910b53b24bb63a79e4f803c2d579 | 9eddacbf8ca5936e9198185a7fe052769483792a | |||
v1.0 | instruct | Filter | Filter_40960_I | Create medium complexity code involving the usage of the binary search algorithm with a twist. Rather than searching for an element in a sorted array, your task will be to find the position of a target element in an array that's sorted in ascending order, but has been rotated at some pivot unknown to you beforehand. | def find_pivot(arr):
low, high = 0, len(arr) - 1
while low < high:
mid = (low + high) // 2
if arr[mid] > arr[high]:
low = mid + 1
else:
high = mid
return low
def binary_search(arr, low, high, target):
while low <= high:
mid = (low + high) // 2
... | from solution import search_rotated_array
def test_search_rotated_array():
assert search_rotated_array([6,7,8,1,2,3,4,5], 3) == 5
assert search_rotated_array([6,7,8,1,2,3,4,5], 6) == 0
assert search_rotated_array([6,7,8,1,2,3,4,5], 1) == 3
assert search_rotated_array([4,5,6,7,0,1,2], 0) == 4
assert... | [
{
"docstring": null,
"function_declaration": "def find_pivot(arr):",
"function_name": "find_pivot",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, low, high, target):",
"function_name": "binary_search",
"parameter_list": "(arr, l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_in_rotated_sorted_array(nums, target):\n \"\"\"\n Searches for the target element in a rotated sorted array and returns its index.\n If the target is not found, returns -1.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040960",
"row_id": 40960,
"seed_ids": "['Qwen2-72B-Instruct_89343']"
} | 0.649026 | Filter_40960 | I | [
"find_pivot",
"binary_search",
"search_rotated_array"
] | 3 | [
[
"search_rotated_array",
"binary_search"
],
[
"search_rotated_array",
"find_pivot"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f8c1a04983b52015c3b56dc1a1d0b5f5451b06d9 | 28367188b28d067db385fbddf3480d058785b0da | |||
v1.0 | instruct | Filter | Filter_40964_I | Develop a code implementing the QuickSort algorithm to organize a list of decimal numbers. Also, implement a functionality to handle and check for any non-decimal input. Your program should segregate the decimal numbers from the non-decimal inputs, process only the decimal numbers for sorting and return the sorted list... | def quicksort(arr):
"""
Implements the QuickSort algorithm to sort a list of decimal numbers.
This function assumes that `arr` contains only decimal numbers.
"""
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
mid... | from solution import quicksort, sort_decimals_with_non_decimals
def test_quicksort_basic():
assert quicksort([3.2, 1.5, 2.8]) == [1.5, 2.8, 3.2]
def test_quicksort_empty():
assert quicksort([]) == []
def test_quicksort_single_element():
assert quicksort([1.5]) == [1.5]
def test_sort_decimals_with_non_de... | [
{
"docstring": "Implements the QuickSort algorithm to sort a list of decimal numbers.\nThis function assumes that `arr` contains only decimal numbers.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the decimal... | [
0,
1,
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 Implements the QuickSort algorithm to sort a list of decimal numbers.\n \"\"\"\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040964",
"row_id": 40964,
"seed_ids": "['Qwen2-72B-Instruct_89347']"
} | 0.560517 | Filter_40964 | I | [
"quicksort",
"sort_decimals_with_non_decimals"
] | 2 | [
[
"sort_decimals_with_non_decimals",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd8e860b2d34d8e6575608bf74f4ba213706e25d | bff5654e7418c3ce8b3a0e116ec68bfffd262fb5 | |||
v1.0 | instruct | Filter | Filter_41013_I | Write a Python function `powerful_prime_factors(number)` that takes an integer `number` as an argument. This function should return a list of the biggest prime factors of `number` and their respective powers, where each prime factor is also a power of a prime number. The output should be a list of tuples, each tuple co... | def prime_factors(n):
"""
Returns a dictionary of prime factors and their powers for the given number n.
"""
factors = {}
divisor = 2
while n > 1:
while n % divisor == 0:
if divisor in factors:
factors[divisor] += 1
else:
factors[di... | from solution import powerful_prime_factors
def test_powerful_prime_factors_of_small_numbers():
assert powerful_prime_factors(1) == []
assert powerful_prime_factors(2) == [(2, 1)]
assert powerful_prime_factors(3) == [(3, 1)]
assert powerful_prime_factors(4) == [(2, 2)]
assert powerful_prime_factors... | [
{
"docstring": "Returns a dictionary of prime factors and their powers for the given number n.",
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": "Checks if a number is a power of a prime number.",
"function_decl... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import defaultdict\n\ndef is_prime(n):\n \"\"\"Check if n is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041013",
"row_id": 41013,
"seed_ids": "['Qwen2-72B-Instruct_89431']"
} | 0.760031 | Filter_41013 | I | [
"prime_factors",
"is_power_of_prime",
"powerful_prime_factors"
] | 3 | [
[
"powerful_prime_factors",
"is_power_of_prime"
],
[
"powerful_prime_factors",
"prime_factors"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7b2a3212d704194a1c0bf394a2e47e2cf7b76d37 | 8209401bbc59ae1cf1279097c504ce0562566c2b | |||
v1.0 | instruct | Filter | Filter_41020_I | Please formulate a Python script capable of calculating the cumulative product of all prime numbers present between a defined range of integers. The said range includes integers from 2 up to and including 20. | def is_prime(n):
"""
Determines if a number 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 cumulative_prime_product(start, end):
"""
Calculates the cumulative product of all prime... | from solution import is_prime, cumulative_prime_product
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_cumulative_prime_product():
assert cumulative_prime_product(2, 10) ==... | [
{
"docstring": "Determines if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculates the cumulative product of all prime numbers in the given range [start, end].",
"function_declaration"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import prod\n\ndef 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 return False\n i = 5\n whi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041020",
"row_id": 41020,
"seed_ids": "['Qwen2-72B-Instruct_89449']"
} | 0.571975 | Filter_41020 | I | [
"is_prime",
"cumulative_prime_product"
] | 2 | [
[
"cumulative_prime_product",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 45138764507c7df219fa6a1598869ddb5f72ff17 | 58c994a5d66f4c68b25a30f7e060ee08101137cf | |||
v1.0 | instruct | Filter | Filter_41028_I | -design a console application with flask in python for vs code that accepts segmentation in frozen emails. The app needs an interactive UI design for users to exploit its functionalities perfectly. Majorly, the app must contain input validation to ensure only正规data is entered, and exceptions should be properly handled.... | from flask import Flask, request, jsonify
import re
app = Flask(__name__)
def is_valid_email(email):
"""
Validate email using regex.
"""
regex = r'^\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if re.match(regex, email):
return True
else:
return False
@app.route('/segme... | import pytest
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_segment_email_valid(client):
response = client.post('/segment_email', json={'email': 'test@example.com'})
assert response.status_code == 200
assert response.json == {'lo... | [
{
"docstring": "Validate email using regex.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": null,
"function_declaration": "def segment_email():",
"function_name": "segment_email",
"parameter_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nimport threading\n\napp = Flask(__name__)\n\n# A lock object to handle concurrency\nlock = threading.Lock()\n\n@app.route('/segment', methods=['POST'... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041028",
"row_id": 41028,
"seed_ids": "['Qwen2-72B-Instruct_89464']"
} | 0.347905 | Filter_41028 | I | [
"is_valid_email",
"segment_email"
] | 2 | [
[
"segment_email",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 70a3b00be64be15922f3e5e5b883e9d7e52c9d59 | 2143e80d834265ad99f26e1815ceaa2a7fcf70aa | |||
v1.0 | instruct | Filter | Filter_41032_I | Write a python function that encrypts a string using a Caesar cipher with a random key between 1 and 25, and decrypts it back to the original string. Also, include a check function with provided data points to verify the correctness of your solution. Make sure to take care of lower case and upper case letters separatel... | import random
def encrypt_caesar_cipher(text, shift):
result = []
for char in text:
if char.isupper():
shifted = chr((ord(char) + shift - 65) % 26 + 65)
result.append(shifted)
elif char.islower():
shifted = chr((ord(char) + shift - 97) % 26 + 97)
... | from solution import encrypt_caesar_cipher, decrypt_caesar_cipher, check_caesar_cipher
import random
def test_encrypt_caesar_cipher():
assert encrypt_caesar_cipher("Hello World", 3) == "Khoor Zruog"
def test_decrypt_caesar_cipher():
assert decrypt_caesar_cipher("Khoor Zruog", 3) == "Hello World"
def test_cae... | [
{
"docstring": null,
"function_declaration": "def encrypt_caesar_cipher(text, shift):",
"function_name": "encrypt_caesar_cipher",
"parameter_list": "(text, shift)"
},
{
"docstring": null,
"function_declaration": "def decrypt_caesar_cipher(text, shift):",
"function_name": "decrypt_cae... | [
1,
1,
0
] | 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 encrypt_caesar_cipher(text, key=None):\n \"\"\"\n Encrypt the given text using Caesar cipher with the provided key.\n If no key is provided, a rand... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041032",
"row_id": 41032,
"seed_ids": "['Qwen2-72B-Instruct_89469']"
} | 0.704345 | Filter_41032 | I | [
"encrypt_caesar_cipher",
"decrypt_caesar_cipher",
"check_caesar_cipher"
] | 3 | [
[
"check_caesar_cipher",
"decrypt_caesar_cipher"
],
[
"check_caesar_cipher",
"encrypt_caesar_cipher"
],
[
"decrypt_caesar_cipher",
"encrypt_caesar_cipher"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 596332e20741fbf453b740b2b1a32947fcfb8180 | a170e5db64898830fea30c32956b347b5b69cb3c | |||
v1.0 | instruct | Filter | Filter_41047_I | Write a type checker for a function and assign it to a variable, ensuring that the checker function itself is generic and can work with different data types. Then, implement a decorator using this type checker which can be used to validate the types of the arguments passed to a function. | from typing import Any, Callable, Tuple, Type
def type_checker(*args_types: Type, ret_type: Type) -> Callable:
"""
A type checker function which validates the types of arguments and the return type.
"""
def decorator(func: Callable) -> Callable:
def wrapper(*args: Any, **kwargs: Any) -> Any:
... | from solution import add, type_checker
def test_add_with_correct_types():
assert add(2, 3) == 5
def test_add_with_incorrect_arg_type():
try:
add(2, "3")
except TypeError:
assert True
else:
assert False
def test_add_with_incorrect_return_type():
@type_checker(int, int, ret_... | [
{
"docstring": "A type checker function which validates the types of arguments and the return type.",
"function_declaration": "def type_checker(*args_types, ret_type):",
"function_name": "type_checker",
"parameter_list": "(*args_types, ret_type)"
},
{
"docstring": null,
"function_declara... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import wraps\nfrom typing import Any, Callable, Tuple, Type\n\ndef type_checker(func: Callable) -> Callable:\n \"\"\"\n A decorator to check the types of the arguments pas... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041047",
"row_id": 41047,
"seed_ids": "['Qwen2-72B-Instruct_89492']"
} | 0.573957 | Filter_41047 | I | [
"type_checker",
"add"
] | 2 | [
[
"add",
"type_checker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac3d06356fb787788c83221c8c8fa0fe6610e49a | 5783ece343f27431241cee4e79d29b8540886a26 | |||
v1.0 | instruct | Filter | Filter_41052_I | Given a list of integers, create a new list in Python that contains the square of each element. Additionally, for each square, if it is divisible by a prime number, append the string "divisible by a prime" to the new list. If it is not divisible by any prime number, append the string "not divisible by a prime" instead. | 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 squares_and_prime_info
def test_squares_and_prime_info_basic():
assert squares_and_prime_info([2, 3]) == [
(4, 'divisible by a prime'),
(9, 'divisible by a prime')
]
def test_squares_and_prime_info_single_element():
assert squares_and_prime_info([4]) == [
(16, ... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return a list containing the square of each integer.\nFor each square, append \"divisible by a prime\" i... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Determine if the provided number n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041052",
"row_id": 41052,
"seed_ids": "['Qwen2-72B-Instruct_89498']"
} | 0.664449 | Filter_41052 | I | [
"is_prime",
"squares_and_prime_info"
] | 2 | [
[
"squares_and_prime_info",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6a9be20bf8ae2c7fa89f3446aa4e07895a5f229d | 1d5b9fbcba1c2b3e2f2643a95c915b4fedb6cd0e | |||
v1.0 | instruct | Filter | Filter_41053_I | Create a program to find the prime numbers in a list of positive integers. Also include error handling for cases in which the list might be empty or contains non-integer or non-numeric values. Additionally, include functionality such that if a parameter is passed that specifies only prime numbers strictly less than thi... | def is_prime(n):
"""
Returns True if the number is prime, otherwise False.
"""
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_primes(nums, less_than=None):
"""
Returns a list of prime numbers fro... | from solution import find_primes, is_prime
import pytest
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5) == False
def test_find_primes_regular_case():
assert f... | [
{
"docstring": "Returns True if the number is prime, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers from the input list. If the less_than parameter is provided,\nonly prime... | [
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.\n \"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041053",
"row_id": 41053,
"seed_ids": "['Qwen2-72B-Instruct_89499']"
} | 0.606373 | Filter_41053 | I | [
"is_prime",
"find_primes"
] | 2 | [
[
"find_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3df725e0c66eba9ff362a844d2225322d28389c1 | 216808b10323fbcceaba9fa4f82186b96ccc2c20 | |||
v1.0 | instruct | Filter | Filter_41058_I | Create a Python program that prints a welcome message based on the given user input, adapts the welcome message according to time, and considers potential capitalization and common abbreviations for morning (am/pm) in user input. Furthermore, ensure that the program can handle bad entries and display an appropriate err... | def get_time_of_day_period(user_input):
"""
Returns the time of day period based on the user input.
"""
user_input = user_input.lower().strip()
if 'am' in user_input or 'a.m.' in user_input:
return 'morning'
elif 'pm' in user_input or 'p.m.' in user_input:
return 'afternoon'
... | from solution import welcome_message, get_time_of_day_period
def test_get_time_of_day_period():
assert get_time_of_day_period("10 am") == 'morning'
assert get_time_of_day_period("10 A.M.") == 'morning'
assert get_time_of_day_period("11 pm") == 'afternoon'
assert get_time_of_day_period("23 p.m.") == 'af... | [
{
"docstring": "Returns the time of day period based on the user input.",
"function_declaration": "def get_time_of_day_period(user_input):",
"function_name": "get_time_of_day_period",
"parameter_list": "(user_input)"
},
{
"docstring": "Generate a welcome message based on user input time peri... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def get_time_of_day_period(user_input):\n \"\"\"\n Returns the time of day period based on the user input.\n \"\"\"\n user_input = user_input.lower().strip()\n if 'am' in user_i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041058",
"row_id": 41058,
"seed_ids": "['Qwen2-72B-Instruct_89513']"
} | 0.394354 | Filter_41058 | I | [
"get_time_of_day_period",
"welcome_message"
] | 2 | [
[
"welcome_message",
"get_time_of_day_period"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2f95c8d1cf19fefbe3793708b39dfb39f44f46aa | e9a9e8c3c6b413a3d3c748cd2088b10d042baac8 | |||
v1.0 | instruct | Filter | Filter_41059_I | Use higher order functions to perform operations on the following list of numbers. For each operation, explain the use and benefits of higher order functions. Implement functions to find the sum, product, and average of all numbers in the list, but do not use conventional loop constructs or built-in methods such as `su... | from functools import reduce
def sum_of_list(numbers):
"""
Returns the sum of all numbers in the list using a higher-order function.
"""
return reduce(lambda x, y: x + y, numbers)
def product_of_list(numbers):
"""
Returns the product of all numbers in the list using a higher-order function.
... | from solution import sum_of_list, product_of_list, average_of_list
def test_sum_of_list():
assert sum_of_list([1, 2, 3, 4, 5]) == 15
assert sum_of_list([0, 0, 0, 0, 0]) == 0
assert sum_of_list([-1, -2, -3, -4, -5]) == -15
assert sum_of_list([1.5, 2.5, 3.5]) == 7.5
def test_product_of_list():
asser... | [
{
"docstring": "Returns the sum of all numbers in the list using a higher-order function.",
"function_declaration": "def sum_of_list(numbers):",
"function_name": "sum_of_list",
"parameter_list": "(numbers)"
},
{
"docstring": "Returns the product of all numbers in the list using a higher-orde... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import reduce\n\ndef sum_numbers(numbers):\n \"\"\"\n Returns the sum of all numbers in the list.\n \"\"\"\n return reduce(lambda x, y: x + y, numbers)\n\ndef produc... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041059",
"row_id": 41059,
"seed_ids": "['Qwen2-72B-Instruct_89514']"
} | 0.49872 | Filter_41059 | I | [
"sum_of_list",
"product_of_list",
"average_of_list"
] | 3 | [
[
"average_of_list",
"sum_of_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f916f51eaa0a1b731f9eeccf0e404fdef2d7b7c2 | 49660aa06bef1c87c49e603c0acddc6963716201 | |||
v1.0 | instruct | Filter | Filter_41071_I | Create novel code to simulate a double pendulum with friction and plot its chaotic time evolution using matplotlib in a web-based interactive platform. | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
def double_pendulum_equations(t, state, m1, m2, l1, l2, g, b1, b2):
"""
Defines the differential equations for the double pendulum with friction.
state: vector of the state variables [theta1, omega1, theta2, omega... | from solution import double_pendulum_equations, simulate_double_pendulum
def test_double_pendulum_equations():
t = 0
state = [np.pi/2, 0, np.pi, 0]
m1, m2 = 1.0, 1.0
l1, l2 = 1.0, 1.0
g = 9.81
b1, b2 = 0.1, 0.1
result = double_pendulum_equations(t, state, m1, m2, l1, l2, g, b1, b2)
asse... | [
{
"docstring": "Defines the differential equations for the double pendulum with friction.\n\nstate: vector of the state variables [theta1, omega1, theta2, omega2]\nm1, m2: masses of the pendulums\nl1, l2: lengths of the pendulums\ng: the acceleration due to gravity\nb1, b2: damping coefficients for the two pend... | [
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\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\ndef double_pendulum_with_friction_derivs(t, y, lengths, masses, g, friction):\n theta1, z1, the... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041071",
"row_id": 41071,
"seed_ids": "['Qwen2-72B-Instruct_89536']"
} | 0.460044 | Filter_41071 | I | [
"double_pendulum_equations",
"simulate_double_pendulum",
"plot_double_pendulum"
] | 3 | [
[
"simulate_double_pendulum",
"double_pendulum_equations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 0a93a80b89f63d8aa24d0461c5011958ab722b71 | a87b0507b6cb6221e90faad1de15f29ca08e60dd | |||
v1.0 | instruct | Filter | Filter_41080_I | Create a Python script that acts as a simple calculator with operations such as addition, subtraction, multiplication, division, and modulus. The script should be able to handle multiple calculations in a row before exiting. | def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def modulus(a, b):
return a % b
# Example function to handle operations
def calculator(operation, a, b):
... | from solution import add, subtract, multiply, divide, modulus, calculator
def test_add():
assert add(3, 2) == 5
assert add(-1, 5) == 4
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(5, -2) == 7
def test_multiply():
assert multiply(4, 3) == 12
assert multiply(5, 0) == 0
def t... | [
{
"docstring": null,
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def subtract(a, b):",
"function_name": "subtract",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n return a + b\n\ndef subtract(a, b):\n return a - b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divid... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041080",
"row_id": 41080,
"seed_ids": "['Qwen2-72B-Instruct_89554']"
} | 0.525237 | Filter_41080 | I | [
"add",
"subtract",
"multiply",
"divide",
"modulus",
"calculator"
] | 6 | [
[
"calculator",
"add"
],
[
"calculator",
"divide"
],
[
"calculator",
"modulus"
],
[
"calculator",
"multiply"
],
[
"calculator",
"subtract"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 161b54ba927406de2981b8d28364737036cfa190 | 4756c756a828a9f8432b1b5a8625bf637fe957c1 | |||
v1.0 | instruct | Filter | Filter_41088_I | Write a Python script that not only crafts a function for implementing numeric summation operation for three integer or floating-point number inputs, but also performs error-checking to ensure the inputs are indeed numeric. Once this function is created, use it to create a second function that accepts a list of tuples.... | def sum_three_numbers(a, b, c):
"""
Returns the sum of three numbers a, b, and c if all inputs are numeric.
Raises ValueError if any input is not numeric.
"""
if not all(isinstance(x, (int, float)) for x in [a, b, c]):
raise ValueError("All inputs must be numeric.")
return a + b + c
def... | from solution import sum_three_numbers, process_tuples
def test_sum_three_numbers():
assert sum_three_numbers(1, 2, 3) == 6
assert sum_three_numbers(-1, -2, -3) == -6
assert sum_three_numbers(0, 0, 0) == 0
assert sum_three_numbers(1.5, 2.5, 3) == 7.0
def test_sum_three_numbers_invalid_input():
try... | [
{
"docstring": "Returns the sum of three numbers a, b, and c if all inputs are numeric.\nRaises ValueError if any input is not numeric.",
"function_declaration": "def sum_three_numbers(a, b, c):",
"function_name": "sum_three_numbers",
"parameter_list": "(a, b, c)"
},
{
"docstring": "Takes a ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sum_three_numbers(a, b, c):\n \"\"\"\n Returns the sum of three numbers a, b, and c.\n Raises ValueError if any of the inputs are not numeric.\n \"\"\"\n if not all(isinstan... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041088",
"row_id": 41088,
"seed_ids": "['Qwen2-72B-Instruct_89569']"
} | 0.630108 | Filter_41088 | I | [
"sum_three_numbers",
"process_tuples"
] | 2 | [
[
"process_tuples",
"sum_three_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd8989d2f2161603bc59bdfce1be0764e92e0271 | d8852a4bfcfe9cbf5ba0a8a9365b2a692fe6cb15 | |||
v1.0 | instruct | Filter | Filter_41090_I | You should implement the binary search algorithm in a programming language of your choice. However, there is a twist. Your code should handle arrays that are cyclically shifted. This means that the sorted array has been rotated an unknown number of times. Additionally, discuss the time and space complexity of your solu... | def find_min_index(arr):
low, high = 0, len(arr) - 1
while low < high:
mid = (low + high) // 2
if arr[mid] > arr[high]:
low = mid + 1
else:
high = mid
return low
def binary_search(arr, target, low, high):
while low <= high:
mid = (low + high) // 2... | from solution import search_in_shifted_array, find_min_index, binary_search
def test_find_min_index():
assert find_min_index([3, 4, 5, 1, 2]) == 3
assert find_min_index([4, 5, 6, 7, 0, 1, 2]) == 4
assert find_min_index([1, 2, 3, 4, 5]) == 0
def test_binary_search():
assert binary_search([1, 2, 3, 4, 5... | [
{
"docstring": null,
"function_declaration": "def find_min_index(arr):",
"function_name": "find_min_index",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def binary_search(arr, target, low, high):",
"function_name": "binary_search",
"parameter_list": ... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_min_index(arr):\n low, high = 0, len(arr) - 1\n while low < high:\n mid = (low + high) // 2\n if arr[mid] > arr[high]:\n low = mid + 1\n else:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041090",
"row_id": 41090,
"seed_ids": "['Qwen2-72B-Instruct_89573']"
} | 0.733625 | Filter_41090 | I | [
"find_min_index",
"binary_search",
"search_in_shifted_array"
] | 3 | [
[
"search_in_shifted_array",
"binary_search"
],
[
"search_in_shifted_array",
"find_min_index"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9c08e6959e451ae813f8baa2049c6303d85aa18e | ac46145d44cb1535da2bd0ca8ff0eb697e29657f | |||
v1.0 | instruct | Filter | Filter_41091_I | Construct the transpose of a given 3x3 matrix using Python. Additionally, you should implement your solution using recursion instead of using any built-in functions or libraries. | def transpose(matrix, row=0, col=0, result=None):
"""
Returns the transpose of a 3x3 matrix using recursion.
"""
if result is None:
result = [[0]*3 for _ in range(3)]
if col >= 3:
return result
result[col][row] = matrix[row][col]
if row < 2:
return tran... | from solution import transpose_3x3
def test_transpose_identity_matrix():
matrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
expected = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
assert transpose_3x3(matrix) == expected
def test_transpose_symmetric_matrix():
m... | [
{
"docstring": "Returns the transpose of a 3x3 matrix using recursion.",
"function_declaration": "def transpose(matrix, row=0, col=0, result=None):",
"function_name": "transpose",
"parameter_list": "(matrix, row=0, col=0, result=None)"
},
{
"docstring": null,
"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 transpose_matrix(matrix):\n \"\"\"\n Transposes a 3x3 matrix using recursion.\n \"\"\"\n def transpose_recursive(m, i=0, j=0, transposed=None):\n if transposed is None:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041091",
"row_id": 41091,
"seed_ids": "['Qwen2-72B-Instruct_89574']"
} | 0.529288 | Filter_41091 | I | [
"transpose",
"transpose_3x3"
] | 2 | [
[
"transpose_3x3",
"transpose"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 934542b2885f75afdb7919d19d9ed3b88b67e506 | ed1d33cfafe7706f369219ac2a4fca8899653044 | |||
v1.0 | instruct | Filter | Filter_41106_I | Given a JSON string, write a Python function to parse and organize the contents of the object. The function should handle nested arrays and objects, as well as an arbitrary depth of nesting within the JSON string. Additionally, the function should validate the JSON string before parsing it, checking for the presence of... | import json
def validate_json(json_data, schema):
"""
Validates JSON data against a given schema.
:param json_data: The JSON data to validate.
:param schema: The schema to validate against.
:return: True if valid, raises ValueError otherwise.
"""
for key, value in schema.items():
... | from solution import parse_json, validate_json
import pytest
def test_parse_json_valid():
schema = {
"name": str,
"age": int,
"address": dict,
}
json_string = '{"name": "John", "age": 30, "address": {"city": "New York", "zipcode": "10001"}}'
result = parse_json(json_string, sche... | [
{
"docstring": "Validates JSON data against a given schema.\n\n:param json_data: The JSON data to validate.\n:param schema: The schema to validate against.\n:return: True if valid, raises ValueError otherwise.",
"function_declaration": "def validate_json(json_data, schema):",
"function_name": "validate_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\ndef validate_json(data, schema):\n \"\"\"\n Recursively validate the JSON data against the schema.\n \"\"\"\n if not isinstance(schema, dict):\n raise ValueEr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041106",
"row_id": 41106,
"seed_ids": "['Qwen2-72B-Instruct_89593']"
} | 0.607755 | Filter_41106 | I | [
"validate_json",
"parse_json"
] | 2 | [
[
"parse_json",
"validate_json"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3b19fd6450a1e93b59a85d43b3d191f3dfde0f9a | 547f1bcbcf0266bad0944d22a9fec50e94d61fd9 | |||
v1.0 | instruct | Filter | Filter_41109_I | Develop an enhanced version of the function 'locate_numbers'. This function should return a tuple (a, b, c, d) where 'a' is the smallest prime number and 'b' is the largest prime number in the list. Also, 'c' should be the smallest non-prime number, while 'd' is the largest non-prime number in the list. If there are no... | def is_prime(num):
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
return True
def locate_numbers(lst):
if not lst:
return (None, None, Non... | from solution import locate_numbers
def test_locate_numbers_all_primes():
assert locate_numbers([2, 3, 5, 7, 11]) == (2, 11, None, None)
def test_locate_numbers_all_non_primes():
assert locate_numbers([1, 4, 6, 8, 9]) == (None, None, 1, 9)
def test_locate_numbers_mixed():
assert locate_numbers([1, 2, 3, ... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def locate_numbers(lst):",
"function_name": "locate_numbers",
"parameter_list": "(lst)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n for i in range(3, int(num**0.5) + 1, 2):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041109",
"row_id": 41109,
"seed_ids": "['Qwen2-72B-Instruct_89597']"
} | 0.630679 | Filter_41109 | I | [
"is_prime",
"locate_numbers"
] | 2 | [
[
"locate_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 640c08ca29616034ad769e1587066f1162bb952f | 548401b2751167c82750e2513e099a9fb9be4f00 | |||
v1.0 | instruct | Filter | Filter_41123_I | Implement a program using Python to demonstrate the concept of shallow and deep copy. Explain the differences and show scenarios where each would be most appropriately used. | import copy
def shallow_copy_example(original_list):
"""
Demonstrates shallow copy by copying the original list using copy() method.
Args:
original_list (list): The list to be copied.
Returns:
list: A shallow copy of the original list.
"""
shallow_copied_list = original_list.c... | from solution import shallow_copy_example, deep_copy_example, illustrate_copies
def test_shallow_copy():
original_list = [1, 2, [3, 4]]
shallow_copied_list = shallow_copy_example(original_list)
assert shallow_copied_list == original_list
assert shallow_copied_list is not original_list
ori... | [
{
"docstring": "Demonstrates shallow copy by copying the original list using copy() method.\n\nArgs:\noriginal_list (list): The list to be copied.\n\nReturns:\nlist: A shallow copy of the original list.",
"function_declaration": "def shallow_copy_example(original_list):",
"function_name": "shallow_copy_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import copy\n\ndef demonstrate_copy():\n explanation = {\n 'shallow_copy': 'A shallow copy creates a new object, but inserts references into it to the objects found in the original.'... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041123",
"row_id": 41123,
"seed_ids": "['Qwen2-72B-Instruct_89621']"
} | 0.414575 | Filter_41123 | I | [
"shallow_copy_example",
"deep_copy_example",
"illustrate_copies"
] | 3 | [
[
"illustrate_copies",
"deep_copy_example"
],
[
"illustrate_copies",
"shallow_copy_example"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 81582b27c4bc9938f867f4e936143269ee557765 | 7f41ffae2da30ce255e61398bc856d29504fcd99 | |||
v1.0 | instruct | Filter | Filter_41130_I | Develop a Python function capable of performing an arithmetic operation, whereby two provided numerical inputs are summed. Incorporate multi-step reasoning by both defining this operation and then applying it to an example dataset with a verification process to ensure the accuracy of operation implementation. | def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
def sum_dataset(dataset):
"""
Takes a list of tuples as input, where each tuple contains two numbers.
Returns a list of sums of each tuple.
Example: [(1,2), (3,4)] -> [3, 7]
"""
return [add(a, b) for (a, b) in datas... | from solution import add, sum_dataset
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_with_zero():
assert add(0, 5) == 5
assert add(5, 0) == 5
def test_add_negative_numbers():
assert add(-1, -1) == -2
def test_add_mixed_sign_numbers():
assert add(-1, 3) == 2
def test_sum_dat... | [
{
"docstring": "Returns the sum of a and b.",
"function_declaration": "def add(a, b):",
"function_name": "add",
"parameter_list": "(a, b)"
},
{
"docstring": "Takes a list of tuples as input, where each tuple contains two numbers.\nReturns a list of sums of each tuple.\nExample: [(1,2), (3,4)... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def add(a, b):\n \"\"\"\n Returns the sum of a and b.\n \"\"\"\n return a + b\n\ndef verify_sum_with_example_dataset(data):\n \"\"\"\n Verifies the sum operation with an exam... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041130",
"row_id": 41130,
"seed_ids": "['Qwen2-72B-Instruct_89635']"
} | 0.524854 | Filter_41130 | I | [
"add",
"sum_dataset"
] | 2 | [
[
"sum_dataset",
"add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d994ce1b552b33e8f9f2ceda79616f1296fcf54 | 8431d5925f8314b79f24b8628c13aa65e36c9125 | |||
v1.0 | instruct | Filter | Filter_41137_I | Please write a Python function that implements the ID3 algorithm for decision tree learning. Additionally, provide a detailed explanation of the ID3 algorithm and how it operates, including how it chooses the best attribute to split the data and how it handles continuous valued attributes. | import numpy as np
import pandas as pd
def entropy(y):
"""
Calculate the entropy of label array y.
"""
unique_labels = np.unique(y)
entropy_value = 0
for label in unique_labels:
p_label = len(y[y == label]) / len(y)
entropy_value -= p_label * np.log2(p_label)
return entropy_... | from solution import entropy, information_gain, id3
import pandas as pd
def test_entropy():
y = pd.Series([1, 1, 1, 0, 0, 0])
assert entropy(y) == 1.0
y = pd.Series([1, 1, 1, 1])
assert entropy(y) == 0.0
y = pd.Series([1, 1, 1, 0])
assert abs(entropy(y) - 0.811278) < 1e-6
def test_informatio... | [] | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\n\ndef entropy(y):\n \"\"\"\n Calculate the entropy of label array y.\n \"\"\"\n unique_labels = np.unique(y)\n entropy_value = 0\n fo... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041137",
"row_id": 41137,
"seed_ids": "['Qwen2-72B-Instruct_89648']"
} | 0.415028 | Filter_41137 | I | [
"entropy",
"information_gain",
"id3"
] | 3 | [
[
"id3",
"information_gain"
],
[
"information_gain",
"entropy"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 8c2b5733a579f9c3ef9ed89c31a2c07ca3525d6f | deae4fe47c6f549976f65ee1457f80b3b3fd2d12 | |||
v1.0 | instruct | Filter | Filter_41147_I | Implement a random number generator in Python that returns a random number in the range of 1-100. Importantly, the generator should not use the built-in random module. Instead, use the numpy library to generate the random number. Also, create a function that takes in an integer as input and returns a list of that many ... | import numpy as np
def generate_random_number(seed=None):
"""
Generate a random number between 1 and 100 using numpy.
Parameters:
seed (int): An optional seed for the random number generator.
Returns:
int: A random number between 1 and 100.
"""
if seed is not None:
np.random.s... | from solution import generate_random_number, generate_random_numbers_list
def test_generate_random_number():
number = generate_random_number()
assert 1 <= number <= 100
def test_generate_random_number_with_seed():
number1 = generate_random_number(seed=42)
number2 = generate_random_number(seed=42)
... | [
{
"docstring": "Generate a random number between 1 and 100 using numpy.\n\nParameters:\nseed (int): An optional seed for the random number generator.\n\nReturns:\nint: A random number between 1 and 100.",
"function_declaration": "def generate_random_number(seed=None):",
"function_name": "generate_random... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef generate_random_number():\n \"\"\"\n Generates a random number between 1 and 100 using numpy.\n \"\"\"\n return np.random.randint(1, 101)\n\ndef generate_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041147",
"row_id": 41147,
"seed_ids": "['Qwen2-72B-Instruct_89667']"
} | 0.660287 | Filter_41147 | I | [
"generate_random_number",
"generate_random_numbers_list"
] | 2 | [
[
"generate_random_numbers_list",
"generate_random_number"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | cabb7ad84f623348ff7bb249c03f1da487618d64 | 69d5bf1f5e3cd39129a50457ac0049fda56c43f5 | |||
v1.0 | instruct | Filter | Filter_41164_I | Write an implementation of heapsort which sorts an array in-place. Also, provide a small example. | def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[largest] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr,... | from solution import heapsort
def test_heapsort_empty():
arr = []
heapsort(arr)
assert arr == []
def test_heapsort_single_element():
arr = [1]
heapsort(arr)
assert arr == [1]
def test_heapsort_sorted():
arr = [1, 2, 3, 4, 5]
heapsort(arr)
assert arr == [1, 2, 3, 4, 5]
def test_he... | [
{
"docstring": null,
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def heapsort(arr):",
"function_name": "heapsort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def heapify(arr, n, i):\n \"\"\"\n Helper function to maintain a max heap property.\n \"\"\"\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n \n if l < n and arr[largest... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041164",
"row_id": 41164,
"seed_ids": "['Qwen2-72B-Instruct_89695']"
} | 0.737559 | Filter_41164 | I | [
"heapify",
"heapsort"
] | 2 | [
[
"heapsort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8536992d801f1b383b999129bf0de19921d6cf21 | 120efb33fe807a28ae5c2a2399db47be841bcc9a | |||
v1.0 | instruct | Filter | Filter_41188_I | How would you modify a Python script to create aƎ诵l vector clock Schwartz for every subject, with each vector clock storingIK the timezone and a unique identifier for the subject? The script should be able to process data from multiple input files, each containing an RGB array and its corresponding metadata, including ... | import json
from datetime import datetime
import glob
import os
class VectorClock:
def __init__(self, subject_id, timezone):
self.subject_id = subject_id
self.timezone = timezone
self.vector_clock = {}
def update_clock(self, timestamp):
if timestamp in self.vector_clock:
... | import pytest
import json
import os
from solution import create_vector_clocks, save_vector_clocks_to_json, VectorClock
@pytest.fixture
def setup_files(tmpdir):
# Create some sample input files in the temporary directory
files_data = [
{
'metadata': {
'subject_id': 'subject1'... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nfrom datetime import datetime\nimport glob\nimport os\n\nclass VectorClock:\n def __init__(self, subject_id, timezone):\n self.subject_id = subject_id\n self.time... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041188",
"row_id": 41188,
"seed_ids": "['Qwen2-72B-Instruct_89740']"
} | 0.495424 | Filter_41188 | I | [
"process_file",
"create_vector_clocks",
"save_vector_clocks_to_json",
"main"
] | 4 | [
[
"create_vector_clocks",
"process_file"
]
] | 1 | [] | false | [
"VectorClock"
] | true | pytest | true | [] | true | 30afcda4980687918b4a41a9909277d28aeeab18 | 65a0ec16565bbb56716ec8ad38744f0678bde40f | |||
v1.0 | instruct | Filter | Filter_41210_I | Create a program using Python for managing real-time video processing and handling multiple encoding / decoding libraries simultaneously. In addition to importing the opencv library, add functionality for importing and utilizing the parallel processing library so as to optimize the performance of multi-core systems. | import cv2
import multiprocessing
from multiprocessing import Pool
def process_frame(frame):
"""
Process a single frame using OpenCV.
This function can contain various image processing algorithms.
"""
# Example: Convert the frame to grayscale
processed_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2... | from solution import process_frame, process_video
import cv2
import numpy as np
def test_process_frame():
frame = np.random.randint(0, 256, (480, 640, 3), dtype=np.uint8)
processed_frame = process_frame(frame)
assert processed_frame is not None
assert len(processed_frame.shape) == 2 # The process... | [
{
"docstring": "Process a single frame using OpenCV.\nThis function can contain various image processing algorithms.",
"function_declaration": "def process_frame(frame):",
"function_name": "process_frame",
"parameter_list": "(frame)"
},
{
"docstring": "Process a video file using multi-core p... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport multiprocessing as mp\n\n# Function that processes a video frame and returns the encoded frame\ndef process_frame(frame):\n # Example processing (convert to grayscale)\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041210",
"row_id": 41210,
"seed_ids": "['Qwen2-72B-Instruct_89784']"
} | 0.318687 | Filter_41210 | I | [
"process_frame",
"process_video",
"process_frame_wrapper"
] | 3 | [
[
"process_frame_wrapper",
"process_frame"
],
[
"process_video",
"process_frame_wrapper"
]
] | 2 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | b7e8ad1d74a635959176c270f2192ff2588527ed | cf43168390bdbccae93523ab5d9e6cf58ffafbbb | |||
v1.0 | instruct | Filter | Filter_41212_I | I am trying to refresh my Python knowledge since I haven't done Python programming for a while. Can someone walk me through the syntax for built-in functions used for list and iterate operations, such as filter, map, and reduce? | def is_even(n):
"""
Check if a number is even.
"""
return n % 2 == 0
def filter_even_numbers(numbers):
"""
Filters out even numbers from a list of numbers.
"""
return list(filter(is_even, numbers))
def square(n):
"""
Returns the square of a number.
"""
return n * n
def... | from solution import filter_even_numbers, square_numbers, product_of_numbers
def test_filter_even_numbers():
assert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6]
assert filter_even_numbers([0, 1, 3]) == [0]
assert filter_even_numbers([1, 3, 5]) == []
assert filter_even_numbers([]) == []
def tes... | [
{
"docstring": "Check if a number is even.",
"function_declaration": "def is_even(n):",
"function_name": "is_even",
"parameter_list": "(n)"
},
{
"docstring": "Filters out even numbers from a list of numbers.",
"function_declaration": "def filter_even_numbers(numbers):",
"function_nam... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Function to filter even numbers from a list\ndef filter_even(numbers):\n def is_even(n):\n return n % 2 == 0\n return list(filter(is_even, numbers))\n\n# Function to square each... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041212",
"row_id": 41212,
"seed_ids": "['Qwen2-72B-Instruct_89788']"
} | 0.541911 | Filter_41212 | I | [
"is_even",
"filter_even_numbers",
"square",
"square_numbers",
"multiply",
"product_of_numbers"
] | 6 | [
[
"filter_even_numbers",
"is_even"
],
[
"product_of_numbers",
"multiply"
],
[
"square_numbers",
"square"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 07f82cbf8b8fa88fd1e9931ac4b09b0178ec8ff0 | eb34fb000166812aa24c9783abec65506fa0bfc2 | |||
v1.0 | instruct | Filter | Filter_41221_I | Modify the given python code to find the sum of all prime numbers from 1 to a given number. Also, implement a function to check if a number is prime or not within the solution. | def is_prime(n):
"""
Check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True... | from solution import is_prime, sum_of_primes
def test_is_prime_basic_cases():
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
def test_is_prime_with_small_numbers():
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(6)
assert is_prime(7)
... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Calculate the sum of all prime numbers up to the given limit.",
"function_declaration": "def sum_of_primes(limit):",
"func... | [
1,
1,
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 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": "00041221",
"row_id": 41221,
"seed_ids": "['Qwen2-72B-Instruct_89809']"
} | 0.667958 | Filter_41221 | I | [
"is_prime",
"sum_of_primes"
] | 2 | [
[
"sum_of_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9aeb7db8676a305b5db434d2245f7df7fdf095e7 | 92d48ebada8b50e946da67c87dd5e1a86ffad0c9 | |||
v1.0 | instruct | Filter | Filter_41224_I | Design a Python function that receives a list of at least 3 integers and returns the Lowest Common Multiple (LCM). Also, implement error handling when the input list has less than 3 elements. | import math
from functools import reduce
def lcm_for_two_numbers(a, b):
"""
Helper function to calculate LCM of two numbers.
"""
return abs(a * b) // math.gcd(a, b)
def lcm(numbers):
"""
Calculate the Lowest Common Multiple (LCM) of a list of at least 3 integers.
:param numbers: list ... | from solution import lcm
def test_lcm_valid_input():
assert lcm([2, 3, 5]) == 30
assert lcm([4, 6, 8]) == 24
assert lcm([1, 2, 3, 4, 5]) == 60
def test_lcm_with_prime_numbers():
assert lcm([3, 5, 7]) == 105
assert lcm([11, 13, 17]) == 2431
def test_lcm_with_repetitive_numbers():
assert lcm([2... | [
{
"docstring": "Helper function to calculate LCM of two numbers.",
"function_declaration": "def lcm_for_two_numbers(a, b):",
"function_name": "lcm_for_two_numbers",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the Lowest Common Multiple (LCM) of a list of at least 3 integers.\n\n:... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef lcm_for_two_numbers(a, b):\n \"\"\"\n Helper function to calculate LCM of two numbers.\n \"\"\"\n return abs(a * b) // math.gcd(a, ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041224",
"row_id": 41224,
"seed_ids": "['Qwen2-72B-Instruct_89821']"
} | 0.675144 | Filter_41224 | I | [
"lcm_for_two_numbers",
"lcm"
] | 2 | [
[
"lcm",
"lcm_for_two_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10990e684b0ffa855a598412682c30743f2cd73a | 03ee86be72839ccf47ebde5aed263f477c3a6fd5 | |||
v1.0 | instruct | Filter | Filter_41226_I | Design a Python script that when given an input of a string array, it rearranges the elements in a random order and then applies an encryption algorithm (of your choice) on every element. For the encryption, use the Caesar Cipher with a shifting key that is determined by the first character's numerical equivalent in AS... | import random
def caesar_cipher(text, shift):
"""
Encrypts a text using the Caesar Cipher technique with the given shift value.
"""
result = []
for char in text:
if char.isalpha():
shifted = ord(char) + shift
if char.islower():
if shifted > ord('z'):
... | from solution import random_shuffle_and_encrypt, caesar_cipher
def test_caesar_cipher():
assert caesar_cipher("abc", 1) == "bcd"
assert caesar_cipher("xyz", 3) == "abc"
assert caesar_cipher("ABC", 1) == "BCD"
assert caesar_cipher("XYZ", 3) == "ABC"
assert caesar_cipher("123", 1) == "123" # Non-alp... | [
{
"docstring": "Encrypts a text using the Caesar Cipher technique with the given shift value.",
"function_declaration": "def caesar_cipher(text, shift):",
"function_name": "caesar_cipher",
"parameter_list": "(text, shift)"
},
{
"docstring": "Rearranges elements in a random order and applies ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef caesar_cipher(text, shift):\n \"\"\"\n Encrypts text using a Caesar Cipher with the given shift.\n \"\"\"\n encrypted_text = \"\"\n for char in text:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041226",
"row_id": 41226,
"seed_ids": "['Qwen2-72B-Instruct_89824']"
} | 0.613732 | Filter_41226 | I | [
"caesar_cipher",
"random_shuffle_and_encrypt"
] | 2 | [
[
"random_shuffle_and_encrypt",
"caesar_cipher"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ebe8550a07a7d2c5701b44be77fb056c522408c0 | 6302c6cf37ed116060e5b130eb24bbeb4ee5b55b | |||
v1.0 | instruct | Filter | Filter_41229_I | Write a recursive algorithm that computes and prints the first 10 Fibonacci numbers in reverse order, using a combination of deep copy and memoization technique for optimization. | from copy import deepcopy
def fibonacci(n, memo=None):
if memo is None:
memo = {}
if n == 0:
return 0
if n == 1:
return 1
if n not in memo:
memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, memo)
return memo[n]
def first_n_fibonacci_reverse(n):
fib_seq = []
fo... | from solution import fibonacci, first_n_fibonacci_reverse
def test_fibonacci_base_cases():
assert fibonacci(0) == 0
assert fibonacci(1) == 1
def test_fibonacci_recursive_cases():
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibo... | [
{
"docstring": null,
"function_declaration": "def fibonacci(n, memo=None):",
"function_name": "fibonacci",
"parameter_list": "(n, memo=None)"
},
{
"docstring": null,
"function_declaration": "def first_n_fibonacci_reverse(n):",
"function_name": "first_n_fibonacci_reverse",
"parame... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from copy import deepcopy\n\ndef fibonacci(n, memo=None):\n if memo is None:\n memo = {}\n if n == 0:\n return 0\n if n == 1:\n return 1\n if n not in memo:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041229",
"row_id": 41229,
"seed_ids": "['Qwen2-72B-Instruct_89834']"
} | 0.65009 | Filter_41229 | I | [
"fibonacci",
"first_n_fibonacci_reverse"
] | 2 | [
[
"first_n_fibonacci_reverse",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39a0071551292ee94fcce61d09cd6fc9ad6ee81f | 635022845b5ae092e95e5ffe35ce51dfd9c638e7 | |||
v1.0 | instruct | Filter | Filter_41232_I | Develop a distributed hash table (DHT) using Python for high规模化query operations in a big data scenarios. Implement it using vector clocks for concurrency control and integrate a sharding mechanism to effectively manage nodes. Developing a full Distributed Hash Table (DHT) with complex features like concurrency control ... | from collections import defaultdict
from hashlib import sha1
import time
class VectorClock:
def __init__(self, node_id):
self.node_id = node_id
self.clock = defaultdict(int)
def increment(self):
self.clock[self.node_id] += 1
def update(self, other_clock):
for node, counter... | def test_vector_clock():
vc1 = VectorClock(node_id=1)
vc1.increment()
assert vc1.clock[1] == 1
vc2 = VectorClock(node_id=2)
vc2.increment()
vc2.increment()
assert vc2.clock[2] == 2
vc1.update(vc2)
assert vc1.clock[2] == 2
vc2.update(vc1)
assert vc2.clock[1] == 1
def test_... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nfrom hashlib import sha1\nimport time\n\nclass VectorClock:\n def __init__(self, node_id):\n self.node_id = node_id\n self.clock = default... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041232",
"row_id": 41232,
"seed_ids": "['Qwen2-72B-Instruct_89839']"
} | 0.518965 | Filter_41232 | I | [
"get_node_for_shard",
"store_in_dht",
"retrieve_from_dht",
"create_dht"
] | 4 | [
[
"retrieve_from_dht",
"get_node_for_shard"
],
[
"store_in_dht",
"get_node_for_shard"
]
] | 2 | [] | false | [
"VectorClock",
"DHTNode"
] | true | pytest | false | [] | true | 6c13d91f9e96dc91738a3bf24d4ed14b9bf4c9c7 | 5ab30c3596f35f56e933db6d75ab4587407e6676 | |||
v1.0 | instruct | Filter | Filter_41236_I | Implement `_primorial` function in python that outputs not just the product of prime numbers up to the supplied natural number (n) but also the primes upto a given number. If 'n' is a prime number itself, ensure it's included in the product. Also, for your solution, use the Sieve of Eratosthenes algorithm to find the p... | def sieve_of_eratosthenes(n):
"""
Returns a list of all primes less than or equal to n.
"""
is_prime = [True] * (n + 1)
p = 2
while p**2 <= n:
if is_prime[p]:
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1
primes = [p for p in range(2,... | from solution import _primorial
def test_primorial_with_small_number():
product, primes = _primorial(5)
assert primes == [2, 3, 5]
assert product == 30
def test_primorial_with_non_prime():
product, primes = _primorial(10)
assert primes == [2, 3, 5, 7]
assert product == 210
def test_primorial_... | [
{
"docstring": "Returns a list of all primes less than or equal to n.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Returns the product of prime numbers up to n and also the list of prime number... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def _primorial(n):\n \"\"\"\n Returns the product of prime numbers up to n and the list of primes up to n using the Sieve of Eratosthenes algorithm.\n \"\"\"\n if n < 2:\n r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041236",
"row_id": 41236,
"seed_ids": "['Qwen2-72B-Instruct_89845']"
} | 0.64989 | Filter_41236 | I | [
"sieve_of_eratosthenes",
"_primorial"
] | 2 | [
[
"_primorial",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c4f5b2235bc77e061f74dabeb429c7cb74b57ee4 | 17e434ac64a4cde008f4cca6e3a24ce5d046d852 | |||
v1.0 | instruct | Filter | Filter_41258_I | Design an algorithm using Python, that encrypts a simple string by shifting the order of the alphabets forward by a specified number. For example, if the word is "apple" and the specified shift is 2 then the result would be "crrng". Your algorithm should create an encryption function that can adapt to different shift v... | def encrypt(text, shift):
"""
Encrypts the given text by shifting the letters forward by the specified shift.
"""
result = []
for char in text:
if char.isalpha():
shift_base = 65 if char.isupper() else 97
result.append(chr((ord(char) - shift_base + shift) % 26 + shift... | from solution import encrypt, decrypt
def test_encrypt():
assert encrypt("apple", 2) == "crrng"
assert encrypt("zebra", 1) == "afcsb"
assert encrypt("HELLO", 3) == "KHOOR"
assert encrypt("Hello World!", 5) == "Mjqqt Btwqi!"
def test_decrypt():
assert decrypt("crrng", 2) == "apple"
assert dec... | [
{
"docstring": "Encrypts the given text by shifting the letters forward by the specified shift.",
"function_declaration": "def encrypt(text, shift):",
"function_name": "encrypt",
"parameter_list": "(text, shift)"
},
{
"docstring": "Decrypts the given text by reversing the shift of the letter... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def encrypt(text, shift):\n \"\"\"\n Encrypts the given text by shifting letters forward by the specified shift value.\n \"\"\"\n encrypted_text = []\n for char in text:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041258",
"row_id": 41258,
"seed_ids": "['Qwen2-72B-Instruct_89882']"
} | 0.709803 | Filter_41258 | I | [
"encrypt",
"decrypt"
] | 2 | [
[
"decrypt",
"encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b864d851cfd2608df13a0a6205eebabf6453e289 | a35d60975e11669e3c0758853c8eef8f51b492a1 | |||
v1.0 | instruct | Filter | Filter_41263_I | Implement 'auto_bandwidth_selection' in the code below by modifying the 'width' parameter in the function 'multivariate_gaussian'. This feature should be controlled by a boolean input in the function 'multivariate_gaussian' and must only calculate the bandwidth if 'auto_bandwidth_selection' is True. The 'multivariate_g... | import numpy as np
from scipy.stats import multivariate_normal
from concurrent.futures import ThreadPoolExecutor, as_completed
from scipy.stats import jarque_bera
def is_normal_distributed(xs):
_, p_value = jarque_bera(xs)
return p_value >= 0.05
def simple_bandwidth(xs):
# Implementing the simple bandwidt... | from solution import multivariate_gaussian, simple_bandwidth, advanced_bandwidth, is_normal_distributed
import numpy as np
import pytest
def test_simple_bandwidth():
xs = np.random.normal(loc=0, scale=1, size=100)
bandwidth = simple_bandwidth(xs)
assert bandwidth > 0
def test_advanced_bandwidth():
xs ... | [
{
"docstring": null,
"function_declaration": "def is_normal_distributed(xs):",
"function_name": "is_normal_distributed",
"parameter_list": "(xs)"
},
{
"docstring": null,
"function_declaration": "def simple_bandwidth(xs):",
"function_name": "simple_bandwidth",
"parameter_list": "(... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.spatial.distance import cdist\nfrom sklearn.utils import check_array\nfrom joblib import Parallel, delayed\n\ndef calculate_advanced_bandwidth(xs):\n \"\"\"Ca... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041263",
"row_id": 41263,
"seed_ids": "['Qwen2-72B-Instruct_89888']"
} | 0.475105 | Filter_41263 | I | [
"is_normal_distributed",
"simple_bandwidth",
"advanced_bandwidth",
"multivariate_gaussian"
] | 4 | [
[
"multivariate_gaussian",
"advanced_bandwidth"
],
[
"multivariate_gaussian",
"is_normal_distributed"
],
[
"multivariate_gaussian",
"simple_bandwidth"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 943d00fc33817760a4c06809d8d80efff61325b0 | 76e07c17e54d384b0e21405940f133489ba7d828 | |||
v1.0 | instruct | Filter | Filter_41264_I | Develop a function in Python to modify the given list and remove all strings with length less than three. The function should also remove any strings that contain numbers and any strings that are palindromes. In addition, the function should sort the remaining strings in reverse alphabetical order. | def is_palindrome(s):
return s == s[::-1]
def contains_number(s):
return any(char.isdigit() for char in s)
def filter_and_sort_strings(strings):
filtered_strings = [
s for s in strings
if len(s) >= 3 and not contains_number(s) and not is_palindrome(s)
]
return sorted(filtered_strin... | from solution import filter_and_sort_strings
def test_filter_and_sort_no_removal():
assert filter_and_sort_strings(['apple', 'banana', 'cherry']) == ['cherry', 'banana', 'apple']
def test_filter_and_sort_remove_short_strings():
assert filter_and_sort_strings(['a', 'ab', 'abc', 'abcd']) == ['abcd', 'abc']
def... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def contains_number(s):",
"function_name": "contains_number",
"parameter_list": "(s)"
},
{
"doc... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n return s == s[::-1]\n\ndef contains_number(s):\n return any(char.isdigit() for char in s)\n\ndef filter_and_sort_strings(strings):\n filtered_strings = [\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041264",
"row_id": 41264,
"seed_ids": "['Qwen2-72B-Instruct_89889']"
} | 0.601859 | Filter_41264 | I | [
"is_palindrome",
"contains_number",
"filter_and_sort_strings"
] | 3 | [
[
"filter_and_sort_strings",
"contains_number"
],
[
"filter_and_sort_strings",
"is_palindrome"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3b61d1e92b53e26597e73641f674c80600b1bc72 | 16eb867b9fbbdf2b3b26e64e77c15fcf100acf7e | |||
v1.0 | instruct | Filter | Filter_41268_I | Develop a recursive function to generate the Fibonacci sequence focusing specifically on the first 20 numbers in the series. Additionally, implement a feature to display every even number in the sequence separately. | def fibonacci_recursive(n):
"""
Recursively calculate the nth Fibonacci number.
"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
def generate_fibonacci_sequence(count):
"""
Generate first 'count' Fibon... | from solution import fibonacci_recursive, generate_fibonacci_sequence, find_even_fibonacci_numbers
def test_fibonacci_recursive():
assert fibonacci_recursive(0) == 0
assert fibonacci_recursive(1) == 1
assert fibonacci_recursive(2) == 1
assert fibonacci_recursive(3) == 2
assert fibonacci_recursive(4... | [
{
"docstring": "Recursively calculate the nth Fibonacci number.",
"function_declaration": "def fibonacci_recursive(n):",
"function_name": "fibonacci_recursive",
"parameter_list": "(n)"
},
{
"docstring": "Generate first 'count' Fibonacci numbers.",
"function_declaration": "def generate_fi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci(n, computed={0: 0, 1: 1}):\n \"\"\"\n Returns the nth Fibonacci number.\n \"\"\"\n if n not in computed:\n computed[n] = fibonacci(n-1, computed) + fibonacci(n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041268",
"row_id": 41268,
"seed_ids": "['Qwen2-72B-Instruct_89895']"
} | 0.628292 | Filter_41268 | I | [
"fibonacci_recursive",
"generate_fibonacci_sequence",
"find_even_fibonacci_numbers"
] | 3 | [
[
"generate_fibonacci_sequence",
"fibonacci_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b736e9d18df55046f7e5b0b182c9fa9b92a7f3d | 879d3304dae6425ba24bed8ec289f18d1e279ede | |||
v1.0 | instruct | Filter | Filter_41298_I | Choose your programming language and write code to printout its characters line by line. However, you need to print each character in the language’s reserved keywords only. Additionally, you have to print each character using a different method each time, meaning you cannot use the same printing method more than once. | # Solution Code in Python
import keyword
def print_keywords_characters_line_by_line():
keywords = keyword.kwlist
all_methods = [print_directly, print_join, print_format, print_concatenation]
method_index = 0
used_methods = set()
for word in keywords:
for char in word:
print_u... | from solution import print_keywords_characters_line_by_line
def test_print_keywords_characters_line_by_line(capsys):
print_keywords_characters_line_by_line()
captured = capsys.readouterr()
output = captured.out.strip().split('\n')
assert len(output) > 0 # Output should not be empty
assert all... | [
{
"docstring": null,
"function_declaration": "def print_keywords_characters_line_by_line():",
"function_name": "print_keywords_characters_line_by_line",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def print_using_method(char, method):",
"function_name": "p... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import keyword\n\ndef print_python_keywords():\n # Get list of all Python keywords\n keywords = keyword.kwlist\n methods = [\n print, # Met... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041298",
"row_id": 41298,
"seed_ids": "['Qwen2-72B-Instruct_89952']"
} | 0.504298 | Filter_41298 | I | [
"print_keywords_characters_line_by_line",
"print_using_method",
"print_directly",
"print_join",
"print_format",
"print_concatenation"
] | 6 | [
[
"print_keywords_characters_line_by_line",
"print_using_method"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4087daad4e0207754738e38c64fc1765bf5575aa | 7bbde7d2a1c6d9e966ae9fa7e5993fc3c142d676 | |||
v1.0 | instruct | Filter | Filter_41306_I | How can I count the individual characters, as well as the spaces and punctuation marks, in a string using Python? Furthermore, can you provide a method to display these counts in a sorted format based on the characters' ASCII values? | def count_characters(s):
"""
Counts the individual characters (including spaces and punctuation marks) in a string and
returns a dictionary with characters as keys and their counts as values.
"""
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
return coun... | from solution import count_characters, sorted_character_counts
def test_count_characters_basic():
assert count_characters("hello") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}
def test_count_characters_with_punctuation():
assert count_characters("hello, world!") == {
'h': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' '... | [
{
"docstring": "Counts the individual characters (including spaces and punctuation marks) in a string and \nreturns a dictionary with characters as keys and their counts as values.",
"function_declaration": "def count_characters(s):",
"function_name": "count_characters",
"parameter_list": "(s)"
},... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_characters(s):\n \"\"\"\n Counts the individual characters, spaces, and punctuation marks in a string.\n Returns a dictionary where the keys are the characters and values ar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041306",
"row_id": 41306,
"seed_ids": "['Qwen2-72B-Instruct_89967']"
} | 0.723845 | Filter_41306 | I | [
"count_characters",
"sorted_character_counts"
] | 2 | [
[
"sorted_character_counts",
"count_characters"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ff41da0e4a2b39565077186399ee1f7fc84d85c | 770e56fd1198035c7a0bb3156b14821a79e97d2a | |||
v1.0 | instruct | Filter | Filter_41312_I | Write a Python program with required modifications to print all prime numbers between 1 to n (n is inclusive). Ensure that your program includes an efficient function to determine if a number is prime and handle possible exceptions when the input value for n is not a positive integer. | def is_prime(num):
"""
Check 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:
return False
i +=... | from solution import is_prime, print_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
def test_print_primes_positive... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Print all prime numbers from 1 to n (inclusive).\nHandle cases when n is not a positive integer.",
"function_declaration":... | [
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(num):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n if num % 2 ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041312",
"row_id": 41312,
"seed_ids": "['Qwen2-72B-Instruct_89975']"
} | 0.724561 | Filter_41312 | I | [
"is_prime",
"print_primes"
] | 2 | [
[
"print_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f0d4ccc73c738711403a9c718f8312088915db3 | 590815b067d4f12b860727661c0d25a59469f2f3 | |||
v1.0 | instruct | Filter | Filter_41329_I | Create an array with 5 strings, each containing a random palindrome of length between 5 and 10. Then, modify the array so that each string becomes a "fractal palindrome" which is a special type of palindrome where every half of the string is also a palindrome. Finally, print the array in reverse order. | import random
import string
def generate_palindrome(length):
half = ''.join(random.choices(string.ascii_lowercase, k=length // 2))
if length % 2 == 0:
return half + half[::-1]
else:
return half + random.choice(string.ascii_lowercase) + half[::-1]
def generate_fractal_palindrome(palindrome)... | from solution import generate_palindrome, generate_fractal_palindrome, create_and_modify_array
def test_generate_palindrome_length():
for i in range(5, 11):
palindrome = generate_palindrome(i)
assert len(palindrome) == i
def test_generate_palindrome_property():
palindrome = generate_palindrome... | [
{
"docstring": null,
"function_declaration": "def generate_palindrome(length):",
"function_name": "generate_palindrome",
"parameter_list": "(length)"
},
{
"docstring": null,
"function_declaration": "def generate_fractal_palindrome(palindrome):",
"function_name": "generate_fractal_pal... | [
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 string\n\ndef generate_palindrome(length):\n \"\"\"\n Generates a random palindrome of a specified length.\n \"\"\"\n half_length = (length + 1) // 2\n hal... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041329",
"row_id": 41329,
"seed_ids": "['Qwen2-72B-Instruct_90003']"
} | 0.656258 | Filter_41329 | I | [
"generate_palindrome",
"generate_fractal_palindrome",
"create_and_modify_array"
] | 3 | [
[
"create_and_modify_array",
"generate_fractal_palindrome"
],
[
"create_and_modify_array",
"generate_palindrome"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0582939531b90ce9f261bc36575e37b89807b53d | c5f26329617661a9c9ec9149c6b8c18f1ca42135 | |||
v1.0 | instruct | Filter | Filter_41337_I | Program a binary search algorithm that operates recursively. The function should not only return the index of the found element, but also the total number of operations performed until the element is found or determined to be absent. In case of an absent element, return -1 for the index and the number of operation as n... | def binary_search_recursive(arr, target, left, right, operations=0):
"""
Perform a binary search recursively on a sorted array.
Parameters:
arr (list): The sorted list to search within.
target (int): The target value to search for.
left (int): The starting index of the portion of the list to be... | from solution import binary_search
def test_binary_search_found():
arr = [1, 2, 3, 4, 5, 6, 7]
target = 4
index, operations = binary_search(arr, target)
assert index == 3
assert operations > 0
def test_binary_search_not_found():
arr = [1, 2, 3, 4, 5, 6, 7]
target = 8
index, operations ... | [
{
"docstring": "Perform a binary search recursively on a sorted array.\n\nParameters:\narr (list): The sorted list to search within.\ntarget (int): The target value to search for.\nleft (int): The starting index of the portion of the list to be searched.\nright (int): The ending index of the portion of the list... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def binary_search_recursive(arr, target, left, right, operations=0):\n \"\"\"\n Perform a binary search recursively on a sorted array.\n\n Parameters:\n arr (list): The sorted list... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041337",
"row_id": 41337,
"seed_ids": "['Qwen2-72B-Instruct_90013']"
} | 0.715954 | Filter_41337 | I | [
"binary_search_recursive",
"binary_search"
] | 2 | [
[
"binary_search",
"binary_search_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67c34f3981f4b4416f3e7aa1d63a87848fe89622 | f24428026bb652a90c7efb6853009ac06c0ca07c | |||
v1.0 | instruct | Filter | Filter_41359_I | Develop a game AI which plays Tic-Tac-Toe using minimax algorithm with alpha beta pruning. | import math
def is_moves_left(board):
for row in board:
if 0 in row:
return True
return False
def evaluate(board):
# Check rows
for row in board:
if row[0] == row[1] == row[2]:
if row[0] == 1: # AI wins
return 10
elif row[0] == -1: ... | from solution import is_moves_left, evaluate, minimax, find_best_move
def test_is_moves_left():
board = [
[1, -1, 1],
[-1, 1, -1],
[0, 1, -1]
]
assert is_moves_left(board) == True
board = [
[1, -1, 1],
[-1, 1, -1],
[1, -1, 1]
]
assert is_moves_le... | [
{
"docstring": null,
"function_declaration": "def is_moves_left(board):",
"function_name": "is_moves_left",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def evaluate(board):",
"function_name": "evaluate",
"parameter_list": "(board)"
},
{
"d... | [
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 is_winner(board, player):\n \"\"\"\n Check if a player has won the game.\n \"\"\"\n win_cond = [\n [board[0], board[1], board[2]], # top row\n [boa... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041359",
"row_id": 41359,
"seed_ids": "['Qwen2-72B-Instruct_90073']"
} | 0.441712 | Filter_41359 | I | [
"is_moves_left",
"evaluate",
"minimax",
"find_best_move"
] | 4 | [
[
"find_best_move",
"minimax"
],
[
"minimax",
"evaluate"
],
[
"minimax",
"is_moves_left"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | bb521eb9e72b2da74bc3ce7ca64dee1a230230f1 | c59f8d687cdb7f0696756a87cf9210c2f540777b | |||
v1.0 | instruct | Filter | Filter_41369_I | Print every Fibonacci number between 0 and 100, using Python. Also, optimize your program using memoization to reduce time complexity for consecutive runs where the maximum limit (100 here) might increase up to 1000. | def generate_fibonacci_up_to_100():
"""
Generates all Fibonacci numbers from 0 up to 100 (inclusive).
"""
fib_sequence = []
a, b = 0, 1
while a <= 100:
fib_sequence.append(a)
a, b = b, a + b
return fib_sequence
# Memoization dictionary to cache computed fibonacci numbers
mem... | from solution import generate_fibonacci_up_to_100, fibonacci, generate_optimized_fibonacci_up_to_n
def test_generate_fibonacci_up_to_100():
result = generate_fibonacci_up_to_100()
assert result == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], f"Unexpected result: {result}"
def test_fibonacci_memoization():
#... | [
{
"docstring": "Generates all Fibonacci numbers from 0 up to 100 (inclusive).",
"function_declaration": "def generate_fibonacci_up_to_100():",
"function_name": "generate_fibonacci_up_to_100",
"parameter_list": "()"
},
{
"docstring": "Returns the nth Fibonacci number using memoization.\nThis ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_numbers_upto(n):\n \"\"\"\n Generate all Fibonacci numbers less than or equal to n.\n \"\"\"\n fibs = []\n a, b = 0, 1\n while a <= n:\n fibs.append(a)\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041369",
"row_id": 41369,
"seed_ids": "['Qwen2-72B-Instruct_90088']"
} | 0.737219 | Filter_41369 | I | [
"generate_fibonacci_up_to_100",
"fibonacci",
"generate_optimized_fibonacci_up_to_n"
] | 3 | [
[
"generate_optimized_fibonacci_up_to_n",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aab18130e0c23382bd5c27c6214929560fef4f2c | cfd120ee37c865648157ffd1213518754d58a4f7 | |||
v1.0 | instruct | Filter | Filter_41377_I | Write pseudocode for finding the maximum element in an array using a recursive algorithm. Additionally, implement a check to ensure the array input is not empty and handle edge case scenarios, such as large input sizes or specific data types. | def find_max(arr):
"""
Returns the maximum element in the array using a recursive algorithm.
If the array is empty, returns None.
"""
n = len(arr)
# Handle empty array
if n == 0:
return None
return _find_max_recursive(arr, n)
def _find_max_recursive(arr, n):
# Base... | from solution import find_max
def test_find_max_single_element():
assert find_max([1]) == 1
def test_find_max_two_elements():
assert find_max([1, 2]) == 2
assert find_max([2, 1]) == 2
def test_find_max_multiple_elements():
assert find_max([1, 3, 2, 5, 4]) == 5
assert find_max([10, 20, 30, 40, 50]... | [
{
"docstring": "Returns the maximum element in the array using a recursive algorithm.\nIf the array is empty, returns None.",
"function_declaration": "def find_max(arr):",
"function_name": "find_max",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def _find_ma... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_max(arr):\n \"\"\"\n Returns the maximum element in the array using recursion.\n Assumes the array is not empty.\n \"\"\"\n if len(arr) == 1:\n return arr[0]\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041377",
"row_id": 41377,
"seed_ids": "['Qwen2-72B-Instruct_90100']"
} | 0.649541 | Filter_41377 | I | [
"find_max",
"_find_max_recursive"
] | 2 | [
[
"find_max",
"_find_max_recursive"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ebb266211f3f89ce38ad560a56502cd7d62aaff4 | 51c0faa6c995fc0a813c11a026e815f840ce1e5a | |||
v1.0 | instruct | Filter | Filter_41382_I | Construct the Fibonacci series up to the 20th position using Python programming language, employing a looping mechanism. Also, once the Fibonacci series is constructed, write a function to find the Nth Fibonacci number in the series (where N is a user-input). Test your function for 3 different inputs. Ensure to handle ... | def fibonacci_series_upto_n(n):
"""
Generates the Fibonacci series up to the nth position.
"""
if n < 0:
raise ValueError("n should be a non-negative integer")
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return f... | from solution import fibonacci_series_upto_n, nth_fibonacci_number
def test_fibonacci_series_basic():
assert fibonacci_series_upto_n(1) == [0]
assert fibonacci_series_upto_n(2) == [0, 1]
assert fibonacci_series_upto_n(3) == [0, 1, 1]
assert fibonacci_series_upto_n(5) == [0, 1, 1, 2, 3]
def test_nth_fi... | [
{
"docstring": "Generates the Fibonacci series up to the nth position.",
"function_declaration": "def fibonacci_series_upto_n(n):",
"function_name": "fibonacci_series_upto_n",
"parameter_list": "(n)"
},
{
"docstring": "Returns the Nth Fibonacci number.",
"function_declaration": "def nth_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_fibonacci_series(n):\n \"\"\"\n Generates the Fibonacci series up to the nth position.\n \n Parameters:\n n (int): The position up to which the Fibonacci series is ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041382",
"row_id": 41382,
"seed_ids": "['Qwen2-72B-Instruct_90110']"
} | 0.71695 | Filter_41382 | I | [
"fibonacci_series_upto_n",
"nth_fibonacci_number"
] | 2 | [
[
"nth_fibonacci_number",
"fibonacci_series_upto_n"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ecd7fb1eb7cdf665c17ba60695c19e27a5111fb8 | 7979f5ce62aad7d14f88615952a14d2abee2eefe | |||
v1.0 | instruct | Filter | Filter_41383_I | Create ailly otherwise) recursive algorithm in Python to identify the largest number in a provided list of numbers, without using built-in Python functions. In addition, your algorithm should be able to handle potential issues like empty lists. | def find_largest(nums):
"""
Recursive function to find the largest number in a list.
"""
if not nums:
raise ValueError("List is empty")
return find_largest_helper(nums, len(nums) - 1)
def find_largest_helper(nums, n):
if n == 0:
return nums[0]
return max(nums[n], find_larges... | from solution import find_largest
import pytest
def test_find_largest_single_element():
assert find_largest([42]) == 42
def test_find_largest_positive_numbers():
assert find_largest([1, 2, 3, 4, 5]) == 5
def test_find_largest_negative_numbers():
assert find_largest([-1, -2, -3, -4, -5]) == -1
def test_f... | [
{
"docstring": "Recursive function to find the largest number in a list.",
"function_declaration": "def find_largest(nums):",
"function_name": "find_largest",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def find_largest_helper(nums, n):",
"function_nam... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_largest(nums):\n \"\"\"\n Recursive function to find the largest number in a list.\n \"\"\"\n if not nums:\n raise ValueError(\"List is empty\")\n return find_la... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041383",
"row_id": 41383,
"seed_ids": "['Qwen2-72B-Instruct_90111']"
} | 0.697593 | Filter_41383 | I | [
"find_largest",
"find_largest_helper"
] | 2 | [
[
"find_largest",
"find_largest_helper"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f2ff852d4201bafa61b66eafff4ff3887a1ac72 | 65026b916134a0a010a994f2675a65891b12d954 | |||
v1.0 | instruct | Filter | Filter_41387_I | In Python, write a program that simulates a game of Rock Paper Scissors. The game should allow multiple rounds, and between each round, ask the user if they want to continue playing or not. The final output should show the total count of wins, losses, and draws. | import random
def get_computer_choice():
return random.choice(["rock", "paper", "scissors"])
def determine_winner(player_choice, computer_choice):
if player_choice == computer_choice:
return "draw"
elif (player_choice == "rock" and computer_choice == "scissors") or \
(player_choice == "pa... | from solution import determine_winner, get_computer_choice
def test_determine_winner():
# Testing all win scenarios
assert determine_winner("rock", "scissors") == "win"
assert determine_winner("paper", "rock") == "win"
assert determine_winner("scissors", "paper") == "win"
# Testing all lose sc... | [
{
"docstring": null,
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def determine_winner(player_choice, computer_choice):",
"function_name": "determine_winner",
... | [
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 play_rps_game():\n choices = [\"rock\", \"paper\", \"scissors\"]\n win_count = 0\n loss_count = 0\n draw_count = 0\n while True:\n user_choice = inpu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041387",
"row_id": 41387,
"seed_ids": "['Qwen2-72B-Instruct_90115']"
} | 0.531978 | Filter_41387 | I | [
"get_computer_choice",
"determine_winner",
"rock_paper_scissors"
] | 3 | [
[
"rock_paper_scissors",
"determine_winner"
],
[
"rock_paper_scissors",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7b87f6155b37d372a867caf8218848b9905eaa4e | 36e678576a928f3de791f5c926ba2c642651de8e | |||
v1.0 | instruct | Filter | Filter_41406_I | Given non-negative integer N, we define a new integer Y as a complementary divisor of N, if Y is a positive divisor of N and the sum of its distinct prime factors is exactly equal to N. Your task is to code a function `is_complementary_divisor` that accepts an integer `n` and checks if `n` is a complementary divisor of... | def prime_factors_sum(n):
"""
Returns the sum of distinct prime factors of n.
"""
i = 2
prime_factors = set()
while i * i <= n:
while (n % i) == 0:
prime_factors.add(i)
n //= i
i += 1
if n > 1:
prime_factors.add(n)
return sum(prime_factors)... | from solution import is_complementary_divisor, prime_factors_sum
def test_prime_factors_sum():
assert prime_factors_sum(6) == 5 # 2 + 3 = 5
assert prime_factors_sum(28) == 9 # 2 + 7 = 9
assert prime_factors_sum(30) == 10 # 2 + 3 + 5 = 10
assert prime_factors_sum(1) == 0 # No prime factors for 1
d... | [
{
"docstring": "Returns the sum of distinct prime factors of n.",
"function_declaration": "def prime_factors_sum(n):",
"function_name": "prime_factors_sum",
"parameter_list": "(n)"
},
{
"docstring": "Checks if n is a complementary divisor of its double.",
"function_declaration": "def is_... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def prime_factors_sum(n):\n \"\"\"Helper function to find the sum of distinct prime factors of n.\"\"\"\n i = 2\n factors = set()\n while i * i <= n:\n if n % i:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041406",
"row_id": 41406,
"seed_ids": "['Qwen2-72B-Instruct_90157']"
} | 0.586017 | Filter_41406 | I | [
"prime_factors_sum",
"is_complementary_divisor"
] | 2 | [
[
"is_complementary_divisor",
"prime_factors_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cc67e7aff38c24b305bd5c391d11a4f2c4a2f3a2 | 7c295a10b12563a4553c54d46a59204e5931a3a0 | |||
v1.0 | instruct | Filter | Filter_41423_I | Create a symmetric matrix, write a Python function to evaluate if it is a valid symmetric matrix, and display both the original and converted upper triangular matrix. If the input is not valid, then the function should return an error message. | import numpy as np
def is_symmetric(matrix):
"""
Check if a given matrix is symmetric.
"""
return np.array_equal(matrix, matrix.T)
def to_upper_triangular(matrix):
"""
Converts a matrix to its upper triangular form.
"""
return np.triu(matrix)
def validate_and_convert_to_upper_triangul... | import numpy as np
from solution import validate_and_convert_to_upper_triangular, is_symmetric, to_upper_triangular
def test_is_symmetric():
matrix = np.array([[1, 2, 3], [2, 4, 5], [3, 5, 6]])
assert is_symmetric(matrix) == True
non_symmetric_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
asser... | [
{
"docstring": "Check if a given matrix is symmetric.",
"function_declaration": "def is_symmetric(matrix):",
"function_name": "is_symmetric",
"parameter_list": "(matrix)"
},
{
"docstring": "Converts a matrix to its upper triangular form.",
"function_declaration": "def to_upper_triangular... | [
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 is_symmetric(matrix):\n \"\"\"\n Check if the given matrix is symmetric.\n \"\"\"\n return np.array_equal(matrix, matrix.T)\n\ndef to_upper_triangular(mat... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041423",
"row_id": 41423,
"seed_ids": "['Qwen2-72B-Instruct_90201']"
} | 0.495232 | Filter_41423 | I | [
"is_symmetric",
"to_upper_triangular",
"validate_and_convert_to_upper_triangular"
] | 3 | [
[
"validate_and_convert_to_upper_triangular",
"is_symmetric"
],
[
"validate_and_convert_to_upper_triangular",
"to_upper_triangular"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 954ec4e4696bd24d6dd60acec2098d1a672658c8 | a71157b3c2f7241005fa732827793dc814d2b38a | |||
v1.0 | instruct | Filter | Filter_41428_I | Write a function that not only determines if a given number is even or odd, but also checks whether this number is prime. Additionally, write another function to verify if a series of numbers, specified in an array, are all prime, even, or odd. The function should return appropriate responses for empty arrays. Optimize... | import math
def is_even(n):
"""
Returns True if n is even, False otherwise.
"""
return n % 2 == 0
def is_prime(n):
"""
Returns True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0... | from solution import is_even, is_prime, check_number_properties
def test_is_even():
assert is_even(2) == True
assert is_even(3) == False
assert is_even(0) == True
assert is_even(-2) == True
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == Fal... | [
{
"docstring": "Returns True if n is even, False otherwise.",
"function_declaration": "def is_even(n):",
"function_name": "is_even",
"parameter_list": "(n)"
},
{
"docstring": "Returns True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"functio... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_even(n):\n \"\"\"\n Returns True if n is even, False otherwise.\n \"\"\"\n return n % 2 == 0\n\n\ndef is_prime(n):\n \"\"\"\n Returns True if n is a pri... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041428",
"row_id": 41428,
"seed_ids": "['Qwen2-72B-Instruct_90209']"
} | 0.615608 | Filter_41428 | I | [
"is_even",
"is_prime",
"check_number_properties"
] | 3 | [
[
"check_number_properties",
"is_even"
],
[
"check_number_properties",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ac3b1771328d12edb2709b603fa4b397d2100701 | dbac5755bf49c43a57de234fe359e9a05b1b3563 | |||
v1.0 | instruct | Filter | Filter_41433_I | Create an application using Python 3 to generate the Fibonacci sequence up to a user-defined length, and display each term of the sequence as it's calculated. | def fibonacci_sequence(n):
"""
Generates the Fibonacci sequence up to n terms.
Args:
n (int): The number of terms to generate in the Fibonacci sequence.
Returns:
list: A list containing the Fibonacci sequence up to n terms.
"""
if n <= 0:
return []
elif n == 1:
... | from solution import fibonacci_sequence, display_fibonacci_sequence
import pytest
def test_fibonacci_sequence_zero_terms():
assert fibonacci_sequence(0) == []
def test_fibonacci_sequence_one_term():
assert fibonacci_sequence(1) == [0]
def test_fibonacci_sequence_two_terms():
assert fibonacci_sequence(2) ... | [
{
"docstring": "Generates the Fibonacci sequence up to n terms.\n\nArgs:\nn (int): The number of terms to generate in the Fibonacci sequence.\n\nReturns:\nlist: A list containing the Fibonacci sequence up to n terms.",
"function_declaration": "def fibonacci_sequence(n):",
"function_name": "fibonacci_seq... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def fibonacci_sequence(n):\n \"\"\"\n Generates Fibonacci sequence up to the n-th term.\n \n :param n: int - The length of the Fibonacci sequence to generate.\n :return: list - ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041433",
"row_id": 41433,
"seed_ids": "['Qwen2-72B-Instruct_90218']"
} | 0.671169 | Filter_41433 | I | [
"fibonacci_sequence",
"display_fibonacci_sequence"
] | 2 | [
[
"display_fibonacci_sequence",
"fibonacci_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 39fb23878fcc743e4ca84950749273b7c4cb1a41 | 4ada35d4fc8d5b84f1fc040e99100a55f0d6b28e | |||
v1.0 | instruct | Filter | Filter_41438_I | You need to sort the given array in descending order. However, you cannot use any built-in sorting functions or methods provided by the programming language. You have to implement the sorting algorithm yourself. Additionally, your sorting algorithm must have a time complexity of O(n log n), where n is the length of the... | def quicksort_desc(arr, left, right):
"""
Helper function to perform quicksort in place with descending order.
"""
if left < right:
pivot_index = partition(arr, left, right)
quicksort_desc(arr, left, pivot_index - 1)
quicksort_desc(arr, pivot_index + 1, right)
def partition(arr,... | from solution import sort_array_desc
def test_sort_array_desc_empty():
assert sort_array_desc([]) == []
def test_sort_array_desc_single_element():
assert sort_array_desc([1]) == [1]
def test_sort_array_desc_sorted():
assert sort_array_desc([5, 4, 3, 2, 1]) == [5, 4, 3, 2, 1]
def test_sort_array_desc_rev... | [
{
"docstring": "Helper function to perform quicksort in place with descending order.",
"function_declaration": "def quicksort_desc(arr, left, right):",
"function_name": "quicksort_desc",
"parameter_list": "(arr, left, right)"
},
{
"docstring": "Partition function used by quicksort.",
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def quicksort_descending(arr, low, high):\n \"\"\"\n Sorts the array in place in descending order using a quicksort algorithm.\n \"\"\"\n if low < high:\n partition_index = ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041438",
"row_id": 41438,
"seed_ids": "['Qwen2-72B-Instruct_90229']"
} | 0.695575 | Filter_41438 | I | [
"quicksort_desc",
"partition",
"sort_array_desc"
] | 3 | [
[
"quicksort_desc",
"partition"
],
[
"sort_array_desc",
"quicksort_desc"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 30280ef83b44c33db555ecf1da3a8db5cc4148eb | 5f09ad74681f42d13cb9cd5a7768870ffe62b373 | |||
v1.0 | instruct | Filter | Filter_41441_I | Given an RGB color value(255,128,0) in HTML, write a program to convert it into HEX color value and a descriptive color name according to W3C standards. | def rgb_to_hex(r, g, b):
"""
Converts RGB color value to HEX color value.
"""
return '#{:02X}{:02X}{:02X}'.format(r, g, b)
def rgb_to_color_name(r, g, b):
"""
Determines the color name of the given RGB value according to W3C standards.
"""
color_lookup = {
(255, 0, 0): "Red",
... | from solution import rgb_to_hex_and_color_name
def test_rgb_to_hex_and_color_name_orange():
hex_value, color_name = rgb_to_hex_and_color_name(255, 128, 0)
assert hex_value == "#FF8000"
assert color_name == "Orange"
def test_rgb_to_hex_and_color_unknown():
hex_value, color_name = rgb_to_hex_and_color_n... | [
{
"docstring": "Converts RGB color value to HEX color value.",
"function_declaration": "def rgb_to_hex(r, g, b):",
"function_name": "rgb_to_hex",
"parameter_list": "(r, g, b)"
},
{
"docstring": "Determines the color name of the given RGB value according to W3C standards.",
"function_decl... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rgb_to_hex(r, g, b):\n \"\"\"\n Convert RGB color to HEX color.\n \"\"\"\n return \"#{:02X}{:02X}{:02X}\".format(r, g, b)\n\ndef get_color_name(hex_code):\n \"\"\"\n Get ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041441",
"row_id": 41441,
"seed_ids": "['Qwen2-72B-Instruct_90232']"
} | 0.371449 | Filter_41441 | I | [
"rgb_to_hex",
"rgb_to_color_name",
"rgb_to_hex_and_color_name"
] | 3 | [
[
"rgb_to_hex_and_color_name",
"rgb_to_color_name"
],
[
"rgb_to_hex_and_color_name",
"rgb_to_hex"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 56ef63f40f10362b9b792a688a63b689fda5b5be | 0f1b49722ea52c9c107cb2f41efd300c9fb12f0c | |||
v1.0 | instruct | Filter | Filter_41444_I | Given a list `datalist`, write a program that creates a new list `result` containing all the odd numbers from `datalist` and prints it. Also, find the length of the sublist in `result` which contains all the odd numbers that are prime numbers. A prime number is defined as a number which is only divisible by 1 and itsel... | def is_prime(n):
"""
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 find_odd_primes_length(datalist)... | from solution import is_prime, find_odd_primes_length
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(11) == True
assert is_prime(15) == False
assert is_prime(17) == True
assert is_prime(1) == False
assert is_prime(0... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Create a list of odd numbers and find the number of odd prime numbers in datalist.",
"function_declaration": "def find_odd_pri... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041444",
"row_id": 41444,
"seed_ids": "['Qwen2-72B-Instruct_90235']"
} | 0.56933 | Filter_41444 | I | [
"is_prime",
"find_odd_primes_length"
] | 2 | [
[
"find_odd_primes_length",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 90dfe3b4aa5c4d652d88916b0cae9054ab00c512 | e552813216b5c818cc0b94f4485f325188a95dda | |||
v1.0 | instruct | Filter | Filter_41456_I | Implement a quicksort algorithm in Python to sort a given array. Your implementation should handle arrays with duplicate elements efficiently and should have a time complexity of O(nlogn). Additionally, you are not allowed to use any built-in sorting functions or libraries in your implementation. Furthermore, your quic... | def quicksort(arr):
"""
This function sorts the array using an iterative QuickSort algorithm.
"""
if len(arr) <= 1:
return arr
stack = [(0, len(arr) - 1)]
while stack:
low, high = stack.pop()
if low < high:
pi = partition(arr, low, high)
stack.a... | from solution import quicksort
def test_empty_array():
assert quicksort([]) == []
def test_single_element_array():
assert quicksort([1]) == [1]
def test_sorted_array():
assert quicksort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert quicksort([5, 4, 3, 2, 1]) == [1, 2, 3... | [
{
"docstring": "This function sorts the array using an iterative QuickSort algorithm.",
"function_declaration": "def quicksort(arr):",
"function_name": "quicksort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_n... | [
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 Sorts an array using an iterative quicksort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n\n stack = [(0, len(arr) - 1)]\n\n whi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041456",
"row_id": 41456,
"seed_ids": "['Qwen2-72B-Instruct_90259']"
} | 0.588982 | Filter_41456 | I | [
"quicksort",
"partition"
] | 2 | [
[
"quicksort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 974765e819e7a851f9a72e340047edaa1d0aa785 | 398138e27d864dd40758668e13b36204b01e73e2 | |||
v1.0 | instruct | Filter | Filter_41460_I | Fix the following Python code to create a dictionary where the keys are prime numbers between 1 and 100 and the values are lists containing the corresponding key and its squared value. | def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def create_prime_dict():
prime_dict = {}
for num in range(2, 101):
if is_prime(num):
prime_dict[num] = [num, num**2]
return prime_... | from solution import is_prime, create_prime_dict
def test_is_prime():
assert is_prime(2) == True
assert is_prime(10) == False
assert is_prime(13) == True
assert is_prime(1) == False
assert is_prime(17) == True
def test_create_prime_dict_keys():
prime_dict = create_prime_dict()
expected_key... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def create_prime_dict():",
"function_name": "create_prime_dict",
"parameter_list": "()"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n retur... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041460",
"row_id": 41460,
"seed_ids": "['Qwen2-72B-Instruct_90263']"
} | 0.569482 | Filter_41460 | I | [
"is_prime",
"create_prime_dict"
] | 2 | [
[
"create_prime_dict",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 44cf7587385b5a577fc5853548a40e1cbb550d26 | 4b758b534adbc673edc27ee7528d8f8223d191d3 | |||
v1.0 | instruct | Filter | Filter_41463_I | Given two linked lists, write a Python program to compare them and output true if they are equal, false if not. Each node in the linked list contains a numerical value. The program should also take into consideration the cyclic nature of the linked lists, where a node may point back to a previous node in the list. For ... | class ListNode:
"""
Definition for a singly-linked list node.
"""
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def detect_cycle_and_create_set(head):
"""
Detects cycle in the linked list and returns a set of node values.
"""
node_set = set(... | from solution import ListNode, compare_linked_lists
def test_compare_equal_lists_without_cycle():
# List 1: 1 -> 2 -> 3
node1_1 = ListNode(1)
node1_2 = ListNode(2)
node1_3 = ListNode(3)
node1_1.next = node1_2
node1_2.next = node1_3
# List 2: 1 -> 2 -> 3
node2_1 = ListNode(1)
node2_... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef has_cycle(head):\n slow, fast = head, head\n while fast and fast.next:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041463",
"row_id": 41463,
"seed_ids": "['Qwen2-72B-Instruct_90268']"
} | 0.587247 | Filter_41463 | I | [
"detect_cycle_and_create_set",
"compare_linked_lists"
] | 2 | [
[
"compare_linked_lists",
"detect_cycle_and_create_set"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | e458f8307ef6f4d04394a41316e85826233c444c | ea51c5f9842a360d16ca532b93d500e082181bd8 | |||
v1.0 | instruct | Filter | Filter_41469_I | Given an input matrix, write a Python program to iterate over each row and column while ensuring load is evenly distributed across processors using the multiprocessing library. | import multiprocessing
def process_cell(cell_value):
"""
Function to process each cell value of the matrix.
Modify this function to perform any specific operations required.
"""
# In this example, we will just return the cell value squared (for demonstration purposes).
return cell_value * cell_... | from solution import process_matrix
def test_square_matrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected_output = [
[1, 4, 9],
[16, 25, 36],
[49, 64, 81]
]
assert process_matrix(matrix) == expected_output
def test_single_row_matrix():
... | [
{
"docstring": "Function to process each cell value of the matrix.\nModify this function to perform any specific operations required.",
"function_declaration": "def process_cell(cell_value):",
"function_name": "process_cell",
"parameter_list": "(cell_value)"
},
{
"docstring": "Function to pr... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\n\ndef process_row(row):\n \"\"\"\n Dummy function to process a row. Replace with actual processing logic.\n \"\"\"\n return sum(row)\n\ndef process_matrix(m... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041469",
"row_id": 41469,
"seed_ids": "['Qwen2-72B-Instruct_90275']"
} | 0.46986 | Filter_41469 | I | [
"process_cell",
"process_row",
"process_matrix"
] | 3 | [
[
"process_matrix",
"process_row"
],
[
"process_row",
"process_cell"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 31d8e0b839a9f3dee10af2b888058903a673d77e | a15b76a0403e9cd5277a18afa9435c15f5bc4a72 | |||
v1.0 | instruct | Filter | Filter_41505_I | Implement a client-server model using Python, where the server not only serves the current time but also follows the Daylight Saving Time (DST) rules based on its geographical location. Accommodate for time-zone differences among different geographical locations. The client should be capable of requesting time conversi... | import socket
import pytz
from datetime import datetime
import json
def get_server_time(timezone):
"""
Returns the current time at the given timezone, taking into account DST.
"""
try:
tz = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
return {'error': 'Unknown time zone... | import json
import socket
from threading import Thread
from solution import start_server, get_server_time
# Start server in a separate thread
server_thread = Thread(target=start_server, kwargs={'port': 12346})
server_thread.daemon = True
server_thread.start()
def test_get_server_time():
assert 'Unknown time zone'... | [
{
"docstring": "Returns the current time at the given timezone, taking into account DST.",
"function_declaration": "def get_server_time(timezone):",
"function_name": "get_server_time",
"parameter_list": "(timezone)"
},
{
"docstring": null,
"function_declaration": "def start_server(addres... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport pytz\nfrom datetime import datetime\nimport json\n\ndef get_server_time(timezone):\n \"\"\"\n Returns the current time at the given timezone, taking into account DS... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041505",
"row_id": 41505,
"seed_ids": "['Qwen2-72B-Instruct_90339']"
} | 0.545323 | Filter_41505 | I | [
"get_server_time",
"start_server"
] | 2 | [
[
"start_server",
"get_server_time"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pytz"
] | false | ed10d2ab2e8502a04dcf85e66c4d64677dee5d22 | cafe30d9ee598dbe7396446be906c5b060bb6e8b | |||
v1.0 | instruct | Filter | Filter_41506_I | Write a function to sort a stack in ascending order using recursion only. You cannot use any additional data structure like an array or another stack. Your program should perform all the operations internally using recursive calls. | def sorted_insert(stack, element):
"""
Helper function to insert an element into the sorted stack.
:param stack: List representing the stack.
:param element: Element to be inserted.
"""
if not stack or element > stack[-1]:
stack.append(element)
else:
temp = stack.pop()
... | from solution import sort_stack
def test_sort_stack_already_sorted():
assert sort_stack([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_sort_stack_reverse_sorted():
assert sort_stack([4, 3, 2, 1]) == [1, 2, 3, 4]
def test_sort_stack_mixed_values():
assert sort_stack([3, 1, 4, 2]) == [1, 2, 3, 4]
def test_sort_st... | [
{
"docstring": "Helper function to insert an element into the sorted stack.\n\n:param stack: List representing the stack.\n:param element: Element to be inserted.",
"function_declaration": "def sorted_insert(stack, element):",
"function_name": "sorted_insert",
"parameter_list": "(stack, element)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sorted_insert(stack, element):\n \"\"\"\n Helper function to insert an element into the sorted stack.\n \"\"\"\n if not stack or element > stack[-1]:\n stack.append(elem... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041506",
"row_id": 41506,
"seed_ids": "['Qwen2-72B-Instruct_90341']"
} | 0.558244 | Filter_41506 | I | [
"sorted_insert",
"sort_stack"
] | 2 | [
[
"sort_stack",
"sorted_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c3696336fdda1d4c06d377e7c6dc8b9cbc2ed38 | c153741cd970eb821522a67dc09bbea142a8e22e | |||
v1.0 | instruct | Filter | Filter_41534_I | Given a binary tree, design an algorithm to convert this tree into a circular double-linked list in-place. The input tree is represented by root node. When the tree is converted to the double-linked list, the left pointer of node should point to the previous node and the right pointer should point to the next node in t... | class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def concatenate_lists(left_list, right_list):
if not left_list:
return right_list
if not right_list:
return left_list
left_last = left_list.left
right_last = right_... | from solution import TreeNode, tree_to_circular_doubly_linked_list
def test_empty_tree():
assert tree_to_circular_doubly_linked_list(None) == None
def test_single_node():
root = TreeNode(1)
result = tree_to_circular_doubly_linked_list(root)
assert result == root
assert result.left == root
asse... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef btree_to_circular_dll(root):\n \"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041534",
"row_id": 41534,
"seed_ids": "['Qwen2-72B-Instruct_90394']"
} | 0.484518 | Filter_41534 | I | [
"concatenate_lists",
"tree_to_circular_doubly_linked_list"
] | 2 | [
[
"tree_to_circular_doubly_linked_list",
"concatenate_lists"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | ab3d8a3f14db9107c4d5796755021673ee69f097 | 84376be401db4ff1dd8279b96ff2b42d3df57858 | |||
v1.0 | instruct | Filter | Filter_41542_I | Given a string s, reverse its characters and then check if the string is a palindrome or not. Also implement an auxiliary function checkPalindrome which will take a string, calculate and return how many alteration needed in the original string to form a palindromic string. Both original input string and transformed str... | def reverse_string(s):
"""
Returns the reversed version of the input string s.
"""
return s[::-1]
def is_palindrome(s):
"""
Checks if the input string s is a palindrome.
"""
reversed_s = reverse_string(s)
return s == reversed_s
def check_palindrome(s):
"""
Returns the numbe... | from solution import reverse_string, is_palindrome, check_palindrome
def test_reverse_string():
assert reverse_string("abc") == "cba"
assert reverse_string("!123") == "321!"
assert reverse_string("") == ""
assert reverse_string("a") == "a"
def test_is_palindrome():
assert is_palindrome("madam") ==... | [
{
"docstring": "Returns the reversed version of the input string s.",
"function_declaration": "def reverse_string(s):",
"function_name": "reverse_string",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the input string s is a palindrome.",
"function_declaration": "def is_palindrome... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_string(s):\n \"\"\"\n Reverses the characters of the input string s.\n \"\"\"\n return s[::-1]\n\ndef is_palindrome(s):\n \"\"\"\n Checks if the input string s is... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041542",
"row_id": 41542,
"seed_ids": "['Qwen2-72B-Instruct_90408']"
} | 0.723146 | Filter_41542 | I | [
"reverse_string",
"is_palindrome",
"check_palindrome"
] | 3 | [
[
"is_palindrome",
"reverse_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0dff7e16bf2a1911448ad4536e271b7c4a591238 | cff5659b28f5c37e0a87689563b6c4e6bf5674aa | |||
v1.0 | instruct | Filter | Filter_41545_I | Write a Python script to convert JSON file(s) to CSV format. The script should be capable of handling multiple JSON files at once, as well as nested JSON objects. It should extract key-value pairs in a flattened structure for CSV. Include a function to assist in flattening nested JSON structures. | import json
import csv
import os
def flatten_json(json_obj, delimiter='.'):
"""
Flattens a nested json dictionary.
Parameters:
json_obj (dict): A dictionary representing the json object.
delimiter (str): The delimiter used to join nested keys.
Returns:
dict: A flattened dictionary.
... | from solution import flatten_json, json_files_to_csv
import json
import os
def test_flatten_json():
nested_json = {
"a": 1,
"b": {
"c": 2,
"d": {
"e": 3
}
}
}
expected_flat = {
"a": 1,
"b.c": 2,
"b.d.e": 3
... | [
{
"docstring": "Flattens a nested json dictionary.\n\nParameters:\njson_obj (dict): A dictionary representing the json object.\ndelimiter (str): The delimiter used to join nested keys.\n\nReturns:\ndict: A flattened dictionary.",
"function_declaration": "def flatten_json(json_obj, delimiter='.'):",
"fun... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\nimport csv\nimport os\n\ndef flatten_json(json_obj, parent_key='', sep='_'):\n \"\"\"\n Flattens a nested JSON object.\n \"\"\"\n items = []\n for k, v in json_obj.... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041545",
"row_id": 41545,
"seed_ids": "['Qwen2-72B-Instruct_90412']"
} | 0.699642 | Filter_41545 | I | [
"flatten_json",
"json_files_to_csv"
] | 2 | [
[
"json_files_to_csv",
"flatten_json"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8362fbbb6eead24b6c19d66f0bf5bb021be6ba35 | 8a357baae87a7178d6b377235a9d2452c6c1bc82 | |||
v1.0 | instruct | Filter | Filter_41553_I | There is a list unsorted : [102, 45, 74, 87, 35, 63, 17, 88, 13]. You have to implement your own sort function in Python to sort the list, but for an enhanced challenge, implement it using a less common sorting algorithm called "Tree Sort". Do not use the inbuilt 'sort()'. Also, make sure to eliminate any repeated valu... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, val... | from solution import tree_sort
def test_tree_sort_with_unsorted_list():
assert tree_sort([102, 45, 74, 87, 35, 63, 17, 88, 13]) == [13, 17, 35, 45, 63, 74, 87, 88, 102]
def test_tree_sort_with_duplicates():
assert tree_sort([102, 45, 74, 87, 35, 63, 45, 87, 88, 74, 17, 88, 13, 17]) == [13, 17, 35, 45, 63, 74,... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef insert(root, key):\n if root is None:\n return TreeN... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041553",
"row_id": 41553,
"seed_ids": "['Qwen2-72B-Instruct_90423']"
} | 0.647728 | Filter_41553 | I | [
"insert",
"in_order_traversal",
"tree_sort"
] | 3 | [
[
"tree_sort",
"in_order_traversal"
],
[
"tree_sort",
"insert"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 3d47c16c65fba70ca55a215dc654f0a21c708289 | 73b851896b19d57e99223159d237aae2ff6b977e | |||
v1.0 | instruct | Filter | Filter_41585_I | Write a code to find all the prime numbers from 0 to 100 and return them in a sorted order, while optimizing for efficiency and minimizing memory usage. | def sieve_of_eratosthenes(limit):
"""
Finds all prime numbers up to and including the given limit using the Sieve of Eratosthenes algorithm.
"""
if limit < 2:
return []
primes = [True] * (limit + 1)
primes[0] = primes[1] = False
p = 2
while p * p <= limit:
if primes... | from solution import primes_up_to_100
def test_primes_up_to_100():
prime_numbers = primes_up_to_100()
expected_primes = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97
]
assert prime_numbers == expected_primes
def test_primes_below_negat... | [
{
"docstring": "Finds all prime numbers up to and including the given limit using the Sieve of Eratosthenes algorithm.",
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Returns all prime num... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_primes(n=100):\n \"\"\"\n Finds all prime numbers from 0 to n and returns them in a sorted order.\n \"\"\"\n if n < 2:\n return []\n \n sieve = [True] * (n + ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041585",
"row_id": 41585,
"seed_ids": "['Qwen2-72B-Instruct_90472']"
} | 0.562771 | Filter_41585 | I | [
"sieve_of_eratosthenes",
"primes_up_to_100"
] | 2 | [
[
"primes_up_to_100",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f15f28968087610f30e2bdffafa8d88b3fef8b64 | f94f89798ad0bd817441e3117ff8bec3fd99b53c | |||
v1.0 | instruct | Filter | Filter_41592_I | Can you generate all unique permutations or combinations of a given list in an ordered manner without using any library function? Also, implement functionality to solve either for permutations or combinations, based on user input. Be sure to handle potential error conditions such as an empty list or an input that isn't... | def generate_permutations(lst):
if not isinstance(lst, list):
raise ValueError("Input must be a list")
if not lst:
return []
def _permute(data, start, end, result):
if start == end:
result.append(data[:])
else:
for i in range(start, end+1):
... | from solution import generate_permutations_or_combinations, generate_permutations, generate_combinations
def test_generate_permutations():
assert generate_permutations([1, 2, 3]) == [
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[2, 3, 1],
[3, 2, 1],
[3, 1, 2]
]
assert g... | [
{
"docstring": null,
"function_declaration": "def generate_permutations(lst):",
"function_name": "generate_permutations",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def generate_combinations(lst):",
"function_name": "generate_combinations",
"parame... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_permutations(arr):\n \"\"\"\n Generate all unique permutations of the given list in an ordered manner.\n \"\"\"\n if not isinstance(arr, list):\n return \"Input... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041592",
"row_id": 41592,
"seed_ids": "['Qwen2-72B-Instruct_90494']"
} | 0.637087 | Filter_41592 | I | [
"generate_permutations",
"generate_combinations",
"generate_permutations_or_combinations"
] | 3 | [
[
"generate_permutations_or_combinations",
"generate_combinations"
],
[
"generate_permutations_or_combinations",
"generate_permutations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2746fde891bd55b1523a41fdfa20cb1e595e18d1 | f30759e04dff67f2c48dc11e88ca7ebe59f82c37 | |||
v1.0 | instruct | Filter | Filter_41600_I | Write a Python code to compute the scalar product of two given vectors. Add validation checks to ensure the vectors have the same size and contain only numerical values. Also, instead of using built-in sum function, write your own summation function. | def sum_elements(elements):
"""
Returns the sum of the elements in the list.
Assumes all elements are numerical.
"""
total = 0
for element in elements:
total += element
return total
def scalar_product(vector1, vector2):
"""
Computes the scalar product (dot product) of two v... | from solution import scalar_product, sum_elements
def test_sum_elements():
assert sum_elements([1, 2, 3, 4]) == 10
assert sum_elements([0, 0, 0]) == 0
assert sum_elements([-1, 1, -1, 1]) == 0
def test_scalar_product_same_size_vectors():
assert scalar_product([1, 2, 3], [4, 5, 6]) == 32 # 1*4 + 2*5 + ... | [
{
"docstring": "Returns the sum of the elements in the list. \nAssumes all elements are numerical.",
"function_declaration": "def sum_elements(elements):",
"function_name": "sum_elements",
"parameter_list": "(elements)"
},
{
"docstring": "Computes the scalar product (dot product) of two vect... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def scalar_product(vector1, vector2):\n \"\"\"\n Returns the scalar product of two vectors.\n\n :param vector1: List of numerical values representing the first vector\n :param vect... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041600",
"row_id": 41600,
"seed_ids": "['Qwen2-72B-Instruct_90510']"
} | 0.532578 | Filter_41600 | I | [
"sum_elements",
"scalar_product"
] | 2 | [
[
"scalar_product",
"sum_elements"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a521745930e557262009560a778c4e70b74901d8 | 9d15f0e0acf1f12599f4e0cdba0d64189ec72570 | |||
v1.0 | instruct | Filter | Filter_41606_I | Write a Python program that generates a regularly advancing clock animation using ASCII characters, and write it to the standard output. The clock shows hours, minutes, and seconds. The output refreshes every second and erases the previous display. Overrun or non-printable characters from peripheral areas of the screen... | import time
import os
def get_time_string():
"""
Returns the current time formatted as HH:MM:SS
"""
return time.strftime("%H:%M:%S", time.localtime())
def clear_screen():
"""
Clears the terminal screen.
"""
os.system('cls' if os.name == 'nt' else 'clear')
def display_clock():
"""
... | from solution import get_time_string
def test_get_time_string_format():
current_time = get_time_string()
assert len(current_time) == 8
assert current_time[2] == ':' and current_time[5] == ':'
assert current_time[:2].isdigit()
assert current_time[3:5].isdigit()
assert current_time[6:].isdigit()
... | [
{
"docstring": "Returns the current time formatted as HH:MM:SS",
"function_declaration": "def get_time_string():",
"function_name": "get_time_string",
"parameter_list": "()"
},
{
"docstring": "Clears the terminal screen.",
"function_declaration": "def clear_screen():",
"function_name... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport os\n\ndef display_clock():\n while True:\n # Get the current time in hours, minutes, and seconds\n current_time = time.strftime('%H:%M:%S')\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041606",
"row_id": 41606,
"seed_ids": "['Qwen2-72B-Instruct_90532']"
} | 0.470555 | Filter_41606 | I | [
"get_time_string",
"clear_screen",
"display_clock"
] | 3 | [
[
"display_clock",
"clear_screen"
],
[
"display_clock",
"get_time_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6110b784bacf81d0656bf8a988e8baa2211053cd | 46e1c4ce6e3b1fc6530d3e3d99199054b3bfc691 | |||
v1.0 | instruct | Filter | Filter_41609_I | Modify the program so that the "count" variable counts from 0 to 100, but only prints the prime numbers. | def is_prime(n):
"""
Returns True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n == 2:
return True # 2 is the only even prime number
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
retur... | from solution import is_prime, print_prime_numbers
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(11) == True
assert is_prime(1) == False
assert is_prime(0) ==... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Prints prime numbers from 0 to 100.",
"function_declaration": "def print_prime_numbers():",
"fun... | [
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 <= 3:\n return True\n if n % 2 == 0 or ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041609",
"row_id": 41609,
"seed_ids": "['Qwen2-72B-Instruct_90537']"
} | 0.578142 | Filter_41609 | I | [
"is_prime",
"print_prime_numbers"
] | 2 | [
[
"print_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16859ae060e4d937ed52f9b45778c5951e7f93b0 | 3b0f04f1c81a1a231b2b018354d243b83161262c | |||
v1.0 | instruct | Filter | Filter_41619_I | How can I write a function in Python that calculates the Euclidean distance between two points (x1, y1) and (x2, y2) on a 2D plane? Furthermore, how can we modify this function to calculate the Euclidean distances between multiple points and a single reference point at once, returned as a list of distances? Also, expla... | import math
from typing import List, Tuple
def euclidean_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculate the Euclidean distance between two points (x1, y1) and (x2, y2).
"""
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def batch_euclidean_distance(points: List[Tuple[f... | from solution import euclidean_distance, batch_euclidean_distance
def test_euclidean_distance():
assert math.isclose(euclidean_distance(0, 0, 3, 4), 5.0, rel_tol=1e-9)
assert math.isclose(euclidean_distance(1, 1, 4, 5), 5.0, rel_tol=1e-9)
assert math.isclose(euclidean_distance(-1, -1, -4, -5), 5.0, rel_tol... | [
{
"docstring": "Calculate the Euclidean distance between two points (x1, y1) and (x2, y2).",
"function_declaration": "def euclidean_distance(x1, y1, x2, y2):",
"function_name": "euclidean_distance",
"parameter_list": "(x1, y1, x2, y2)"
},
{
"docstring": "Calculate the Euclidean distances bet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(x1, y1, x2, y2):\n \"\"\"\n Computes the Euclidean distance between two points (x1, y1) and (x2, y2).\n \"\"\"\n return math.sqrt((x2 - x1) **... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041619",
"row_id": 41619,
"seed_ids": "['Qwen2-72B-Instruct_90551']"
} | 0.704559 | Filter_41619 | I | [
"euclidean_distance",
"batch_euclidean_distance"
] | 2 | [
[
"batch_euclidean_distance",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3080ecbb0320ff3dfb0ff922b3fa1d032a80b2c2 | 356891397fa4ce3ca1ac40c7b4dcd1bcce2b6f05 | |||
v1.0 | instruct | Filter | Filter_41633_I | Write a Python function that checks if a string is a palindrome. A palindrome is a sequence of characters that reads the same backward as forward. Your function should be case-insensitive and handle punctuation. Also, write a function to check if every word in a given sentence is a palindrome. | def is_palindrome(s):
"""
Checks if the given string s is a palindrome.
This function is case-insensitive and ignores punctuation.
"""
import re
s = re.sub(r'[^A-Za-z0-9]', '', s).lower()
return s == s[::-1]
def all_words_palindrome(sentence):
"""
Checks if every word in the given s... | from solution import is_palindrome, all_words_palindrome
def test_is_palindrome():
assert is_palindrome("A man, a plan, a canal, Panama!") == True
assert is_palindrome("No 'x' in Nixon") == True
assert is_palindrome("hello") == False
assert is_palindrome("madam") == True
assert is_palindrome("Madam... | [
{
"docstring": "Checks if the given string s is a palindrome.\nThis function is case-insensitive and ignores punctuation.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Checks if every word in the given sentence... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_palindrome(s):\n \"\"\"\n Check if a given string is a palindrome.\n This function is case-insensitive and ignores punctuation.\n \"\"\"\n # Remove non-alpha... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041633",
"row_id": 41633,
"seed_ids": "['Qwen2-72B-Instruct_90582']"
} | 0.803901 | Filter_41633 | I | [
"is_palindrome",
"all_words_palindrome"
] | 2 | [
[
"all_words_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97766b7b6b5756fdcf7476a69b9c0c6e09a1af63 | 9811c1e80c36c5a3ca60fc1d739856414e0a8482 | |||
v1.0 | instruct | Filter | Filter_41657_I | Implement a k-nearest neighbor (k-NN) approach, a simple yet effective supervised machine learning algorithm using iris data. However, set certain limitations. Your task includes providing handwritten, well-commented, and clean code without the application of machine learning libraries like sklearn. Also, remember to n... | import math
from collections import Counter
def euclidean_distance(point1, point2):
"""
Calculates the Euclidean distance between two points in n-dimensional space.
"""
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def normalize(data):
"""
Normalizes the input data to hav... | import pytest
from solution import k_nearest_neighbors, load_iris_data
def test_knn_with_iris_data():
# Load Iris data
data, labels = load_iris_data()
# Define test cases (query points with expected class)
test_queries = [
([5.8, 2.7, 5.1, 1.9], 'Iris-virginica'),
([5.1, 3.5, 1.4, ... | [
{
"docstring": "Calculates the Euclidean distance between two points in n-dimensional space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Normalizes the input data to have m... | [
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 collections import Counter\nfrom operator import itemgetter\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Compute the Euclidean distance between two poin... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041657",
"row_id": 41657,
"seed_ids": "['Qwen2-72B-Instruct_90622']"
} | 0.382054 | Filter_41657 | I | [
"euclidean_distance",
"normalize",
"k_nearest_neighbors",
"load_iris_data"
] | 4 | [
[
"k_nearest_neighbors",
"euclidean_distance"
],
[
"k_nearest_neighbors",
"normalize"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dd8a96eafc15cb0435fdacf6532e83e86183dbfa | e911c7b2fc640e7d12603f6d3ffeffb0380beda1 | |||
v1.0 | instruct | Filter | Filter_41701_I | Source and work through a complex programming problem that requires understanding and applying the core concepts of the K Nearest Neighbors (KNN) algorithm. Your explanation should discuss different edge cases, the efficiency of the algorithm in various scenarios, and any steps in your resolution of this problem to hig... | import math
from collections import Counter
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
Each point is an iterable of coordinates.
"""
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def k_nearest_neighbors(train, test_point, ... | from solution import euclidean_distance, k_nearest_neighbors, predict_classification
def test_euclidean_distance():
assert euclidean_distance((1, 2), (4, 6)) == math.sqrt(25)
def test_k_nearest_neighbors():
dataset = [
[2, 2, 0],
[1, 1, 0],
[3, 3, 1],
[6, 6, 1]
]
te... | [
{
"docstring": "Calculate the Euclidean distance between two points.\nEach point is an iterable of coordinates.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the k neare... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n Each point is an iterable of ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041701",
"row_id": 41701,
"seed_ids": "['Qwen2-72B-Instruct_90703']"
} | 0.518905 | Filter_41701 | I | [
"euclidean_distance",
"k_nearest_neighbors",
"predict_classification"
] | 3 | [
[
"k_nearest_neighbors",
"euclidean_distance"
],
[
"predict_classification",
"k_nearest_neighbors"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ba6df397f50bbd0a1ee9a0793f819916d223bfb3 | e6c4533cbc24b1f54043b7760564e1127a5ab5eb | |||
v1.0 | instruct | Filter | Filter_41713_I | Craft a program function enabling computation of intersection within a pair of unsorted, node-based linear-structured data objects, also known as linked lists. The function should maintain the integrity of the original lists. | class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def get_list_elements(head):
"""
Retrieves all elements from the linked list starting with 'head' into a set.
"""
elements = set()
current = head
while current:
elements.add(c... | from solution import ListNode, find_intersection
def build_linked_list(values):
"""
Helper function to build a linked list from an iterable of values.
"""
dummy_head = ListNode(0)
current = dummy_head
for value in values:
current.next = ListNode(value)
current = current.next
... | [] | [
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, val=0, next=None):\n self.val = val\n self.next = next\n\ndef get_linked_list_intersection(headA, headB):\n \"\"\"\n Find the inters... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041713",
"row_id": 41713,
"seed_ids": "['Qwen2-72B-Instruct_90727']"
} | 0.467526 | Filter_41713 | I | [
"get_list_elements",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_list_elements"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 8a8d3047b27ebd55b669bf7c80f4dce9be94cceb | 02ca03d6ca37b9db6286e4e82661d29009ba63d0 | |||
v1.0 | instruct | Filter | Filter_41722_I | Could you write a python code to take N numbers of inputs from the user and sort them in increasing order using the 'Insertion Sort' algorithm? You are not allowed to use inbuild sorting function. | def insertion_sort(arr):
"""
Sorts a list of numbers in increasing order using the insertion sort algorithm.
Parameters:
arr (list of int/float): The list of numbers to be sorted.
Returns:
list of int/float: The sorted list of numbers.
"""
for i in range(1, len(arr)):
... | from solution import collect_and_sort_numbers, insertion_sort
def test_insertion_sort_empty_list():
assert insertion_sort([]) == []
def test_insertion_sort_single_element():
assert insertion_sort([1]) == [1]
def test_insertion_sort_sorted_list():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
... | [
{
"docstring": "Sorts a list of numbers in increasing order using the insertion sort algorithm.\n\nParameters:\n arr (list of int/float): The list of numbers to be sorted.\n\nReturns:\n list of int/float: The sorted list of numbers.",
"function_declaration": "def insertion_sort(arr):",
"function_n... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr):\n \"\"\"\n Sorts a list of numbers in increasing order using the insertion sort algorithm.\n \n Parameters:\n arr (list of int/float): The list of n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041722",
"row_id": 41722,
"seed_ids": "['Qwen2-72B-Instruct_90745']"
} | 0.604809 | Filter_41722 | I | [
"insertion_sort",
"collect_and_sort_numbers"
] | 2 | [
[
"collect_and_sort_numbers",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bd4d0c08c1dca50991f46c77a1b6475c8d03433a | 3fa9c0ee6f11c2fe0baecc507d29bae5eab81c32 | |||
v1.0 | instruct | Filter | Filter_41726_I | Given a list of numbers, write a Python program to create two dictionaries. The first dictionary should map each number to its cube, but only if it is a prime number. The second dictionary should map each number to the sum of its digits, but only if it is a composite number. | def is_prime(n):
"""Returns True if n is a prime number, otherwise False"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def sum_of_digits(n):
"""Returns the sum of the digits of n"""
return sum(int(digit) for di... | from solution import create_dictionaries, is_prime, sum_of_digits
def test_is_prime():
assert is_prime(2) == True
assert is_prime(4) == False
assert is_prime(11) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-3) == False
def test_sum_of_digits():
assert su... | [
{
"docstring": "Returns True if n is a prime number, otherwise False",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of the digits of n",
"function_declaration": "def sum_of_digits(n):",
"function_n... | [
1,
0,
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 if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041726",
"row_id": 41726,
"seed_ids": "['Qwen2-72B-Instruct_90752']"
} | 0.588462 | Filter_41726 | I | [
"is_prime",
"sum_of_digits",
"create_dictionaries"
] | 3 | [
[
"create_dictionaries",
"is_prime"
],
[
"create_dictionaries",
"sum_of_digits"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1b1ea0fdbd1218e28c3fdcdd56d894d16a27074c | da04084c23f61e00172ac08050b197fbeb3d5c64 | |||
v1.0 | instruct | Filter | Filter_41750_I | Generate a list of prime numbers from 1 to 100 using list comprehension in Python and also print the count of those prime numbers. Additionally, use the Sieve of Eratosthenes algorithm for finding prime numbers. | def sieve_of_eratosthenes(n):
"""
Returns a list of all prime numbers up to and including n using the Sieve of Eratosthenes algorithm.
Also returns the count of those prime numbers.
"""
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, False # 0 and 1 are not prime numbers
p = 2
whi... | from solution import sieve_of_eratosthenes, primes_up_to_100
def test_sieve_of_eratosthenes():
primes, count = sieve_of_eratosthenes(100)
expected_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
expected_count = 25
assert primes == expected_prim... | [
{
"docstring": "Returns a list of all prime numbers up to and including n using the Sieve of Eratosthenes algorithm.\nAlso returns the count of those prime numbers.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sieve_of_eratosthenes(limit):\n \"\"\"\n Generate a list of prime numbers from 2 to the given limit using the Sieve of Eratosthenes algorithm.\n \"\"\"\n sieve = [True] * (limi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041750",
"row_id": 41750,
"seed_ids": "['Qwen2-72B-Instruct_90796']"
} | 0.681102 | Filter_41750 | I | [
"sieve_of_eratosthenes",
"primes_up_to_100"
] | 2 | [
[
"primes_up_to_100",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de504853379ce44f2050d0e2ed7ec284e1bb53b1 | 9a958a90b4671d6d041cd83cc3102aff5a6a9c9d | |||
v1.0 | instruct | Filter | Filter_41755_I | Modify this code such that it returns a new list that contains elements from the given list only if they are multiples of 3 and 5, and are also prime numbers. The function should return the resulting list in reverse order. | 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 Tru... | from solution import filter_multiples_of_3_and_5_and_prime, is_prime
def test_is_prime():
assert is_prime(5) == True
assert is_prime(15) == False
assert is_prime(2) == True
assert is_prime(1) == False
assert is_prime(29) == True
def test_filter_multiples_of_3_and_5_and_prime_all_conditions_met():
... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filters elements from the given list that are multiples of both 3 and 5,\nand are also prime numbers, then returns the resulting ... | [
1,
0,
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 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": "00041755",
"row_id": 41755,
"seed_ids": "['Qwen2-72B-Instruct_90806']"
} | 0.580414 | Filter_41755 | I | [
"is_prime",
"filter_multiples_of_3_and_5_and_prime"
] | 2 | [
[
"filter_multiples_of_3_and_5_and_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c62634088b13648db81fff45eb4b6a107ba61ddb | c8c2af363dafcec84d5c8094ccd046c3d9722b3e | |||
v1.0 | instruct | Filter | Filter_41766_I | Given a list of integers, write a Python function using recursion to print the second last element of the list. You should not use direct indexing (like using list[-2]) to find the second last element, instead, you should implement your own logic to reach the solution. | def second_last_element(lst):
"""
Returns the second last element of the list using recursion.
"""
if len(lst) < 2:
raise ValueError("List must contain at least two elements")
return find_second_last(lst)
def find_second_last(lst):
if len(lst) == 2:
return lst[0]
return find... | from solution import second_last_element
def test_second_last_element():
assert second_last_element([1, 2, 3, 4]) == 3
def test_second_last_element_two_elements():
assert second_last_element([5, 6]) == 5
def test_second_last_element_large_list():
assert second_last_element([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])... | [
{
"docstring": "Returns the second last element of the list using recursion.",
"function_declaration": "def second_last_element(lst):",
"function_name": "second_last_element",
"parameter_list": "(lst)"
},
{
"docstring": null,
"function_declaration": "def find_second_last(lst):",
"fun... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def second_last_element(lst):\n \"\"\"\n Returns the second last element of the list using recursion.\n \"\"\"\n if len(lst) < 2:\n raise ValueError(\"List must contain at l... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041766",
"row_id": 41766,
"seed_ids": "['Qwen2-72B-Instruct_90831']"
} | 0.680734 | Filter_41766 | I | [
"second_last_element",
"find_second_last"
] | 2 | [
[
"second_last_element",
"find_second_last"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b329b58f9523cdfb823f91b8f63a1fefa0cb2bee | a1e80b61b5543bd6e32fcdf6600bf9afe433e993 | |||
v1.0 | instruct | Filter | Filter_41768_I | Develop a Python code to sort the given list of complex numbers in ascending order based on their magnitude. Also, you are required to design your own sorting algorithm instead of using Python's built-in sorting methods. Your algorithm should have a better time complexity than bubble sort which is O(n²). | def magnitude_complex(c):
"""
Returns the magnitude of a complex number.
"""
return (c.real**2 + c.imag**2)**0.5
def partition(arr, low, high):
"""
Helper function for the quicksort sorting algorithm.
"""
pivot = magnitude_complex(arr[high])
i = low - 1
for j in range(low, high)... | from solution import sort_complex_numbers
def test_sort_empty_list():
assert sort_complex_numbers([]) == []
def test_sort_single_element():
assert sort_complex_numbers([3 + 4j]) == [3 + 4j]
def test_sort_two_elements():
assert sort_complex_numbers([3 + 4j, 1 + 1j]) == [1 + 1j, 3 + 4j]
def test_sort_mult... | [
{
"docstring": "Returns the magnitude of a complex number.",
"function_declaration": "def magnitude_complex(c):",
"function_name": "magnitude_complex",
"parameter_list": "(c)"
},
{
"docstring": "Helper function for the quicksort sorting algorithm.",
"function_declaration": "def partition... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def magnitude(complex_number):\n \"\"\"\n Returns the magnitude of a complex number.\n \"\"\"\n return abs(complex_number)\n\ndef sort_complex_numbers(lst):\n \"\"\"\n Sorts ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041768",
"row_id": 41768,
"seed_ids": "['Qwen2-72B-Instruct_90834']"
} | 0.482108 | Filter_41768 | I | [
"magnitude_complex",
"partition",
"quicksort",
"sort_complex_numbers"
] | 4 | [
[
"partition",
"magnitude_complex"
],
[
"quicksort",
"partition"
],
[
"sort_complex_numbers",
"quicksort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a0c093788cce5695f37af7dc22a5eee9a2a2de64 | 406d0d3e54d911362888254550c754a0882eaef9 | |||
v1.0 | instruct | Filter | Filter_41785_I | Consider a "Hamming Compressor" that takes in long strings of English words and treats spaces between words as characters to compress them to a normalized form using Hamming codes. The objective is to find the indexes of certain characters in a series of words that makes it easy to reconstruct the string using less inf... | def hamming_distance(s1, s2):
"""
Compute the Hamming distance between two equal-length strings.
"""
if len(s1) != len(s2):
raise ValueError("Strings must be of the same length for Hamming distance computation.")
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def hamming_compressor(hex_stri... | from solution import hamming_compressor
def test_hamming_compressor_basic():
# Basic test case
hex_string = "1a2b 3c4d"
min_coords, max_coords = hamming_compressor(hex_string)
assert min_coords == (0, 1)
assert max_coords == (0, 1)
def test_hamming_compressor_identical():
# Identical words sho... | [
{
"docstring": "Compute the Hamming distance between two equal-length strings.",
"function_declaration": "def hamming_distance(s1, s2):",
"function_name": "hamming_distance",
"parameter_list": "(s1, s2)"
},
{
"docstring": "Returns the coordinates (word_id, char_id) with the minimum and maxim... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def hamming_distance(s1, s2):\n \"\"\"\n Compute the Hamming distance between two equal-length strings.\n \"\"\"\n if len(s1) != len(s2):\n raise ValueError(\"Strings must b... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041785",
"row_id": 41785,
"seed_ids": "['Qwen2-72B-Instruct_90870']"
} | 0.650749 | Filter_41785 | I | [
"hamming_distance",
"hamming_compressor"
] | 2 | [
[
"hamming_compressor",
"hamming_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 65fd0167ba0d818de2f31e2f4f3a6508e1e43ae7 | 27544a84c2adbbfcab94384d0fcc2f18720f6223 | |||
v1.0 | instruct | Filter | Filter_41788_I | I want to write a Python program to simulate a rock-paper-scissors game. The program should allow a user to input their choice (rock, paper, or scissors), and then generate a random choice for the computer opponent. Additionally, the program should include simple scoring logic. Once the user has played 3 games, it shou... | import random
def get_computer_choice():
"""
Returns a random choice of 'rock', 'paper', or 'scissors' for the computer.
"""
return random.choice(['rock', 'paper', 'scissors'])
def determine_winner(user_choice, computer_choice):
"""
Determines the winner of a rock-paper-scissors game.
... | from solution import get_computer_choice, determine_winner
def test_get_computer_choice():
choice = get_computer_choice()
assert choice in ['rock', 'paper', 'scissors']
def test_determine_winner_draw():
assert determine_winner('rock', 'rock') == 'draw'
assert determine_winner('paper', 'paper') == 'dra... | [
{
"docstring": "Returns a random choice of 'rock', 'paper', or 'scissors' for the computer.",
"function_declaration": "def get_computer_choice():",
"function_name": "get_computer_choice",
"parameter_list": "()"
},
{
"docstring": "Determines the winner of a rock-paper-scissors game.\n\nReturn... | [
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 get_computer_choice():\n return random.choice([\"rock\", \"paper\", \"scissors\"])\n\ndef determine_winner(user_choice, computer_choice):\n if user_choice == compute... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041788",
"row_id": 41788,
"seed_ids": "['Qwen2-72B-Instruct_90877']"
} | 0.427624 | Filter_41788 | I | [
"get_computer_choice",
"determine_winner",
"play_rock_paper_scissors"
] | 3 | [
[
"play_rock_paper_scissors",
"determine_winner"
],
[
"play_rock_paper_scissors",
"get_computer_choice"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9ea79793b113e647d7fb3a64de0abf4ff3a0cc42 | 0bc75249792dbe07d370e104a7e1c291be51db79 | |||
v1.0 | instruct | Filter | Filter_41795_I | Implement a collaboration filter recommendation engine for a movie recommendation system using Python. | import numpy as np
from collections import defaultdict
def cosine_similarity(vec1, vec2):
"""
Returns the cosine similarity between two vectors.
"""
dot_product = np.dot(vec1, vec2)
norm_vec1 = np.linalg.norm(vec1)
norm_vec2 = np.linalg.norm(vec2)
return dot_product / (norm_vec1 * norm_vec2... | from solution import cosine_similarity, collaborative_filtering
def test_cosine_similarity():
vec1 = [1, 2, 3]
vec2 = [1, 2, 3]
assert cosine_similarity(vec1, vec2) == 1.0
vec1 = [1, 0, 0]
vec2 = [0, 1, 0]
assert cosine_similarity(vec1, vec2) == 0.0
vec1 = [1, 1, 1]
vec2 = [1, 2, 1]
... | [
{
"docstring": "Returns the cosine similarity between two vectors.",
"function_declaration": "def cosine_similarity(vec1, vec2):",
"function_name": "cosine_similarity",
"parameter_list": "(vec1, vec2)"
},
{
"docstring": "Generates movie recommendations for a user based on collaborative filte... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom collections import defaultdict\n\ndef cosine_similarity(vec1, vec2):\n \"\"\"\n Returns the cosine similarity between two vectors.\n \"\"\"\n dot_product =... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041795",
"row_id": 41795,
"seed_ids": "['Qwen2-72B-Instruct_90888']"
} | 0.360791 | Filter_41795 | I | [
"cosine_similarity",
"collaborative_filtering"
] | 2 | [
[
"collaborative_filtering",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 975f40680d0d00346976a63d72dcb73a9b9d747a | bf577a0ac7764049b2374b21bc527e9a7f5a73c9 | |||
v1.0 | instruct | Filter | Filter_41801_I | Write a piece of code in Python to print a list of numbers and then print only the prime numbers in that list. | def is_prime(n):
"""
Returns True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def filter_primes(numbers):
"""
Given a list of numbers, return a list containin... | from solution import is_prime, filter_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(-1) == False
assert is_prime(0) == False
assert is_prime(1) == False
def test_filter_primes():
... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of numbers, return a list containing only the prime numbers.",
"function_declaration": ... | [
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.\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": "00041801",
"row_id": 41801,
"seed_ids": "['Qwen2-72B-Instruct_90900']"
} | 0.689157 | Filter_41801 | I | [
"is_prime",
"filter_primes"
] | 2 | [
[
"filter_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9a6bbf93897cf0c40da9882de0dd5ebf09b59fa1 | b8ae00b97a32185b1b7d2c2f5956e0b6fe145b32 | |||
v1.0 | instruct | Filter | Filter_41828_I | Develop a Python programme that not only computes the volume of a tetrahedron using the sides' lengths but also verifies the existence of the tetrahedron with given side lengths. The prompt will be extended with instructions and an example to clear up any potential confusion or ambiguity about the desired functionality... | import math
import numpy as np
def volume_of_tetrahedron(edges):
"""
Computes the volume of a tetrahedron given its side lengths.
Parameters:
- edges: A list of 6 edge lengths (a, b, c, d, e, f)
Returns:
- volume of the tetrahedron if it exists, else None
"""
if len(edges)... | def test_volume_of_tetrahedron_valid():
edges = [3, 3, 3, 3, 3, 3]
vol = volume_of_tetrahedron(edges)
assert vol is not None
assert math.isclose(vol, 3.18198, rel_tol=1e-5)
def test_volume_of_tetrahedron_invalid():
edges = [1, 1, 1, 5, 5, 5]
vol = volume_of_tetrahedron(edges)
assert vol is ... | [
{
"docstring": "Computes the volume of a tetrahedron given its side lengths.\n\nParameters:\n- edges: A list of 6 edge lengths (a, b, c, d, e, f)\n\nReturns:\n- volume of the tetrahedron if it exists, else None",
"function_declaration": "def volume_of_tetrahedron(edges):",
"function_name": "volume_of_te... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nimport numpy as np\n \ndef volume_of_tetrahedron(edges):\n \"\"\"\n Computes the volume of a tetrahedron given its side lengths.\n \n Parameters:\n - edges: A li... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00041828",
"row_id": 41828,
"seed_ids": "['Qwen2-72B-Instruct_90944']"
} | 0.540096 | Filter_41828 | I | [
"volume_of_tetrahedron",
"can_form_tetrahedron"
] | 2 | [
[
"volume_of_tetrahedron",
"can_form_tetrahedron"
]
] | 1 | [] | false | [] | false | pytest | false | [
"numpy"
] | false | 05914fff7fbdafbdb20a807c10556d76327ed153 | 40e00b01c3fbed8d85885c34d1cb37aa946d2bf9 | |||
v1.0 | instruct | Filter | Filter_41838_I | Build an application using Flask which takes a temperature as input and returns a corresponding temperature range category (Cold, Cool, Moderate, Warm, Hot). | from flask import Flask, request, jsonify
app = Flask(__name__)
def categorize_temperature(temp):
"""Categorizes the given temperature into a temperature range."""
if temp < 0:
return "Cold"
elif 0 <= temp < 15:
return "Cool"
elif 15 <= temp < 25:
return "Moderate"
elif 25 ... | import pytest
from solution import categorize_temperature
def test_categorize_temperature_cold():
assert categorize_temperature(-5) == "Cold"
def test_categorize_temperature_cool():
assert categorize_temperature(10) == "Cool"
def test_categorize_temperature_moderate():
assert categorize_temperature(20) =... | [
{
"docstring": "Categorizes the given temperature into a temperature range.",
"function_declaration": "def categorize_temperature(temp):",
"function_name": "categorize_temperature",
"parameter_list": "(temp)"
},
{
"docstring": null,
"function_declaration": "def temperature():",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\ndef get_temperature_category(temp):\n \"\"\"\n Returns the temperature range category based on the input temperature... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041838",
"row_id": 41838,
"seed_ids": "['Qwen2-72B-Instruct_90963']"
} | 0.429395 | Filter_41838 | I | [
"categorize_temperature",
"temperature"
] | 2 | [
[
"temperature",
"categorize_temperature"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | e25ea0c7415e1370c51bdf21016c6008677826c2 | 1014e8ad74463033be75204da52da252afb09735 | |||
v1.0 | instruct | Filter | Filter_41841_I | Create a python function that will shuffle the elements in a list in a manner that doesn't rely on the inbuilt shuffle function or any randomization libraries. Your function should implement a custom random function. To ensure correctness, also write a testing function that checks the correctness of your solution by te... | def pseudo_random(seed, limit):
"""
A very basic pseudo-random number generator function.
"""
variability = 6364136223846793005
incrementer = 1
seed = (seed * variability + incrementer) % limit
return seed
def custom_shuffle(lst):
"""
Shuffles a list without using in-built shuffle o... | from solution import custom_shuffle
def test_shuffle_unique_elements():
original = [1, 2, 3, 4, 5]
shuffled = custom_shuffle(original[:])
assert sorted(shuffled) == sorted(original)
def test_shuffle_same_elements():
original = [1, 1, 1, 1]
shuffled = custom_shuffle(original[:])
assert sorted(s... | [
{
"docstring": "A very basic pseudo-random number generator function.",
"function_declaration": "def pseudo_random(seed, limit):",
"function_name": "pseudo_random",
"parameter_list": "(seed, limit)"
},
{
"docstring": "Shuffles a list without using in-built shuffle or random libraries.",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_shuffle(lst):\n \"\"\"\n Shuffle elements in a list using a simple custom random-like process.\n \"\"\"\n n = len(lst)\n shuffled_lst = lst[:]\n \n def random_s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041841",
"row_id": 41841,
"seed_ids": "['Qwen2-72B-Instruct_90969']"
} | 0.652903 | Filter_41841 | I | [
"pseudo_random",
"custom_shuffle"
] | 2 | [
[
"custom_shuffle",
"pseudo_random"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 20cea3c5a0a9b366aab62a5a0624632823d3afc0 | 3c88259cd52ee221b4d8865d0985d9b542a09769 | |||
v1.0 | instruct | Filter | Filter_41853_I | Modified Himmelblau's Function: The standard Himmelblau's function defined as f(x, y) = (x^2 + y - 11)^2 + (x + y^2 -7)^2 has 4 minimum values, each with coordinates (-2.8051, 3.1313), (-3.7793, -3.2831), (3.5844, -1.8482), (3.5844, -1.8482). For each of these local minimum, write a Python function to return the base-2... | import numpy as np
import math
import csv
def himmelblau_function(x, y):
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
def modified_himmelblau_function(x, y):
"""
This function calculates log2(|6 * f(x, y) - 11|) where f(x, y) is the
Himmelblau's function.
"""
f_val = himmelblau_function(x, y)... | from solution import modified_himmelblau_function, apply_modified_himmelblau_function_to_data
def test_modified_himmelblau_function_known_points():
assert math.isclose(modified_himmelblau_function(-2.8051, 3.1313), math.log2(abs(6 * himmelblau_function(-2.8051, 3.1313) - 11)), rel_tol=1e-5)
assert math.isclose... | [
{
"docstring": null,
"function_declaration": "def himmelblau_function(x, y):",
"function_name": "himmelblau_function",
"parameter_list": "(x, y)"
},
{
"docstring": "This function calculates log2(|6 * f(x, y) - 11|) where f(x, y) is the\nHimmelblau's function.",
"function_declaration": "d... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\n\ndef himmelblau_function(x, y):\n \"\"\"\n Calculate the value of the Himmelblau's function.\n \"\"\"\n return (x**2 + y - 11)**2 + (x + y... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041853",
"row_id": 41853,
"seed_ids": "['Qwen2-72B-Instruct_90995']"
} | 0.457989 | Filter_41853 | I | [
"himmelblau_function",
"modified_himmelblau_function",
"load_coordinates_from_csv",
"apply_modified_himmelblau_function_to_data"
] | 4 | [
[
"apply_modified_himmelblau_function_to_data",
"load_coordinates_from_csv"
],
[
"apply_modified_himmelblau_function_to_data",
"modified_himmelblau_function"
],
[
"modified_himmelblau_function",
"himmelblau_function"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 5ae7d6afd192a41d20fb18751991727a5714a519 | 1dc36d933a1cc384beca887078ee438a4a56f0af | |||
v1.0 | instruct | Filter | Filter_41855_I | Suppose we need to measure the approximate time complexity of two sorting algorithms: Bubble Sort and Quick Sort, and to determine which performs better. To do so, we will create two Python programs. The first program will implement Bubble Sort, and the second will implement Quick Sort. We will then time the execution ... | import time
import random
def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x f... | import time
import random
from solution import bubble_sort, quick_sort, measure_time
def test_bubble_sort():
arr = [5, 3, 8, 4, 2]
bubble_sort(arr)
assert arr == [2, 3, 4, 5, 8]
def test_quick_sort():
arr = [5, 3, 8, 4, 2]
sorted_arr = quick_sort(arr)
assert sorted_arr == [2, 3, 4, 5, 8]
def ... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def quick_sort(arr):",
"function_name": "quick_sort",
"parameter_list": "(arr)"
},
{
"docstring... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport random\n\ndef bubble_sort(arr):\n \"\"\"\n Sorts an array using the bubble sort algorithm.\n \"\"\"\n n = len(arr)\n for i in range(n):\n for j in ran... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041855",
"row_id": 41855,
"seed_ids": "['Qwen2-72B-Instruct_90999']"
} | 0.433027 | Filter_41855 | I | [
"bubble_sort",
"quick_sort",
"measure_time",
"measure_sorting_algorithms"
] | 4 | [
[
"measure_sorting_algorithms",
"bubble_sort"
],
[
"measure_sorting_algorithms",
"measure_time"
],
[
"measure_sorting_algorithms",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d4c6aa5711e8ca1cf4507a2d04e190356d4e412c | b213f035c744b8aae290323f0f704e0eebbb112d | |||
v1.0 | instruct | Filter | Filter_41862_I | Could you write equivalent parallelized version of the given Python-OpenCV code for processing images? The original code filters an input image using a threshold value before applying a median blur. Also, if multiple images need to be processed, could you modify the code to process multiple images concurrently using th... | import cv2
from multiprocessing import Pool
def process_image(image_path, threshold_value=127, ksize=5):
"""
Processes an image by applying a threshold and then a median blur.
Parameters:
image_path (str): Path to the input image file.
threshold_value (int): Value for thresholding (def... | import cv2
import numpy as np
import tempfile
import os
from multiprocessing import Pool
from solution import process_image, process_multiple_images
def create_temp_image(size=(100, 100), color=128):
"""
Creates a temporary grayscale image for testing.
Parameters:
size (tuple): Size of the ima... | [
{
"docstring": "Processes an image by applying a threshold and then a median blur.\n\nParameters:\n image_path (str): Path to the input image file.\n threshold_value (int): Value for thresholding (default: 127).\n ksize (int): Kernel size for median blur (should be odd and greater than 1) (default: 5).... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cv2\nimport numpy as np\nfrom multiprocessing import Pool\n\ndef process_image(image_path, threshold_value=127, blur_ksize=5):\n \"\"\"\n This function reads an image, applies a b... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00041862",
"row_id": 41862,
"seed_ids": "['Qwen2-72B-Instruct_91009']"
} | 0.638958 | Filter_41862 | I | [
"process_image",
"process_multiple_images"
] | 2 | [
[
"process_multiple_images",
"process_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"numpy"
] | false | 1e978b831cb6b28b4f4158c546b28e84853212a1 | 666258c95dce8f5c16b0b8b9f402493956601d5a | |||
v1.0 | instruct | Filter | Filter_41877_I | Create a program that randomly generates an n x m matrix with integer values. Then, implement a method to calculate the determinant of the matrix manually (do not use any library with ready made determinant calculating functions). Moreover, you should implement exception handling, so the program notifies the user when ... | import random
def generate_matrix(n, m):
"""
Generates an n x m matrix with random integer values between 0 and 10.
"""
return [[random.randint(0, 10) for _ in range(m)] for _ in range(n)]
def get_matrix_minor(matrix, i, j):
"""
Helper function to get the minor matrix by removing the ith row a... | from solution import generate_matrix, calculate_determinant, get_matrix_minor
import pytest
def test_generate_matrix():
matrix = generate_matrix(3, 3)
assert len(matrix) == 3
assert all(len(row) == 3 for row in matrix)
def test_calculate_determinant_1x1():
matrix = [[5]]
assert calculate_deter... | [
{
"docstring": "Generates an n x m matrix with random integer values between 0 and 10.",
"function_declaration": "def generate_matrix(n, m):",
"function_name": "generate_matrix",
"parameter_list": "(n, m)"
},
{
"docstring": "Helper function to get the minor matrix by removing the ith row and... | [
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_matrix(n, m):\n \"\"\"\n Generates an n x m matrix with random integer values.\n \"\"\"\n return [[random.randint(0, 10) for _ in range(m)] for _ in r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00041877",
"row_id": 41877,
"seed_ids": "['Qwen2-72B-Instruct_91044']"
} | 0.481167 | Filter_41877 | I | [
"generate_matrix",
"get_matrix_minor",
"calculate_determinant"
] | 3 | [
[
"calculate_determinant",
"get_matrix_minor"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0cd4c3bff77b8b0b0703af16315ab56b63da7d18 | 190232d6f48f7dbac54f9588c17632da85246d45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.