Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
32
32
problem
stringlengths
207
3.86k
reference
stringlengths
114
5.46k
tests
listlengths
10
10
function
stringlengths
1
53
signature
stringlengths
9
432
score
float64
0.3
1
domain
stringclasses
2 values
3390a0c7ea8f29471e3af9c131b11afc
You are given a list of integers. Your task is to implement a function `sort_odd_even` that processes this list by separating the odd and even numbers, sorting each group individually, and then returning a dictionary with the keys `'odd'` and `'even'`. Each key should map to a list of sorted numbers. For instance, if t...
def sort_odd_even(numbers): """ Separates the odd and even numbers from the input list, sorts them individually, and returns a dictionary with keys 'odd' and 'even' mapping to the sorted lists. :param numbers: List of integers to be processed. :return: Dictionary with sorted odd and even number...
[ "assert sort_odd_even([3, 1, 4, 2, 5, 7]) == {'odd': [1, 3, 5, 7], 'even': [2, 4]}", "assert sort_odd_even([10, 15, 20, 25, 30]) == {'odd': [15, 25], 'even': [10, 20, 30]}", "assert sort_odd_even([1, 3, 5, 7, 9]) == {'odd': [1, 3, 5, 7, 9], 'even': []}", "assert sort_odd_even([2, 4, 6, 8, 10]) == {'odd': [], ...
sort_odd_even
def sort_odd_even(numbers):
1
generic
cc3c4af08ad12c106078ff34ee7e761e
You are tasked with implementing an efficient algorithm to compute the nth Fibonacci number. To optimize your solution, you must use memoization to avoid redundant calculations. Your function should handle large values of n efficiently. **Input:** - An integer `n` (0 ≤ n ≤ 50). **Output:** - The nth Fibonacci number....
def fibonacci(n, memo=None): """ Calculate the nth Fibonacci number using memoization. :param n: The position in the Fibonacci sequence (0-indexed). :param memo: A dictionary to store previously computed Fibonacci numbers. :return: The nth Fibonacci number. """ if memo is None: memo...
[ "assert fibonacci(0) == 0", "assert fibonacci(1) == 1", "assert fibonacci(2) == 1", "assert fibonacci(3) == 2", "assert fibonacci(4) == 3", "assert fibonacci(5) == 5", "assert fibonacci(10) == 55", "assert fibonacci(15) == 610", "assert fibonacci(20) == 6765", "assert fibonacci(25) == 75025" ]
fibonacci
def fibonacci(n, memo=None):
1
generic
6873e18d76d98ed34c268930f78caa3a
You are given a dictionary where each key is associated with a list of integers. Your task is to write a function `sort_dict_values` that returns a new dictionary with the same keys, but with the values sorted in ascending order. The function should handle any dictionary of this form. **Sample Input:** ```python {'a':...
def sort_dict_values(input_dict): """ Sorts the values of each key in the input dictionary in ascending order. Parameters: input_dict (dict): A dictionary where each key is associated with a list of integers. Returns: dict: A new dictionary with the same keys and sorted values. """ ret...
[ "assert sort_dict_values({'a': [3, 1, 2], 'b': [5, 4]}) == {'a': [1, 2, 3], 'b': [4, 5]}", "assert sort_dict_values({'x': [10, 9, 8], 'y': [7, 6, 5]}) == {'x': [8, 9, 10], 'y': [5, 6, 7]}", "assert sort_dict_values({'z': [1], 'w': [2]}) == {'z': [1], 'w': [2]}", "assert sort_dict_values({'m': [3, 3, 3], 'n': ...
sort_dict_values
def sort_dict_values(input_dict):
1
generic
82e41b742749b30e0324bc07098489d3
You are given a list of intervals, where each interval is represented as a tuple of two integers. Your task is to merge all overlapping intervals and return a new list of non-overlapping intervals sorted in ascending order based on their start times. **Input:** - A list of tuples, where each tuple represents an interv...
def merge_intervals(intervals): """ Merges all overlapping intervals from the given list and returns a new list of non-overlapping intervals. :param intervals: List of tuples, where each tuple represents an interval [start, end]. :return: List of tuples representing the merged intervals. """ ...
[ "assert merge_intervals([(1, 3), (2, 5), (8, 10)]) == [(1, 5), (8, 10)]", "assert merge_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_intervals([(1, 3), (2, 6), (5, 7), (8, 10), (12, 16)]) == [(1, 7), (8, 10), (12, 16)]"...
merge_intervals
def merge_intervals(intervals):
1
generic
9f1b8c6714ee7e0b93961402ffa24f94
You are given a list of data sets, each characterized by its sum-of-squared-deviations (sosd), the number of items (num), and the degrees of freedom (ddof). Your task is to compute the variance for each data set if the number of items is a prime number. The variance is defined as the sum-of-squared-deviations divided b...
def is_prime(n): """Check if a number is a prime number.""" 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 ...
[ "assert calculate_variance(100, 7, 1) == 100 / (7 - 1)", "assert calculate_variance(50, 11, 2) == 50 / (11 - 2)", "assert calculate_variance(200, 13, 3) == 200 / (13 - 3)", "assert calculate_variance(0, 17, 0) == 0 / (17 - 0)", "assert calculate_variance(150, 4, 1) == None", "assert calculate_variance(25,...
calculate_variance
def calculate_variance(sosd, num, ddof):
1
generic
fe1244087aaf4997613ffe6585258c0a
You are given an array of integers `nums` and an integer `k`. Your task is to find the maximum sum of any contiguous subarray of length `k`. If `k` is larger than the length of the array, return `None`. **Input:** - The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the array. - The secon...
def find_max_subarray_sum(nums, k): """ Finds the maximum sum of any contiguous subarray of length k. :param nums: List[int] - The list of integers. :param k: int - The length of the subarray. :return: int or None - The maximum sum of any subarray of length k, or None if k is greater than the l...
[ "assert find_max_subarray_sum([1, 2, 3, 4, 5], 2) == 9", "assert find_max_subarray_sum([1, 2, 3, 4, 5], 5) == 15", "assert find_max_subarray_sum([1, 2, 3, 4, 5], 6) == None", "assert find_max_subarray_sum([5, 1, 3, 2, 4], 3) == 10", "assert find_max_subarray_sum([-1, -2, -3, -4, -5], 2) == -3", "assert fi...
find_max_subarray_sum
def find_max_subarray_sum(nums, k):
0.9
generic
2c703003ed920c5ce86160a9938d61f0
You are given two integers `n` and `k`. Your task is to generate all possible combinations of `k` distinct numbers chosen from the range `[1, n]`. The combinations should be returned as a list of lists, where each inner list represents a unique combination. The order of combinations in the output list does not matter. ...
def generate_combinations(n, k): """ Generate all possible combinations of k numbers out of the range [1, n]. :param n: The upper bound of the range (inclusive). :param k: The number of elements in each combination. :return: A list of lists, where each inner list is a unique combination of k number...
[ "assert generate_combinations(4, 2) == [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]", "assert generate_combinations(3, 2) == [[1, 2], [1, 3], [2, 3]]", "assert generate_combinations(5, 3) == [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]", "a...
generate_combinations
def generate_combinations(n, k):
1
generic
4321c0d4d41c6d4526c3a6dc7beeff5f
You are tasked with implementing a function `calculate_area` that computes the area of a rectangle given its width and height. The function should correctly multiply the width by the height to determine the area. Your implementation should handle positive integer inputs for both dimensions. Below is an erroneous versio...
def calculate_area(width, height): """ Calculate the area of a rectangle given its width and height. Parameters: width (int): The width of the rectangle. height (int): The height of the rectangle. Returns: int: The area of the rectangle. """ return width * height
[ "assert calculate_area(5, 10) == 50", "assert calculate_area(0, 10) == 0", "assert calculate_area(7, 3) == 21", "assert calculate_area(1, 1) == 1", "assert calculate_area(10, 0) == 0", "assert calculate_area(2.5, 4) == 10.0", "assert calculate_area(3, 3.5) == 10.5", "assert calculate_area(0, 0) == 0",...
calculate_area
def calculate_area(width, height):
1
generic
47f547d4e5e9aaca56c14aba9891223a
You are given a nested dictionary that may contain other dictionaries and lists. Your task is to create a function that generates a unique string identifier for this dictionary. The identifier should be constructed by flattening the dictionary into a single string, where keys and values are separated by a colon (`:`), ...
def flatten_dict(d, parent_key='', sep='.'): """ Flattens a nested dictionary into a single-level dictionary with compound keys. :param d: The dictionary to flatten. :param parent_key: The base key string used in recursion. :param sep: The separator between parent and child keys. :return: A...
[ "assert generate_unique_identifier({'a': 1, 'b': 2}) == 'a:1,b:2'", "assert generate_unique_identifier({'a': {'b': 2}}) == 'a.b:2'", "assert generate_unique_identifier({'a': [1, 2, 3]}) == 'a[0]:1,a[1]:2,a[2]:3'", "assert generate_unique_identifier({'a': [1, {'b': 2}]}) == 'a[0]:1,a[1].b:2'", "assert genera...
generate_unique_identifier
def generate_unique_identifier(input_dict, key_val_sep=':', pair_sep=','):
0.9
generic
158a98f866684cd485f609ef3b7ed67b
You are given a nested dictionary structure where each key-value pair can either be another dictionary or a value that is either a number or a string. Your task is to compute the sum of all numeric values within this structure. The structure can be arbitrarily deep. Write a recursive Python function to accomplish this....
def sum_nested_numbers(data): """ Recursively computes the sum of all numeric values in a nested dictionary structure. :param data: A nested dictionary or a numeric/string value. :return: The sum of all numeric values in the structure. """ if isinstance(data, dict): return sum(sum_neste...
[ "assert sum_nested_numbers({\"x\": 1, \"y\": {\"z\": 2, \"w\": 3}, \"a\": \"string\", \"b\": {\"c\": {\"d\": 4}}}) == 10", "assert sum_nested_numbers({\"x\": 1, \"y\": 2, \"z\": 3}) == 6", "assert sum_nested_numbers({\"x\": {\"y\": {\"z\": 1}}}) == 1", "assert sum_nested_numbers({\"x\": \"string\", \"y\": \"a...
sum_nested_numbers
def sum_nested_numbers(data):
1
algorithmic
ee10d41bf40f8a7f2413bf32e52a844e
You are given a list of integers, which may include both positive and negative numbers. Your task is to implement a function `count_duplicates` that returns a dictionary. The keys of this dictionary should be the integers from the list, and the corresponding values should represent the frequency of each integer in the ...
def count_duplicates(lst): """ Returns a dictionary with integers from the list as keys and their frequencies as values. :param lst: List of integers :return: Dictionary with integer frequencies """ counts = {} for num in lst: if num in counts: counts[num] += 1 e...
[ "assert count_duplicates([1, 2, 2, 3, 3, 3]) == {1: 1, 2: 2, 3: 3}", "assert count_duplicates([-1, -2, -2, -3, -3, -3]) == {-1: 1, -2: 2, -3: 3}", "assert count_duplicates([0, 0, 0, 0]) == {0: 4}", "assert count_duplicates([1, 1, 2, 2, 3, 3, 4, 4]) == {1: 2, 2: 2, 3: 2, 4: 2}", "assert count_duplicates([]) ...
count_duplicates
def count_duplicates(lst):
1
generic
da831c2b6a26e2fabcb59ac148a0f34d
Given a string `s`, your task is to write a function `generate_permutations(s)` that returns all unique permutations of the string in lexicographical order. You are not allowed to use any built-in functions that directly generate permutations. **Input:** - A single string `s` (1 ≤ |s| ≤ 8), consisting of lowercase Eng...
def generate_permutations(s): """ Generate all unique permutations of a given string s in lexicographical order. :param s: A string consisting of lowercase English letters. :return: A list of strings, each representing a unique permutation of s. """ def backtrack(start, end): if sta...
[ "assert generate_permutations(\"a\") == [\"a\"]", "assert generate_permutations(\"ab\") == [\"ab\", \"ba\"]", "assert generate_permutations(\"abc\") == [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"]", "assert generate_permutations(\"aabb\") == [\"aabb\", \"abab\", \"abba\", \"baab\", \"baba\", \"bbaa\...
generate_permutations
def generate_permutations(s):
0.7
generic
e44602d306b85ef35140aa14e313326b
You are given an integer `number`. Your task is to determine whether this number is a palindrome. A number is considered a palindrome if it reads the same backward as forward. For example, 121, 12321, and 1221 are palindromes, whereas 123 is not. **Input:** - An integer `number` (0 ≤ number ≤ 10^9) **Output:** - Retu...
def is_palindrome_number(number): """ Determines if the given integer is a palindrome. Args: number (int): The integer to check. Returns: bool: True if the number is a palindrome, False otherwise. """ str_number = str(number) return str_number == str_number[::-1]
[ "assert is_palindrome_number(121) == True", "assert is_palindrome_number(12321) == True", "assert is_palindrome_number(1221) == True", "assert is_palindrome_number(123) == False", "assert is_palindrome_number(0) == True", "assert is_palindrome_number(10) == False", "assert is_palindrome_number(1001) == ...
is_palindrome_number
def is_palindrome_number(number):
1
generic
0be10a3545264a2640b0648c26780740
You are tasked with developing a function for a non-profit organization that generates thank-you letters for different types of donations. The organization sends out three types of letters: individual, annual, and sustaining donations. Each letter has a specific format: - **Individual Donation Letter:** - Header: `S...
from datetime import datetime def generate_letter(donation_type, donor_info): """ Generates a thank-you letter based on the type of donation and donor information. Parameters: donation_type (str): The type of donation ('individual', 'annual', or 'sustaining'). donor_info (dict): A dictionary conta...
[ "assert generate_letter('individual', {'name': 'John Doe', 'amount': '100'}) == f\"Seattle, WA {datetime.now().strftime('%B %d, %Y')}\\nDear John Doe,\\nThank you for your very kind donation of $100. It will be put to very good use.\\nSincerely,\\n-The Team\"", "assert generate_letter('annual', {'name': 'Jane Smi...
generate_letter
def generate_letter(donation_type, donor_info):
1
generic
5eb7c39df5cca0f680dfc7438067af98
You are tasked with writing a Python script that processes a directory and its subdirectories to identify all `.csv` files. For each `.csv` file, your script should determine and output the number of rows and columns. Your script must handle potential errors gracefully, such as the directory not existing or `.csv` file...
import os import csv def get_csv_info(directory): """ Processes a directory and its subdirectories to identify all .csv files. For each .csv file, prints the number of rows and columns. Handles errors such as directory not existing or malformed .csv files. :param directory: Path to the directory t...
[ "assert get_csv_info(\"/nonexistent_directory\") is None", "assert get_csv_info(\"/path/to/directory/with/no/csv\") is None", "assert get_csv_info(\"/path/to/directory/with/single/csv\") is None", "assert get_csv_info(\"/path/to/directory/with/multiple/csv/files\") is None", "assert get_csv_info(\"/path/to/...
get_csv_info
def get_csv_info(directory):
1
generic
309528d81ec004742bb5f82c6ac9b21d
You are given a string `s` that contains multiple sentences. Your task is to implement a function `split_string_into_sentences(s)` that splits the string into individual sentences based on punctuation marks such as period (.), exclamation mark (!), and question mark (?). The function should ignore any spaces or punctua...
import re def split_string_into_sentences(s): """ Splits a given string into sentences based on punctuation marks '.', '!', and '?'. Ignores any spaces or punctuation marks that come immediately after these punctuation marks. :param s: Input string containing multiple sentences. :return: List ...
[ "assert split_string_into_sentences(\"Hello world! How are you doing today? I hope you're well. Alright then.\") == ['Hello world', 'How are you doing today', \"I hope you're well\", 'Alright then']", "assert split_string_into_sentences(\"This is a test. This is only a test.\") == ['This is a test', 'This is only...
split_string_into_sentences
def split_string_into_sentences(s):
1
generic
6271bfded21859e48b646e6ab32cf553
You are given a string `s` and a target word `target`. Your task is to implement a function `find_target_indices(s, target)` that returns a list of starting indices of all occurrences of the target word within the string `s`. The search should be case-insensitive and consider only complete words. The input string `s` d...
def find_target_indices(s, target): """ Returns a list of starting indices of all occurrences of the target word within the string s. :param s: The input string to search within. :param target: The target word to find. :return: A list of starting indices of all occurrences of the target word. ...
[ "assert find_target_indices(\"hello world\", \"world\") == [1]", "assert find_target_indices(\"hello world\", \"hello\") == [0]", "assert find_target_indices(\"hello world\", \"test\") == []", "assert find_target_indices(\"the quick brown fox jumps over the lazy dog\", \"the\") == [0, 6]", "assert find_targ...
find_target_indices
def find_target_indices(s, target):
1
generic
17d3811545f72b19941b994de8cb96cb
You are tasked with writing a Python script that reads a JSON configuration file named `config.json` and extracts specific settings. The JSON file contains the following keys: `server_address`, `port`, `use_ssl`, and `timeout`. Your script should handle cases where some keys might be missing by providing a default valu...
import json def read_config(file_name): """ Reads a JSON configuration file and extracts specific settings. Handles missing keys by providing a default value of "Not specified". Gracefully handles file not found and JSON decoding errors. :param file_name: The name of the JSON configuration file. ...
[ "assert read_config('non_existent_file.json') == None", "assert read_config('invalid_json_file.json') == None", "assert read_config('config_with_missing_keys.json') == None", "assert read_config('config_with_all_keys.json') == None", "assert read_config('config_with_empty_values.json') == None", "assert r...
read_config
def read_config(file_name):
1
generic
704b2f7a891cbab827b4e0fec624b1d8
You are given a list containing various types of objects. Your task is to implement a function `total_memory_usage` that computes the total memory usage of all objects in the list in bytes. The function should handle different data types such as integers, strings, lists, and dictionaries. **Input:** - A list of objec...
import sys def total_memory_usage(obj_list): """ Calculate the total memory usage of all the objects stored in the given list. Parameters: obj_list (list): A list of objects whose memory usage needs to be calculated. Returns: int: The total memory usage of the objects in bytes. ""...
[ "assert total_memory_usage([]) == 0", "assert total_memory_usage([1]) == sys.getsizeof(1)", "assert total_memory_usage(['a']) == sys.getsizeof('a')", "assert total_memory_usage([1, 'a']) == sys.getsizeof(1) + sys.getsizeof('a')", "assert total_memory_usage([[], {}]) == sys.getsizeof([]) + sys.getsizeof({})"...
total_memory_usage
def total_memory_usage(obj_list):
1
generic
19afdbd54676397f0509e62199b6abcd
You are given a list of integers `numbers`. Your task is to implement a function `remove_duplicates` that returns a new list containing only the unique elements from the original list, preserving the order of their first appearance. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each intege...
def remove_duplicates(numbers): """ Returns a new list containing only the unique elements from the original list, preserving the order of their first appearance. :param numbers: List of integers :return: List of unique integers in the order of their first appearance """ seen = set() un...
[ "assert remove_duplicates([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5]", "assert remove_duplicates([10, 20, 20, 10, 30]) == [10, 20, 30]", "assert remove_duplicates([1, 1, 1, 1, 1]) == [1]", "assert remove_duplicates([]) == []", "assert remove_duplicates([7, 8, 9]) == [7, 8, 9]", "assert remove_duplicates([5...
remove_duplicates
def remove_duplicates(numbers):
1
generic
93a441be39b1d1703893a91f7e4ebc3d
In a strategic game, two players take turns removing stones from a pile. Initially, there are `n` stones in the pile. During each turn, a player can remove a number of stones that is a power of 2 (i.e., 1, 2, 4, 8, ...). The player who removes the last stone wins. Both players play optimally. Determine the optimal move...
def compute_grundy_numbers(max_n): """ Computes the Grundy numbers for the game up to max_n stones. :param max_n: The maximum number of stones to compute Grundy numbers for. :return: A list of Grundy numbers up to max_n. """ grundy = [0] * (max_n + 1) for i in range(1, max_n + 1): ...
[ "assert find_optimal_move(1) == 1", "assert find_optimal_move(2) == 2", "assert find_optimal_move(3) == 1", "assert find_optimal_move(4) == 4", "assert find_optimal_move(5) == 1", "assert find_optimal_move(6) == 2", "assert find_optimal_move(7) == 1", "assert find_optimal_move(8) == 8", "assert find...
find_optimal_move
def find_optimal_move(n):
0.4
generic
898194bf1d8e9db09ebc66a8fdec84b4
You are given a 3D grid defined by its bounds `(mx, Mx, my, My, mz, Mz)`, where `mx < Mx`, `my < My`, and `mz < Mz`. Each cell in the grid is identified by its coordinates `(x, y, z)`. Your task is to implement a function `find_adjacent_cells(bounds, position, query_cell_value)` that identifies all adjacent cells to a ...
def find_adjacent_cells(bounds, position, query_cell_value): """ Finds all adjacent cells to the given position within the grid boundaries that contain a non-zero value. :param bounds: A tuple (mx, Mx, my, My, mz, Mz) defining the grid boundaries. :param position: A tuple (x, y, z) representing the...
[ "assert find_adjacent_cells((0, 3, 0, 3, 0, 3), (1, 1, 1), lambda bounds, pos: 1) == [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0),...
find_adjacent_cells
def find_adjacent_cells(bounds, position, query_cell_value):
0.9
generic
b3790434e7feb3885bb2552566ea7d03
You are given a list of integers `lst`. Your task is to implement a function `remove_duplicates(lst)` that returns a new list with all duplicate elements removed, while maintaining the original order of the elements. The input list may be empty and will only contain integers. **Sample Input:** ``` [1, 2, 2, 3, 4, 4, 5...
def remove_duplicates(lst): """ Removes all duplicate elements from the given list lst and returns a new list with duplicates removed, preserving the original order of elements. :param lst: List of integers :return: New list with duplicates removed """ seen = set() result = [] f...
[ "assert remove_duplicates([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5]", "assert remove_duplicates([1, 1, 1, 1, 1]) == [1]", "assert remove_duplicates([]) == []", "assert remove_duplicates([10, 20, 30, 40, 50]) == [10, 20, 30, 40, 50]", "assert remove_duplicates([5, 4, 3, 2, 1, 1, 2, 3, 4, 5]) == [5, 4, 3, 2, ...
remove_duplicates
def remove_duplicates(lst):
1
generic
8ec9d1aa4000b1dd5f49ac653a58b6a1
You are given two sorted lists, `list1` and `list2`, consisting of integers and/or floating-point numbers. Your task is to implement a function `merge_sorted_lists` that merges these two lists into a single sorted list. The function should operate with a time complexity of O(n + m), where n and m are the lengths of `li...
def merge_sorted_lists(list1, list2): """ Merges two sorted lists into a single sorted list. Parameters: list1 (list): The first sorted list. list2 (list): The second sorted list. Returns: list: A merged and sorted list containing all elements from list1 and list2. """ merg...
[ "assert merge_sorted_lists([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]", "assert merge_sorted_lists([], [1, 2, 3]) == [1, 2, 3]", "assert merge_sorted_lists([1, 2, 3], []) == [1, 2, 3]", "assert merge_sorted_lists([], []) == []", "assert merge_sorted_lists([1.5, 2.5, 3.5], [1.2, 2.2, 3.2]) == [1.2, 1.5, 2.2...
merge_sorted_lists
def merge_sorted_lists(list1, list2):
1
generic
c7280524a0d8cf8beffa947f31b4ab8f
You are tasked with implementing a function to find all prime numbers up to a given integer `n` using the Sieve of Eratosthenes algorithm. Your function should return a list of all prime numbers less than or equal to `n`. **Input:** - An integer `n` (1 ≤ n ≤ 10^6) **Output:** - A list of integers representing all pri...
def find_primes_up_to_n(n): """ Returns a list of all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm. :param n: An integer representing the upper limit. :return: A list of prime numbers less than or equal to n. """ if n < 2: return [] is_prime =...
[ "assert find_primes_up_to_n(10) == [2, 3, 5, 7]", "assert find_primes_up_to_n(1) == []", "assert find_primes_up_to_n(2) == [2]", "assert find_primes_up_to_n(19) == [2, 3, 5, 7, 11, 13, 17, 19]", "assert find_primes_up_to_n(0) == []", "assert find_primes_up_to_n(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]"...
find_primes_up_to_n
def find_primes_up_to_n(n):
1
generic
34a3730599b238372ff020a976594b46
You are given an undirected graph `G` with `N` nodes and `M` edges. The graph is represented as an adjacency list, where each node is an integer from `0` to `N-1`, and each edge is a pair of integers. Your task is to determine whether the graph contains a cycle. Write a function `has_cycle` that returns `True` if the g...
def has_cycle(G): """ Determines if the given undirected graph contains a cycle. :param G: List of lists representing the adjacency list of the graph. :return: True if the graph contains a cycle, False otherwise. """ def dfs(node, parent): visited[node] = True in_stack[node] = T...
[ "assert has_cycle([[], [2], [1]]) == False", "assert has_cycle([[1], [2], [0]]) == True", "assert has_cycle([[1, 2], [2], []]) == True", "assert has_cycle([[], [], []]) == False", "assert has_cycle([[1], [2], [3], [4], [0]]) == True", "assert has_cycle([[1], [2], [3], [4], [5], [6], [7], [8], [9], [5]]) =...
has_cycle
def has_cycle(G):
0.6
generic
d01db553f78e6c135f2e43232b2aa31e
You are given a list of integers `nums`. Your task is to implement a function `find_prime_factors(nums)` that returns a list of lists, where each sublist contains the prime factors of the corresponding integer in `nums`. A prime factor is a factor that is a prime number. **Input:** - A list of integers `nums` (1 ≤ len...
def find_prime_factors(nums): """ Returns a list of lists, where each sublist contains the prime factors of the corresponding integer in nums. :param nums: List of integers :return: List of lists containing prime factors """ def prime_factors(n): """ Returns a list of prime ...
[ "assert find_prime_factors([12, 15, 21]) == [[2, 2, 3], [3, 5], [3, 7]]", "assert find_prime_factors([1, 2, 3]) == [[], [2], [3]]", "assert find_prime_factors([4, 6, 8]) == [[2, 2], [2, 3], [2, 2, 2]]", "assert find_prime_factors([9, 10, 11]) == [[3, 3], [2, 5], [11]]", "assert find_prime_factors([13, 14, 1...
find_prime_factors
def find_prime_factors(nums):
1
generic
6ad9241ee298572c9c5b1f5fd1a4f834
You are given a string `text`. Your task is to implement a function `check_palindrome` that determines whether the string is a palindrome, considering only alphanumeric characters and ignoring case differences. A string is a palindrome if it reads the same backward as forward. **Input:** - A single string `text` (1 ≤ ...
def check_palindrome(text): """ Determines if the given string is a palindrome, considering only alphanumeric characters and ignoring case differences. :param text: The input string to check. :return: True if the string is a palindrome, False otherwise. """ # Remove non-alphanumeric charact...
[ "assert check_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert check_palindrome(\"racecar\") == True", "assert check_palindrome(\"No lemon, no melon\") == True", "assert check_palindrome(\"Was it a car or a cat I saw?\") == True", "assert check_palindrome(\"Hello, World!\") == False", "ass...
check_palindrome
def check_palindrome(text):
1
generic
8bb3d567ab7a514ba38f2498fd3aea13
You are given a string `s`. Your task is to write a function `reverse_vowels` that returns a new string where the order of the vowels ('a', 'e', 'i', 'o', 'u', both uppercase and lowercase) is reversed, while the order of all other characters remains unchanged. **Constraints:** - The length of the string `s` is betwe...
def reverse_vowels(s: str) -> str: """ Reverses the order of vowels in the given string while keeping other characters in their original positions. :param s: Input string :return: New string with vowels reversed """ vowels = "aeiouAEIOU" s_list = list(s) i, j = 0, len(s) - 1 wh...
[ "assert reverse_vowels(\"Hello, World!\") == \"Hollo, Werld!\"", "assert reverse_vowels(\"Programming\") == \"Prigrammong\"", "assert reverse_vowels(\"Python\") == \"Pythpn\"", "assert reverse_vowels(\"AEIOU\") == \"UOIEA\"", "assert reverse_vowels(\"aeiou\") == \"uoiea\"", "assert reverse_vowels(\"abcdef...
reverse_vowels
def reverse_vowels(s: str) -> str:
0.7
generic
7c6229706975bcbc5460293cd8974b62
You are given a convolutional layer in a neural network with the following parameters: the number of input channels (`num_in`), the height and width of the input (`height_in`, `width_in`), the kernel size (`kernel_size`), the stride (`stride`), and the asymmetric padding (`padding_top`, `padding_bottom`, `padding_left`...
def calculate_output_shape(num_in, num_out, height_in, width_in, kernel_size, stride, padding_top, padding_bottom, padding_left, padding_right): """ Calculate the shape of the output tensor after a convolution operation. Parameters: num_in (int): Number of input channels. ...
[ "assert calculate_output_shape(1, 32, 32, 32, 3, 1, 1, 1, 1, 1) == [32, 32, 32]", "assert calculate_output_shape(3, 64, 224, 224, 3, 1, 1, 1, 1, 1) == [64, 224, 224]", "assert calculate_output_shape(3, 64, 224, 224, 5, 2, 2, 2, 2, 2) == [64, 112, 112]", "assert calculate_output_shape(1, 1, 28, 28, 2, 2, 0, 0,...
calculate_output_shape
def calculate_output_shape(num_in, num_out, height_in, width_in, kernel_size, stride, padding_top, padding_bottom, padding_left, padding_right):
1
generic
a24b6160f79a9d7022f577bbc5e21a17
You are given a positive integer `n` greater than 1. Your task is to implement a function `find_largest_prime(n)` that returns the largest prime number less than or equal to `n`. **Input:** - A single integer `n` (2 ≤ n ≤ 10^6) **Output:** - A single integer representing the largest prime number less than or equal t...
def find_largest_prime(n): """ Finds the largest prime number less than or equal to a given number n. Parameters: n (int): A positive integer greater than 1. Returns: int: The largest prime number less than or equal to n. """ def is_prime(num): """ Checks if a number is...
[ "assert find_largest_prime(10) == 7", "assert find_largest_prime(20) == 19", "assert find_largest_prime(2) == 2", "assert find_largest_prime(17) == 17", "assert find_largest_prime(1) == None", "assert find_largest_prime(100) == 97", "assert find_largest_prime(30) == 29", "assert find_largest_prime(50)...
find_largest_prime
def find_largest_prime(n):
1
generic
8a4befdf818932808e35e9a76fc8ac84
You are given a list of integers. Your task is to write a Python function that returns the two largest distinct numbers in the list. If the list contains fewer than two distinct numbers, the function should raise a `ValueError`. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is...
def find_two_largest_numbers(numbers): """ Returns the two largest distinct numbers in the list. :param numbers: List of integers :return: Tuple of two largest distinct integers :raises ValueError: If the list contains fewer than two distinct numbers """ if len(numbers) < 2: rai...
[ "assert find_two_largest_numbers([1, 2]) == (2, 1)", "assert find_two_largest_numbers([10, 20, 30, 40, 50]) == (50, 40)", "assert find_two_largest_numbers([50, 40, 30, 20, 10]) == (50, 40)", "assert find_two_largest_numbers([100, 100, 100, 100]) == (100, 100)", "assert find_two_largest_numbers([-1, -2, -3, ...
find_two_largest_numbers
def find_two_largest_numbers(numbers):
0.8
algorithmic
3c30e4606cc5da385d0f9a8370dbba15
You are given a list of integers. Your task is to implement a function `find_min_max` that takes this list as input and returns a tuple containing the minimum and maximum values in the list. You are not allowed to use any built-in functions to determine the minimum or maximum values. **Input:** - A list of integers `n...
def find_min_max(numbers): """ Finds the minimum and maximum values in a list of integers without using built-in functions. Parameters: numbers (list): A list of integers. Returns: tuple: A tuple containing the minimum and maximum values in the list. """ # Initialize the first element ...
[ "assert find_min_max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == (1, 9)", "assert find_min_max([100, 200, 300, 400, 500]) == (100, 500)", "assert find_min_max([-10, -20, -30, -40, -50]) == (-50, -10)", "assert find_min_max([0, 0, 0, 0, 0]) == (0, 0)", "assert find_min_max([42]) == (42, 42)", "assert find_min_ma...
find_min_max
def find_min_max(numbers):
1
generic
7e564d03573b7c122cdbd74ea23fd68d
You are given a string that potentially contains a JSON array. The string may have leading or trailing whitespace and may not be properly formatted. Your task is to implement a function `parse_json_array` that processes the string and returns the corresponding Python list. If the string does not represent a valid JSON ...
import json def parse_json_array(json_string): """ Parses a string containing a JSON array and returns the corresponding Python list. If the string is not a valid JSON array, returns an empty list. :param json_string: A string that may contain a JSON array. :return: A Python list if the string...
[ "assert parse_json_array(' [1, 2, 3, 4, 5] ') == [1, 2, 3, 4, 5]", "assert parse_json_array('{\"key\": \"value\"}') == []", "assert parse_json_array(' [1, 2, \"three\", 4, 5] ') == [1, 2, \"three\", 4, 5]", "assert parse_json_array('') == []", "assert parse_json_array(' ') == []", "assert parse_json_arr...
parse_json_array
def parse_json_array(json_string):
1
generic
0d3b51ebed53b1bd2d80e63a6ffb652f
You are given a thermostat with a current temperature and a desired temperature range defined by a minimum and maximum temperature. The thermostat must adjust the current temperature to ensure it stays within the specified range. If the current temperature is below the minimum, it should be incremented in steps of 0.5 ...
def adjust_thermostat(current_temp, min_temp, max_temp): """ Adjusts the current temperature to ensure it stays within the specified range. Parameters: current_temp (float): The current temperature. min_temp (float): The minimum temperature of the range. max_temp (float): The maximum temper...
[ "assert adjust_thermostat(18.0, 20.0, 25.0) == 20.0", "assert adjust_thermostat(22.0, 20.0, 25.0) == 22.0", "assert adjust_thermostat(26.0, 20.0, 25.0) == 25.0", "assert adjust_thermostat(19.5, 20.0, 25.0) == 20.0", "assert adjust_thermostat(25.5, 20.0, 25.0) == 25.0", "assert adjust_thermostat(15.0, 15.0...
adjust_thermostat
def adjust_thermostat(current_temp, min_temp, max_temp):
1
generic
5933329b7d9d65742c8aecced1b09610
You are tasked with implementing a function to generate all prime numbers up to a given integer `n` (inclusive) using the Sieve of Eratosthenes algorithm. Your function should return a list of these prime numbers. If `n` is less than 2, return an empty list. **Input:** - An integer `n` (0 ≤ n ≤ 10^6) **Output:** - A ...
def generate_primes(n): """Generate a list of prime numbers up to n (inclusive) using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit of the range to generate prime numbers for. Returns: list: A list of prime numbers up to n. """ if n < 2: return...
[ "assert generate_primes(10) == [2, 3, 5, 7]", "assert generate_primes(20) == [2, 3, 5, 7, 11, 13, 17, 19]", "assert generate_primes(1) == []", "assert generate_primes(2) == [2]", "assert generate_primes(0) == []", "assert generate_primes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]", "assert generate_pri...
generate_primes
def generate_primes(n):
1
generic
ab4eac00663efcb04aff51f59063e004
In the realm of quantum mechanics, the energy of an electron in a hydrogen atom can be determined using the formula \( E = -\frac{13.6}{n^2} \), where \( n \) is the principal quantum number and the energy is measured in electron volts (eV). Your task is to implement a function that computes this energy given the princ...
def calculate_energy(n): """ Calculate the energy of an electron in a hydrogen atom given the principal quantum number. Parameters: n (int): The principal quantum number (1 ≤ n ≤ 1000). Returns: float: The energy of the electron in electron volts (eV), rounded to five decimal places. """ ...
[ "assert calculate_energy(1) == -13.6", "assert calculate_energy(2) == -3.4", "assert calculate_energy(3) == -1.51111", "assert calculate_energy(4) == -0.85", "assert calculate_energy(5) == -0.544", "assert calculate_energy(10) == -0.136", "assert calculate_energy(100) == -0.00136", "assert calculate_e...
calculate_energy
def calculate_energy(n):
1
generic
cc79836dc6ad3ce09b75e5c538a7d0ae
You are given an array of integers `arr` and a positive integer `k`. Your task is to implement a function `find_k_largest_elements(arr, k)` that returns a list containing any `k` largest elements from the array `arr`. The order of elements in the output list does not matter. **Input:** - The first argument is an array...
def find_k_largest_elements(arr, k): """ Returns a list of k largest elements from the array arr. :param arr: List[int] - The input array of integers. :param k: int - The number of largest elements to return. :return: List[int] - A list containing any k largest elements from arr. """ re...
[ "assert find_k_largest_elements([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3) == [9, 6, 5]", "assert find_k_largest_elements([10, 7, 11, 5, 2, 13, 1], 2) == [13, 11]", "assert find_k_largest_elements([1, 2, 3, 4, 5], 5) == [5, 4, 3, 2, 1]", "assert find_k_largest_elements([5, 5, 5, 5, 5], 3) == [5, 5, 5]", "assert ...
find_k_largest_elements
def find_k_largest_elements(arr, k):
0.9
generic
4ab5639f9c2276727548b7dc3a721732
You are given a temperature in Fahrenheit and your task is to write a function `convert_to_celsius(fahrenheit)` that converts this temperature to Celsius using the formula `(Fahrenheit - 32) * 5/9`. Your function should return the temperature in Celsius as a floating-point number. **Sample Input:** ``` 68 ``` **Sampl...
def convert_to_celsius(fahrenheit): """ Convert a temperature from Fahrenheit to Celsius. Parameters: fahrenheit (float): Temperature in Fahrenheit. Returns: float: Temperature in Celsius. """ celsius = (fahrenheit - 32) * 5 / 9 return celsius # Example usage: # celsius_temp = con...
[ "assert convert_to_celsius(32) == 0.0", "assert convert_to_celsius(212) == 100.0", "assert convert_to_celsius(98.6) == 37.0", "assert convert_to_celsius(-40) == -40.0", "assert convert_to_celsius(0) == -17.77777777777778", "assert convert_to_celsius(100) == 37.77777777777778", "assert convert_to_celsius...
convert_to_celsius
def convert_to_celsius(fahrenheit):
1
generic
f382d93fd54c35e65d889499f8bdcb3a
You are given a positive integer `n`. Your task is to compute the factorial of `n` efficiently. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. For example, the factorial of 5 is `5 * 4 * 3 * 2 * 1 = 120`. To optimize the performance, implement a memoizat...
def memoize(f): """ Decorator to memoize a function's results to avoid redundant calculations. """ memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper @memoize def factorial(n): """ Compute the factorial of a giv...
[ "assert factorial(0) == 1", "assert factorial(1) == 1", "assert factorial(2) == 2", "assert factorial(3) == 6", "assert factorial(4) == 24", "assert factorial(5) == 120", "assert factorial(6) == 720", "assert factorial(10) == 3628800", "assert factorial(12) == 479001600", "assert factorial(20) == ...
factorial
def factorial(n):
1
generic
bf09d66c94ea15e4627daa8137bce06c
You are given a list of integers `data` and an integer `window_size`. Your task is to implement a function `calculate_moving_average(data, window_size)` that computes the moving average of the list using a sliding window of the specified size. The function should return a list of moving averages, where each element is ...
def calculate_moving_average(data, window_size): """ Calculate the moving average of a list of numbers using a sliding window. :param data: List of integers representing the data. :param window_size: Integer representing the size of the sliding window. :return: List of floating-point numbers repres...
[ "assert calculate_moving_average([1, 2, 3, 4, 5], 2) == [1.5, 2.5, 3.5, 4.5]", "assert calculate_moving_average([10, 20, 30, 40, 50], 3) == [20.0, 30.0, 40.0]", "assert calculate_moving_average([5, 10, 15, 20, 25], 5) == [15.0]", "assert calculate_moving_average([1, 2, 3], 4) == []", "assert calculate_movin...
calculate_moving_average
def calculate_moving_average(data, window_size):
1
generic
37f38016cbdb8a93f69729e897f47a78
You are tasked with developing a function `find_keywords` for a text analysis tool. The function should process a given string `text` and return a list of the top 5 most frequent words. Words should be converted to lowercase, and all punctuation should be removed. The function should handle multiple sentences and varyi...
import re from collections import Counter def find_keywords(text): """ Extracts the top 5 most frequent words from the given text. Parameters: text (str): The input text from which to extract keywords. Returns: list: A list of the top 5 most frequent words in lowercase. """ # ...
[ "assert find_keywords(\"Hello, world! Hello, everyone. Welcome to the world of programming.\") == ['hello', 'world', 'welcome', 'everyone', 'programming']", "assert find_keywords(\"Python is great. Python is fun. Python is powerful.\") == ['python', 'is', 'great', 'fun', 'powerful']", "assert find_keywords(\"Da...
find_keywords
def find_keywords(text):
0.8
generic
c5c667f76ad9a280a4d1cda2d19bd6fc
You are given a list of sessions, each represented as a tuple of two strings indicating the start and end times in the format "HH:MM:SS". Your task is to calculate the total time spent on a website by merging overlapping sessions and summing their durations. Implement the function `calculate_total_time(sessions)` witho...
def calculate_total_time(sessions): """ Calculate the total time spent on a website by merging overlapping sessions. :param sessions: List of tuples, where each tuple contains two strings representing the start and end times of a session. :return: A string representing the total time spent on the websi...
[ "assert calculate_total_time([(\"01:00:00\", \"02:00:00\"), (\"02:00:00\", \"03:00:00\")]) == \"2 hours 0 minutes 0 seconds\"", "assert calculate_total_time([(\"09:00:00\", \"10:00:00\"), (\"10:00:00\", \"11:00:00\"), (\"11:00:00\", \"12:00:00\")]) == \"3 hours 0 minutes 0 seconds\"", "assert calculate_total_ti...
calculate_total_time
def calculate_total_time(sessions):
0.9
generic
148946f78813a6d6c5c75f74fa09f3cb
You are given a list of integers `numbers` representing the scores of students in a class. Your task is to implement a function `calculate_statistics` that computes the mean, median, and mode of the scores. The function should return a dictionary with the keys `"mean"`, `"median"`, and `"mode"` corresponding to the com...
from collections import Counter from statistics import mean, median, mode def calculate_statistics(numbers): """ Computes the mean, median, and mode of a list of integers. Parameters: numbers (list of int): A list of integers representing scores. Returns: dict: A dictionary with keys 'mean', ...
[ "assert calculate_statistics([85, 90, 78, 85, 92]) == {\"mean\": 86.0, \"median\": 85.0, \"mode\": 85}", "assert calculate_statistics([100, 100, 100]) == {\"mean\": 100.0, \"median\": 100.0, \"mode\": 100}", "assert calculate_statistics([50, 60, 70, 80, 90]) == {\"mean\": 70.0, \"median\": 70.0, \"mode\": 50}",...
calculate_statistics
def calculate_statistics(numbers):
1
generic
046e57a8de193158b3f4011cdd65b3e7
You are required to design a hash function for a custom string-to-integer dictionary. The hash function should map strings to integers in a way that minimizes collisions. The function must satisfy the following criteria: - **Deterministic**: The same input string must always produce the same output integer. - **Versat...
def custom_hash(s): """ Computes a hash value for a given string using a polynomial rolling hash function. Parameters: s (str): The input string to hash. Returns: int: The hash value of the string, guaranteed to be a 32-bit signed integer. """ base = 31 modulo = 2**31 - 1 ...
[ "assert custom_hash(\"hello\") == custom_hash(\"hello\")", "assert custom_hash(\"world\") == custom_hash(\"world\")", "assert custom_hash(\"hello\") != custom_hash(\"world\")", "assert custom_hash(\"a\") == custom_hash(\"a\")", "assert custom_hash(\"!@#$%^&*()\") == custom_hash(\"!@#$%^&*()\")", "assert c...
custom_hash
def custom_hash(s):
1
generic
467e1cd93f4432879eac1e00d5378b20
You are given a non-empty array of integers, `numbers`. Your task is to construct a new array, `result`, of the same length as `numbers` such that `result[i]` is the product of the absolute values of the maximum and minimum elements in the subarray `numbers[0..i]` (both inclusive). **Constraints:** - The length of `nu...
def product_of_extremes(numbers): """ Constructs a new array where each element at index i is the product of the absolute values of the maximum and minimum elements in the subarray numbers[0..i]. :param numbers: List[int] - A non-empty list of integers. :return: List[int] - A list of integers repre...
[ "assert product_of_extremes([2, -3, 4, -5]) == [6, 6, 12, 20]", "assert product_of_extremes([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert product_of_extremes([-1, -2, -3, -4, -5]) == [1, 2, 3, 4, 5]", "assert product_of_extremes([5, 4, 3, 2, 1]) == [5, 8, 9, 8, 5]", "assert product_of_extremes([-5, -4, -3, ...
product_of_extremes
def product_of_extremes(numbers):
0.5
generic
e90d9fbd176e69e2ab056cc9750ee48d
You are given a dataset consisting of multiple data points. Each data point is represented as a list with three elements: a timestamp in the format "YYYY-MM-DD HH:MM:SS", a numeric value, and an altitude. Your task is to filter this dataset based on the altitude criteria and return a new list containing only the timest...
def is_prime(n): """Check if a number is a prime number.""" if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def filter_by_altitude(data_points): ...
[ "assert filter_by_altitude([[\"2023-01-01 12:00:00\", 10.5, 29]]) == []", "assert filter_by_altitude([[\"2023-01-01 12:01:00\", 11.5, 31]]) == [(\"2023-01-01 12:01:00\", 11.5)]", "assert filter_by_altitude([[\"2023-01-01 12:02:00\", 12.5, 37]]) == [(\"2023-01-01 12:02:00\", 12.5)]", "assert filter_by_altitude...
filter_by_altitude
def filter_by_altitude(data_points):
1
generic
4964f369c1573e937316f93dd19cabc0
You are given a list of non-empty strings `words`. Your task is to implement a function `longest_common_prefix` that determines the longest common prefix shared by all strings in the list. If no common prefix exists, the function should return an empty string. **Constraints:** - The list `words` contains at least one ...
def longest_common_prefix(words): """ Finds the longest common prefix among all the words in the list. :param words: List of non-empty strings :return: Longest common prefix string, or an empty string if no common prefix exists """ # Take the first word as the reference prefix = words[0...
[ "assert longest_common_prefix([\"flower\", \"flow\", \"flight\"]) == \"fl\"", "assert longest_common_prefix([\"dog\", \"racecar\", \"car\"]) == \"\"", "assert longest_common_prefix([\"prefix\", \"preposition\", \"prevent\"]) == \"pre\"", "assert longest_common_prefix([\"apple\", \"application\", \"appetite\"]...
longest_common_prefix
def longest_common_prefix(words):
1
generic
c096f91b9436cbb4ffb1edd865066524
You are given a sentence as a string. Your task is to implement a function `find_duplicate_words` that identifies and returns a list of duplicate words in the sentence. The function should treat words in a case-insensitive manner, meaning 'Word' and 'word' should be considered the same. Additionally, punctuation marks ...
import re from collections import Counter def find_duplicate_words(sentence): """ Identifies and returns a list of duplicate words and punctuation in a given sentence. Parameters: sentence (str): The input sentence containing words and punctuation. Returns: list: A list of duplicate w...
[ "assert find_duplicate_words(\"Hello, world! Hello, universe. Hello, world?\") == ['hello', 'world']", "assert find_duplicate_words(\"This is a test. This test is only a test.\") == ['this', 'is', 'a', 'test']", "assert find_duplicate_words(\"No duplicates here.\") == []", "assert find_duplicate_words(\"A man...
find_duplicate_words
def find_duplicate_words(sentence):
0.6
generic
fe995e4ea5901c6f8c38450efbc154f6
You are given an array of integers `numbers` and an integer `target_sum`. Your task is to determine if there are any two distinct numbers in the array that add up to `target_sum`. If such a pair exists, return a tuple containing the two numbers in any order. If no such pair exists, return `None`. **Constraints:** - Th...
def find_pair_with_sum(numbers, target_sum): """ Determines if there are any two distinct numbers in the array that add up to the target_sum. :param numbers: List[int] - A list of integers. :param target_sum: int - The target sum to find in the list. :return: Tuple[int, int] or None - A tuple o...
[ "assert find_pair_with_sum([2, 7, 11, 15], 9) == (2, 7)", "assert find_pair_with_sum([3, 2, 4], 6) == (2, 4)", "assert find_pair_with_sum([3, 3], 6) == (3, 3)", "assert find_pair_with_sum([1, 2, 3, 4, 5], 10) == None", "assert find_pair_with_sum([1, 2, 3, 4, 5], 8) == (3, 5)", "assert find_pair_with_sum([...
find_pair_with_sum
def find_pair_with_sum(numbers, target_sum):
1
algorithmic
aa58befebe81d0bb6486aed4209c323c
You are tasked with writing a Python function that reads the contents of a file using a context manager. Your function should handle exceptions that may occur during the file operation, such as the file not being found or other I/O errors. Your function should print the contents of the file if successful, or an appropr...
def read_file(file_path: str) -> None: """ Reads the contents of a file using a context manager and handles exceptions. Args: file_path (str): The path to the file to be read. Returns: None: Prints the file contents or an error message. """ try: with open(file_path, 'r'...
[ "assert read_file('non_existent_file.txt') is None", "assert read_file('') is None", "assert read_file(None) is None", "assert read_file('/invalid/path/to/file') is None", "assert read_file('read_file_test.txt') is None # Assuming this file exists and is readable", "assert read_file('read_file_test.txt')...
read_file
def read_file(file_path: str) -> None:
1
generic
ea48f8f1a52179bb87b354b45b663ac9
You are given a 2D binary matrix of size `n x m` consisting of 0s and 1s. Each 1 represents a piece of land, and each 0 represents water. An island is defined as a group of connected 1s, where two 1s are considered connected if they are adjacent horizontally, vertically, or diagonally. Your task is to determine the max...
def maxAreaOfIsland(matrix): """ Returns the maximum area of an island in the given 2D binary matrix. :param matrix: List[List[int]] - A 2D list representing the binary matrix. :return: int - The maximum area of an island. """ if not matrix or not matrix[0]: return 0 num_ro...
[ "assert maxAreaOfIsland([[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]) == 0", "assert maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]) == 4", "assert maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,1,1],[0,0,1,1,1]]) == 6", "assert maxAreaOfIsland([[1]]) == 1", "assert maxAreaOfIsland(...
maxAreaOfIsland
def maxAreaOfIsland(matrix):
0.3
generic
ede3c8438c7896bdb184c6865456e5d9
You are given a piece of code. Your task is to classify it into one of the following programming paradigms: functional programming, object-oriented programming, or procedural programming. Provide the classification as the output. **Sample Input:** ```python def greet(name): return "Hello, " + name def main(): names...
def greet(name): """ Returns a greeting message for the given name. Parameters: name (str): The name of the person to greet. Returns: str: A greeting message. """ return "Hello, " + name def main(): """ Prints greeting messages for a list of names. """ names = ["Alice"...
[ "assert greet(\"Alice\") == \"Hello, Alice\"", "assert greet(\"Bob\") == \"Hello, Bob\"", "assert greet(\"Charlie\") == \"Hello, Charlie\"", "assert greet(\"\") == \"Hello, \"", "assert greet(\"123\") == \"Hello, 123\"", "assert greet(\"!@#\") == \"Hello, !@#\"", "assert greet(\" \") == \"Hello, \"", ...
greet
def greet(name):
1
algorithmic
4430d088e17a9c761d292e819793cf2c
You are given a list of strings `words`. Your task is to implement a function `find_anagrams(words)` that returns a dictionary. Each key in the dictionary should be a sorted tuple of characters, and each value should be a list of words from the input that are anagrams of each other. The comparison should be case-insens...
def find_anagrams(words): """ Returns a dictionary where each key is a sorted tuple of characters, and each value is a list of words that are anagrams of each other. :param words: List of strings :return: Dictionary with sorted tuples of characters as keys and lists of anagrams as values ""...
[ "assert find_anagrams(['listen', 'silent', 'enlist']) == {('e', 'i', 'l', 'n', 's', 't'): ['listen', 'silent', 'enlist']}", "assert find_anagrams(['google', 'gooegl']) == {('e', 'g', 'g', 'l', 'o'): ['google', 'gooegl']}", "assert find_anagrams(['apple']) == {('a', 'e', 'l', 'p', 'p'): ['apple']}", "assert fi...
find_anagrams
def find_anagrams(words):
0.7
generic
e4bb188dff44393ab7d0995f3329df97
You are given a list of integers. Your task is to write a function that returns the second largest unique number from the list. If there is no such number, the function should return `None`. **Input:** - A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer is in the range [-10^9, 10^9]. **Output:** -...
def second_largest_unique(nums): """ Returns the second largest unique number from the list. If there is no such number, returns None. :param nums: List of integers :return: Second largest unique integer or None """ unique_nums = set(nums) if len(unique_nums) < 2: return Non...
[ "assert second_largest_unique([1, 2, 2, 3, 4]) == 3", "assert second_largest_unique([5, 5, 5, 5]) == None", "assert second_largest_unique([10]) == None", "assert second_largest_unique([1, 2]) == 1", "assert second_largest_unique([4, 4, 3, 3, 2, 2, 1, 1]) == 3", "assert second_largest_unique([7, 7, 7, 8, 8...
second_largest_unique
def second_largest_unique(nums):
1
generic
adb0b394fa735c667a07f5aa14ae3de0
You are given a nested list structure consisting of integers and other lists. Your task is to write a function `flatten_list` that takes this nested list as input and returns a single flattened list containing all the integers in the order they appear. The input list can be arbitrarily nested. **Sample Input:** ``` [1...
def flatten_list(nested_list): """ Flattens a nested list structure into a single flat list. Parameters: nested_list (list): A list that may contain other lists. Returns: list: A flat list with all the elements. """ flat_list = [] for item in nested_list: if isinsta...
[ "assert flatten_list([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]", "assert flatten_list([[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6]", "assert flatten_list([1, 2, [3, [4, 5], [6, 7]], 8, 9]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert flatten_list([1, [2, 3], [4, [5, 6]], 7]) == [1, 2, 3, 4, 5, 6, 7]", "a...
flatten_list
def flatten_list(nested_list):
1
generic
be8ac91b5a5bd0f2921a9f9a7d1d7919
You are given a list of rectangles, each represented by a pair of integers indicating its width and height. Your task is to filter out rectangles where the length of the longest side is less than a specified minimum diameter. Ensure that each rectangle appears only once in the resulting list, even if it appears multipl...
def filter_rectangles(rectangles, min_diameter): """ Filters out rectangles with the longest side less than the specified minimum diameter. Ensures no rectangle is included more than once in the resulting list. :param rectangles: List of tuples, where each tuple contains two integers representing the w...
[ "assert filter_rectangles([(3, 5), (5, 3), (2, 2), (4, 4), (3, 5)], 4) == [(3, 5), (5, 3), (4, 4)]", "assert filter_rectangles([(1, 1), (2, 2), (3, 3)], 4) == []", "assert filter_rectangles([(4, 4), (4, 4), (4, 4)], 4) == [(4, 4)]", "assert filter_rectangles([(5, 5), (5, 5), (5, 5)], 6) == []", "assert filt...
filter_rectangles
def filter_rectangles(rectangles, min_diameter):
0.4
generic
3a2fd6331149355af23c1e52aa562665
You are given a string `bracket_seq` consisting solely of opening `(` and closing `)` parentheses. Your task is to determine if the parentheses in the string are correctly nested and if each pair of matching parentheses encloses at least one unique lowercase English letter that is not enclosed by any other pair of pare...
def validate_parentheses(bracket_seq): """ Validates if the parentheses in the given string are correctly nested and each pair of matching parentheses encloses at least one unique lowercase English letter not enclosed by another pair. :param bracket_seq: A string containing only '(' and ')' charact...
[ "assert validate_parentheses(\"(a)\") == True", "assert validate_parentheses(\"((ab))\") == True", "assert validate_parentheses(\"(a)(b)\") == True", "assert validate_parentheses(\"((a)(b))\") == True", "assert validate_parentheses(\"()\") == False", "assert validate_parentheses(\"(a(b)c)\") == True", "...
validate_parentheses
def validate_parentheses(bracket_seq):
0.3
generic
3e9b22a5b054918503567ee3e3c4ed9b
You are tasked with implementing a function to validate IPv4 addresses. An IPv4 address consists of four decimal numbers, each ranging from 0 to 255, separated by dots. Each number must not have leading zeros unless it is exactly zero. Your function should return `True` if the input string is a valid IPv4 address, and ...
def validate_ip_address(ip): """ Validates if the given string is a valid IPv4 address. :param ip: A string representing the IP address to validate. :return: True if the IP address is valid, False otherwise. """ parts = ip.split('.') if len(parts) != 4: return False for...
[ "assert validate_ip_address(\"192.168.1.1\") == True", "assert validate_ip_address(\"256.256.256.256\") == False", "assert validate_ip_address(\"0.0.0.0\") == True", "assert validate_ip_address(\"255.255.255.255\") == True", "assert validate_ip_address(\"192.168.1\") == False", "assert validate_ip_address...
validate_ip_address
def validate_ip_address(ip):
1
generic
b1b60954d43f45797a7735eff69c50c6
You are tasked with implementing a function for a natural language processing pipeline that performs tokenization. Given a string `input_text`, your function should return a list of tokens, where each token is a sequence of word characters (letters, digits, and underscores) separated by non-word characters. **Input:*...
import re def tokenize_text(input_text): """ Tokenizes the input text into a list of word tokens. Parameters: input_text (str): The text to be tokenized. Returns: list: A list of tokens, where each token is a sequence of word characters. """ # Use regular expression to split the text ...
[ "assert tokenize_text(\"Hello, world!\") == [\"Hello\", \"world\"]", "assert tokenize_text(\"This is a test.\") == [\"This\", \"is\", \"a\", \"test\"]", "assert tokenize_text(\"Let's tokenize this!\") == [\"Lets\", \"tokenize\", \"this\"]", "assert tokenize_text(\"123 456 789\") == [\"123\", \"456\", \"789\"]...
tokenize_text
def tokenize_text(input_text):
0.9
generic
c44b9323de707c11e782b2c21d8c52ac
You are given an unsorted array of integers `nums` and an integer `k`. Your task is to find the `k`th largest element in the array. You may assume that `k` is always valid, i.e., `1 <= k <= len(nums)`. Your solution should have an average time complexity of O(n). **Input:** - The first line contains an integer `n` (1 ...
import random def partition(nums, left, right, pivot_index): """ Partitions the array around the pivot element such that elements greater than the pivot are on the left and elements less than the pivot are on the right. :param nums: List of integers to be partitioned. :param left: Starting ind...
[ "assert find_kth_largest([3,2,1,5,6,4], 2) == 5", "assert find_kth_largest([3,2,3,1,2,4,5,5,6], 4) == 4", "assert find_kth_largest([1], 1) == 1", "assert find_kth_largest([7,6,5,4,3,2,1], 7) == 1", "assert find_kth_largest([1,2,3,4,5,6,7], 1) == 7", "assert find_kth_largest([10,20,30,40,50], 3) == 30", ...
find_kth_largest
def find_kth_largest(nums, k):
1
generic
442fc204f87e1747c0240a2be094ef02
You are given a string representing a simple mathematical expression. The expression consists of an operation followed by two operands. The operation can be one of the following: 'add', 'subtract', 'multiply', or 'divide'. Each operand can be a positive integer or a floating-point number with up to two decimal places. ...
def parse_math_expression(expression): """ Parses a mathematical expression string and returns a list containing the operation and the two operands as floats. Returns 'error' if the input is not in the correct format. :param expression: A string representing a mathematical expression. :return: ...
[ "assert parse_math_expression('add 3.14 5') == ['add', 3.14, 5.0]", "assert parse_math_expression('multiply 4.25 6.00') == ['multiply', 4.25, 6.0]", "assert parse_math_expression('divide 10 2') == ['divide', 10.0, 2.0]", "assert parse_math_expression('subtract 7.5 3.25') == ['subtract', 7.5, 3.25]", "assert...
parse_math_expression
def parse_math_expression(expression):
1
generic
8bc9e2f5ccd6b9dab133f73fefe7527d
You are tasked with implementing a function `extract_phone_numbers_and_emails` that processes a given string of text and extracts all phone numbers and email addresses. Phone numbers can appear in the following formats: `(123) 456-7890`, `123-456-7890`, or `123.456.7890`. Email addresses should be in the format `user@d...
import re def extract_phone_numbers_and_emails(text): """ Extracts phone numbers and email addresses from the given text. Args: text (str): The input text to search for phone numbers and email addresses. Returns: list: A list of strings, each representing a phone number or email addre...
[ "assert extract_phone_numbers_and_emails(\"My phone number is (123) 456-7890. You can also reach me at 123.456.7890.\") == [\"(123) 456-7890\", \"123.456.7890\"]", "assert extract_phone_numbers_and_emails(\"I don't have a phone number.\") == []", "assert extract_phone_numbers_and_emails(\"My phone numbers are 1...
extract_phone_numbers_and_emails
def extract_phone_numbers_and_emails(text):
0.8
generic
8d9cbef37f8702af9cd5f8760b16f890
You are given a string `s`. Your task is to transform the string such that the first letter of each word is capitalized and all other letters are in lowercase. A word is defined as a sequence of characters separated by spaces. **Input:** - A single string `s` (1 ≤ |s| ≤ 1000), consisting of lowercase and uppercase En...
def capitalize_words(input_string): """ Transforms the input string such that the first letter of each word is capitalized and all other letters are in lowercase. :param input_string: A string to be transformed. :return: A transformed string with capitalized words. """ return input_stri...
[ "assert capitalize_words(\"hello world\") == \"Hello World\"", "assert capitalize_words(\"HELLO WORLD\") == \"Hello World\"", "assert capitalize_words(\"hElLo WoRlD\") == \"Hello World\"", "assert capitalize_words(\"python programming\") == \"Python Programming\"", "assert capitalize_words(\"123abc def456\"...
capitalize_words
def capitalize_words(input_string):
1
generic
0ea62771c117a70b3910262baec5fa28
You are given a list of integers that may include positive numbers, negative numbers, and zeros. Your task is to sort this list in ascending order using the insertion sort algorithm. Implement a function that takes a list of integers as input and returns the sorted list. **Sample Input:** ``` [3, -1, 4, 0, -5, 2, 7, -...
def insertion_sort(arr): """ Sorts a list of integers in ascending order using the insertion sort algorithm. Parameters: arr (list): A list of integers to be sorted. Returns: list: The sorted list of integers. """ for i in range(1, len(arr)): key = arr[i] j = i - 1 ...
[ "assert insertion_sort([3, -1, 4, 0, -5, 2, 7, -3]) == [-5, -3, -1, 0, 2, 3, 4, 7]", "assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]", "assert insertion_sort([-1, -2, -3, -4, -5]) == [-5, -4, -3, -2, -1]", "assert insertion_sort([0, 0, ...
insertion_sort
def insertion_sort(arr):
1
algorithmic
0f96476a730355eeda56babb876dc76a
You are tasked with writing a Python script to process a CSV file named "sales_data.csv" located in the same directory as the script. The CSV file contains sales data with the following columns: product name, quantity sold, and unit price. Your program should compute the total sales by multiplying the quantity sold by ...
import csv import os def calculate_total_sales(): """ Calculates the total sales from a CSV file named 'sales_data.csv'. The CSV file should contain columns for product name, quantity sold, and unit price. Prints the total sales or an error message if the file is not accessible. """ total_sales...
[ "assert calculate_total_sales() is None # Assuming the file does not exist or is not accessible, the function should return None", "assert calculate_total_sales() is None # Assuming the file is not readable, the function should return None", "assert calculate_total_sales() is None # Assuming the file is empt...
calculate_total_sales
def calculate_total_sales():
1
generic
8e6001e7018835ad821e1921c7f26e0a
You are given a list of strings. Your task is to implement a function that identifies and returns a new list containing only the strings that are palindromes. A palindrome is defined as a string that reads the same forwards and backwards. For example, "racecar" and "level" are palindromes, whereas "hello" and "world" a...
def find_palindromes(strings): """ Returns a list of strings that are palindromes from the input list. :param strings: List of strings to be checked. :return: List of palindromic strings. """ return [s for s in strings if s == s[::-1]] # Example usage: input_strings = ["racecar", "level", "hel...
[ "assert find_palindromes([\"racecar\", \"level\", \"hello\", \"world\", \"radar\", \"python\"]) == [\"racecar\", \"level\", \"radar\"]", "assert find_palindromes([\"\", \"a\", \"bb\", \"abc\", \"aba\"]) == [\"\", \"a\", \"bb\", \"aba\"]", "assert find_palindromes([\"noon\", \"civic\", \"rotor\", \"deified\", \"...
find_palindromes
def find_palindromes(strings):
1
generic
f441438d8c5f064edb2c4f0590d539f2
You are given a list of strings. Your task is to write a Python function that groups all the anagrams together. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should return a list of lists, where each su...
def group_anagrams(words): """ Groups all the anagrams together from the given list of strings. :param words: List of strings to be grouped. :return: A list of lists, where each sublist contains anagrams. """ anagrams = {} for word in words: sorted_word = ''.join(sorted(word)) ...
[ "assert group_anagrams([\"listen\", \"silent\", \"enlist\"]) == [[\"listen\", \"silent\", \"enlist\"]]", "assert group_anagrams([\"abc\", \"bca\", \"cab\", \"xyz\"]) == [[\"abc\", \"bca\", \"cab\"], [\"xyz\"]]", "assert group_anagrams([\"a\", \"b\", \"c\", \"d\"]) == [[\"a\"], [\"b\"], [\"c\"], [\"d\"]]", "as...
group_anagrams
def group_anagrams(words):
0.9
generic
58a5a64d691db7d56ff0ea949393580c
You are given a dictionary `d` where keys are strings and values are integers. Your task is to write a function `find_keys_with_max_value` that returns a list of all keys that have the maximum value in the dictionary. If the dictionary is empty, return an empty list. **Sample Input:** ```python {'apple': 5, 'banana': ...
def find_keys_with_max_value(d): """ Returns a list of keys with the maximum value in the dictionary. :param d: Dictionary with string keys and integer values. :return: List of keys with the maximum value. """ if not d: return [] max_value = max(d.values()) keys_with_ma...
[ "assert find_keys_with_max_value({'a': 1, 'b': 2, 'c': 2}) == ['b', 'c']", "assert find_keys_with_max_value({'x': 3, 'y': 1, 'z': 3}) == ['x', 'z']", "assert find_keys_with_max_value({'one': 10, 'two': 10, 'three': 10}) == ['one', 'two', 'three']", "assert find_keys_with_max_value({'single': 42}) == ['single'...
find_keys_with_max_value
def find_keys_with_max_value(d):
1
algorithmic
5ba3a946ac14f28a6416ae82b2ba790a
You are given an array `prices` where `prices[i]` is the price of a given stock on the `i-th` day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achi...
def max_profit(prices): """ Calculate the maximum profit from a single buy and sell transaction. :param prices: List[int] - A list of integers representing the stock prices on consecutive days. :return: int - The maximum profit that can be achieved. If no profit is possible, returns 0. """ if n...
[ "assert max_profit([7, 1, 5, 3, 6, 4]) == 5", "assert max_profit([7, 6, 4, 3, 1]) == 0", "assert max_profit([1, 2, 3, 4, 5]) == 4", "assert max_profit([3, 3, 5, 0, 0, 3, 1, 4]) == 4", "assert max_profit([1, 2]) == 1", "assert max_profit([2, 1, 2, 1, 0, 1, 2]) == 2", "assert max_profit([1]) == 0", "ass...
max_profit
def max_profit(prices):
1
generic
42f71a2468e4cb36a8e081c62fc736d9
You are given a URL string as input. Your task is to implement a function `parse_query_params` that extracts and returns the query parameters from the URL as a dictionary. The function should correctly handle URL-encoded characters and support multiple values for a single parameter. **Input:** - A single string repres...
from urllib.parse import urlparse, parse_qs def parse_query_params(url): """ Parses the query parameters from a given URL and returns them as a dictionary. Args: url (str): The URL string from which to extract query parameters. Returns: dict: A dictionary of query parameters, with sin...
[ "assert parse_query_params(\"https://example.com/path?name=John+Doe&age=25\") == {'name': 'John Doe', 'age': '25'}", "assert parse_query_params(\"https://example.com/path?name=John+Doe&hobbies=reading&hobbies=writing\") == {'name': 'John Doe', 'hobbies': ['reading', 'writing']}", "assert parse_query_params(\"ht...
parse_query_params
def parse_query_params(url):
1
algorithmic
45d2b3bcfbd7053fb1632bd03b3a7618
You are given a list of integers. Your task is to implement a function `second_smallest_unique` that determines the second smallest unique number in the list. If there is no such number, the function should return `None`. The function should be efficient and handle edge cases appropriately. **Input:** - A list of inte...
def second_smallest_unique(numbers): """ Returns the second smallest unique number in the list. If there is no such number, returns None. :param numbers: List of integers :return: Second smallest unique integer or None """ unique_numbers = set(numbers) if len(unique_numbers) < 2: ...
[ "assert second_smallest_unique([1, 2, 3, 4, 5]) == 2", "assert second_smallest_unique([5, 1, 4, 3, 2]) == 2", "assert second_smallest_unique([10, 10, 10]) == None", "assert second_smallest_unique([1]) == None", "assert second_smallest_unique([2, 2, 3, 1, 4, 4]) == 2", "assert second_smallest_unique([7, 7,...
second_smallest_unique
def second_smallest_unique(numbers):
1
generic
e1011eecc702cf1e44f1ac320a719852
You are given a date in the format `year`, `month`, and `day`. Your task is to write a function `next_date` that calculates the next date after the given date, considering the number of days in each month and leap years. The function should handle dates from 1900-01-01 to 2100-12-31. A leap year is defined as a year th...
def next_date(year, month, day): """ Calculate the next date after the given date, considering leap years and the number of days in each month. Parameters: year (int): The year of the given date. month (int): The month of the given date. day (int): The day of the given date. Return...
[ "assert next_date(2023, 2, 28) == (2023, 3, 1)", "assert next_date(2020, 2, 29) == (2020, 3, 1)", "assert next_date(2023, 12, 31) == (2024, 1, 1)", "assert next_date(2000, 4, 30) == (2000, 5, 1)", "assert next_date(1900, 2, 28) == (1900, 3, 1)", "assert next_date(2004, 2, 28) == (2004, 2, 29)", "assert ...
next_date
def next_date(year, month, day):
1
generic
e3a2215520af09f840c2cca8ea61485f
You are given a list of dictionaries, where each dictionary represents a person with keys `name`, `age`, and `city`. Your task is to write a function that sorts this list of dictionaries based on a specified key. The key to sort by will be provided as an input parameter to the function. **Input:** - A list of diction...
def sort_people_by_key(people, key): """ Sorts a list of dictionaries representing people based on a specified key. Parameters: people (list of dict): A list where each dictionary contains 'name', 'age', and 'city' keys. key (str): The key to sort the list by ('name', 'age', or 'city'). Return...
[ "assert sort_people_by_key([{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}], 'age') == [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'ag...
sort_people_by_key
def sort_people_by_key(people, key):
1
generic
349f75f4a6d623d628f48075ad7f296c
You are tasked with implementing a function named `calculate_sum`. This function should accept two parameters, `x` and `y`. The function should return the sum of `x` and `y` if both are integers and fall within the inclusive range of -1000 to 1000. If either `x` or `y` does not meet these criteria, the function should ...
def calculate_sum(x, y): """ Returns the sum of x and y if both are integers within the range -1000 to 1000. Otherwise, returns an error message. Parameters: x (int): The first integer. y (int): The second integer. Returns: int or str: The sum of x and y if valid, otherwise an ...
[ "assert calculate_sum(500, 500) == 1000", "assert calculate_sum(-500, 500) == 0", "assert calculate_sum(1000, -1000) == 0", "assert calculate_sum(0, 0) == 0", "assert calculate_sum(1001, 1000) == \"Error: Both parameters must be integers within the range -1000 to 1000.\"", "assert calculate_sum(-1001, -10...
calculate_sum
def calculate_sum(x, y):
1
generic
End of preview. Expand in Data Studio

OpenCodeInstruct RL tasks

Code tasks for RL with a verifiable reward, derived from nvidia/OpenCodeInstruct (CC BY 4.0, NVIDIA): write one Python function, checked by the row's assert unit tests.

Fields

Field Content
id Row id in nvidia/OpenCodeInstruct
problem The problem statement (input)
function, signature The function every test calls, and its def line in the reference
tests The assert statements, one per element
reference The dataset's solution (code only)
score average_test_score: fraction of tests the reference passed in NVIDIA's run
domain generic or algorithmic

How it was built

70% of each split are tasks whose reference passes all its tests (score 1), and 30% tasks whose reference fails some (score < 1): there the tests, or the reference, are partly wrong, and even a correct solution may not pass them all.

  • data/train-00000-of-00050.parquet of nvidia/OpenCodeInstruct: 100,000 rows
  • tests all call one function defined in the reference: 80,449
  • score 1: 27,328; 0.2 < score < 1: 28,262
  • random sample (seed 0): 25,000, 30% with score < 1 in every split
  • splits: test 500, val 500, train 24,000

Caveat: score comes from NVIDIA's execution environment. Re-running the references shows that some tasks need files or third-party packages: filter by re-running the reference in your own sandbox before training.

Downloads last month
42