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_31297_I
Develop a function that not only verifies if the accumulated sum of all individual digits of a provided integer is an odd number, but also determines if that sum is a prime number. This function should generate a boolean value, true when the criteria is met and false otherwise. Moreover, the function should be designed...
import math def is_prime(n): 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 def isPrimeOddSum(num): """ ...
from solution import isPrimeOddSum, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(11) == True assert is_prime(15) == False def test_isPrimeOddSum_positive_integer(): assert isPrimeO...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Checks if the sum of the digits of the given number (rounded, if necessary) is an odd prime number.", "function_declaration": "def isPrimeOddSum(num):"...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00031297", "row_id": 31297, "seed_ids": "['Qwen2-72B-Instruct_72500']" }
0.592236
Filter_31297
I
[ "is_prime", "isPrimeOddSum" ]
2
[ [ "isPrimeOddSum", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0aa11e8f19af282fd8e2d5f1b9d6b6fba22e2f07
4c63b297d3bd555ee6c5640f12eda57e6a079c78
v1.0
instruct
Filter
Filter_31445_I
Write a code script that generates a potentially infinite square matrix suffused with prime integers, beginning from the numeral 2 and proceeding in an orderly fashion. The script should also be able to handle requests for specific elements from this matrix (like the 3rd element in the 7th row, for example).
import itertools def is_prime(num): """Helper function to check if a number is prime.""" if num <= 1: return False for n in range(2, int(num**0.5) + 1): if num % n == 0: return False return True def generate_primes(): """Generate an infinite sequence of prime numbers.""...
from solution import is_prime, generate_primes, generate_prime_matrix, get_element_from_prime_matrix 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(11) == True assert is_prime(15) == False def te...
[ { "docstring": "Helper function to check if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Generate an infinite sequence of prime numbers.", "function_declaration": "def generate_primes():", ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031445", "row_id": 31445, "seed_ids": "['Qwen2-72B-Instruct_72747']" }
0.464049
Filter_31445
I
[ "is_prime", "generate_primes", "generate_prime_matrix", "get_element_from_prime_matrix" ]
4
[ [ "generate_prime_matrix", "generate_primes" ], [ "generate_primes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3b2de99d409e7e63bc7675d8b5585b6a8025f2ca
1a70d952408318e046b30dcf0401783c84a276e3
v1.0
instruct
Filter
Filter_31607_I
Create a program that reads a list of words and outputs the longest palindrome present in the list. If there are multiple palindromes of the same maximum length, output all of them. The program should handle large input sizes efficiently.
def is_palindrome(word): """ Check if the given word is a palindrome. """ return word == word[::-1] def longest_palindromes(words): """ Returns the list of longest palindromes in the input list of words. """ max_length = 0 result = [] for word in words: if is_palindrome...
from solution import is_palindrome, longest_palindromes def test_empty_list(): assert longest_palindromes([]) == [] def test_single_palindrome(): assert longest_palindromes(["racecar"]) == ["racecar"] def test_multiple_equal_length_palindromes(): assert longest_palindromes(["madam", "racecar", "noon", "l...
[ { "docstring": "Check if the given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Returns the list of longest palindromes in the input list of words.", "function_declaration": "de...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_longest_palindromes(words):\n \"\"\"\n Returns a list of the longest palindromes present in the input list.\n If there are multiple palindromes of the same maximum length, al...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00031607", "row_id": 31607, "seed_ids": "['Qwen2-72B-Instruct_73020']" }
0.769192
Filter_31607
I
[ "is_palindrome", "longest_palindromes" ]
2
[ [ "longest_palindromes", "is_palindrome" ] ]
1
[]
false
[]
false
pytest
true
[]
true
408f95da6f5cb6b276846380242a4fdf66deeb04
efb56542404df5678e3b2b71f4b064248cb46192
v1.0
instruct
Filter
Filter_31648_I
Implement a mutual recursion function in programming and explain the concept of mutual recursion. Provide an example of how mutual recursion can be used to solve a specific problem. Additionally, your solution should include error handling for potential stack overflow caused by excessive recursive calls.
def is_even(n): """ Determines if a number n is even using mutual recursion with is_odd. """ if n < 0: raise ValueError("Input must be a non-negative integer") if n == 0: return True else: return is_odd(n - 1) def is_odd(n): """ Determines if a number n is odd us...
from solution import is_even, is_odd def test_is_even_zero(): assert is_even(0) == True def test_is_even_positive(): assert is_even(4) == True assert is_even(10) == True def test_is_odd_positive(): assert is_odd(1) == True assert is_odd(9) == True def test_is_even_odd_relationship(): assert ...
[ { "docstring": "Determines if a number n is even using mutual recursion with is_odd.", "function_declaration": "def is_even(n):", "function_name": "is_even", "parameter_list": "(n)" }, { "docstring": "Determines if a number n is odd using mutual recursion with is_even.", "function_declar...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\n# Set a recursion limit to prevent potential stack overflow\nsys.setrecursionlimit(1000)\n\ndef is_even(n, depth=0):\n if depth > 1000:\n raise RecursionError(\"Maximum...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031648", "row_id": 31648, "seed_ids": "['Qwen2-72B-Instruct_73092']" }
0.461597
Filter_31648
I
[ "is_even", "is_odd" ]
2
[ [ "is_even", "is_odd" ], [ "is_odd", "is_even" ] ]
2
[]
false
[]
false
pytest
true
[]
true
503e62ac836854e4f6db31e3a930cf54232e234c
f34cd9720dcb44aed9d9340193e4da7ec5877dcc
v1.0
instruct
Filter
Filter_31758_I
Sort the strings in a given list of strings based on their length using bubble sort. Additionally, each string must be checked to ensure it contains only unique characters before it is sorted. If a string does not have all unique characters, it should be removed from the list.
def has_unique_chars(s): """ Check if a string has all unique characters. """ return len(s) == len(set(s)) def bubble_sort_by_length(strings): """ Bubble sort a list of strings based on their length, only including strings with unique characters. """ # Filter the strings to only inc...
from solution import bubble_sort_by_length, has_unique_chars def test_has_unique_chars(): assert has_unique_chars("abcdef") == True assert has_unique_chars("hello") == False assert has_unique_chars("") == True assert has_unique_chars("a") == True def test_bubble_sort_by_length(): assert bubble_sor...
[ { "docstring": "Check if a string has all unique characters.", "function_declaration": "def has_unique_chars(s):", "function_name": "has_unique_chars", "parameter_list": "(s)" }, { "docstring": "Bubble sort a list of strings based on their length,\nonly including strings with unique characte...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def has_unique_characters(s):\n \"\"\"\n Checks if a string has all unique characters.\n \"\"\"\n return len(s) == len(set(s))\n\ndef bubble_sort_by_length(strings):\n \"\"\"\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00031758", "row_id": 31758, "seed_ids": "['Qwen2-72B-Instruct_73297']" }
0.608134
Filter_31758
I
[ "has_unique_chars", "bubble_sort_by_length" ]
2
[ [ "bubble_sort_by_length", "has_unique_chars" ] ]
1
[]
false
[]
false
pytest
true
[]
true
39e3c04699da273caeef0e34931cf722b8a4b5a8
fa4725b23ca69e38571abc14911c7c878c29cfd9
v1.0
instruct
Filter
Filter_31786_I
Given the following code snippet in Python, which contains errors and does not function as expected, correct and enhance it to create a robust function. This function should verify if a given input is a perfect square, a perfect cube, or neither. Additionally, your solution must accommodate for negative numbers and zer...
import math def is_perfect_square(n): if n < 0: return False root = int(math.isqrt(n)) return root * root == n def is_perfect_cube(n): if n < 0: n = -n root = round(n ** (1. / 3)) return root * root * root == n def check_number(n): if n == 0: return "Perfect square...
from solution import is_perfect_square, is_perfect_cube, check_number def test_is_perfect_square(): assert is_perfect_square(0) == True assert is_perfect_square(1) == True assert is_perfect_square(4) == True assert is_perfect_square(9) == True assert is_perfect_square(-4) == False assert is_per...
[ { "docstring": null, "function_declaration": "def is_perfect_square(n):", "function_name": "is_perfect_square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_perfect_cube(n):", "function_name": "is_perfect_cube", "parameter_list": "(n)" }, { ...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def check_number(num):\n \"\"\"\n Returns a string indicating if the number is a perfect square, perfect cube, both, or neither.\n \"\"\"\n if num < 0:\n return \"Negative n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00031786", "row_id": 31786, "seed_ids": "['Qwen2-72B-Instruct_73339']" }
0.702533
Filter_31786
I
[ "is_perfect_square", "is_perfect_cube", "check_number" ]
3
[ [ "check_number", "is_perfect_cube" ], [ "check_number", "is_perfect_square" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3249126dbc99d1394a092e7a3ab95c22ace2891a
85e7f6e7a01a2449e16af3db08c8c41ce600b3ff
v1.0
instruct
Filter
Filter_31816_I
Design a Python function that computes not only the total volume but also the total surface area of a list of cylinders, spheres, and cones. Each entity is represented by a dictionary containing 'type', 'radius', 'height' (only for cylinders and cones), and 'segment' which refers to a segment of the total entity which ...
import math def compute_total_volume_and_surface_area(shapes): total_volume = 0 total_surface_area = 0 for shape in shapes: if shape['type'] == 'cylinder': volume, surface_area = cylinder_volume_and_surface_area(shape) elif shape['type'] == 'sphere': volume, surface...
from solution import compute_total_volume_and_surface_area def test_compute_total_volume_and_surface_area_cylinder(): shapes = [ {'type': 'cylinder', 'radius': 1, 'height': 2, 'segment': 1}, {'type': 'cylinder', 'radius': 2.5, 'height': 4.5, 'segment': 2} ] total_volume, total_surface_area ...
[ { "docstring": null, "function_declaration": "def compute_total_volume_and_surface_area(shapes):", "function_name": "compute_total_volume_and_surface_area", "parameter_list": "(shapes)" }, { "docstring": null, "function_declaration": "def cylinder_volume_and_surface_area(cylinder):", ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef calculate_volume_and_surface_area(shapes):\n \"\"\"\n Calculate total volume and surface area for a list of cylinders, spheres, and cones.\n\n Args:\n shapes (li...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031816", "row_id": 31816, "seed_ids": "['Qwen2-72B-Instruct_73391']" }
0.536806
Filter_31816
I
[ "compute_total_volume_and_surface_area", "cylinder_volume_and_surface_area", "sphere_volume_and_surface_area", "cone_volume_and_surface_area" ]
4
[ [ "compute_total_volume_and_surface_area", "cone_volume_and_surface_area" ], [ "compute_total_volume_and_surface_area", "cylinder_volume_and_surface_area" ], [ "compute_total_volume_and_surface_area", "sphere_volume_and_surface_area" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2a0356bcf35aecbd0baebd0b2a6361656b4db9cd
6c68b923aad8c52e7abd552251565cd88f20b6d4
v1.0
instruct
Filter
Filter_31847_I
Write a Python program that uses dynamic programming to find the longest common substring between two strings input by the user. Your program should consider that the input strings may contain uppercase, lowercase letters, digits, and special characters. Also, your program should be optimized such that the time complex...
import time def longest_common_substring(str1, str2): """ Returns the longest common substring between str1 and str2. """ if not str1 or not str2: return "" n = len(str1) m = len(str2) # Create a 2D array to store lengths of longest common suffixes # of substrings. ...
from solution import longest_common_substring def test_longest_common_substring_empty_input(): assert longest_common_substring("", "") == "" assert longest_common_substring("abc", "") == "" assert longest_common_substring("", "abc") == "" def test_longest_common_substring_no_common_substring(): assert...
[ { "docstring": "Returns the longest common substring between str1 and str2.", "function_declaration": "def longest_common_substring(str1, str2):", "function_name": "longest_common_substring", "parameter_list": "(str1, str2)" }, { "docstring": "Allow the user to test multiple pairs of strings...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef longest_common_substring(str1, str2):\n \"\"\"\n Returns the longest common substring between two input strings.\n\n Args:\n str1: The first input string.\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031847", "row_id": 31847, "seed_ids": "['Qwen2-72B-Instruct_73444']" }
0.640264
Filter_31847
I
[ "longest_common_substring", "run_tests" ]
2
[ [ "run_tests", "longest_common_substring" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eee7aac59d8ca7e25ad428fe6b7a466f60e6a3c9
40cc1453c3d1c8ad8f9679c8db6140f68fa7390f
v1.0
instruct
Filter
Filter_31910_I
Write the code for a function that takes three parameters n, m, and x and returns the sum of the first n prime numbers starting from m, where each prime number must be greater than x.
def is_prime(num): """ Check if the number is a prime. """ if num <= 1: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(num**0.5) + 1, 2): if num % i == 0: return False return True def sum_primes(n, m,...
from solution import sum_primes, is_prime def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(5) == True assert is_prime(29) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-1) == False d...
[ { "docstring": "Check if the number is a prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Return the sum of the first n prime numbers starting from m,\nwhere each prime number must be greater than x.", "funct...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 ==...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031910", "row_id": 31910, "seed_ids": "['Qwen2-72B-Instruct_73564']" }
0.635625
Filter_31910
I
[ "is_prime", "sum_primes" ]
2
[ [ "sum_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
116a4e1f1b3623a0202fbc09820c7df785a8c109
7843186ef80cf7326fb6535c41eed90cec4880fd
v1.0
instruct
Filter
Filter_32064_I
Given a list of words, generate all possible anagrams by reordering the characters in the words. However, the anagrams generated should only include words that are present in a given dictionary. The dictionary is provided as a separate file in a specified format. Additionally, the anagrams generated should not contain ...
import itertools import unicodedata def normalize_word(word): # Normalize unicode characters to their simplest form return unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('ascii') def load_dictionary(file_path): with open(file_path, 'r', encoding='utf-8') as f: dictionary = se...
import tempfile import os from solution import load_dictionary, generate_anagrams def test_normalize_word(): from solution import normalize_word assert normalize_word("é") == "e" def test_load_dictionary(): dict_content = "cat\nbat\ntab\nrat\n" with tempfile.NamedTemporaryFile(delete=False, mode='w', ...
[ { "docstring": null, "function_declaration": "def normalize_word(word):", "function_name": "normalize_word", "parameter_list": "(word)" }, { "docstring": null, "function_declaration": "def load_dictionary(file_path):", "function_name": "load_dictionary", "parameter_list": "(file_...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef load_dictionary(dictionary_file):\n \"\"\"\n Loads the dictionary from the specified file.\n Returns a set of words present in the dictionary.\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032064", "row_id": 32064, "seed_ids": "['Qwen2-72B-Instruct_73814']" }
0.607057
Filter_32064
I
[ "normalize_word", "load_dictionary", "generate_anagrams" ]
3
[ [ "generate_anagrams", "normalize_word" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8f5cfccefb8d5fc19ce6c8d3e41d20da601c13a8
bcd6b13804b0f87303eff32b115863c032b2954c
v1.0
instruct
Filter
Filter_32095_I
Write a function in Python that takes a list of strings as input and returns a list with the strings that have the lowest number of vowels.
def count_vowels(s): vowels = "aeiouAEIOU" return sum(1 for char in s if char in vowels) def strings_with_lowest_vowels(strings): if not strings: return [] vowel_counts = [count_vowels(s) for s in strings] min_vowels = min(vowel_counts) return [s for s, count in zip(strings, v...
from solution import strings_with_lowest_vowels def test_strings_with_no_vowels(): assert strings_with_lowest_vowels(["dry", "fly", "myth"]) == ["dry", "fly", "myth"] def test_mixed_vowel_and_consonant_strings(): assert strings_with_lowest_vowels(["hello", "world", "sky"]) == ["sky"] def test_all_vowel_strin...
[ { "docstring": null, "function_declaration": "def count_vowels(s):", "function_name": "count_vowels", "parameter_list": "(s)" }, { "docstring": null, "function_declaration": "def strings_with_lowest_vowels(strings):", "function_name": "strings_with_lowest_vowels", "parameter_list...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def count_vowels(s):\n \"\"\"Helper function to count the number of vowels in a string.\"\"\"\n vowels = 'aeiouAEIOU'\n return sum(1 for char in s if char in vowels)\n\ndef strings_wi...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00032095", "row_id": 32095, "seed_ids": "['Qwen2-72B-Instruct_73864']" }
0.74868
Filter_32095
I
[ "count_vowels", "strings_with_lowest_vowels" ]
2
[ [ "strings_with_lowest_vowels", "count_vowels" ] ]
1
[]
false
[]
false
pytest
true
[]
true
79835b46a512f47fd7de71bddc2edc5446c3b1f9
4ddfdfabd6cdb52016e54ed00cd4d89f6273112e
v1.0
instruct
Filter
Filter_32101_I
Write a Python program that not only reverses the order of a given list of integers but also, for the challenge, sorts any sublist of 3 elements in ascending order before the reversal. If the total number of elements in the list is less than 3, then just reverse the order of elements without sorting. Remember not to us...
def sort_three_elements(sublist): """ Sorts a sublist of three elements in ascending order using a simple sorting algorithm (e.g., bubble sort). """ for i in range(2): for j in range(2 - i): if sublist[j] > sublist[j + 1]: sublist[j], sublist[j + 1] = sublist[j +...
from solution import custom_reverse_and_sort_sublists def test_single_element(): assert custom_reverse_and_sort_sublists([1]) == [1] def test_two_elements(): assert custom_reverse_and_sort_sublists([2, 1]) == [1, 2] def test_three_elements_sorted(): assert custom_reverse_and_sort_sublists([3, 1, 2]) == [...
[ { "docstring": "Sorts a sublist of three elements in ascending order using a simple \nsorting algorithm (e.g., bubble sort).", "function_declaration": "def sort_three_elements(sublist):", "function_name": "sort_three_elements", "parameter_list": "(sublist)" }, { "docstring": "Reverses the or...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_list_with_sorting_sublists(lst):\n \"\"\"\n Reverses the order of a given list of integers. \n For sublists of 3 elements, sorts them in ascending order before the reversa...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00032101", "row_id": 32101, "seed_ids": "['Qwen2-72B-Instruct_73875']" }
0.662259
Filter_32101
I
[ "sort_three_elements", "custom_reverse_and_sort_sublists" ]
2
[ [ "custom_reverse_and_sort_sublists", "sort_three_elements" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9018235f07828dd96fb0c9e9c920893023926b02
296f18ec22a9b28902da7214a06a7d5e59e932ed
v1.0
instruct
Filter
Filter_32194_I
Haiku is a traditional form of Japanese poetry, consisting of three lines. The first and last lines of a Haiku have five syllables and the middle line has seven syllables (5, 7, 5). Write a function in Python that takes a string as input and checks whether it follows the syllable pattern of a Haiku. Your function shoul...
def count_syllables(word): vowels = "aeiouy" word = word.lower().strip() syllable_count = 0 if word: if word[0] in vowels: syllable_count += 1 for index in range(1, len(word)): if word[index] in vowels and word[index - 1] not in vowels: syllable_co...
from solution import is_haiku def test_is_haiku_correct_haiku(): haiku = "An old silent pond\nA frog jumps into the pond\nSplash! Silence again." assert is_haiku(haiku) == True def test_is_haiku_wrong_syllable_pattern(): haiku = "An old silent pond\nA frog jumps into pond\nSplash! Silence again." asse...
[ { "docstring": null, "function_declaration": "def count_syllables(word):", "function_name": "count_syllables", "parameter_list": "(word)" }, { "docstring": null, "function_declaration": "def is_haiku(poem):", "function_name": "is_haiku", "parameter_list": "(poem)" } ]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef count_syllables(text):\n \"\"\"\n Helper function to count the number of syllables in a given text.\n \"\"\"\n # Removing punctuation marks and converting to lower...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00032194", "row_id": 32194, "seed_ids": "['Qwen2-72B-Instruct_74022']" }
0.576039
Filter_32194
I
[ "count_syllables", "is_haiku" ]
2
[ [ "is_haiku", "count_syllables" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5571c3e3ce72f3dcb0c9c5325851be54ebb7fed8
beec689791662ec7e22b6a22d33eedbffda2f180
v1.0
instruct
Filter
Filter_32261_I
Write a code to create a FizzBuzz game, that prints the numbers from 1 to 100, replacing all the numbers divisible by 3 with the word "Fizz" and the numbers divisible by 5 with the word "Buzz". Additionally, for numbers divisible by both 3 and 5, replace them with the word "FizzBuzz". However, instead of using the modu...
def is_divisible_by(n, divisor): """ Checks if the number n is divisible by the given divisor without using any mathematical operators. """ count = 0 current = divisor while current <= n: current += divisor count += 1 return current - divisor == n def fizzbuzz_c...
from solution import is_divisible_by, fizzbuzz_custom def test_is_divisible_by(): assert is_divisible_by(9, 3) == True assert is_divisible_by(10, 5) == True assert is_divisible_by(15, 3) == True assert is_divisible_by(14, 5) == False assert is_divisible_by(17, 3) == False assert is_divisible_by...
[ { "docstring": "Checks if the number n is divisible by the given divisor without using\nany mathematical operators.", "function_declaration": "def is_divisible_by(n, divisor):", "function_name": "is_divisible_by", "parameter_list": "(n, divisor)" }, { "docstring": "Runs the FizzBuzz game fro...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_divisible_by(n, divisor):\n \"\"\"\n Check if a number n is divisible by a given divisor without\n using any mathematical operators or built-in functions.\n \"\"\"\n # Co...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032261", "row_id": 32261, "seed_ids": "['Qwen2-72B-Instruct_74120']" }
0.679532
Filter_32261
I
[ "is_divisible_by", "fizzbuzz_custom" ]
2
[ [ "fizzbuzz_custom", "is_divisible_by" ] ]
1
[]
false
[]
false
pytest
true
[]
true
97a9704c21451d0a2c3f49d6222e25b6b0b64f3f
ca762ab86db0de68254f272041f7b25ccf491c1b
v1.0
instruct
Filter
Filter_32349_I
Develop a Python program that determines and displays all the Fibonacci prime numbers that are less than a given number N. Remember, a Fibonacci prime is a Fibonacci number that is prime. For instance, if N = 1000, the output should include all Fibonacci primes less than 1000.
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 def fibo...
from solution import is_prime, fibonacci_numbers, fibonacci_primes def test_is_prime(): assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(9) assert is_prime(13) def test_fibonacci_numbers(): assert fibonacci_numbers(10) == [0, 1, 1, 2, 3, 5...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generate Fibonacci numbers up to a given limit.", "function_declaration": "def fibonacci_numbers(limit):", "function_name"...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(num):\n \"\"\" Check if a number is prime. \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032349", "row_id": 32349, "seed_ids": "['Qwen2-72B-Instruct_74287']" }
0.73675
Filter_32349
I
[ "is_prime", "fibonacci_numbers", "fibonacci_primes" ]
3
[ [ "fibonacci_primes", "fibonacci_numbers" ], [ "fibonacci_primes", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8b788854cfcb45b3282b5c61db3b840f675285e3
3405f328b91f52bd444b82628422da13afac1ba6
v1.0
instruct
Filter
Filter_32380_I
Create a Python program to not only search a pattern in a given text using the Boyer Moore algorithm, but also return the starting indexes of all occurrences of the pattern. Additionally, implement a function to preprocess the pattern for the algorithm. Your solution should also account for patterns and texts with a la...
def preprocess_bad_character(pattern): """ Preprocess the pattern to create the bad character shift table. """ bad_char = [-1] * 256 for i in range(len(pattern)): bad_char[ord(pattern[i])] = i return bad_char def boyer_moore_search(text, pattern): """ Search for all occurrences ...
from solution import boyer_moore_search def test_pattern_found_once(): text = "HERE IS A SIMPLE EXAMPLE" pattern = "EXAMPLE" assert boyer_moore_search(text, pattern) == [17] def test_pattern_not_found(): text = "HERE IS A SIMPLE EXAMPLE" pattern = "NOTFOUND" assert boyer_moore_search(text, pat...
[ { "docstring": "Preprocess the pattern to create the bad character shift table.", "function_declaration": "def preprocess_bad_character(pattern):", "function_name": "preprocess_bad_character", "parameter_list": "(pattern)" }, { "docstring": "Search for all occurrences of the pattern in the g...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def preprocess_bm_bad_char(pattern):\n \"\"\"\n Preprocess the pattern and create the bad character shift table.\n \"\"\"\n bad_char_shift = {}\n pattern_length = len(pattern)\n...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00032380", "row_id": 32380, "seed_ids": "['Qwen2-72B-Instruct_74336']" }
0.536608
Filter_32380
I
[ "preprocess_bad_character", "boyer_moore_search" ]
2
[ [ "boyer_moore_search", "preprocess_bad_character" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4fdcfe77c0cf754e059a710d8b720fa5583f6637
4eb72c8ed844bc2864fa6922f8fa0be5107111ea
v1.0
instruct
Filter
Filter_32393_I
Write a Python code to sort the names into ascending and descending order based on the number of vowels in the name. Tie breakers should be the length of the names. If these parameters fail to break a tie, names should be ordered alphabetically.
def count_vowels(name): vowels = {'a', 'e', 'i', 'o', 'u'} return sum(1 for char in name.lower() if char in vowels) def sort_names_ascending(names): """ Sorts the names in ascending order based on the number of vowels. Tie breakers are the length of the name and alphabetical order. """ retu...
from solution import count_vowels, sort_names_ascending, sort_names_descending def test_count_vowels(): assert count_vowels("Daniel") == 3 assert count_vowels("Alex") == 2 assert count_vowels("Bryce") == 1 assert count_vowels("Sky") == 0 def test_sort_names_ascending(): names = ["Daniel", "Alex", ...
[ { "docstring": null, "function_declaration": "def count_vowels(name):", "function_name": "count_vowels", "parameter_list": "(name)" }, { "docstring": "Sorts the names in ascending order based on the number of vowels.\nTie breakers are the length of the name and alphabetical order.", "fun...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def count_vowels(name):\n \"\"\"\n Counts the number of vowels in a given name.\n \"\"\"\n vowels = 'aeiouAEIOU'\n return sum(1 for char in name if char in vowels)\n\ndef sort_n...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032393", "row_id": 32393, "seed_ids": "['Qwen2-72B-Instruct_74352']" }
0.627374
Filter_32393
I
[ "count_vowels", "sort_names_ascending", "sort_names_descending" ]
3
[ [ "sort_names_ascending", "count_vowels" ], [ "sort_names_descending", "count_vowels" ] ]
2
[]
false
[]
false
pytest
true
[]
true
46108da6bae993477053b2917151cc60b62a8043
f4fa4321d745542f20f3a0dd73b250d4a20dabb0
v1.0
instruct
Filter
Filter_32398_I
Write a program that generates a random number between 1 and 100 and allows the user to guess the number. The program should give feedback to the user whether their guess is too high, too low, or correct. After the user guesses the number correctly, the program should display the number of attempts it took for the user...
import random def guess_number_game(): attempts = 0 number_to_guess = random.randint(1, 100) guess = None while guess != number_to_guess: guess = int(input("Enter your guess (between 1 and 100): ")) attempts += 1 if guess < number_to_guess: print("Your guess is ...
from solution import guess_number_game, play_game import pytest import builtins def test_guess_number_game_correct_guess(monkeypatch): inputs = iter([50, 50, 50]) # assuming the generated random number is 50 monkeypatch.setattr('builtins.input', lambda _: next(inputs)) monkeypatch.setattr('random.randint'...
[ { "docstring": null, "function_declaration": "def guess_number_game():", "function_name": "guess_number_game", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def play_game():", "function_name": "play_game", "parameter_list": "()" } ]
[ 0, 0, 0, 1, 1, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef generate_random_number():\n return random.randint(1, 100)\n\ndef guess_number():\n target = generate_random_number()\n attempts = 0\n while True:\n gues...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00032398", "row_id": 32398, "seed_ids": "['Qwen2-72B-Instruct_74362']" }
0.521221
Filter_32398
I
[ "guess_number_game", "play_game" ]
2
[ [ "play_game", "guess_number_game" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5c5388af2e39483a63f7f1b75e246f8397b03a7c
76464b3f30fec1aa3b8edd8449d3ac868a2d2c2c
v1.0
instruct
Filter
Filter_32526_I
Suppose we have a string like "aeiou". Design a function that accepts a sentence and the above-mentioned string. The function should return the number of words in the sentence that only have substrings from the given string. Moreover, the sentence may have punctuation and uppercase letters. Your function must also hand...
import string def is_only_from_substring(word, allowed_chars): """ Checks if the given word consists only of characters from allowed_chars. """ return all(char in allowed_chars for char in word) def count_words_with_only_substring(sentence, substring): """ Returns the number of words in the se...
from solution import count_words_with_only_substring def test_count_words_with_only_substring_all(): assert count_words_with_only_substring("aeiou, aeiou.", "aeiou") == 2 def test_count_words_with_only_substring_mixed(): assert count_words_with_only_substring("Hello, aeioU!", "aeiou") == 1 def test_count_wor...
[ { "docstring": "Checks if the given word consists only of characters from allowed_chars.", "function_declaration": "def is_only_from_substring(word, allowed_chars):", "function_name": "is_only_from_substring", "parameter_list": "(word, allowed_chars)" }, { "docstring": "Returns the number of...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import string\n\ndef count_valid_words(sentence, valid_chars):\n \"\"\"\n Returns the number of words in the sentence that only have characters from the valid_chars string.\n \n Pa...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032526", "row_id": 32526, "seed_ids": "['Qwen2-72B-Instruct_74573']" }
0.722948
Filter_32526
I
[ "is_only_from_substring", "count_words_with_only_substring" ]
2
[ [ "count_words_with_only_substring", "is_only_from_substring" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a4e62e45fda598513d29803ffa739b427f380a62
08972cdaf7750016a49e535affb6f1836d6e41ac
v1.0
instruct
Filter
Filter_32547_I
Implement the insertion sort algorithm to sort the given array of integers in descending order. Instead of swapping elements, however, you should use a binary search to find the correct position for each element. Also, for every operation that moves an element (excluding the initial placement of the element to be inser...
def binary_search_desc(arr, val, start, end): while start < end: mid = (start + end) // 2 if arr[mid] > val: start = mid + 1 else: end = mid return start def insertion_sort_desc_with_moves(arr): move_count = 0 for i in range(1, len(arr)): val = ar...
from solution import insertion_sort_desc_with_moves def test_sorted_array(): arr, moves = insertion_sort_desc_with_moves([5, 3, 2, 1]) assert arr == [5, 3, 2, 1] assert moves == 0 def test_reverse_sorted_array(): arr, moves = insertion_sort_desc_with_moves([1, 2, 3, 4]) assert arr == [4, 3, 2, 1] ...
[ { "docstring": null, "function_declaration": "def binary_search_desc(arr, val, start, end):", "function_name": "binary_search_desc", "parameter_list": "(arr, val, start, end)" }, { "docstring": null, "function_declaration": "def insertion_sort_desc_with_moves(arr):", "function_name":...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def binary_search(arr, val, start, end):\n \"\"\"\n Helper function to perform binary search.\n Finds the index where `val` should be inserted in the array from start to end.\n \"\...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00032547", "row_id": 32547, "seed_ids": "['Qwen2-72B-Instruct_74602']" }
0.645404
Filter_32547
I
[ "binary_search_desc", "insertion_sort_desc_with_moves" ]
2
[ [ "insertion_sort_desc_with_moves", "binary_search_desc" ] ]
1
[]
false
[]
false
pytest
true
[]
true
46f3bee5a04409b131325bcb26b9321c245909d2
caf3f5d40443f22ec22b9c45e941cdcdd4e9a945
v1.0
instruct
Filter
Filter_32572_I
Given a huge text data T (up to 1GB), implement a program that finds the longest repeated substring not only in common English words but also considers numerals, punctuation, and special characters. In addition, compare the result with the set of common English substrings provided. Misleadingly, a preliminary function ...
def find_longest_repeated_substring(text): """ Finds the longest repeated substring in the given text. """ n = len(text) suffixes = sorted((text[i:], i) for i in range(n)) longest_substring = "" for i in range(n - 1): lcp = _longest_common_prefix(suffixes[i][0], suffixes[i + 1][...
from solution import find_longest_repeated_substring, filter_common_substrings def test_find_longest_repeated_substring(): text = "banana" assert find_longest_repeated_substring(text) == "ana" def test_find_longest_repeated_substring_with_special_chars(): text = "abc!abc$abc" assert find_longest_repea...
[ { "docstring": "Finds the longest repeated substring in the given text.", "function_declaration": "def find_longest_repeated_substring(text):", "function_name": "find_longest_repeated_substring", "parameter_list": "(text)" }, { "docstring": "Finds the longest common prefix between two string...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def longest_repeated_substring(T):\n \"\"\"\n Returns the longest repeated substring in the given text T.\n \"\"\"\n n = len(T)\n suffixes = sorted([T[i:] for i in range(n)])\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032572", "row_id": 32572, "seed_ids": "['Qwen2-72B-Instruct_74639']" }
0.704284
Filter_32572
I
[ "find_longest_repeated_substring", "_longest_common_prefix", "filter_common_substrings" ]
3
[ [ "find_longest_repeated_substring", "_longest_common_prefix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1d78e1aa179025504f52cf7aa99df4f9460a1717
6e30a444d048e45631b7960ab07c385131562d77
v1.0
instruct
Filter
Filter_32609_I
Write a Python code segment using the Beautiful Soup library to parse an HTML page and present the equivalent of its structure in a tree data-type. Your function should also handle HTTP errors and SSL exceptions, without using try/except block from scratch; rather, use specific exceptions from requests module. Before y...
import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import os def check_content_type(url): response = requests.head(url, allow_redirects=True) return response.headers['Content-Type'] def download_pdf(url, filename='downloaded.pdf'): response = requests.get(url) with open(fi...
import pytest from solution import check_content_type, download_pdf, parse_html_to_tree from unittest.mock import patch import requests TEST_HTML = """ <!DOCTYPE html> <html> <head> <title>Test HTML</title> </head> <body> <h1>Heading</h1> <p>Paragraph</p> </body> </html> """ TEST_URL_HTML = "http://exampl...
[ { "docstring": null, "function_declaration": "def check_content_type(url):", "function_name": "check_content_type", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def download_pdf(url, filename='downloaded.pdf'):", "function_name": "download_pdf", "par...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\nimport os\n\ndef fetch_and_parse_url(url, save_path):\n \"\"\"\n Fetches the content from the given URL. If the content is HTML,\n it p...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00032609", "row_id": 32609, "seed_ids": "['Qwen2-72B-Instruct_74697']" }
0.605481
Filter_32609
I
[ "check_content_type", "download_pdf", "parse_html_to_tree" ]
3
[ [ "parse_html_to_tree", "check_content_type" ], [ "parse_html_to_tree", "download_pdf" ] ]
2
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
eba8a6931b7558034bed1c40bff75157d9ec252c
47f8dbc6ba0d743f3de2d432dee6b3d2c5a0fdc1
v1.0
instruct
Filter
Filter_32612_I
Given a list of emails and corresponding info, write a code to keep only the emails and transform the list into a dictionary of emails and corresponding info. Each email must be validated to ensure it is in the correct format of [username]@[domain].[extension]. The dictionary should also include the length of each emai...
import re def valid_email(email): """ Validate if the email is in the correct format [username]@[domain].[extension] """ email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$' return re.match(email_regex, email) is not None def transform_list_to_dict(email_info_list): """ Transform list of emails and c...
from solution import valid_email, transform_list_to_dict def test_valid_email(): assert valid_email("user@example.com") assert not valid_email("userexample.com") assert valid_email("user.name@example.co.uk") assert not valid_email("user@.com") assert not valid_email("user@domain") def test_transfo...
[ { "docstring": "Validate if the email is in the correct format [username]@[domain].[extension]", "function_declaration": "def valid_email(email):", "function_name": "valid_email", "parameter_list": "(email)" }, { "docstring": "Transform list of emails and corresponding info into a \ndictiona...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef validate_email(email):\n \"\"\"\n Validates if the email is in the correct format [username]@[domain].[extension].\n \"\"\"\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032612", "row_id": 32612, "seed_ids": "['Qwen2-72B-Instruct_74702']" }
0.552539
Filter_32612
I
[ "valid_email", "transform_list_to_dict" ]
2
[ [ "transform_list_to_dict", "valid_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6d112d0dbb1216870fef65da532d230dcd04bea7
10836f697e857866c74723de108935b3fc7c0f18
v1.0
instruct
Filter
Filter_32697_I
Given a list of words and a string, create a function that finds the word in the list that can be formed by deleting some characters of the given string. The resulting word must be the longest word in the list that can be formed by this operation. If there are multiple words of the same length, return the one that appe...
def can_form_by_deleting(word, s): """ Checks if the word can be formed by deleting some characters in s. """ it = iter(s) return all(ch in it for ch in word) def find_longest_word(words, s): """ Finds the longest word in the list that can be formed by deleting some characters of s. If ...
from solution import find_longest_word def test_find_longest_word_single_match(): assert find_longest_word(['a', 'b', 'c'], 'abc') == 'a' def test_find_longest_word_multiple_matches(): assert find_longest_word(['ale', 'apple', 'monkey', 'plea'], 'abpcplea') == 'apple' def test_find_longest_word_multiple_...
[ { "docstring": "Checks if the word can be formed by deleting some characters in s.", "function_declaration": "def can_form_by_deleting(word, s):", "function_name": "can_form_by_deleting", "parameter_list": "(word, s)" }, { "docstring": "Finds the longest word in the list that can be formed b...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_longest_word(words, string):\n def can_form(word, string):\n it = iter(string)\n return all(char in it for char in word)\n \n longest_word = \"\"\n for word ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032697", "row_id": 32697, "seed_ids": "['Qwen2-72B-Instruct_74831']" }
0.652562
Filter_32697
I
[ "can_form_by_deleting", "find_longest_word" ]
2
[ [ "find_longest_word", "can_form_by_deleting" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9c021c8ced9d67fb65f61b2ce289e88e2b30c022
fede0ad7064db449397402781ee4905016691283
v1.0
instruct
Filter
Filter_32728_I
Write a Python function that finds the average value of every third element in a given list of integers starting from the third element. Also, write a separate function to validate the input list based on certain criteria - it should only allow lists of non-zero integers with a length of at least seven.
def validate_input_list(lst): """ Validate the input list based on the following criteria: - The list should contain only non-zero integers. - The length of the list should be at least seven. Returns True if the input list is valid, otherwise False. """ return isinstance(lst, list) and ...
from solution import validate_input_list, average_of_every_third_element def test_validate_input_list_valid(): assert validate_input_list([1, 2, 3, 4, 5, 6, 7]) == True assert validate_input_list([10, 20, 30, 40, 50, 60, 70, 80, 90]) == True def test_validate_input_list_invalid(): assert validate_input_li...
[ { "docstring": "Validate the input list based on the following criteria:\n- The list should contain only non-zero integers.\n- The length of the list should be at least seven.\n\nReturns True if the input list is valid, otherwise False.", "function_declaration": "def validate_input_list(lst):", "functio...
[ 0, 0, 0, 0, 1, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_average_of_every_third_element(numbers):\n \"\"\"\n Finds the average value of every third element in the given list of integers, \n starting from the third element.\n \n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00032728", "row_id": 32728, "seed_ids": "['Qwen2-72B-Instruct_74883']" }
0.67343
Filter_32728
I
[ "validate_input_list", "average_of_every_third_element" ]
2
[ [ "average_of_every_third_element", "validate_input_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9bc2a8d63dad88f2709b39bb9339a3b7b9680f33
66d8929948be2af56e3147d23ce65cb372abc7e2
v1.0
instruct
Filter
Filter_33009_I
Write a python function that takes a matrix of integers and a list of indices as inputs. The function should only add up the elements at each index in the list, but only if the sum of digits of the row and column indices (sum of digits of row index + sum of digits of column index) is an odd number. In this task, the in...
def digit_sum(n): """ Helper function to calculate the sum of digits of a number. """ return sum(int(digit) for digit in str(n)) def special_sum(matrix, indices): """ Returns the sum of matrix elements at specified indices where the sum of the digits of row and column indices is an odd numb...
from solution import special_sum def test_special_sum_non_matching_indices(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] indices = [(0, 0), (1, 1), (2, 2)] assert special_sum(matrix, indices) == 0 # All indices' sum of digits are even. def test_special_sum_some_matching_indi...
[ { "docstring": "Helper function to calculate the sum of digits of a number.", "function_declaration": "def digit_sum(n):", "function_name": "digit_sum", "parameter_list": "(n)" }, { "docstring": "Returns the sum of matrix elements at specified indices where\nthe sum of the digits of row and ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sum_at_indices_if_odd_digit_sum(matrix, indices):\n \"\"\"\n Sums elements at specified indices in the matrix if the sum \n of digits of the row and column indices is an odd numbe...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033009", "row_id": 33009, "seed_ids": "['Qwen2-72B-Instruct_75361']" }
0.710239
Filter_33009
I
[ "digit_sum", "special_sum" ]
2
[ [ "special_sum", "digit_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9cef91c31fd42d48c96389b97779b375b572d531
e838521eac186bc3717cc8fba71ce3879a2e42bd
v1.0
instruct
Filter
Filter_33059_I
You need to print all possible paths from top left to bottom right of a mXn matrix mat. The matrix elements contains 0 or 1. A value of mat[i][j] as 1 means the cell is invalid and cannot be traversed, but 0 means it can be traversed. Note, you can only traverse down and right.
def print_all_paths(mat, i, j, path, res): """ Helper function to find all paths from top left to bottom right of the matrix mat. """ # dimensions of the matrix m = len(mat) n = len(mat[0]) # if destination (bottom-right) is reached if i == m - 1 and j == n - 1: path.append((i, ...
from solution import get_all_paths def test_no_obstacles(): mat = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] expected_paths = [ [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)], [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)], [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)], [(0,...
[ { "docstring": "Helper function to find all paths from top left to bottom right of the matrix mat.", "function_declaration": "def print_all_paths(mat, i, j, path, res):", "function_name": "print_all_paths", "parameter_list": "(mat, i, j, path, res)" }, { "docstring": "Returns all possible pa...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def find_paths(matrix):\n \"\"\"\n Finds all possible paths from top left to bottom right of the matrix,\n only traversing cells with value 0 and only moving down and right.\n\n :p...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033059", "row_id": 33059, "seed_ids": "['Qwen2-72B-Instruct_75461']" }
0.586735
Filter_33059
I
[ "print_all_paths", "get_all_paths" ]
2
[ [ "get_all_paths", "print_all_paths" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5321d0b3d5730df1745fe0de6bee1c45dd5e26a6
965d8a54427ddd720f319f8dc624016e7278a3b1
v1.0
instruct
Filter
Filter_33068_I
Given an array of integers, implement the merge sort algorithm to sort the array in non-decreasing order. Do not use any built-in sorting functions or methods. Additionally, your implementation should be able to handle large arrays of up to 10^6 elements efficiently.
def merge_sort(array): """ Sorts an array using the merge sort algorithm. :param array: List of integers to be sorted :return: Sorted list of integers in non-decreasing order """ if len(array) <= 1: return array # Split the array into two halves mid = len(array) // 2 ...
from solution import merge_sort def test_merge_sort_empty_array(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_sorted_array(): assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_merge_sort_reverse_sorted_array(): ass...
[ { "docstring": "Sorts an array using the merge sort algorithm.\n\n:param array: List of integers to be sorted\n:return: Sorted list of integers in non-decreasing order", "function_declaration": "def merge_sort(array):", "function_name": "merge_sort", "parameter_list": "(array)" }, { "docstri...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts an array of integers in non-decreasing order using the merge sort algorithm.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n mid =...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033068", "row_id": 33068, "seed_ids": "['Qwen2-72B-Instruct_75477']" }
0.700327
Filter_33068
I
[ "merge_sort", "merge" ]
2
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d0312bf364749fde016f4cde55deaa8abae8c8d5
eb1cc92ab1bda3110b79271b2c7437d62c229c2b
v1.0
instruct
Filter
Filter_33084_I
Given the set of characters S which can only consist of '{}', '()' or '[]', write a function that will generate and return every possible balanced bracket sequence of length n, where n is a multiple of the length of S, using each type of bracket in S at least once in every sequence. Sequences differing just by the orde...
from itertools import permutations def is_balanced(sequence): stack = [] bracket_map = {')': '(', ']': '[', '}': '{'} for char in sequence: if char in bracket_map.values(): stack.append(char) elif char in bracket_map.keys(): if stack == [] or bracket_map[char] != sta...
from solution import generate_bracket_sequences, is_balanced def test_generate_balanced_sequence(): result = generate_bracket_sequences('{}()[]', 6) assert "{[()]}" in result or "{[()()]}" in result def test_generate_balanced_sequence_impossible_case(): result = generate_bracket_sequences('{}()[]', 5) ...
[ { "docstring": null, "function_declaration": "def is_balanced(sequence):", "function_name": "is_balanced", "parameter_list": "(sequence)" }, { "docstring": null, "function_declaration": "def generate_bracket_sequences(S, n):", "function_name": "generate_bracket_sequences", "param...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef generate_balanced_sequences(S, n):\n if n % len(S) != 0:\n return \"It is impossible to generate such sequences of length n\"\n \n def...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00033084", "row_id": 33084, "seed_ids": "['Qwen2-72B-Instruct_75509']" }
0.685965
Filter_33084
I
[ "is_balanced", "generate_bracket_sequences" ]
2
[ [ "generate_bracket_sequences", "is_balanced" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b0a951a9aebaa2e1b2ffd876fa39fe0c20bf76e5
62b4972df6613a0f8e3cf565cfefa62f37c055a3
v1.0
instruct
Filter
Filter_33160_I
Given a table with fruit prices in Euro, create a Python function that takes in the table as input, and a desired fruit. The function should check if the fruit is in the table, and if so, return the equivalent price in both US dollars and Mexican Pesos, using real-time exchange rates from reliable web services. If the ...
import requests def get_exchange_rates(): """ Fetches real-time exchange rates for USD and MXN against Euro. """ # Using predefined conversion rates for simplicity in this example. exchange_rates = { "USD": 1.1, # 1 Euro = 1.1 USD "MXN": 23.5 # 1 Euro = 23.5 MXN } ...
import pytest from solution import fruit_price_in_usd_and_mxn fruit_table = { "apple": 1.0, # Price in Euro "banana": 0.30, "orange": 0.50 } def test_fruit_price_in_usd_and_mxn_banana(): price_in_usd, price_in_mxn = fruit_price_in_usd_and_mxn(fruit_table, "banana") assert pytest.approx(pric...
[ { "docstring": "Fetches real-time exchange rates for USD and MXN against Euro.", "function_declaration": "def get_exchange_rates():", "function_name": "get_exchange_rates", "parameter_list": "()" }, { "docstring": "This function takes a table of fruit prices in Euro and a desired fruit as in...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\n\ndef get_exchange_rates():\n \"\"\"\n Fetches real-time exchange rates of USD to Euro and USD to MXN.\n Returns the exchange rates as a dictionary.\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033160", "row_id": 33160, "seed_ids": "['Qwen2-72B-Instruct_75646']" }
0.494304
Filter_33160
I
[ "get_exchange_rates", "fruit_price_in_usd_and_mxn" ]
2
[ [ "fruit_price_in_usd_and_mxn", "get_exchange_rates" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
6c3727d13e5b402b5a7e599bf55023ad1b69442c
b30bf71c9f6a6ee5bdb3f9293604d24ccf8dc3ce
v1.0
instruct
Filter
Filter_33230_I
Use Python code to generate a list of prime numbers between 1000 and 2000, and print out the sum of these prime numbers. Additionally, make sure the program uses multi-threading to speed up the computation process.
import threading 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 find_primes_in_range(start, end, result): pr...
from solution import is_prime, generate_primes_and_sum 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(20) == False assert is_prime(1013) == True assert is_prime(2000) == False def test_gener...
[ { "docstring": null, "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def find_primes_in_range(start, end, result):", "function_name": "find_primes_in_range", "parameter_list": "(...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl", "solution_code": "import threading\n\ndef is_prime(n):\n \"\"\"Return True if n is a prime number, else False.\"\"\"\n if n <= 1:\n return False\n if n == 2:\n re...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033230", "row_id": 33230, "seed_ids": "['Qwen2-72B-Instruct_75769']" }
0.593172
Filter_33230
I
[ "is_prime", "find_primes_in_range", "generate_primes_and_sum" ]
3
[ [ "find_primes_in_range", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4690e64c99ac8b3e174b0efb16a424c594b8311
82758f88a6d8fa56ca75ff4f91e3cab4a5d2bcf0
v1.0
instruct
Filter
Filter_33312_I
You are tasked with developing a Python function that sorts a dictionary of various, multilingual strings. The function should classify the strings based on their language, and within the language groups, it should sort the strings alphabetically. Your program should also include language detection functionality, which...
from collections import defaultdict def detect_language(sample): english_words = {"the", "hello", "world", "and", "is", "in", "this", "you", "are", "program"} spanish_words = {"el", "hola", "mundo", "y", "es", "en", "este", "tu", "eres", "programa"} french_words = {"le", "bonjour", "monde", "et", "est", "d...
from solution import sort_dictionary_by_language def test_detect_language(): assert detect_language("hello world") == "english" assert detect_language("el hola mundo") == "spanish" assert detect_language("bonjour le monde") == "french" assert detect_language("hello el bonjour") == "english" def test_s...
[ { "docstring": null, "function_declaration": "def detect_language(sample):", "function_name": "detect_language", "parameter_list": "(sample)" }, { "docstring": null, "function_declaration": "def sort_dictionary_by_language(d):", "function_name": "sort_dictionary_by_language", "pa...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict\nimport re\n\n# Simple set-based language detection\nENGLISH_WORDS = {\"the\", \"and\", \"is\", \"in\", \"it\"}\nSPANISH_WORDS = {\"el\", \"y\", \"es\", \"e...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00033312", "row_id": 33312, "seed_ids": "['Qwen2-72B-Instruct_75927']" }
0.55204
Filter_33312
I
[ "detect_language", "sort_dictionary_by_language" ]
2
[ [ "sort_dictionary_by_language", "detect_language" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1b2c2b8b8d33cc8f2261edc61dd8d78d74e327bf
9eaf82643b9491916ec5e9be2c5915c1a4a754fc
v1.0
instruct
Filter
Filter_33385_I
You're participating in a puzzle challenge in which you're given multiple questions, and randomStream() function. You need to solve one question from the given three: '1149', '1091', '0989'. You can only pick one, but before doing so, you need to use randomStream() to generate a random integer between 1 and 3 (inclusiv...
import random def randomStream(): return random.randint(1, 3) def is_palindrome(n): s = str(n) return s == s[::-1] def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def largest_prime_palindrome(arr)...
import pytest from solution import largest_prime_palindrome, add_strings, pick_and_solve_question def test_largest_prime_palindrome(): assert largest_prime_palindrome([1, 3, 7, 11, 101, 131, 181]) == 181 assert largest_prime_palindrome([2, 6, 8, 142, 232, 787]) == 787 assert largest_prime_palindrome([4, 6,...
[ { "docstring": null, "function_declaration": "def randomStream():", "function_name": "randomStream", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def is_palindrome(n):", "function_name": "is_palindrome", "parameter_list": "(n)" }, { "docstring":...
[ 0, 0, 0, 1, 0, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\nquestions = ['1149', '1091', '0989']\n\ndef randomStream():\n return random.randint(1, 3)\n\ndef is_prime(n):\n if n <= 1:\n return False\n for i in range(2, i...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00033385", "row_id": 33385, "seed_ids": "['Qwen2-72B-Instruct_76065']" }
0.481369
Filter_33385
I
[ "randomStream", "is_palindrome", "is_prime", "largest_prime_palindrome", "add_strings", "execute_question", "pick_and_solve_question" ]
7
[ [ "execute_question", "add_strings" ], [ "execute_question", "largest_prime_palindrome" ], [ "largest_prime_palindrome", "is_palindrome" ], [ "largest_prime_palindrome", "is_prime" ], [ "pick_and_solve_question", "execute_question" ], [ "pick_and_solve...
6
[]
false
[]
false
pytest
true
[]
true
babb5c59d22ccba4c0e5a7f36e6252382804a768
ccca33fa32e6912275da8eaa6102eea39641f285
v1.0
instruct
Filter
Filter_33409_I
Implement a parallel version of quick sort algorithm in Python using multiprocessing, that can sort a list of 10,000 integers efficiently. The implementation should partition the list into smaller sublists based on a pivot element, sort the sublists independently using multiple processes, and then merge the sorted subl...
from multiprocessing import Pool def quicksort_parallel(arr): if len(arr) <= 1: return arr else: pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort_paralle...
from solution import parallel_sort def test_parallel_sort_empty_list(): assert parallel_sort([]) == [] def test_parallel_sort_single_element(): assert parallel_sort([1]) == [1] def test_parallel_sort_already_sorted(): assert parallel_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] def test_parallel_sort_revers...
[ { "docstring": null, "function_declaration": "def quicksort_parallel(arr):", "function_name": "quicksort_parallel", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def parallel_sort(arr):", "function_name": "parallel_sort", "parameter_list": "(arr)" }...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing as mp\n\ndef quick_sort_parallel(arr):\n if len(arr) <= 1:\n return arr\n\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00033409", "row_id": 33409, "seed_ids": "['Qwen2-72B-Instruct_76110']" }
0.49805
Filter_33409
I
[ "quicksort_parallel", "parallel_sort" ]
2
[ [ "parallel_sort", "quicksort_parallel" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ddaf13c7140ead4b8baed3f53599d1192b114d8c
f3b42b69e70fb62a57445de2104d1a8bf1408fb9
v1.0
instruct
Filter
Filter_33484_I
Given a list of integers, write a Python function to find all the numbers with exactly three divisors using functional programming concepts.
def has_three_divisors(n): """ Helper function to check if a number has exactly three divisors. """ if n < 2: return False sqrt_n = int(n**0.5) if sqrt_n**2 != n: return False # Check if sqrt_n is a prime number for i in range(2, int(sqrt_n**0.5) + 1): if sq...
from solution import find_numbers_with_three_divisors def test_find_numbers_with_three_divisors_empty(): assert find_numbers_with_three_divisors([]) == [] def test_find_numbers_with_three_divisors_no_matches(): assert find_numbers_with_three_divisors([1, 2, 3, 5, 7, 11]) == [] def test_find_numbers_with_thre...
[ { "docstring": "Helper function to check if a number has exactly three divisors.", "function_declaration": "def has_three_divisors(n):", "function_name": "has_three_divisors", "parameter_list": "(n)" }, { "docstring": "Finds all the numbers with exactly three divisors in the provided list.",...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom functools import partial\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n max_div...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00033484", "row_id": 33484, "seed_ids": "['Qwen2-72B-Instruct_76241']" }
0.727315
Filter_33484
I
[ "has_three_divisors", "find_numbers_with_three_divisors" ]
2
[ [ "find_numbers_with_three_divisors", "has_three_divisors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7705570d561ba5ca2d7af75aa708b2d210f48186
75dde6ec4aea289086d6ec133b92248721cf81a4
v1.0
instruct
Filter
Filter_33504_I
Build a script in Python that can identify all the duplicate files within a specific directory and its subdirectories. The script should compare files with identical names and contents and should prompt you before deleting the duplicates. In addition, the script should generate a report file listing all duplicates foun...
import os import hashlib import shutil import time from pathlib import Path from collections import defaultdict def hash_file(filepath): """Generate MD5 hash for a file.""" hasher = hashlib.md5() with open(filepath, 'rb') as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update...
import os import tempfile import pytest from solution import find_duplicates, generate_report, prompt_delete_duplicates, prompt_backup_duplicates, rename_files_with_timestamp @pytest.fixture def setup_test_files(): with tempfile.TemporaryDirectory() as temp_dir: d1 = Path(temp_dir) / "dir1" d2 = Pa...
[ { "docstring": "Generate MD5 hash for a file.", "function_declaration": "def hash_file(filepath):", "function_name": "hash_file", "parameter_list": "(filepath)" }, { "docstring": "Find and list duplicate files in directory and its subdirectories.", "function_declaration": "def find_dupli...
[ 0, 0, 0, 1, 1, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport hashlib\nimport shutil\nfrom collections import defaultdict\n\ndef calculate_hash(file_path):\n \"\"\"\n Calculates the SHA-256 hash of a file.\n \"\"\"\n hasher ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00033504", "row_id": 33504, "seed_ids": "['Qwen2-72B-Instruct_76274']" }
0.582799
Filter_33504
I
[ "hash_file", "find_duplicates", "generate_report", "prompt_delete_duplicates", "prompt_backup_duplicates", "rename_files_with_timestamp" ]
6
[ [ "find_duplicates", "hash_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c5d7f85675655a3af54aaa98caa991034cf761a9
4e56d0ae5e63d8e913f3eaf76b3dcfa8745973c0
v1.0
instruct
Filter
Filter_33526_I
Can you explain A* pathfinding algorithm in simple terms and provide an implementation in Python?
import heapq def a_star(start, goal, neighbors_fn, heuristic_fn, cost_fn): """ Implementation of the A* pathfinding algorithm. :param start: The starting node :param goal: The goal node :param neighbors_fn: A function that takes a node and returns its neighbors :param heuristic_fn: A function ...
import pytest from solution import a_star def neighbors_fn(node): neighbors = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'] } return neighbors.get(node, []) def heuristic_fn(no...
[ { "docstring": "Implementation of the A* pathfinding algorithm.\n\n:param start: The starting node\n:param goal: The goal node\n:param neighbors_fn: A function that takes a node and returns its neighbors\n:param heuristic_fn: A function that takes two nodes and returns the heuristic estimate of the cost to reac...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef heuristic(a, b):\n \"\"\"\n Returns the Manhattan distance between points a and b.\n \"\"\"\n (x1, y1) = a\n (x2, y2) = b\n return abs(x1 - x2) + abs(y1 -...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033526", "row_id": 33526, "seed_ids": "['Qwen2-72B-Instruct_76312']" }
0.41865
Filter_33526
I
[ "a_star", "reconstruct_path" ]
2
[ [ "a_star", "reconstruct_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f11876cc0239a52001a048ebafb7005f2e3b83a6
cfcde31aa81ebdad19f926c52a1495ca4554d7aa
v1.0
instruct
Filter
Filter_33553_I
Create a program to find the closest string to the given string from a list of strings. The closest string is defined as the one that requires the minimum number of character modifications (insertions, deletions, or substitutions) to transform it into the given string. If there are multiple closest strings, return the ...
import itertools def levenshtein_distance(s1, s2): """ Compute the Levenshtein distance between two strings. """ if len(s1) < len(s2): return levenshtein_distance(s2, s1) # Initialize a matrix previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = ...
from solution import closest_string, levenshtein_distance def test_levenshtein_distance(): assert levenshtein_distance("kitten", "sitting") == 3 assert levenshtein_distance("flaw", "lawn") == 2 assert levenshtein_distance("", "abc") == 3 assert levenshtein_distance("abc", "abc") == 0 assert levensh...
[ { "docstring": "Compute the Levenshtein distance between two strings.", "function_declaration": "def levenshtein_distance(s1, s2):", "function_name": "levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": "Finds the closest string to the given string based on the Levenshtein ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def levenshtein_distance(s1, s2):\n \"\"\"\n Calculate the Levenshtein distance between two strings.\n \"\"\"\n if len(s1) < len(s2):\n return levenshtein_distance(s2, s1)\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033553", "row_id": 33553, "seed_ids": "['Qwen2-72B-Instruct_76364']" }
0.761469
Filter_33553
I
[ "levenshtein_distance", "closest_string" ]
2
[ [ "closest_string", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
011651ff2d9c5943b99ce71616093c25a0aca2d0
e91120cb7de367d1843c8551c6cf191a69c75883
v1.0
instruct
Filter
Filter_33602_I
Write a Python program to compare two strings s and t. The program should determine if t is an anagram of s. Additionally, implement a function that counts how many anagrams of s exist in t. Consider only unique anagrams.
from collections import Counter def is_anagram(s, t): """ Determines if t is an anagram of s. """ return Counter(s) == Counter(t) def count_unique_anagrams_in_text(s, t): """ Counts unique anagrams of s in t. """ len_s = len(s) count = 0 anagrams_set = set() for i in range(...
from solution import is_anagram, count_unique_anagrams_in_text def test_is_anagram_true(): assert is_anagram("listen", "silent") == True assert is_anagram("triangle", "integral") == True def test_is_anagram_false(): assert is_anagram("hello", "billion") == False assert is_anagram("rat", "car") == Fals...
[ { "docstring": "Determines if t is an anagram of s.", "function_declaration": "def is_anagram(s, t):", "function_name": "is_anagram", "parameter_list": "(s, t)" }, { "docstring": "Counts unique anagrams of s in t.", "function_declaration": "def count_unique_anagrams_in_text(s, t):", ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_anagram(s, t):\n \"\"\"\n Returns True if t is an anagram of s, False otherwise.\n \"\"\"\n return sorted(s) == sorted(t)\n\ndef count_unique_anagrams(s, t):\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033602", "row_id": 33602, "seed_ids": "['Qwen2-72B-Instruct_76444']" }
0.638684
Filter_33602
I
[ "is_anagram", "count_unique_anagrams_in_text" ]
2
[ [ "count_unique_anagrams_in_text", "is_anagram" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4383a9836abc3ce30c386f2bc5b654fe48b60844
1dd46e9800106042d30b3bfae68f6853777850c8
v1.0
instruct
Filter
Filter_33611_I
Create a Python program that builds a CLI-based Hangman game including audio hints for each wrong guess.
import random import os import sys import wave import contextlib def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def play_audio_hint(): try: os.system("aplay incorrect_guess.wav" if os.name == 'posix' else 'start incorrect_guess.wav') except: print("Audio hint not supp...
import pytest from solution import get_word, display_hangman def test_get_word(): word = get_word() assert word in ["python", "hangman", "challenge", "programming", "test"] def test_display_hangman(): assert display_hangman(0) == """ -------- | | | | ...
[ { "docstring": null, "function_declaration": "def clear_screen():", "function_name": "clear_screen", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def play_audio_hint():", "function_name": "play_audio_hint", "parameter_list": "()" }, { "docstring...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport os\nimport simpleaudio as sa\n\ndef load_words(file_path):\n \"\"\"\n Load words from a file and return as a list.\n \"\"\"\n with open(file_path, 'r') as fil...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033611", "row_id": 33611, "seed_ids": "['Qwen2-72B-Instruct_76457']" }
0.492473
Filter_33611
I
[ "clear_screen", "play_audio_hint", "get_word", "display_hangman", "hangman" ]
5
[ [ "hangman", "clear_screen" ], [ "hangman", "display_hangman" ], [ "hangman", "get_word" ], [ "hangman", "play_audio_hint" ] ]
4
[]
false
[]
false
pytest
true
[]
true
1cef2a12ce2894fe228befcfc49a3cabc6816d05
60952d41249c3ff8bee9fd8c9a6e6b16024fe0f6
v1.0
instruct
Filter
Filter_33777_I
Rewrite the code to use recursion instead of a for loop to calculate the sum of numbers from 0 to n (inclusive). Additionally, you are not allowed to use any built-in arithmetic operations or operators in your solution. Instead, you can only use the following operations: incrementation (num++), decrementation (num--), ...
def increment(num): return num + 1 def decrement(num): return num - 1 def add(num1, num2): while num2 > 0: num1 = increment(num1) num2 = decrement(num2) return num1 def recursive_sum(n): if n > 0: return add(n, recursive_sum(decrement(n))) else: return 0
from solution import recursive_sum def test_recursive_sum_zero(): assert recursive_sum(0) == 0 def test_recursive_sum_one(): assert recursive_sum(1) == 1 def test_recursive_sum_five(): assert recursive_sum(5) == 15 # 0+1+2+3+4+5=15 def test_recursive_sum_ten(): assert recursive_sum(10) == 55 # 0+1...
[ { "docstring": null, "function_declaration": "def increment(num):", "function_name": "increment", "parameter_list": "(num)" }, { "docstring": null, "function_declaration": "def decrement(num):", "function_name": "decrement", "parameter_list": "(num)" }, { "docstring": nul...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def increment(n):\n if n == 0:\n return 1\n return n + 1 - 1 # Ensure the incrementation remains legal without built-in operators\n\ndef decrement(n):\n if n == 0:\n re...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00033777", "row_id": 33777, "seed_ids": "['Qwen2-72B-Instruct_76750']" }
0.616921
Filter_33777
I
[ "increment", "decrement", "add", "recursive_sum" ]
4
[ [ "add", "decrement" ], [ "add", "increment" ], [ "recursive_sum", "add" ], [ "recursive_sum", "decrement" ] ]
4
[]
false
[]
false
pytest
true
[]
true
54fd774a2eaa4467d75cf81c9d6042fcfc446c82
1b9e740278a213c3425477f5d69b8dee6fecbfdb
v1.0
instruct
Filter
Filter_33784_I
Write a recursive function in Python to generate a list with the factorial of numbers from 1 to the given number, but instead of returning the actual factorial values, return the sum of digits in each factorial. Also, return the time complexity of your solution. Number: 15
def sum_of_digits(num): """ Calculate the sum of the digits of a number. """ return sum(int(digit) for digit in str(num)) def factorial(n): """ Calculate the factorial of a given number. """ if n == 0 or n == 1: return 1 return n * factorial(n - 1) def factorial_digits_sum_...
def test_sum_of_digits(): assert sum_of_digits(123) == 6 assert sum_of_digits(405) == 9 def test_factorial(): assert factorial(0) == 1 assert factorial(1) == 1 assert factorial(5) == 120 def test_factorial_digits_sum_list(): assert factorial_digits_sum_list(1) == [1] assert factorial_digit...
[ { "docstring": "Calculate the sum of the digits of a number.", "function_declaration": "def sum_of_digits(num):", "function_name": "sum_of_digits", "parameter_list": "(num)" }, { "docstring": "Calculate the factorial of a given number.", "function_declaration": "def factorial(n):", "...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sum_of_digits(n):\n \"\"\"Returns the sum of the digits of a number.\"\"\"\n return sum(int(digit) for digit in str(n))\n\ndef factorial(n):\n \"\"\"Returns the factorial of a num...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033784", "row_id": 33784, "seed_ids": "['Qwen2-72B-Instruct_76763']" }
0.698518
Filter_33784
I
[ "sum_of_digits", "factorial", "factorial_digits_sum_list" ]
3
[ [ "factorial_digits_sum_list", "factorial" ], [ "factorial_digits_sum_list", "sum_of_digits" ] ]
2
[]
false
[]
false
pytest
false
[]
true
0771027f81e1daae74602648d86f5837b2e66169
4c5bb55ef857a9c17e4832975f2b8a0cad36f146
v1.0
instruct
Filter
Filter_33825_I
How can I create a program using AI to predict if a given text is a spam email or not?
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score def preprocess_data(data): """ Prepares the data for training by converting it into a Dat...
from solution import train_spam_filter, predict_spam def test_train_spam_filter(): data = [ ("Win a free iPhone now!", "spam"), ("Meeting notes from yesterday", "not spam"), ("Congratulations! You've been selected...", "spam"), ("Can we reschedule our meeting?", "not spam"), ] ...
[ { "docstring": "Prepares the data for training by converting it into a DataFrame.", "function_declaration": "def preprocess_data(data):", "function_name": "preprocess_data", "parameter_list": "(data)" }, { "docstring": "Trains a spam filter model using a Naive Bayes classifier.", "functi...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import m...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033825", "row_id": 33825, "seed_ids": "['Qwen2-72B-Instruct_76828']" }
0.534088
Filter_33825
I
[ "preprocess_data", "train_spam_filter", "predict_spam" ]
3
[ [ "train_spam_filter", "preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
e12193e46b949f7f1cfe47b73988f98a20955fae
041c78fed1f64d3b042749ddb1e168f35d089a42
v1.0
instruct
Filter
Filter_33852_I
Write a code to check for palindromic spelled words within a given sentence and remedy the non-palindromic ones by reordering the letters to form a palindrome. Discuss the limitations and potential improvements for the algorithm's efficacy.
def is_palindrome(word): """ Helper function to check if a word is a palindrome. """ return word == word[::-1] def reorder_to_palindrome(word): """ Attempts to reorder the letters of a word to form a palindrome. If it's not possible, return the word unchanged. """ from collections i...
from solution import is_palindrome, reorder_to_palindrome, remedy_non_palindromic_words def test_is_palindrome(): assert is_palindrome("racecar") assert not is_palindrome("hello") assert is_palindrome("madam") assert is_palindrome("a") def test_reorder_to_palindrome(): assert reorder_to_palindrome...
[ { "docstring": "Helper function to check if a word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Attempts to reorder the letters of a word to form a palindrome.\nIf it's not possible, ret...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome(word):\n return word == word[::-1]\n\ndef make_palindrome(word):\n from collections import Counter\n counts = Counter(word)\n odd_chars = [char for char, count in...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033852", "row_id": 33852, "seed_ids": "['Qwen2-72B-Instruct_76870']" }
0.679804
Filter_33852
I
[ "is_palindrome", "reorder_to_palindrome", "remedy_non_palindromic_words" ]
3
[ [ "remedy_non_palindromic_words", "is_palindrome" ], [ "remedy_non_palindromic_words", "reorder_to_palindrome" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e2e507af0ccab5db6071531f5bd4fa6fba5c742c
5c5606d22abcfe9b390a8714614891530c55cf0b
v1.0
instruct
Filter
Filter_33853_I
Given a large piece of hexadecimal data, develop a Python program that can not only convert this data to binary, but also has the functionality to reverse the binary sequence and convert it back into hexadecimal. Additionally, ensure that the program can handle both uppercase and lowercase hexadecimal letters.
def hex_to_bin(hex_data): """ Converts a hexadecimal string to a binary string. """ return bin(int(hex_data, 16))[2:].zfill(len(hex_data) * 4) def bin_to_hex(bin_data): """ Converts a binary string to a hexadecimal string. """ return format(int(bin_data, 2), 'x') def reverse_bin(hex_da...
from solution import hex_to_bin, bin_to_hex, reverse_bin def test_hex_to_bin(): assert hex_to_bin('A') == '1010' assert hex_to_bin('1f') == '00011111' assert hex_to_bin('1F') == '00011111' assert hex_to_bin('FF') == '11111111' def test_bin_to_hex(): assert bin_to_hex('1010') == 'a' assert bin_...
[ { "docstring": "Converts a hexadecimal string to a binary string.", "function_declaration": "def hex_to_bin(hex_data):", "function_name": "hex_to_bin", "parameter_list": "(hex_data)" }, { "docstring": "Converts a binary string to a hexadecimal string.", "function_declaration": "def bin_t...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def hex_to_binary(hex_data):\n \"\"\"\n Convert hexadecimal data to binary data.\n \n Parameters:\n hex_data (str): Hexadecimal data as a string.\n \n Returns:\n str: B...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033853", "row_id": 33853, "seed_ids": "['Qwen2-72B-Instruct_76872']" }
0.580715
Filter_33853
I
[ "hex_to_bin", "bin_to_hex", "reverse_bin" ]
3
[ [ "reverse_bin", "bin_to_hex" ], [ "reverse_bin", "hex_to_bin" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f771a7a4309342ba95fcd765b11c5ff5093228ad
76c3d564e9fbbc65233d0225e130d4af441e6f09
v1.0
instruct
Filter
Filter_33875_I
Can you provide a Python code that calculates the String Similarity between two given strings under a particular similarity measure and a condition that the similarity should be above a certain threshold? Additionally, can you define a decorator that can be used to cache the results of this function to improve its perf...
from functools import lru_cache from difflib import SequenceMatcher def similarity_ratio(s1, s2): """ Returns the similarity ratio between two strings using SequenceMatcher. """ return SequenceMatcher(None, s1, s2).ratio() def cache_results(func): """ Decorator to cache results of the function...
from solution import is_similarity_above_threshold def test_similarity_above_threshold(): assert is_similarity_above_threshold("hello", "hallo", 0.7) == True def test_similarity_below_threshold(): assert is_similarity_above_threshold("hello", "world", 0.5) == False def test_similarity_exact_threshold(): ...
[ { "docstring": "Returns the similarity ratio between two strings using SequenceMatcher.", "function_declaration": "def similarity_ratio(s1, s2):", "function_name": "similarity_ratio", "parameter_list": "(s1, s2)" }, { "docstring": "Decorator to cache results of the function using Least Recen...
[ 0, 0, 0, 0, 1, 1, 1, 1, 1 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import lru_cache\n\ndef jaccard_similarity(str1, str2):\n \"\"\"\n Calculate the Jaccard Similarity between two strings.\n \"\"\"\n set1 = set(str1)\n set2 = set(...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033875", "row_id": 33875, "seed_ids": "['Qwen2-72B-Instruct_76899']" }
0.730619
Filter_33875
I
[ "similarity_ratio", "cache_results", "is_similarity_above_threshold" ]
3
[ [ "is_similarity_above_threshold", "similarity_ratio" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff5142fbdf9129540f7cc96ff3f7b02497104674
9a1880437a0dfc8d23b77f5aa6174b4a1130de25
v1.0
instruct
Filter
Filter_33886_I
Generate a 3 dimentional array of size 2x3x3 with all elements set to 0. Additionally, ensure that the array is initialized using a recursive function rather than a simple array initialization method.
def generate_3d_array(x, y, z): """ Generates a 3D array of dimensions x by y by z filled with zeros using recursion. """ if x == 0: return [] if y == 0: return generate_3d_array(x - 1, 3, z) if z == 0: return generate_3d_array(x, y - 1, 3) return [0] + generate_3d_ar...
from solution import generate_3d_array, reshape_3d_array, generate_3x3x3 def test_generate_3x3x3(): result = generate_3x3x3() expected = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] assert result == expected def test_generate_3d_array(): flat_array = gene...
[ { "docstring": "Generates a 3D array of dimensions x by y by z filled with zeros using recursion.", "function_declaration": "def generate_3d_array(x, y, z):", "function_name": "generate_3d_array", "parameter_list": "(x, y, z)" }, { "docstring": "Reshapes the flat array generated into a 3D ar...
[ 0, 0, 0, 1, 0, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_3d_array(dim_1, dim_2, dim_3):\n \"\"\"\n Create a 3-dimensional array of specified dimensions with all elements set to 0.\n This is achieved using a recursive function.\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033886", "row_id": 33886, "seed_ids": "['Qwen2-72B-Instruct_76914']" }
0.596275
Filter_33886
I
[ "generate_3d_array", "reshape_3d_array", "generate_3x3x3" ]
3
[ [ "generate_3x3x3", "generate_3d_array" ], [ "generate_3x3x3", "reshape_3d_array" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a6cc81c1cd0ff53bf1a1a34d6cca3cbfff3b2211
11bcec46e79a77baddf52baa368a6abb9ec3444a
v1.0
instruct
Filter
Filter_33919_I
Can you implement the Radix sort algorithm in a programming language of your choice that can sort a list of decimal floating point numbers? Besides the sorting function, include a function to also damp down the precision of the numbers to two decimal places.
def damp_to_two_decimal_places(numbers): """ Adjust the given list of floating point numbers to two decimal places. """ return [round(num, 2) for num in numbers] def counting_sort_for_radix(arr, exp, radix): """ A counting sort function to be used by radix sort for floating point numbers. "...
from solution import damp_to_two_decimal_places, radix_sort def test_damp_to_two_decimal_places(): assert damp_to_two_decimal_places([3.14159, 2.71828, 1.61803, 0.57721]) == [3.14, 2.72, 1.62, 0.58] assert damp_to_two_decimal_places([0.123456, 0.987654]) == [0.12, 0.99] assert damp_to_two_decimal_places([1...
[ { "docstring": "Adjust the given list of floating point numbers to two decimal places.", "function_declaration": "def damp_to_two_decimal_places(numbers):", "function_name": "damp_to_two_decimal_places", "parameter_list": "(numbers)" }, { "docstring": "A counting sort function to be used by ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def radix_sort(arr):\n \"\"\"\n Sorts a list of floating point numbers using Radix Sort algorithm.\n It first normalizes the precision of the numbers to two decimal places.\n \"\"\...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033919", "row_id": 33919, "seed_ids": "['Qwen2-72B-Instruct_76978']" }
0.487526
Filter_33919
I
[ "damp_to_two_decimal_places", "counting_sort_for_radix", "radix_sort" ]
3
[ [ "radix_sort", "counting_sort_for_radix" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ec9b074597d75dfc5b2bef68f876788816d0a19a
41c4b40d9e6b4b472840a9cfe298fc9d0ec073ae
v1.0
instruct
Filter
Filter_33946_I
Develop a Python program that performs error correction on a string of text using the Levenshtein Distance algorithm. This program should not only identify the errors but also correct them by comparing the given text with a reference text. In addition to this, implement a feature that can handle multilingual input and ...
import numpy as np def levenshtein_distance(s1, s2): """ Calculate the Levenshtein distance between two strings. """ len_s1 = len(s1) + 1 len_s2 = len(s2) + 1 matrix = np.zeros((len_s1, len_s2), dtype=int) for x in range(len_s1): matrix[x, 0] = x for y in range(len_s2): ...
from solution import levenshtein_distance, correct_text, keep_format def test_levenshtein_distance(): assert levenshtein_distance('kitten', 'sitting') == 3 assert levenshtein_distance('flaw', 'lawn') == 2 assert levenshtein_distance('gumbo', 'gambol') == 2 assert levenshtein_distance('', 'test') == 4 ...
[ { "docstring": "Calculate the Levenshtein distance between two strings.", "function_declaration": "def levenshtein_distance(s1, s2):", "function_name": "levenshtein_distance", "parameter_list": "(s1, s2)" }, { "docstring": "Correct the input text by comparing it with the reference text using...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import Levenshtein\n\ndef error_correct(text, reference):\n \"\"\"\n Corrects errors in the given text by comparing it with the reference text using the Levenshtein Distance algorithm.\n...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033946", "row_id": 33946, "seed_ids": "['Qwen2-72B-Instruct_77029']" }
0.58579
Filter_33946
I
[ "levenshtein_distance", "correct_text", "keep_format" ]
3
[ [ "correct_text", "levenshtein_distance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
1eba3a96ec40725405af8fc3ead2400b00f7c64f
e837cc0649e83f7d6a32201613e80c505816fdb0
v1.0
instruct
Filter
Filter_34134_I
I'm writing a script to insert the tips in the slot every day in a 5x5 ticket using Python. I'm trying to work out the best way to input a list of the numbers for the 6 daily draws; classic, express, flash, turbo1, turbo2 and sprint. Each column on the ticket can only contain one unique number from a predefined pool of...
import pandas as pd import random # Define the ticket size and numbers pool ticket_rows, ticket_columns = 5, 5 numbers_pool = list(range(1, 40)) assert len(numbers_pool) >= ticket_rows * ticket_columns # Define the days of the draw draw_days = ["classic", "express", "flash", "turbo1", "turbo2", "sprint"] # Initializ...
from solution import assign_ticket_numbers, numbers_pool def test_ticket_has_unique_numbers(): assign_ticket_numbers() used_numbers = set() for column in ticket.columns: for number in ticket[column]: assert number not in used_numbers, f"Number {number} is used more than once." ...
[ { "docstring": null, "function_declaration": "def assign_ticket_numbers():", "function_name": "assign_ticket_numbers", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def get_next_available_number():", "function_name": "get_next_available_number", "paramet...
[ 0, 0, 0, 1, 1, 1, 0, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport pandas as pd\n\ndef generate_ticket():\n \"\"\"\n Generate a 5x5 ticket with numbers from 1 to 39 ensuring each column\n contains unique numbers from a predefine...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00034134", "row_id": 34134, "seed_ids": "['Qwen2-72B-Instruct_77377']" }
0.534268
Filter_34134
I
[ "assign_ticket_numbers", "get_next_available_number", "simulate_draw" ]
3
[ [ "simulate_draw", "get_next_available_number" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
09404049388562b88726ee8cc4f023513fea5068
270c72cd8bc9bef2cebcbd0f9def91baa5b31ca7
v1.0
instruct
Filter
Filter_34162_I
Use PyTorch to write a function that predicts a class label based on five numerical features. The function should include a data preprocessing step that scales the input features between -1 and 1 using the Tanh scaling method. Additionally, the function should output both the predicted class probabilities and the predi...
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer class DeepNN(nn.Module): def __init__(self): super(DeepNN, self).__init__() ...
def test_preprocess_data(): data = np.array([[5, 3, np.nan, 4, 2], [10, np.nan, 5, 8, 9], [np.nan, 7, 6, 3, 2]]) processed_data = preprocess_data(data) assert processed_data.shape == (3, 5) assert not np.isnan(processed_data).any() assert np.all(processed_data >= -1) and np.all(processed_data <...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.impute import SimpleImputer\nfro...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00034162", "row_id": 34162, "seed_ids": "['Qwen2-72B-Instruct_77434']" }
0.447667
Filter_34162
I
[ "preprocess_data", "early_stopping", "predict_class" ]
3
[ [ "predict_class", "preprocess_data" ] ]
1
[]
false
[ "DeepNN" ]
true
pytest
false
[ "numpy", "sklearn", "torch" ]
false
cbc5f998dbd6a51317e897f7379209cb1f79863d
a0ea0d4b0b3ae8b8df4ec4ebbc798b34835b11de
v1.0
instruct
Filter
Filter_34205_I
Given a list of points in the format (x,y), create a function in Python that returns a list of point pairs [(x0,y0), (x1,y1)], where (x0,y0) is nearest to any other point (including itself), and (x1,y1) is the second nearest point to (x0,y0).
import math def distance(point1, point2): """ Calculate the Euclidean distance between two points. """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) def nearest_points(points): """ Given a list of points, returns a list of tuples where each tuple contains a poin...
from solution import nearest_points def test_nearest_points_sample(): points = [(0, 0), (1, 1), (2, 2), (3, 1)] expected = [((0, 0), (1, 1)), ((1, 1), (0, 0)), ((2, 2), (1, 1)), ((3, 1), (2, 2))] assert nearest_points(points) == expected def test_nearest_points_single_point(): points = [(0, 0)] ex...
[ { "docstring": "Calculate the Euclidean distance between two points.", "function_declaration": "def distance(point1, point2):", "function_name": "distance", "parameter_list": "(point1, point2)" }, { "docstring": "Given a list of points, returns a list of tuples where each tuple\ncontains a p...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import sqrt\n\ndef distance(point1, point2):\n return sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)\n\ndef nearest_points(points):\n results = []\n for i...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00034205", "row_id": 34205, "seed_ids": "['Qwen2-72B-Instruct_77502']" }
0.70317
Filter_34205
I
[ "distance", "nearest_points" ]
2
[ [ "nearest_points", "distance" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a57cb8e84c439545d0cd6c5ab4e7b77054648ec0
c1069c790a0fe96d0d7ba309fc6ab1987eb5d9a8
v1.0
instruct
Filter
Filter_34239_I
Create a Python program that takes in a list of integers and returns a new list where each element is the product of the previous and next prime numbers in the original list. The first and last elements in the original list should be treated as if they have a previous or next prime of 1. The program should also output ...
from sympy import isprime def find_previous_prime(x): """ Find the previous prime number before x. If x is 2 or less, return 1. """ if x <= 2: return 1 candidate = x - 1 while candidate > 1: if isprime(candidate): return candidate candidate -= 1 retur...
from solution import prime_product_list def test_prime_product_list(): # Test case 1 input_list = [10, 20, 30, 40] result, total_sum = prime_product_list(input_list) assert result == [1*11, 19*23, 29*31, 37*1] assert total_sum == (1*11 + 19*23 + 29*31 + 37*1) # Test case 2 input_list =...
[ { "docstring": "Find the previous prime number before x.\nIf x is 2 or less, return 1.", "function_declaration": "def find_previous_prime(x):", "function_name": "find_previous_prime", "parameter_list": "(x)" }, { "docstring": "Find the next prime number after x.", "function_declaration":...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sympy\n\ndef find_previous_prime(number):\n if number <= 2:\n return 1\n return sympy.prevprime(number)\n\ndef find_next_prime(number):\n if number <= 1:\n return...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034239", "row_id": 34239, "seed_ids": "['Qwen2-72B-Instruct_77554']" }
0.623303
Filter_34239
I
[ "find_previous_prime", "find_next_prime", "prime_product_list" ]
3
[ [ "prime_product_list", "find_next_prime" ], [ "prime_product_list", "find_previous_prime" ] ]
2
[]
false
[]
false
pytest
true
[ "sympy" ]
false
4bb131c05bb05ce519a4f188987cd4e251802f52
99b97b59d36b4474fe453462990330ee00c88f2b
v1.0
instruct
Filter
Filter_34249_I
Write a Python program that generates all possible permutations of a given list of numbers and finds the inversion count for each permutation. Then, print the permutation with the maximum number of inversions.
from itertools import permutations def count_inversions(lst): """ Count the number of inversions in the list. An inversion is a pair (i, j) such that i < j and lst[i] > lst[j]. """ inv_count = 0 n = len(lst) for i in range(n): for j in range(i + 1, n): if lst[i] > lst[j]...
from solution import count_inversions, max_inversion_permutation def test_count_inversions(): assert count_inversions([1, 2, 3]) == 0 assert count_inversions([1, 3, 2]) == 1 assert count_inversions([3, 2, 1]) == 3 assert count_inversions([3, 1, 2]) == 2 def test_max_inversion_permutation_single_elemen...
[ { "docstring": "Count the number of inversions in the list.\nAn inversion is a pair (i, j) such that i < j and lst[i] > lst[j].", "function_declaration": "def count_inversions(lst):", "function_name": "count_inversions", "parameter_list": "(lst)" }, { "docstring": "Find the permutation with ...
[ 0, 0, 0, 1, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import permutations\n\ndef count_inversions(arr):\n \"\"\"\n Counts the number of inversions in an array.\n An inversion is a pair (i, j) such that i < j and arr[i] > a...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00034249", "row_id": 34249, "seed_ids": "['Qwen2-72B-Instruct_77574']" }
0.745224
Filter_34249
I
[ "count_inversions", "max_inversion_permutation" ]
2
[ [ "max_inversion_permutation", "count_inversions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
537841658af7606b3befda12621d0147350d3ecf
0639d917c5d007bf6a3c7d0e1613dd7b90be23cc
v1.0
instruct
Filter
Filter_34304_I
Please write a Python program that adds two numbers and multiplies them. The program should also check if the product of the two numbers is a perfect square. Additionally, the program should return the prime factors of the product if it is not a perfect square.
import math def is_perfect_square(n): sqrt_n = int(math.sqrt(n)) return sqrt_n * sqrt_n == n def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) r...
from solution import add_multiply_and_analyze, is_perfect_square, prime_factors def test_add_multiply_and_analyze_perfect_square(): result = add_multiply_and_analyze(4, 4) assert result['sum'] == 8 assert result['product'] == 16 assert result['perfect_square'] == True assert result['prime_factors']...
[ { "docstring": null, "function_declaration": "def is_perfect_square(n):", "function_name": "is_perfect_square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def prime_factors(n):", "function_name": "prime_factors", "parameter_list": "(n)" }, { ...
[ 0, 0, 0, 1, 1, 1, 0, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import isqrt\n\ndef add_and_multiply(a, b):\n \"\"\"\n Returns the sum of a and b, their product,\n a boolean indicating if the product is a perfect square, \n and the pr...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034304", "row_id": 34304, "seed_ids": "['Qwen2-72B-Instruct_77663']" }
0.715366
Filter_34304
I
[ "is_perfect_square", "prime_factors", "add_multiply_and_analyze" ]
3
[ [ "add_multiply_and_analyze", "is_perfect_square" ], [ "add_multiply_and_analyze", "prime_factors" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b5bc394836c94f9b6676cf95a0eddb3a404fdc3c
e3b1460b7646addf35e0171f9965af1aec2694b3
v1.0
instruct
Filter
Filter_34348_I
How can I implement a perceptron learning algorithm using cosine similarity as the similarity measure in Python, given a set of input vectors X and a set of output labels Y? The input vectors can have different lengths and may contain categorical and numerical features. Also, how can I use the trained perceptron to mak...
import numpy as np from collections import defaultdict def cosine_similarity(x, y): """ Compute the cosine similarity between two vectors. """ dot_product = np.dot(x, y) norm_x = np.linalg.norm(x) norm_y = np.linalg.norm(y) return dot_product / (norm_x * norm_y) def perceptron_train(X, Y, ...
import numpy as np from solution import perceptron_train, perceptron_predict, polynomial_kernel def test_perceptron_with_linear_data(): X = [np.array([1, 2]), np.array([2, 3]), np.array([3, 4]), np.array([4, 5])] Y = [1, 1, -1, -1] w, b = perceptron_train(X, Y, epochs=10) assert perceptron_predict(np.a...
[ { "docstring": "Compute the cosine similarity between two vectors.", "function_declaration": "def cosine_similarity(x, y):", "function_name": "cosine_similarity", "parameter_list": "(x, y)" }, { "docstring": "Train a Perceptron model using cosine similarity.\nParameters:\n- X: Input feature ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\n\ndef cosine_similarity(vec1, vec2):\n numerator = np.dot(vec1, vec2)\n...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00034348", "row_id": 34348, "seed_ids": "['Qwen2-72B-Instruct_77737']" }
0.354096
Filter_34348
I
[ "cosine_similarity", "perceptron_train", "perceptron_predict", "polynomial_kernel" ]
4
[ [ "perceptron_predict", "cosine_similarity" ], [ "perceptron_train", "cosine_similarity" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy" ]
false
5c726451f791f758a19dd3bf97c0983a4cc3f3a5
f302a1120c54907fd46c3caeb1ae7b5d3f28ef56
v1.0
instruct
Filter
Filter_34454_I
I would like to train a multi-class classification model using Hugging Face's framework in PyTorch for a scientific dataset of articles. I have labeled each article with one of six distinct field names which act as the classes for my problem. The code provided needs to be updated to function correctly with the multi-cl...
import torch from torch import nn from torch.utils.data import DataLoader, Dataset from transformers import BertTokenizer, BertForSequenceClassification, AdamW, get_scheduler from sklearn.metrics import accuracy_score, f1_score import numpy as np class ArticleDataset(Dataset): def __init__(self, articles, labels, ...
from solution import ArticleDataset, custom_loss_function, compute_metrics import torch from torch.utils.data import DataLoader from transformers import BertTokenizer def test_article_dataset(): tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') articles = ["This is a test article.", "This is anoth...
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nfrom transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments\nfrom datasets import load_dataset, load_metric\n\ndef co...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00034454", "row_id": 34454, "seed_ids": "['Qwen2-72B-Instruct_77931']" }
0.334867
Filter_34454
I
[ "custom_loss_function", "compute_metrics", "train_and_evaluate_model" ]
3
[ [ "train_and_evaluate_model", "compute_metrics" ], [ "train_and_evaluate_model", "custom_loss_function" ] ]
2
[]
false
[ "ArticleDataset" ]
true
pytest
true
[ "numpy", "sklearn", "torch", "transformers" ]
false
18ca963c665c8b53e3cebe89e8bf5f33c5c3f46b
1e63f3de27ea2cb473575aa0e52b30c87b91b1b2
v1.0
instruct
Filter
Filter_34690_I
Develop a program that not only generates the Lucas sequence but also counts and returns the occurrence of prime numbers within a given range of the sequence. Furthermore, ensure your algorithm maintains optimal time complexity. The program should be able to handle large ranges in the Lucas sequence.
from math import sqrt def is_prime(num): """Helper function to determine if a number is prime.""" if num <= 1: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(sqrt(num)) + 1, 2): if num % i == 0: return False ...
from solution import is_prime, lucas_number, lucas_sequence_and_prime_count 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 def test_lucas_number(): ...
[ { "docstring": "Helper function to determine if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Function to generate the nth Lucas number.", "function_declaration": "def lucas_number(n):", "f...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from math import isqrt\n\ndef 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 == ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00034690", "row_id": 34690, "seed_ids": "['Qwen2-72B-Instruct_78340']" }
0.627561
Filter_34690
I
[ "is_prime", "lucas_number", "lucas_sequence_and_prime_count" ]
3
[ [ "lucas_sequence_and_prime_count", "is_prime" ], [ "lucas_sequence_and_prime_count", "lucas_number" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d74b74e9601bc075b37c222f235c62534efb5780
58b11d71c14c9987cbabdec36b7505bbd2eab9e9
v1.0
instruct
Filter
Filter_34692_I
Write a python script that, with some parameter (for example ```chartman```, shows the first few hundred lines that the courses have seen. This example here is looking in all files that someone with the username "courses" has written. The script can have multiple options, let's say ``onlypython`` and ``specifieddate`...
import os import glob from datetime import datetime def filter_by_extension(file_path, extension): return file_path.endswith(extension) def filter_by_date(file_path, date): file_date = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d') return file_date == date def get_lines_from_fil...
import pytest from unittest.mock import patch, mock_open from solution import filter_by_extension, filter_by_date, get_lines_from_file, show_first_hundred_lines def test_filter_by_extension(): assert filter_by_extension("script.py", ".py") == True assert filter_by_extension("script.txt", ".py") == False def t...
[ { "docstring": null, "function_declaration": "def filter_by_extension(file_path, extension):", "function_name": "filter_by_extension", "parameter_list": "(file_path, extension)" }, { "docstring": null, "function_declaration": "def filter_by_date(file_path, date):", "function_name": "...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport datetime\n\ndef show_lines(username, onlypython=False, specifieddate=None):\n \"\"\"\n Show the first few lines from files written by the specified user.\n \n Arg...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034692", "row_id": 34692, "seed_ids": "['Qwen2-72B-Instruct_78343']" }
0.380968
Filter_34692
I
[ "filter_by_extension", "filter_by_date", "get_lines_from_file", "show_first_hundred_lines" ]
4
[ [ "show_first_hundred_lines", "filter_by_date" ], [ "show_first_hundred_lines", "filter_by_extension" ], [ "show_first_hundred_lines", "get_lines_from_file" ] ]
3
[]
false
[]
false
pytest
true
[]
true
fe40e71b1238d8b222bae3d9356b8f033c19d711
2c76b6ed5322adbbfad940724ea98f8ff0f10fee
v1.0
instruct
Filter
Filter_34702_I
Write a program to implement the bubble sort algorithm to sort an array of integers in ascending order. The program should also include a function to reverse the sorted array in descending order. Additionally, the program should only use recursion to implement the bubble sort algorithm, without using any loops. The pro...
def remove_duplicates(arr): """ Remove duplicates from an array. """ return list(set(arr)) def bubble_sort_recursive(arr, n=None): """ Recursive implementation of the bubble sort algorithm. """ if n is None: n = len(arr) # Base case if n <= 1: return arr...
from solution import remove_duplicates, bubble_sort_recursive, reverse_array, bubble_sort_and_reverse def test_remove_duplicates(): assert remove_duplicates([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5] assert remove_duplicates([4, 4, 4, 4]) == [4] assert remove_duplicates([1, 2, 3, 1, 2]) == [1, 2, 3] def te...
[ { "docstring": "Remove duplicates from an array.", "function_declaration": "def remove_duplicates(arr):", "function_name": "remove_duplicates", "parameter_list": "(arr)" }, { "docstring": "Recursive implementation of the bubble sort algorithm.", "function_declaration": "def bubble_sort_r...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def bubble_sort_recursive(arr, n):\n \"\"\"\n A recursive implementation of Bubble Sort.\n It sorts the array in ascending order.\n \"\"\"\n # Base case\n if n == 1:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00034702", "row_id": 34702, "seed_ids": "['Qwen2-72B-Instruct_78359']" }
0.58562
Filter_34702
I
[ "remove_duplicates", "bubble_sort_recursive", "reverse_array", "bubble_sort_and_reverse" ]
4
[ [ "bubble_sort_and_reverse", "bubble_sort_recursive" ], [ "bubble_sort_and_reverse", "remove_duplicates" ], [ "bubble_sort_and_reverse", "reverse_array" ] ]
3
[]
false
[]
false
pytest
true
[]
true
82120f2a6d68cba6d49890311d722b3bfca6f961
ed667ddefd873e961b36d76afe78ee427fcb099c
v1.0
instruct
Filter
Filter_34709_I
Write a Python code snippet to find the product of all unique Fibonacci numbers in a given two-dimensional array. Also, handle any possible exceptions, like non-numeric elements.
def fibonacci(n): """ Returns True if n is a Fibonacci number, else False. """ if n < 0: return False a, b = 0, 1 while a < n: a, b = b, a + b return a == n def product_of_unique_fibonacci_elements(matrix): """ Returns the product of all unique Fibonacci numbers in a...
from solution import fibonacci, product_of_unique_fibonacci_elements # Test cases for fibonacci function def test_fibonacci_with_fibonacci_numbers(): assert fibonacci(0) == True assert fibonacci(1) == True assert fibonacci(2) == True assert fibonacci(3) == True assert fibonacci(5) == True asser...
[ { "docstring": "Returns True if n is a Fibonacci number, else False.", "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": "Returns the product of all unique Fibonacci numbers in a given two-dimensional array.", "function_d...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_fibonacci(n):\n \"\"\"\n Helper function to check if n is a Fibonacci number.\n \"\"\"\n if n < 0:\n return False\n x, y = 0, 1\n while x < n:\n x, y = y...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00034709", "row_id": 34709, "seed_ids": "['Qwen2-72B-Instruct_78372']" }
0.642763
Filter_34709
I
[ "fibonacci", "product_of_unique_fibonacci_elements" ]
2
[ [ "product_of_unique_fibonacci_elements", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6f1c20d5a481a8e300b2fe316cef770ca5122e4c
dd9477c35df70d1670536a7cc1af5096e5688f25
v1.0
instruct
Filter
Filter_34750_I
Develop a program in your favorite language that illustrates the concept and implementation of mutual recursion. Explain your code and ensure you include functionality for handling potential stack overflow issues that might stem from excessive recursion.
def is_even(n): """ Returns True if n is even, otherwise False. Uses mutual recursion with is_odd function. """ if n == 0: return True return is_odd(n - 1) def is_odd(n): """ Returns True if n is odd, otherwise False. Uses mutual recursion with is_even function. """ ...
from solution import is_even, is_odd, safe_is_even, safe_is_odd def test_is_even(): assert is_even(0) == True assert is_even(1) == False assert is_even(2) == True assert is_even(100) == True assert is_even(101) == False def test_is_odd(): assert is_odd(0) == False assert is_odd(1) == True ...
[ { "docstring": "Returns True if n is even, otherwise False.\nUses mutual recursion with is_odd function.", "function_declaration": "def is_even(n):", "function_name": "is_even", "parameter_list": "(n)" }, { "docstring": "Returns True if n is odd, otherwise False. \nUses mutual recursion with...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\n# Set the maximum depth for recursion\nsys.setrecursionlimit(1000)\n\ndef is_even(n, depth=0):\n \"\"\"\n Return True if n is even, False if n is odd.\n \"\"\"\n # Ba...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034750", "row_id": 34750, "seed_ids": "['Qwen2-72B-Instruct_78454']" }
0.408483
Filter_34750
I
[ "is_even", "is_odd", "safe_is_even", "safe_is_odd" ]
4
[ [ "is_even", "is_odd" ], [ "is_odd", "is_even" ], [ "safe_is_odd", "safe_is_even" ] ]
3
[]
false
[]
false
pytest
true
[]
true
c298026052549de5795eca18a0edde053d8f867c
ce729d5a1beda3f519c64345f77ea96538f80ee9
v1.0
instruct
Filter
Filter_34798_I
Write a Python script that uses multiple commands and functions to convert a positive integer input (in the range of 1 to 5000) into its lowercase roman numeral equivalent, and vice versa. Additionally, the script should include a function that validates whether the input is a valid positive integer or a correctly form...
import re from datetime import datetime ROMAN_NUMERAL_MAP = [ ('m', 1000), ('cm', 900), ('d', 500), ('cd', 400), ('c', 100), ('xc', 90), ('l', 50), ('xl', 40), ('x', 10), ('ix', 9), ('v', 5), ('iv', 4), ('i', 1) ] def int_to_roman(num): """ Convert an integer to a Roman numeral. """ if...
from solution import int_to_roman, roman_to_int, is_valid_input, convert_and_log def test_int_to_roman(): assert int_to_roman(1) == 'i' assert int_to_roman(4) == 'iv' assert int_to_roman(9) == 'ix' assert int_to_roman(58) == 'lviii' assert int_to_roman(1994) == 'mcmxciv' def test_roman_to_int(): ...
[ { "docstring": "Convert an integer to a Roman numeral.", "function_declaration": "def int_to_roman(num):", "function_name": "int_to_roman", "parameter_list": "(num)" }, { "docstring": "Convert a Roman numeral to an integer.", "function_declaration": "def roman_to_int(s):", "function_...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom datetime import datetime\n\n# Dictionary to map Roman numerals to integer values\nroman_to_int_map = {\n 'M': 1000, 'CM': 900, 'D': 500, 'CD': 400,\n 'C': 100, 'XC': 90, ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034798", "row_id": 34798, "seed_ids": "['Qwen2-72B-Instruct_78527']" }
0.730893
Filter_34798
I
[ "int_to_roman", "roman_to_int", "is_valid_input", "log_conversion", "convert_and_log" ]
5
[ [ "convert_and_log", "int_to_roman" ], [ "convert_and_log", "log_conversion" ], [ "convert_and_log", "roman_to_int" ], [ "is_valid_input", "roman_to_int" ] ]
4
[]
false
[]
false
pytest
true
[]
true
254f4b16877d1afb440923fa7b1f726dd0c55251
71d511e38603d4894b9898c7fddf49cce55ec0a7
v1.0
instruct
Filter
Filter_34806_I
I need help expanding the functionality of a Python generator that can generate all possible combinations of organizing a given list of cities into groups of a given size while ensuring that no two cities from the same group are adjacent. Can you help modify the provided function to also include conditions whereby no g...
from itertools import combinations, chain def is_palindrome(word): """Checks if a given word is a palindrome.""" return word == word[::-1] def filter_palindromes(groups): """Ensures no groups contain the same number of palindromic cities.""" for group in groups: palindromes_count = sum(is_pali...
from solution import generate_all_group_combinations def test_valid_groups_with_palindromes(): cities = ["anna", "bob", "civic", "level", "deed", "madam", "noon"] group_size = 2 valid_combinations = generate_all_group_combinations(cities, group_size) for combination in valid_combinations: for g...
[ { "docstring": "Checks if a given word is a palindrome.", "function_declaration": "def is_palindrome(word):", "function_name": "is_palindrome", "parameter_list": "(word)" }, { "docstring": "Ensures no groups contain the same number of palindromic cities.", "function_declaration": "def fi...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from itertools import combinations\n\ndef is_palindromic(city):\n return city.lower() == city.lower()[::-1]\n\ndef valid_group(group):\n # Check for unique starting letters\n starting...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00034806", "row_id": 34806, "seed_ids": "['Qwen2-72B-Instruct_78539']" }
0.498341
Filter_34806
I
[ "is_palindrome", "filter_palindromes", "filter_starting_letters", "validate_adjacent_pairs", "generate_valid_groups", "generate_all_group_combinations" ]
6
[ [ "filter_palindromes", "is_palindrome" ], [ "generate_all_group_combinations", "filter_palindromes" ], [ "generate_all_group_combinations", "filter_starting_letters" ], [ "generate_all_group_combinations", "generate_valid_groups" ], [ "generate_valid_groups", ...
7
[]
false
[]
false
pytest
true
[]
true
664275cf48d9ed7729d262394ea1ff1fda9d0301
5771d1b25ef3de483c396f9dc32327a5a91cac52
v1.0
instruct
Filter
Filter_34902_I
Create a Python script that scrapes episode titles from The Wire and Pulp Fiction, creating a dictionary that corresponds the number of words in each title to its corresponding show. The keys should represent the word count for that show's episode. If two shows have multiple word counts the same, aggregate those using ...
import requests from bs4 import BeautifulSoup def get_show_titles(url): """ Scrapes episode titles from the given show's Wikipedia page. Args: url (str): URL of the show's Wikipedia page. Returns: list: List of episode titles. """ response = requests.get(url) soup = BeautifulS...
from solution import get_show_titles, count_words_in_titles, create_episode_title_dictionary def test_count_words_in_titles(): titles = ["Title One", "Another Title", "Short"] word_counts = count_words_in_titles(titles) assert word_counts == {2: 2, 1: 1} def test_create_episode_title_dictionary(): sho...
[ { "docstring": "Scrapes episode titles from the given show's Wikipedia page.\n\nArgs:\nurl (str): URL of the show's Wikipedia page.\n\nReturns:\nlist: List of episode titles.", "function_declaration": "def get_show_titles(url):", "function_name": "get_show_titles", "parameter_list": "(url)" }, {...
[ 0, 0, 0, 1, 1, 1, 0, 0, 0 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom bs4 import BeautifulSoup\n\ndef scrape_episode_titles(show_name, url):\n response = requests.get(url)\n soup = BeautifulSoup(response.content, 'html.parser')\n \...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034902", "row_id": 34902, "seed_ids": "['Qwen2-72B-Instruct_78710']" }
0.446966
Filter_34902
I
[ "get_show_titles", "count_words_in_titles", "create_episode_title_dictionary" ]
3
[ [ "create_episode_title_dictionary", "count_words_in_titles" ], [ "create_episode_title_dictionary", "get_show_titles" ] ]
2
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
424b393520d725a115fa723394f891b61ed68ee6
4abb941a3ef6152df50da7f6d2c920b3eaa3e945
v1.0
instruct
Filter
Filter_34908_I
Is it possible to create an AI program for a Snake game using Python? Could you provide an example of how to implement it?
import random class SnakeGame: def __init__(self, width=10, height=10): self.width = width self.height = height self.snake = [(width // 2, height // 2)] self.food = self._place_food() self.direction = (0, 1) # Right self.game_over = False def _place_food(se...
from solution import SnakeGame, play_game, bfs_ai def test_initial_state(): game = SnakeGame() assert game.get_state()['snake'] == [(5, 5)] assert not game.get_state()['game_over'] def test_snake_growth(): game = SnakeGame() game.food = (5, 6) # Mock food position game.move() assert l...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pygame\nimport random\n\n# Initialize Pygame\npygame.init()\n\n# Screen dimensions\nWIDTH, HEIGHT = 600, 600\n\n# Colors\nBLACK = (0, 0, 0)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\n\n# ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00034908", "row_id": 34908, "seed_ids": "['Qwen2-72B-Instruct_78718']" }
0.509697
Filter_34908
I
[ "bfs_ai", "play_game" ]
2
[ [ "play_game", "bfs_ai" ] ]
1
[]
false
[ "SnakeGame" ]
true
pytest
true
[]
true
537a04c1c6a8b153854f4ff2f457bb39498e8db8
120509141acb3667747888269f3b1e69d963a8df
v1.0
instruct
Filter
Filter_34913_I
Write a function in Python that takes a list of 4 numbers as input and returns the largest product of any two numbers. Additionally, write a separate method to validate that the input list always contains exactly 4 numbers. If the list is not valid (does not contain exactly 4 numbers), the function should not proceed, ...
def validate_input(numbers): """ Validates that the input list contains exactly 4 numbers. Returns True if valid, False otherwise. """ if len(numbers) == 4: return True else: print("Invalid input") return False def largest_product(numbers): """ Returns the larges...
from solution import validate_input, largest_product def test_validate_input_valid(): assert validate_input([1, 2, 3, 4]) == True def test_validate_input_invalid(): assert validate_input([1, 2, 3]) == False assert validate_input([1, 2, 3, 4, 5]) == False def test_largest_product_valid(): assert large...
[ { "docstring": "Validates that the input list contains exactly 4 numbers.\nReturns True if valid, False otherwise.", "function_declaration": "def validate_input(numbers):", "function_name": "validate_input", "parameter_list": "(numbers)" }, { "docstring": "Returns the largest product of any ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def validate_input(numbers):\n \"\"\"\n Validates that the input list contains exactly 4 numbers.\n \"\"\"\n if len(numbers) != 4:\n print(\"Invalid input\")\n return...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034913", "row_id": 34913, "seed_ids": "['Qwen2-72B-Instruct_78729']" }
0.678466
Filter_34913
I
[ "validate_input", "largest_product" ]
2
[ [ "largest_product", "validate_input" ] ]
1
[]
false
[]
false
pytest
true
[]
true
94dba47f007dd21c79b4d292376f4b65ee83bc63
af1506f640bb03476d1d0e0754c4186586db275a
v1.0
instruct
Filter
Filter_34919_I
Given a list of DNA sequences in FASTA format and a reverse complement function, create a program that can generate the reverse complement of each sequence. In addition, ensure that the program can handle variation in the input format of DNA sequences, such as including or excluding the '>' symbol at the beginning of e...
def reverse_complement(dna_sequence): """ Returns the reverse complement of the given DNA sequence. """ complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return ''.join(complement[base] for base in reversed(dna_sequence)) def calculate_gc_content(dna_sequence): """ Returns the GC conten...
from solution import reverse_complement, calculate_gc_content, fasta_processing def test_reverse_complement(): assert reverse_complement('ATCG') == 'CGAT' assert reverse_complement('GGCC') == 'GGCC' assert reverse_complement('AACGTG') == 'CACGTT' def test_calculate_gc_content(): assert calculate_gc_co...
[ { "docstring": "Returns the reverse complement of the given DNA sequence.", "function_declaration": "def reverse_complement(dna_sequence):", "function_name": "reverse_complement", "parameter_list": "(dna_sequence)" }, { "docstring": "Returns the GC content percentage of the given DNA sequenc...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def reverse_complement(dna):\n \"\"\"\n Returns the reverse complement of a DNA sequence.\n \"\"\"\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}\n return ''.join(compl...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00034919", "row_id": 34919, "seed_ids": "['Qwen2-72B-Instruct_78737']" }
0.457558
Filter_34919
I
[ "reverse_complement", "calculate_gc_content", "fasta_processing" ]
3
[ [ "fasta_processing", "calculate_gc_content" ], [ "fasta_processing", "reverse_complement" ] ]
2
[]
false
[]
false
pytest
true
[]
true
74e74e63fdd01b3e97d4197f9baa12bc5a72f9e0
4f52665e2608f37217628c41f717aeba2d1aff6c
v1.0
instruct
Filter
Filter_34940_I
Write a python function that converts a given dictionary with complex nested structures into a YAML string with alignment preserved. Furthermore, your function should also have the capacity to handle custom data types if they're included in dictionary value or nested structure. The function should appropriately seriali...
import yaml def custom_representer(dumper, data): """ This function is used to serialize custom data types. Custom objects are represented as dictionaries containing their properties. """ return dumper.represent_dict(data.__dict__) def dict_to_yaml(data): """ Converts a dictionary wit...
from solution import dict_to_yaml class Custom: def __init__(self, x, y): self.x = x self.y = y def test_simple_dict(): data = {'key1': 'value1', 'key2': 'value2'} yaml_str = dict_to_yaml(data) expected = "key1: value1\nkey2: value2\n" assert yaml_str == expected def test_nested_d...
[ { "docstring": "This function is used to serialize custom data types.\nCustom objects are represented as dictionaries \ncontaining their properties.", "function_declaration": "def custom_representer(dumper, data):", "function_name": "custom_representer", "parameter_list": "(dumper, data)" }, { ...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import yaml\n\ndef serialize_to_yaml(data):\n \"\"\"\n Converts a given dictionary with complex nested structures into a YAML string \n with alignment preserved. Custom data types wit...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034940", "row_id": 34940, "seed_ids": "['Qwen2-72B-Instruct_78769']" }
0.580115
Filter_34940
I
[ "custom_representer", "dict_to_yaml" ]
2
[ [ "dict_to_yaml", "custom_representer" ] ]
1
[]
false
[]
false
pytest
true
[ "yaml" ]
false
92d483654d0a2a083e7f4a450defebdcd9eea4f1
f93c83ca58ee66697b6588ce63930aac99120013
v1.0
instruct
Filter
Filter_34998_I
Write a python script to process waveform files for detectors and generate an output in hdf5 format. The script should have advanced data validation and error handling mechanisms in place. Additionally, it should follow a functional programming style and leverage multiprocessing for enhanced performance. The hdf5 outpu...
import h5py import numpy as np import os import datetime import multiprocessing as mp def validate_waveform_data(data): if not isinstance(data, np.ndarray): raise ValueError("Data should be a numpy array.") if data.ndim != 1: raise ValueError("Waveform data should be a one-dimensional array.") ...
import numpy as np import os import h5py from solution import validate_waveform_data, process_waveform, write_to_hdf5, multiprocess_waveform def test_validate_waveform_data(): # Test valid input valid_data = np.array([1, 2, 3, 4]) validate_waveform_data(valid_data) # Test invalid data type (not nu...
[ { "docstring": null, "function_declaration": "def validate_waveform_data(data):", "function_name": "validate_waveform_data", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def process_waveform(file_path, detector_name, sampling_freq):", "function_name": "...
[ 0, 0, 0, 0, 1, 0, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import h5py\nimport numpy as np\nimport os\nfrom datetime import datetime\nfrom multiprocessing import Pool\nimport json\n\ndef validate_waveform_data(data):\n \"\"\"\n Validate waveform...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00034998", "row_id": 34998, "seed_ids": "['Qwen2-72B-Instruct_78864']" }
0.348591
Filter_34998
I
[ "validate_waveform_data", "process_waveform", "write_to_hdf5", "multiprocess_waveform" ]
4
[ [ "multiprocess_waveform", "process_waveform" ], [ "multiprocess_waveform", "write_to_hdf5" ], [ "process_waveform", "validate_waveform_data" ] ]
3
[]
false
[]
false
pytest
true
[ "h5py", "numpy" ]
false
492252cb81fbb9712738bb52283db8edacf42339
c4847ce9d6d72db6042ae958c3809d044d4c4ed0
v1.0
instruct
Filter
Filter_35012_I
Write a Python program that multiplies two input numbers and factorizes the result into its prime factors.
from math import sqrt def multiply_and_factorize(a, b): """ Multiplies two numbers and returns the prime factors of the result. Args: a (int): The first number. b (int): The second number. Returns: tuple: A tuple where the first element is the product of the two numbers, an...
from solution import multiply_and_factorize, prime_factors def test_multiply_and_factorize_simple(): product, factors = multiply_and_factorize(6, 8) assert product == 48 assert factors == [2, 2, 2, 2, 3] def test_multiply_and_factorize_prime(): product, factors = multiply_and_factorize(13, 7) asse...
[ { "docstring": "Multiplies two numbers and returns the prime factors of the result.\n\nArgs:\na (int): The first number.\nb (int): The second number.\n\nReturns:\ntuple: A tuple where the first element is the product of the two numbers,\n and the second element is a list of the prime factors of the produc...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def multiply_and_factorize(a, b):\n \"\"\"\n Multiplies two input numbers and factorizes the result into its prime factors.\n \"\"\"\n def prime_factors(n):\n i = 2\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00035012", "row_id": 35012, "seed_ids": "['Qwen2-72B-Instruct_78881']" }
0.754294
Filter_35012
I
[ "multiply_and_factorize", "prime_factors" ]
2
[ [ "multiply_and_factorize", "prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be8def6a3431a05aa0d76bbb05020706d8afdf33
c55d500839e6cfed959b25454af694fe7ca53dc0
v1.0
instruct
Filter
Filter_35071_I
Carry out a function to perform an XOR gate operation on two 1-bit binary numbers. Further, develop a method to handle a string of binary inputs instead of only two and return the XOR operation result of the entire string. Remember, if all bits are 1 in the string, the result should be 0 (as per XOR rules).
def xor_two_bits(a, b): """ Returns the XOR operation of two 1-bit binary numbers. """ # XOR operation using ^ operator return str(int(a) ^ int(b)) def xor_string_bits(binary_string): """ Returns the XOR operation result of a string of binary inputs. """ result = binary_string[0] ...
from solution import xor_two_bits, xor_string_bits def test_xor_two_bits(): assert xor_two_bits('0', '0') == '0' assert xor_two_bits('0', '1') == '1' assert xor_two_bits('1', '0') == '1' assert xor_two_bits('1', '1') == '0' def test_xor_string_bits(): assert xor_string_bits('0') == '0' assert ...
[ { "docstring": "Returns the XOR operation of two 1-bit binary numbers.", "function_declaration": "def xor_two_bits(a, b):", "function_name": "xor_two_bits", "parameter_list": "(a, b)" }, { "docstring": "Returns the XOR operation result of a string of binary inputs.", "function_declaratio...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def xor_gate(a, b):\n \"\"\"\n Returns the result of XOR operation between two 1-bit binary numbers a and b.\n \"\"\"\n return int(a) ^ int(b)\n\ndef xor_string(binary_string):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00035071", "row_id": 35071, "seed_ids": "['Qwen2-72B-Instruct_78987']" }
0.666002
Filter_35071
I
[ "xor_two_bits", "xor_string_bits" ]
2
[ [ "xor_string_bits", "xor_two_bits" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fa1e789783d645ea7968d65ea430ead03326912d
37ee2fcb436264e3514257243c97cdff556b8ba8
v1.0
instruct
Filter
Filter_35092_I
Given a string s, write a function to check if the string is a palindrome, but ignore any non-alphabetical characters and consider case insensitivity. Also, return the longest palindromic substring found in s.
import re def clean_string(s): """ Removes non-alphabetical characters from string and converts it to lowercase. """ return re.sub(r'[^a-zA-Z]', '', s).lower() def is_palindrome(s): """ Check if the given string s is a palindrome. """ cleaned = clean_string(s) return cleaned == cle...
from solution import clean_string, is_palindrome, longest_palindromic_substring def test_clean_string(): assert clean_string("A man, a plan, a canal, Panama!") == "amanaplanacanalpanama" def test_is_palindrome(): assert is_palindrome("A man, a plan, a canal, Panama!") == True assert is_palindrome("racecar...
[ { "docstring": "Removes non-alphabetical characters from string and converts it to lowercase.", "function_declaration": "def clean_string(s):", "function_name": "clean_string", "parameter_list": "(s)" }, { "docstring": "Check if the given string s is a palindrome.", "function_declaration...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_palindrome_and_longest_substring(s):\n \"\"\"\n Check if a string is a palindrome (ignoring non-alphabetical \n characters and case) and return the longest palindromic substrin...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035092", "row_id": 35092, "seed_ids": "['Qwen2-72B-Instruct_79023']" }
0.795505
Filter_35092
I
[ "clean_string", "is_palindrome", "longest_palindromic_substring" ]
3
[ [ "is_palindrome", "clean_string" ], [ "longest_palindromic_substring", "clean_string" ] ]
2
[]
false
[]
false
pytest
true
[]
true
95ff154e2dc61d80703dbf78c5138d2ede388960
0ffe12d102dc73d0c9cf615253f9ad7033a279ca
v1.0
instruct
Filter
Filter_35149_I
Develop a Python program that manipulates multiple linked lists simultaneously. Each linked list represents a series of volumes (1000 to 1231), overlapped by some criteria (for example, if one volume in a list is 1007, the next linked list should begin at 1006 or earlier).
class ListNode: def __init__(self, x): self.val = x self.next = None def create_linked_list(values): if not values: return None head = ListNode(values[0]) current = head for value in values[1:]: current.next = ListNode(value) current = current.next return...
from solution import ListNode, create_linked_list, merge_linked_lists, print_linked_list def test_create_linked_list(): values = [1000, 1001, 1002] head = create_linked_list(values) assert head.val == 1000 assert head.next.val == 1001 assert head.next.next.val == 1002 assert head.next.next.next...
[]
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "class ListNode:\n def __init__(self, volume, next_node=None):\n self.volume = volume\n self.next = next_node\n \nclass LinkedList:\n def __init__(self):\n sel...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00035149", "row_id": 35149, "seed_ids": "['Qwen2-72B-Instruct_79108']" }
0.413974
Filter_35149
I
[ "create_linked_list", "merge_linked_lists", "print_linked_list" ]
3
[ [ "merge_linked_lists", "create_linked_list" ] ]
1
[]
false
[ "ListNode" ]
true
pytest
true
[]
true
1c60eab09a075cedf2a747913aa7ca87af1abf73
847b5a7196c8e5399102f87f853838b21ea8eaca
v1.0
instruct
Filter
Filter_35199_I
Develop a Python program to compute the shortest path between any two points on a grid with obstacles using heuristic based A* algorithm. Incorporate a feature that allows the user to randomize the size of the grid and the number and placement of the obstacles. Also, the user should be able to customize the heuristic f...
import heapq import math import random import time def euclidean_heuristic(a, b): return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) def manhattan_heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def astar_search(start, goal, grid, heuristic=manhattan_heuristic): n = len(grid) m = l...
from solution import find_shortest_path, manhattan_heuristic, euclidean_heuristic def test_find_shortest_path_basic(): path, nodes_produced, elapsed_time, grid = find_shortest_path(5, (0, 0), (4, 4), 20, manhattan_heuristic) assert path[0] == (0, 0) assert path[-1] == (4, 4) assert nodes_produced > 0 ...
[ { "docstring": null, "function_declaration": "def euclidean_heuristic(a, b):", "function_name": "euclidean_heuristic", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def manhattan_heuristic(a, b):", "function_name": "manhattan_heuristic", "parameter_l...
[ 0, 0, 0, 0, 0, 1, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nimport math\nimport random\nimport time\n\ndef heuristic(a, b, method='manhattan'):\n if method == 'manhattan':\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n elif m...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00035199", "row_id": 35199, "seed_ids": "['Qwen2-72B-Instruct_79195']" }
0.544917
Filter_35199
I
[ "euclidean_heuristic", "manhattan_heuristic", "astar_search", "generate_grid", "find_shortest_path" ]
5
[ [ "find_shortest_path", "astar_search" ], [ "find_shortest_path", "generate_grid" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4de773cf17dcf692d9f216a24e3c3d257480f3a2
3bd2820631f49ab33db16c0c1ed8fc92da898b70
v1.0
instruct
Filter
Filter_35237_I
Code up an example of the Mandelbrot set in Python using NumPy and Matplotlib libraries and display its graphical representation. Make sure your code implements the Mandelbrot set formula and dynamically generates the complex number plane around the set.
import numpy as np import matplotlib.pyplot as plt def mandelbrot(c, max_iter): """ Compute the Mandelbrot series for a given complex number c up to max_iter iterations. Returns the iteration count when the magnitude of the resulting complex number exceeds 2. """ z = 0 for n in range(max_iter):...
import numpy as np from solution import mandelbrot, generate_mandelbrot_set, plot_mandelbrot def test_mandelbrot(): c_in_set = 0 + 0j c_out_set = 2 + 2j assert mandelbrot(c_in_set, 100) == 100 assert mandelbrot(c_out_set, 100) < 100 def test_generate_mandelbrot_set(): mandelbrot_set = generat...
[ { "docstring": "Compute the Mandelbrot series for a given complex number c up to max_iter iterations.\nReturns the iteration count when the magnitude of the resulting complex number exceeds 2.", "function_declaration": "def mandelbrot(c, max_iter):", "function_name": "mandelbrot", "parameter_list": ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef mandelbrot(c, max_iter):\n \"\"\"\n Determine if c is in the Mandelbrot set.\n \n Parameters:\n c (complex): The compl...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00035237", "row_id": 35237, "seed_ids": "['Qwen2-72B-Instruct_79257']" }
0.382347
Filter_35237
I
[ "mandelbrot", "generate_mandelbrot_set", "plot_mandelbrot" ]
3
[ [ "generate_mandelbrot_set", "mandelbrot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy" ]
false
ae488a39551e515f43c10ef573853f813ee6eed7
a0b1907933c00d93d6183f234ece9f66cc56b852
v1.0
instruct
Filter
Filter_35285_I
Develop a Python program for linguistic research, which automatically creates a form of transcript of TV speech shows by merging video files with a separate external audio caption txt file to create自动an enhanced subtitle file.
import re import os def merge_captions_video(video_filename, captions, output_filename): """ This function takes a video file and a list of timed captions, and generates an enhanced subtitle file. :param video_filename: Path to the video file as a string. :param captions: List of caption dictionar...
import pytest from solution import merge_captions_video, format_time def test_format_time(): assert format_time(0) == '00:00:00,000' assert format_time(1.5) == '00:00:01,500' assert format_time(3661.123) == '01:01:01,123' def test_merge_captions_video(tmpdir): video_filename = "dummy_video.mp4" ca...
[ { "docstring": "This function takes a video file and a list of timed captions,\nand generates an enhanced subtitle file.\n\n:param video_filename: Path to the video file as a string.\n:param captions: List of caption dictionaries. Each dictionary should have 'start', 'end', and 'text' keys.\n:param output_filen...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom moviepy.editor import VideoFileClip, concatenate_videoclips\nfrom moviepy.video.tools.subtitles import SubtitlesClip\nimport shutil\nimport codecs\n\ndef merge_video_audio(vide...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00035285", "row_id": 35285, "seed_ids": "['Qwen2-72B-Instruct_79327']" }
0.439649
Filter_35285
I
[ "merge_captions_video", "format_time" ]
2
[ [ "merge_captions_video", "format_time" ] ]
1
[]
false
[]
false
pytest
true
[]
true
afdb4c1d397ca594eadc385de6ef78e692df4da6
845d0e313bda0178b568a4b1ba99a5dc02946f34
v1.0
instruct
Filter
Filter_35337_I
In a Python script that reads GPS sensor data for timestamps, longitude, and latitude from multiple log files, how can you modify the code to filter and export only records of a specific file within a given time range to a separate CSV file? Further, adjust the method for calculating speed between consecutive data poin...
import csv from datetime import datetime, timedelta import math def haversine(lat1, lon1, lat2, lon2): """ Calculate the great-circle distance between two points on the Earth. """ R = 6371 # Earth radius in kilometers dLat = math.radians(lat2 - lat1) dLon = math.radians(lon2 - lon1) a = ma...
import os from solution import filter_and_export_gps_data from datetime import datetime def create_test_csv(file_name, rows): with open(file_name, mode='w', newline='') as file: writer = csv.DictWriter(file, fieldnames=['timestamp', 'longitude', 'latitude']) writer.writeheader() for row in ...
[ { "docstring": "Calculate the great-circle distance between two points on the Earth.", "function_declaration": "def haversine(lat1, lon1, lat2, lon2):", "function_name": "haversine", "parameter_list": "(lat1, lon1, lat2, lon2)" }, { "docstring": null, "function_declaration": "def filter_...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nimport math\nfrom datetime import datetime\n\ndef haversine(lat1, lon1, lat2, lon2):\n \"\"\"\n Calculate the great-circle distance between two points \n on the Earth surf...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035337", "row_id": 35337, "seed_ids": "['Qwen2-72B-Instruct_79416']" }
0.560397
Filter_35337
I
[ "haversine", "filter_and_export_gps_data" ]
2
[ [ "filter_and_export_gps_data", "haversine" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f70b5c9b5a04ed5adf38196b718a4e67366ac43e
314f7730fa1c5de5d52e07fcec84d9ec4bc59b23
v1.0
instruct
Filter
Filter_35413_I
In the context of a programming interview, you are presented with a flawed code snippet for a function designed to find the maximum numerical value in a list of integers. Alongside identifying and resolving the bugs in the provided code, you're also tasked with enhancing the function to handle edge cases—such as empty ...
import time from functools import wraps def rate_limited(max_per_second): min_interval = 1.0 / max_per_second def decorator(func): last_time_called = [0.0] @wraps(func) def rate_limited_function(*args, **kwargs): elapsed = time.time() - last_time_called[0] ...
import pytest from solution import find_max def test_find_max(): assert find_max([1, 2, 3, 4, 5]) == 5 assert find_max([-5, -2, 0, 1, 3]) == 3 assert find_max([3, 3, 3, 3, 3]) == 3 assert find_max([100000]) == 100000 def test_find_max_with_empty_list(): with pytest.raises(ValueError): find...
[ { "docstring": null, "function_declaration": "def rate_limited(max_per_second):", "function_name": "rate_limited", "parameter_list": "(max_per_second)" }, { "docstring": null, "function_declaration": "def find_max(integers):", "function_name": "find_max", "parameter_list": "(inte...
[ 0, 0, 0, 1, 0, 1, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport time\n\nclass RateLimiter:\n def __init__(self, max_calls: int, period: float):\n self.max_calls = max_calls\n self.period = period\n se...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00035413", "row_id": 35413, "seed_ids": "['Qwen2-72B-Instruct_79561']" }
0.557979
Filter_35413
I
[ "rate_limited", "find_max" ]
2
[ [ "find_max", "rate_limited" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1d417087d172fe49594d38df0c218376a65e13f
f6c9b3387c3f6eca79057b6b311bb2946ff2e822
v1.0
instruct
Filter
Filter_35443_I
Create a program to not only generate a list of the first N prime numbers, but also add functions that test the efficiency of the program for different values of N. This new function will need to take random large integers as N, carry out the prime number generation, time the duration, and summarize the results. Also e...
import time import random def is_prime(num): """ Checks if a number is prime. """ if num <= 1: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(num**0.5) + 1, 2): if num % i == 0: return False return Tr...
from solution import is_prime, generate_primes, time_prime_generation def test_is_prime_basic(): 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 def test_generate_primes_basic...
[ { "docstring": "Checks if a number is prime.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Generates a list of the first n prime numbers.", "function_declaration": "def generate_primes(n):", "function_name": ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nimport random\n\ndef is_prime(num):\n \"\"\"\n Check if the given number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00035443", "row_id": 35443, "seed_ids": "['Qwen2-72B-Instruct_79620']" }
0.571282
Filter_35443
I
[ "is_prime", "generate_primes", "time_prime_generation" ]
3
[ [ "generate_primes", "is_prime" ], [ "time_prime_generation", "generate_primes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
102229dfc2cb3310daf55aba1ceaa2b152ea369b
d5872049151e8f1c7e97039c6468763cc671fc66
v1.0
instruct
Filter
Filter_35466_I
Write a code that changes a string into all lowercase characters, but ignore any special characters and count the number of lowercase vowels in the string. The string is: "Th1s 1s @ stRIng t#st!" Additionally, if the number of lowercase vowels is prime, return true. If not, return false.
def process_string_and_check_prime(s): """ Convert the string to all lowercase characters, ignore special characters and counts the number of lowercase vowels in the string. Args: s (str): The input string to process. Returns: bool: True if the number of lowercase vowels is prime, ...
import pytest from solution import process_string_and_check_prime def test_process_string_and_check_prime_with_sample_string(): assert process_string_and_check_prime("Th1s 1s @ stRIng t#st!") == False def test_process_string_and_check_prime_with_all_vowels(): assert process_string_and_check_prime("aeiou") == ...
[ { "docstring": "Convert the string to all lowercase characters, ignore special characters\nand counts the number of lowercase vowels in the string.\n\nArgs:\ns (str): The input string to process.\n\nReturns:\nbool: True if the number of lowercase vowels is prime, otherwise False.", "function_declaration": "...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef process_string(s):\n \"\"\"\n Converts the input string to all lowercase, ignoring any special characters,\n and counts the number of lowercase vowels in the string.\...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035466", "row_id": 35466, "seed_ids": "['Qwen2-72B-Instruct_79655']" }
0.650085
Filter_35466
I
[ "process_string_and_check_prime", "is_prime" ]
2
[ [ "process_string_and_check_prime", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0f3a3835f1f549b6fa5b315fc3807a44fe774ba0
5681451d622439d77862f77019d03cf79ccf59de
v1.0
instruct
Filter
Filter_35507_I
Create a Python function that validates if a given number is a prime palindrome and also calculates the highest prime palindrome that is smaller than the input number. This function should work for both positive integers greater than 300 and real numbers greater than 300. If the input number is less than 300 or not a r...
def is_prime(n): 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 def is_palindrome(n): return str(n) == str...
from solution import highest_prime_palindrome, is_prime, is_palindrome 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(25) == False def test_is_palindrome(): assert is_palindrome(121) == True ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def is_palindrome(n):", "function_name": "is_palindrome", "parameter_list": "(n)" }, { "docstring": null,...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00035507", "row_id": 35507, "seed_ids": "['Qwen2-72B-Instruct_79730']" }
0.668391
Filter_35507
I
[ "is_prime", "is_palindrome", "highest_prime_palindrome" ]
3
[ [ "highest_prime_palindrome", "is_palindrome" ], [ "highest_prime_palindrome", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
88c3a5a44ba39b5826d05a2ac935e37525cf1c26
d4b2005a6cb95a568ae5d327747cddd745885041
v1.0
instruct
Filter
Filter_35532_I
Complete the function below to generate a list of n prime numbers that are also Fibonacci numbers and return the result. The function should use the Sieve of Eratosthenes algorithm to find the prime numbers efficiently. The implementation should be done without using any additional data structures apart from the final ...
def sieve_of_eratosthenes(limit): primes = [True] * (limit + 1) p = 2 while p * p <= limit: if primes[p]: for i in range(p * p, limit + 1, p): primes[i] = False p += 1 return [p for p in range(2, limit + 1) if primes[p]] def generate_fibonacci(limit): fib...
def test_fibonacci_primes_empty(): assert fibonacci_primes(0) == [] def test_fibonacci_primes_single(): result = fibonacci_primes(1) assert result == [2], f"Expected [2] but got {result}" def test_fibonacci_primes_first_three(): result = fibonacci_primes(3) assert result == [2, 3, 5], f"Expected [...
[ { "docstring": null, "function_declaration": "def sieve_of_eratosthenes(limit):", "function_name": "sieve_of_eratosthenes", "parameter_list": "(limit)" }, { "docstring": null, "function_declaration": "def generate_fibonacci(limit):", "function_name": "generate_fibonacci", "parame...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef sieve(n):\n \"\"\"\n Returns a list of boolean values representing whether numbers are prime.\n \"\"\"\n prime = [True] * (n + 1)\n p = 2\n while p * p <= ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00035532", "row_id": 35532, "seed_ids": "['Qwen2-72B-Instruct_79772']" }
0.682567
Filter_35532
I
[ "sieve_of_eratosthenes", "generate_fibonacci", "fibonacci_primes" ]
3
[ [ "fibonacci_primes", "generate_fibonacci" ], [ "fibonacci_primes", "sieve_of_eratosthenes" ] ]
2
[]
false
[]
false
pytest
false
[]
true
061d69f276699e3773ecdf4d5ecbfae67097cf4d
4628f32b8059054b894fb3a0ef78894729be22dd
v1.0
instruct
Filter
Filter_35565_I
In Python programming, would you be able to create a function that generates an iterator that yields the vowels from a provided word in the order they are encountered? Furthermore, can you include an algorithm to check whether these vowels are in alphabetical order within the original word? Use the following word as a ...
def vowels_generator(word): """ This function generates an iterator that yields the vowels from the provided word in the order they are encountered. """ vowels = "aeiouAEIOU" for letter in word: if letter in vowels: yield letter def are_vowels_in_alphabetical_order(w...
from solution import vowels_generator, are_vowels_in_alphabetical_order def test_vowels_generator(): word = "Ancestors" vowels = list(vowels_generator(word)) assert vowels == ['A', 'e', 'o'] def test_vowels_generator_empty(): word = "rhythm" vowels = list(vowels_generator(word)) assert vowels ...
[ { "docstring": "This function generates an iterator that yields the vowels from the provided word in the order they are encountered.", "function_declaration": "def vowels_generator(word):", "function_name": "vowels_generator", "parameter_list": "(word)" }, { "docstring": "This function check...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def vowel_iterator(word):\n \"\"\"\n Generator function that yields vowels from the provided word.\n \"\"\"\n vowels = \"aeiouAEIOU\"\n for char in word:\n if char in vow...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00035565", "row_id": 35565, "seed_ids": "['Qwen2-72B-Instruct_79832']" }
0.660308
Filter_35565
I
[ "vowels_generator", "are_vowels_in_alphabetical_order" ]
2
[ [ "are_vowels_in_alphabetical_order", "vowels_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be06d498d8fab85a4b0ae7d427232cb0b116520f
c679b849b3151db418f24737a61021166df0ebee
v1.0
instruct
Filter
Filter_35612_I
Write a Python program to encode data using the Huffman Encoding technique. Then, implement a decoding function to decode this data back. Also, incorporate error-handling capability in your program in such a way that if any anomaly occurs during encoding or decoding, the program should print a suitable error message.
import heapq from collections import defaultdict, Counter class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(text): ...
from solution import huffman_encoding, huffman_decoding, build_huffman_tree, build_codes def test_huffman_encoding_decoding(): text = "this is an example for huffman encoding" encoded_text, tree = huffman_encoding(text) assert encoded_text is not None assert tree is not None decoded_text = huffman_...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nfrom collections import defaultdict, Counter\nimport sys\n\nclass HuffmanNode:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n s...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00035612", "row_id": 35612, "seed_ids": "['Qwen2-72B-Instruct_79918']" }
0.526053
Filter_35612
I
[ "build_huffman_tree", "build_codes", "huffman_encoding", "huffman_decoding" ]
4
[ [ "huffman_encoding", "build_codes" ], [ "huffman_encoding", "build_huffman_tree" ] ]
2
[]
false
[ "HuffmanNode" ]
true
pytest
true
[]
true
58cde41f1694eb68bb395d29be9eaf0d5243c147
6205794d916266ad4958031d789361a1b695fe75
v1.0
instruct
Filter
Filter_35634_I
What is the most efficient algorithm for sorting an array of numbers in Python? Implement the algorithm in a way that also considers memory efficiency, taking into account the additional constraints of sorting the array in-place without using any extra space. Additionally, the algorithm should have a time complexity of...
def quicksort(arr, low, high): """ Quicksort algorithm to sort an array in-place with O(nlogn) time complexity. """ if low < high: pivot_index = partition(arr, low, high) quicksort(arr, low, pivot_index - 1) quicksort(arr, pivot_index + 1, high) def partition(arr, low, high): ...
from solution import quicksort def test_quicksort_with_sorted_array(): arr = [1, 2, 3, 4, 5] quicksort(arr, 0, len(arr) - 1) assert arr == [1, 2, 3, 4, 5] def test_quicksort_with_reverse_sorted_array(): arr = [5, 4, 3, 2, 1] quicksort(arr, 0, len(arr) - 1) assert arr == [1, 2, 3, 4, 5] def te...
[ { "docstring": "Quicksort algorithm to sort an array in-place with O(nlogn) time complexity.", "function_declaration": "def quicksort(arr, low, high):", "function_name": "quicksort", "parameter_list": "(arr, low, high)" }, { "docstring": "Helper function to partition the array for the quicks...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def quicksort(arr, low, high):\n \"\"\"\n An in-place quicksort implementation with O(nlogn) average time complexity.\n This function sorts the array from index low to high.\n \"\"...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00035634", "row_id": 35634, "seed_ids": "['Qwen2-72B-Instruct_79963']" }
0.647411
Filter_35634
I
[ "quicksort", "partition" ]
2
[ [ "quicksort", "partition" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d27461c8a9608a9f2c363f22be08971bc96abdee
bdfaf149931da5edf6364c05b7e78d960c157107
v1.0
instruct
Filter
Filter_35676_I
Create a Python function that takes two arguments, a positive integer and a boolean. The integer should be between 5 and 50 (inclusive) and the boolean should represent an odd or even number. If the boolean is True, the function should return the nearest odd prime number greater than the input integer; if False, it sho...
def is_prime(num): """ Returns True if num is a prime number, False otherwise. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: ...
from solution import find_nearest_prime def test_find_nearest_prime_odd_greater(): assert find_nearest_prime(5, True) == 7 assert find_nearest_prime(25, True) == 29 assert find_nearest_prime(50, True) == 53 def test_find_nearest_prime_even_smaller(): assert find_nearest_prime(50, False) == 47 asse...
[ { "docstring": "Returns True if num is a prime number, False otherwise.", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Returns the nearest odd prime greater than n if find_odd is True;\notherwise returns the nearest e...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"Check if a number is prime or not.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n retur...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00035676", "row_id": 35676, "seed_ids": "['Qwen2-72B-Instruct_80040']" }
0.593109
Filter_35676
I
[ "is_prime", "nearest_prime", "find_nearest_prime" ]
3
[ [ "find_nearest_prime", "nearest_prime" ], [ "nearest_prime", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
7e12987c0003c7ae26368eeb5f577af746399bd1
feec54ed0505b50600c9493f4f63a89db56ec9cf
v1.0
instruct
Filter
Filter_35712_I
Given two strings, write a function that determines if they are an anagram of each other. Then, if they are anagrams, find how many character swaps are required to convert one string into the other. Note: The strings may contain duplicates.
def are_anagrams(s1, s2): """ Determine if two strings are anagrams of each other. """ return sorted(s1) == sorted(s2) def minimum_swaps_to_anagram(s1, s2): """ Finds the minimum number of swaps required to turn s1 into s2, given that s1 and s2 are anagrams. """ if not are_anagrams(s1, ...
from solution import are_anagrams, minimum_swaps_to_anagram import pytest def test_are_anagrams_true(): assert are_anagrams("listen", "silent") == True assert are_anagrams("triangle", "integral") == True def test_are_anagrams_false(): assert are_anagrams("hello", "world") == False assert are_anagrams(...
[ { "docstring": "Determine if two strings are anagrams of each other.", "function_declaration": "def are_anagrams(s1, s2):", "function_name": "are_anagrams", "parameter_list": "(s1, s2)" }, { "docstring": "Finds the minimum number of swaps required to turn s1 into s2, given that s1 and s2 are...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def are_anagrams(str1, str2):\n \"\"\"\n Determines if two strings are anagrams of each other.\n \"\"\"\n if sorted(str1) == sorted(str2):\n return True\n else:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00035712", "row_id": 35712, "seed_ids": "['Qwen2-72B-Instruct_80104']" }
0.659188
Filter_35712
I
[ "are_anagrams", "minimum_swaps_to_anagram" ]
2
[ [ "minimum_swaps_to_anagram", "are_anagrams" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b8f6a59869b04e76a75645f7c34932302d0839b4
66dbb4e80dd10c4936273e6aafc4b1d75f669f30
v1.0
instruct
Filter
Filter_35906_I
Given a string sequence, design a program in Python that creates all possible continuous subsequences. After generating these subsequences, the program should filter and return only those sequences that can be read the same forwards and backwards (palindromes). The function should then return the longest palindrome tha...
def generate_continuous_subsequences(sequence): """ Generates all continuous subsequences of the given sequence. """ subsequences = [] n = len(sequence) for i in range(n): for j in range(i + 1, n + 1): subsequences.append(sequence[i:j]) return subsequences def is_palindr...
from solution import generate_continuous_subsequences, is_palindrome, longest_palindrome_subsequence def test_generate_continuous_subsequences(): assert generate_continuous_subsequences("abba") == [ 'a', 'ab', 'abb', 'abba', 'b', 'bb', 'bba', 'b', 'ba', 'a' ] def test_is_pal...
[ { "docstring": "Generates all continuous subsequences of the given sequence.", "function_declaration": "def generate_continuous_subsequences(sequence):", "function_name": "generate_continuous_subsequences", "parameter_list": "(sequence)" }, { "docstring": "Checks if the given string s is a p...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def longest_palindromic_subsequence(sequence):\n \"\"\"\n Given a string sequence, this function returns the longest palindromic subsequence.\n If no palindromes can be formed, it ret...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00035906", "row_id": 35906, "seed_ids": "['Qwen2-72B-Instruct_80470']" }
0.732123
Filter_35906
I
[ "generate_continuous_subsequences", "is_palindrome", "longest_palindrome_subsequence" ]
3
[ [ "longest_palindrome_subsequence", "generate_continuous_subsequences" ], [ "longest_palindrome_subsequence", "is_palindrome" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f74f42cb2de25522186002250f457f17d8597f37
6e01b16f2f8b58d9009fbdc80d90bf3135605478
v1.0
instruct
Filter
Filter_35976_I
Create a for loop in Python to calculate the total sum of all elements in the given list. However, the loop should only iterate over the odd indices of the list, and only if the element at that index is a prime number. If the element is not a prime number, it should be skipped in the calculation.
def is_prime(n): """ Checks if a number is a prime. """ 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_prime_elements_at_odd_indices(lst): """ Returns the sum of all prime elements at odd indices ...
from solution import is_prime, sum_prime_elements_at_odd_indices 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(0) == False assert is_prime(17) == True assert is_prime(-1) == False def test_s...
[ { "docstring": "Checks if a number is a prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Returns the sum of all prime elements at odd indices in the list.", "function_declaration": "def sum_prime_elements_at_odd_...
[ 0, 0, 0, 1, 0, 1, 0, 0, 1 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(num):\n \"\"\"\n Determines if a number is a prime number.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00035976", "row_id": 35976, "seed_ids": "['Qwen2-72B-Instruct_80584']" }
0.662776
Filter_35976
I
[ "is_prime", "sum_prime_elements_at_odd_indices" ]
2
[ [ "sum_prime_elements_at_odd_indices", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
45a85025766ced4c1a6e3cabe9f1eaf7f40949b8
ac70d0933a960fc545a2148b357a50547eafcce6
v1.0
instruct
Filter
Filter_36114_I
Rotate an array of integers by k positions to the right. The rotation should be performed in place, meaning that the array should be modified directly without creating a new array. Additionally, you are not allowed to use any extra data structures or built-in functions to perform the rotation.
def rotate_array(nums, k): """ Rotate an array of integers by k positions to the right, in place. """ n = len(nums) k = k % n # to handle the case when k is larger than the length of nums reverse(nums, 0, n - 1) # reverse the entire array reverse(nums, 0, k - 1) # reverse the first k elem...
from solution import rotate_array def test_rotate_array_small_k(): nums = [1, 2, 3, 4, 5, 6, 7] rotate_array(nums, 3) assert nums == [5, 6, 7, 1, 2, 3, 4] def test_rotate_array_large_k(): nums = [1, 2, 3, 4, 5, 6, 7] rotate_array(nums, 10) # equivalent to rotating by 3 positions in this case ...
[ { "docstring": "Rotate an array of integers by k positions to the right, in place.", "function_declaration": "def rotate_array(nums, k):", "function_name": "rotate_array", "parameter_list": "(nums, k)" }, { "docstring": "Reverse the elements of the array from index start to index end.", ...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def rotate_array(nums, k):\n \"\"\"\n Rotates the array to the right by k steps.\n :param nums: List[int]\n :param k: int\n \"\"\"\n n = len(nums)\n k = k % n # To handle...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036114", "row_id": 36114, "seed_ids": "['Qwen2-72B-Instruct_80839']" }
0.6279
Filter_36114
I
[ "rotate_array", "reverse" ]
2
[ [ "rotate_array", "reverse" ] ]
1
[]
false
[]
false
pytest
true
[]
true
85c5866db3ec72556fdfeccf2dd4956743a073fe
548131f932fc95a101af4b087a0995e7a89b7134
v1.0
instruct
Filter
Filter_36118_I
Create a code to not only estimate the value of Pi to the nth decimal point, but also represent it spigot algorithmically using generators. Also, include a functionality through which one can choose between different algorithms (Monte Carlo, Nilakantha series and Gregory-Leibniz series) for the calculation of Pi. Here,...
import math import random import threading from decimal import Decimal, getcontext from typing import Generator, Callable # Function to generate Pi using the Spigot algorithm def spigot_pi() -> Generator[int, None, None]: q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 while True: if 4 * q + r - t < n * t: ...
import pytest from decimal import Decimal from solution import calculate_pi, spigot_pi # Pi value for assertions PI_APPROX = Decimal('3.1415926535') def test_calculate_pi_monte_carlo(): pi_value = calculate_pi('Monte Carlo', precision=10, num_points=100000) assert abs(pi_value - PI_APPROX) < Decimal('0.01') ...
[ { "docstring": null, "function_declaration": "def spigot_pi():", "function_name": "spigot_pi", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def monte_carlo_pi(num_points):", "function_name": "monte_carlo_pi", "parameter_list": "(num_points)" }, { ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport itertools\nimport random\n\ndef spigot_pi():\n \"\"\"\n Generator for calculating digits of Pi using the spigot algorithm.\n \"\"\"\n q, r, t, k, n, l = 1,...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00036118", "row_id": 36118, "seed_ids": "['Qwen2-72B-Instruct_80846']" }
0.563799
Filter_36118
I
[ "spigot_pi", "monte_carlo_pi", "nilakantha_series", "gregory_leibniz_series", "calculate_pi" ]
5
[ [ "calculate_pi", "gregory_leibniz_series" ], [ "calculate_pi", "monte_carlo_pi" ], [ "calculate_pi", "nilakantha_series" ] ]
3
[]
false
[]
false
pytest
true
[]
true
66f305a05e416a79d12d36ddffd41471dbdded04
9556fb2a53a6dc9cf6c4fcc484f069f788008bf5
v1.0
instruct
Filter
Filter_36123_I
Develop a Python function that will return an element from a provided list at a specified index. However, the index is determined by your own pseudo-random number generator function, which takes into account a seed value and the total length of the list. Implement this pseudo-random number generator where the index = (...
def pseudo_random_index(seed, length): """ Returns a pseudo-random index for a list based on the seed and length of the list. The index is calculated as seed % length. :param seed: The seed value for generating the index. :param length: The length of the list. :return: The generated index. ...
from solution import pseudo_random_index, get_element_at_pseudo_random_index def test_pseudo_random_index(): assert pseudo_random_index(5, 10) == 5 assert pseudo_random_index(15, 10) == 5 assert pseudo_random_index(3, 3) == 0 assert pseudo_random_index(14, 5) == 4 def test_get_element_at_pseudo_random...
[ { "docstring": "Returns a pseudo-random index for a list based on the seed and length of the list.\nThe index is calculated as seed % length.\n\n:param seed: The seed value for generating the index.\n:param length: The length of the list.\n:return: The generated index.", "function_declaration": "def pseudo_...
[ 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def pseudo_random_index(seed, length):\n \"\"\"\n Generate a pseudo-random index based on a seed value and the length of the list.\n \"\"\"\n return seed % length\n\ndef get_elemen...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036123", "row_id": 36123, "seed_ids": "['Qwen2-72B-Instruct_80855']" }
0.590523
Filter_36123
I
[ "pseudo_random_index", "get_element_at_pseudo_random_index" ]
2
[ [ "get_element_at_pseudo_random_index", "pseudo_random_index" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7c54700d1fe5c60e33521894cdabcb069e766bda
8a66d6123667f6510842f2ca4720ea258d11ee38
v1.0
instruct
Filter
Filter_36149_I
Create a function that not only reverses the order of elements in a given array, but also replaces every even-indexed integer with its factorial. Don't use in-built factorial function, you need to create your own logic for the factorial.
def factorial(n): """ Returns the factorial of a given integer n. """ if n == 0: return 1 result = 1 for i in range(1, n + 1): result *= i return result def reverse_and_replace(arr): """ Reverses the order of elements in the given list and replaces every even-indexed...
from solution import reverse_and_replace def test_reverse_and_replace_all_integers(): assert reverse_and_replace([1, 2, 3, 4, 5]) == [120, 4, 6, 2, 1] def test_reverse_and_replace_mixed(): assert reverse_and_replace([2, "hello", 4, "world", 6]) == [720, 'world', 24, 'hello', 2] def test_reverse_and_repla...
[ { "docstring": "Returns the factorial of a given integer n.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Reverses the order of elements in the given list and replaces every even-indexed integer with its factorial.", ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def factorial(n):\n \"\"\"\n Returns the factorial of a given non-negative integer n.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n result = 1\n for i in range(2, n + 1...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036149", "row_id": 36149, "seed_ids": "['Qwen2-72B-Instruct_80883']" }
0.652341
Filter_36149
I
[ "factorial", "reverse_and_replace" ]
2
[ [ "reverse_and_replace", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2e28e89fda088bf540adec4676dbd900d032f003
6188c05138ce4b9062edba193c42afa573d45a8c
v1.0
instruct
Filter
Filter_36212_I
Let's have a Python function that takes in two parameters, a count indexes of which to apply a sigmoid function on, and a tensor values. If the length of indexes is 0, the function should return the original tensor. Otherwise, a new tensor should be composed that resembles the original one, but with the values at speci...
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def apply_sigmoid_on_indexes(indexes, tensor): """ Applies a sigmoid function to specified indexes of a tensor. Parameters: indexes (list of int): The indexes at which to apply the sigmoid function. tensor (numpy.ndarray): ...
import numpy as np from solution import apply_sigmoid_on_indexes, sigmoid def test_apply_sigmoid_no_indexes(): tensor = np.array([1.0, 2.0, 3.0]) result = apply_sigmoid_on_indexes([], tensor) expected = tensor assert np.array_equal(result, expected) def test_apply_sigmoid_single_index(): tensor = ...
[ { "docstring": null, "function_declaration": "def sigmoid(x):", "function_name": "sigmoid", "parameter_list": "(x)" }, { "docstring": "Applies a sigmoid function to specified indexes of a tensor.\nParameters:\n indexes (list of int): The indexes at which to apply the sigmoid function.\n ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Apply sigmoid function to input x.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef apply_sigmoid_on_indexes(indexes, tensor):\n \"...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036212", "row_id": 36212, "seed_ids": "['Qwen2-72B-Instruct_81007']" }
0.573831
Filter_36212
I
[ "sigmoid", "apply_sigmoid_on_indexes" ]
2
[ [ "apply_sigmoid_on_indexes", "sigmoid" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
706a486c1f44a88c339f2be06a2746067bf95b5f
c8c5100fdb047643c05ca307047a66eac5d06b85
v1.0
instruct
Filter
Filter_36251_I
Develop a calculator that can execute operations like addition, subtraction, multiplication, division, and also exponentiation, taking into consideration the operational precedence (PEMDAS/ BODMAS rule). You should also incorporate error handling for division by zero, negative root square, and unexpected characters. Th...
import re def evaluate_expression(expression): try: # Replace '^' with '**' for exponentiation expression = expression.replace('^', '**') # Validate the expression to allow only numbers and valid operators valid_chars = re.compile(r'^[\d\+\-\*/\^\(\)\. ]*$') if not ...
from solution import text_calculator def test_addition(): assert text_calculator("2 + 3") == 5 def test_subtraction(): assert text_calculator("5 - 2") == 3 def test_multiplication(): assert text_calculator("3 * 2") == 6 def test_division(): assert text_calculator("6 / 3") == 2.0 def test_exponentia...
[ { "docstring": null, "function_declaration": "def evaluate_expression(expression):", "function_name": "evaluate_expression", "parameter_list": "(expression)" }, { "docstring": null, "function_declaration": "def text_calculator(input_text):", "function_name": "text_calculator", "p...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef evaluate_expression(expression):\n \"\"\"\n Evaluate a mathematical expression with +, -, *, /, and ^ (exponentiation) operations.\n Implements PEMDAS/BODMAS rule for...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00036251", "row_id": 36251, "seed_ids": "['Qwen2-72B-Instruct_81071']" }
0.484955
Filter_36251
I
[ "evaluate_expression", "text_calculator" ]
2
[ [ "text_calculator", "evaluate_expression" ] ]
1
[]
false
[]
false
pytest
true
[]
true
204b43ad22176f54a27a5aa1826f24ffdc2fe479
2bf3efa2bd8ebc5089dcff7ebd018e912ffd71dc
v1.0
instruct
Filter
Filter_36265_I
Write a function in Python to select all the prime numbers from a list whose index is a multiple of a given input 'k'.
def is_prime(n): """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def se...
from solution import is_prime, select_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(29) == True assert is_prime(1) == False assert is_prime(-3) == False def test_select_prime_n...
[ { "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 a list of prime numbers from lst whose indices are multiples of k.", "function_declaration":...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n):\n \"\"\"\n Helper function to determine if n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036265", "row_id": 36265, "seed_ids": "['Qwen2-72B-Instruct_81094']" }
0.624477
Filter_36265
I
[ "is_prime", "select_prime_numbers" ]
2
[ [ "select_prime_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
838d699eb5e2bcdd8231862b32986305691dd576
d0358d28da54f2471256a9a2f9ea8b8640191bd2
v1.0
instruct
Filter
Filter_36300_I
Given a 2D matrix, write a program that transposes the matrix and calculates the product of each row and column in the transposed matrix. The matrix should only contain integers in the range of -1000 to 1000. The program should handle matrices with dimensions up to 1000x1000.
def transpose_and_calculate_products(matrix): """ Transpose the given 2D matrix and calculate the product of each row and column in the transposed matrix. Args: matrix (list of list of int): The input 2D matrix containing integers. Returns: tuple: A tuple containing the transposed...
from solution import transpose_and_calculate_products, product def test_transpose_and_calculate_products(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] transposed_matrix, row_products, col_products = transpose_and_calculate_products(matrix) expected_transposed_matrix = [ ...
[ { "docstring": "Transpose the given 2D matrix and calculate the product of each row and column \nin the transposed matrix.\n\nArgs:\nmatrix (list of list of int): The input 2D matrix containing integers.\n\nReturns:\ntuple: A tuple containing the transposed matrix, list of row products, and list of column produ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def transpose(matrix):\n \"\"\"\n Transposes the given 2D matrix.\n \"\"\"\n return [list(row) for row in zip(*matrix)]\n\ndef row_column_product(matrix):\n \"\"\"\n Calculat...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00036300", "row_id": 36300, "seed_ids": "['Qwen2-72B-Instruct_81151']" }
0.564612
Filter_36300
I
[ "transpose_and_calculate_products", "product" ]
2
[ [ "transpose_and_calculate_products", "product" ] ]
1
[]
false
[]
false
pytest
true
[]
true
616e02b1dec1d0496f7d0b2131a85c3994e8168f
873e4955e926079fc65fe03046bb982c3f9c434d
v1.0
instruct
Filter
Filter_36320_I
Revise the rudimentary program structure provided below by incorporating additional functions and recursion for generating the next initial quantity of lexical terms (anagrams) retrieved from a specified document. The custom methodology should also count and display the frequency of each anagram in the document and be ...
from collections import Counter from itertools import permutations def generate_anagrams(word): """ Generates all anagrams of a given word. This function does not eliminate duplicate anagrams. """ return [''.join(p) for p in permutations(word)] def count_anagrams(terms, text): """ Counts t...
from solution import generate_anagrams, count_anagrams, find_anagrams_in_text def test_generate_anagrams(): result = generate_anagrams('abc') expected = ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] assert sorted(result) == sorted(expected) def test_count_anagrams(): terms = ['abc', 'acb', 'bca'] tex...
[ { "docstring": "Generates all anagrams of a given word.\nThis function does not eliminate duplicate anagrams.", "function_declaration": "def generate_anagrams(word):", "function_name": "generate_anagrams", "parameter_list": "(word)" }, { "docstring": "Counts the frequency of provided anagram...
[ 0, 0, 1, 0, 0, 1, 1, 0, 1 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "from collections import defaultdict\nfrom itertools import permutations\n\ndef get_anagrams(word):\n \"\"\"\n Returns a set of all possible anagrams from the letters of the given word.\n...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00036320", "row_id": 36320, "seed_ids": "['Qwen2-72B-Instruct_81182']" }
0.540422
Filter_36320
I
[ "generate_anagrams", "count_anagrams", "find_anagrams_in_text" ]
3
[ [ "find_anagrams_in_text", "count_anagrams" ], [ "find_anagrams_in_text", "generate_anagrams" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e2832fb341f3aa56b22720c58b2ee8a2eb017583
5eb67eef4a4f9d102800e37b25e2442b7d78b777
v1.0
instruct
Filter
Filter_36391_I
Build a radix sort algorithm in Python that works on both positive and negative numbers without converting them to any other data type except for int or long. Your solution must deal with a special case: if the input list contains only negative numbers, the smallest number should appear at the beginning of the list whe...
def counting_sort(arr, exp, is_negative=False): n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): if is_negative: index = (abs(arr[i]) // exp) % 10 else: index = (arr[i] // exp) % 10 count[index] += 1 for i in range(1, 10): co...
from solution import radix_sort def test_single_negative_number(): assert radix_sort([-1]) == [-1] def test_all_negative_numbers(): assert radix_sort([-5, -3, -4, -2, -1]) == [-5, -4, -3, -2, -1] def test_single_positive_number(): assert radix_sort([2]) == [2] def test_all_positive_numbers(): assert...
[ { "docstring": null, "function_declaration": "def counting_sort(arr, exp, is_negative=False):", "function_name": "counting_sort", "parameter_list": "(arr, exp, is_negative=False)" }, { "docstring": null, "function_declaration": "def radix_sort(arr):", "function_name": "radix_sort", ...
[ 0, 0, 0, 1, 1, 1, 0, 1, 0 ]
4
medium
0.444
{ "trial_gpt4o_0": { "file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl", "solution_code": "def radix_sort(arr):\n \"\"\"\n Perform radix sort on the given list, handling both positive and negative numbers.\n \"\"\"\n if not arr:\n return []\n\n # Separate posit...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00036391", "row_id": 36391, "seed_ids": "['Qwen2-72B-Instruct_81301']" }
0.623403
Filter_36391
I
[ "counting_sort", "radix_sort" ]
2
[ [ "radix_sort", "counting_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8f4648d4f10d69ae283854b2f208636bc2211dea
56f897a8b9561bad1256bbb50fe78ff30cde590a