Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
32
32
problem
stringlengths
199
3.86k
reference
stringlengths
73
5.46k
tests
listlengths
10
10
function
stringlengths
1
51
signature
stringlengths
9
295
score
float64
1
1
domain
stringclasses
2 values
9aac63c7dd10888ced31876536b371f0
You are given an unsorted list of integers which may contain duplicates and negative numbers. Your task is to determine the smallest positive integer that is not present in the list. **Input:** - A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer `x` satisfies -10^5 ≤ x ≤ 10^5. **Output:** - Return...
def find_smallest_missing_positive(nums): """ Finds the smallest missing positive integer in the given list of integers. :param nums: List[int] - A list of integers which may contain duplicates and negative numbers. :return: int - The smallest positive integer that is missing from the list. """...
[ "assert find_smallest_missing_positive([3, 4, -1, 1]) == 2", "assert find_smallest_missing_positive([1, 2, 0]) == 3", "assert find_smallest_missing_positive([7, 8, 9, 11, 12]) == 1", "assert find_smallest_missing_positive([1, 2, 3]) == 4", "assert find_smallest_missing_positive([0, -1, -2]) == 1", "assert...
find_smallest_missing_positive
def find_smallest_missing_positive(nums):
1
algorithmic
a88e34bfeca0b6c18a8056cbceeb5a65
You are tasked with writing a Python program to analyze a text file named "ratings.txt" and compute the average rating. The file consists of one rating per line, where each rating is an integer between 1 and 10 (inclusive). Your program must handle scenarios where the file may not exist or contain invalid ratings. In s...
def calculate_average_rating(file_name): """ Calculates the average rating from a file named 'ratings.txt'. Each line in the file should contain a single integer rating between 1 and 10. Prints the average rating rounded to two decimal places or an error message if issues arise. """ try: ...
[ "assert calculate_average_rating('empty.txt') is None", "assert calculate_average_rating('nonexistentfile.txt') is None", "assert calculate_average_rating('invalid_ratings.txt') is None", "assert calculate_average_rating('single_valid_rating.txt') is None", "assert calculate_average_rating('multiple_valid_r...
calculate_average_rating
def calculate_average_rating(file_name):
1
generic
92a148421c72cc24c89fef9e2aaf5ee1
You are given a list of non-empty strings. Your task is to find the longest common prefix that is shared by all strings in the list. If no common prefix exists, return an empty string. **Input:** - A list of strings `strs` (1 ≤ len(strs) ≤ 1000), where each string consists of lowercase English letters and has a length...
def longest_common_prefix(strs): """ Finds the longest common prefix shared by all strings in the list. :param strs: List of strings :return: Longest common prefix as a string """ if not strs: return "" strs.sort() first = strs[0] last = strs[-1] i = 0 ...
[ "assert longest_common_prefix([\"flower\",\"flow\",\"flight\"]) == \"fl\"", "assert longest_common_prefix([\"dog\",\"racecar\",\"car\"]) == \"\"", "assert longest_common_prefix([\"interspecies\",\"interstellar\",\"interstate\"]) == \"inters\"", "assert longest_common_prefix([\"throne\",\"throne\"]) == \"thron...
longest_common_prefix
def longest_common_prefix(strs):
1
generic
7f6c6daa8ef32595eac9846da90d7af4
You are given an `AccessLevel` class with the following attributes: - `name`: A string representing the name of the access level. - `permissions`: A list that can contain strings or other `AccessLevel` objects representing the permissions associated with this access level. Your task is to implement a function `access_...
class AccessLevel: def __init__(self, name, permissions): self.name = name self.permissions = permissions def access_level_to_string(access_level): """ Converts an AccessLevel object into a human-readable string. Parameters: access_level (AccessLevel): The AccessLevel object to...
[ "assert access_level_to_string(AccessLevel(\"User\", [\"read\"])) == \"User: read\"", "assert access_level_to_string(AccessLevel(\"Admin\", [\"read\", \"write\", \"delete\"])) == \"Admin: read, write, delete\"", "assert access_level_to_string(AccessLevel(\"Guest\", [])) == \"Guest: \"", "assert access_level_t...
access_level_to_string
def access_level_to_string(access_level):
1
generic
999ff8b93171c8f9061e91719605c93a
You are given a list of integers. Your task is to implement a function `find_smallest_element` that returns the smallest integer in the list. The function must traverse the list exactly once to determine the smallest element. If the list is empty, the function should raise a `ValueError` with the message "The list is e...
def find_smallest_element(numbers): """ Returns the smallest integer in the given list of integers. Raises ValueError if the list is empty. :param numbers: List of integers :return: Smallest integer in the list """ if not numbers: raise ValueError("The list is empty") s...
[ "assert find_smallest_element([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == 1", "assert find_smallest_element([10, 20, 30, 40, 50]) == 10", "assert find_smallest_element([-10, -20, -30, -40, -50]) == -50", "assert find_smallest_element([0, 0, 0, 0, 0]) == 0", "assert find_smallest_element([100]) == 100", "assert ...
find_smallest_element
def find_smallest_element(numbers):
1
generic
ae89c15f9d1e7c1b4b2b229dc2ddc5ec
You are given a task to write a Python script that reads two integers from the command line and outputs their sum. Your program must handle invalid inputs gracefully by displaying an error message to the standard error stream and exiting with a non-zero status code. **Input:** - The program will receive two command-l...
import sys def main(): """ Main function to execute the script. It reads two integers from command-line arguments, calculates their sum, and handles invalid inputs gracefully. """ try: if len(sys.argv) != 3: raise ValueError("Exactly two integers are required.") num1 = i...
[ "assert main() == None # This will not work as is, but it's a placeholder to check if the function runs without errors with correct input", "assert main([\"script.py\", \"3\", \"5\"]) == None # This will not work as is, but it's a placeholder to check if the function runs without errors with correct input", "...
main
def main():
1
generic
7db5fe40a29fba26665fd7ec9506ed49
You are given two sorted lists of integers, `list_a` and `list_b`. Your task is to merge these two lists into a single sorted list, `merged_list`. The lists may contain a sentinel value, `-1`, which should be ignored during the merging process. Specifically, you must remove all occurrences of `-1` from both input lists...
def merge_and_filter(list_a, list_b): """ Merges two sorted lists, removing any occurrences of -1, and returns a single sorted list. :param list_a: First sorted list of integers. :param list_b: Second sorted list of integers. :return: Merged sorted list with -1 values removed. """ # Rem...
[ "assert merge_and_filter([1, 2, 3], [4, 5, 6]) == [1, 2, 3, 4, 5, 6]", "assert merge_and_filter([-1, 1, 2, 3], [4, 5, 6, -1]) == [1, 2, 3, 4, 5, 6]", "assert merge_and_filter([1, 3, 5, -1, 7], [-1, 2, 4, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]", "assert merge_and_filter([-1, -1, -1], [-1, -1, -1]) == []", "asser...
merge_and_filter
def merge_and_filter(list_a, list_b):
1
generic
f2ef668eeb2d8085cc5359b18eb9f864
You are given a list of integers. Your task is to implement a function `remove_duplicates` that processes this list to eliminate any duplicate elements, maintaining the original order of the first occurrence of each element. The function should return a new list containing only the unique elements. **Input:** - A list...
def remove_duplicates(input_list): """ Removes duplicate elements from the input list while preserving the order of the first occurrence of each element. Parameters: input_list (list of int): The list of integers from which duplicates need to be removed. Returns: list of int: A new list contai...
[ "assert remove_duplicates([1, 2, 3, 2, 4, 3, 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(input_list):
1
generic
9fa9fd106fcb329d6327559203953785
You are given a list of integers. Your task is to write a function `filter_even_numbers` that returns a new list containing only the even numbers from the input list. Refactor the provided code to use list comprehensions for improved readability. **Sample Input:** ```python [1, 2, 3, 4, 5, 6] ``` **Sample Output:** `...
def filter_even_numbers(numbers): """ Returns a list of even numbers from the input list. :param numbers: List of integers :return: List of even integers """ return [number for number in numbers if number % 2 == 0]
[ "assert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6]", "assert filter_even_numbers([10, 15, 20, 25, 30]) == [10, 20, 30]", "assert filter_even_numbers([11, 13, 17, 19]) == []", "assert filter_even_numbers([]) == []", "assert filter_even_numbers([0, -2, -4, -5]) == [0, -2, -4]", "assert filter_even...
filter_even_numbers
def filter_even_numbers(numbers):
1
algorithmic
6bff3eecb3ee6675df809f5ca972eb37
You are given a string `s`. Your task is to write a function that returns the number of unique words in the string along with a dictionary where the keys are the unique words (in lowercase) and the values are the counts of each word in the string. Words are defined as sequences of alphabetic characters separated by non...
import re from collections import defaultdict def unique_word_count(input_string): """ Returns a dictionary with the count of each unique word in the input string. Parameters: input_string (str): The input string containing words. Returns: dict: A dictionary with words as keys and the...
[ "assert unique_word_count(\"Hello, world! Hello, Python. Hello, world!\") == {'hello': 3, 'world': 2, 'python': 1}", "assert unique_word_count(\"This is a test. This test is only a test.\") == {'this': 2, 'is': 2, 'a': 2, 'test': 3, 'only': 1}", "assert unique_word_count(\"123 456 789\") == {}", "assert uniqu...
unique_word_count
def unique_word_count(input_string):
1
generic
d5d0ebb382abaca40e645025f91370df
You are given a list of sentences. Your task is to write a Python function that processes this list and returns a new list where each sentence is properly capitalized. Proper capitalization means that the first letter of each sentence is uppercase, and all other letters are lowercase. **Input:** - A list of strings, ...
def capitalize_sentences(sentences): """ Capitalizes each sentence in the given list of sentences. Parameters: sentences (list of str): A list of sentences to be capitalized. Returns: list of str: A list of capitalized sentences. """ return [sentence.capitalize() for sentence i...
[ "assert capitalize_sentences([\"hello world\"]) == [\"Hello world\"]", "assert capitalize_sentences([\"this is a test\", \"another sentence\"]) == [\"This is a test\", \"Another sentence\"]", "assert capitalize_sentences([\"multiple\", \"sentences\", \"here\"]) == [\"Multiple\", \"Sentences\", \"Here\"]", "as...
capitalize_sentences
def capitalize_sentences(sentences):
1
generic
9488f1fb1498cc7ab9ffe76f24ac40f8
You are given a string `s` consisting of uppercase and lowercase English letters, punctuation marks, and spaces. Your task is to write a function that removes all vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') from the string and returns the resulting string. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5...
def remove_vowels(s: str) -> str: """ Removes all vowels from the input string and returns the resulting string. :param s: The input string from which vowels need to be removed. :return: A string with all vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') removed. """ vowels = 'aeiou...
[ "assert remove_vowels(\"Hello, World!\") == \"Hll, Wrld!\"", "assert remove_vowels(\"Python Programming\") == \"Pythn Prgrmmng\"", "assert remove_vowels(\"AEIOUaeiou\") == \"\"", "assert remove_vowels(\"abcdefghijklmnopqrstuvwxyz\") == \"bcdfghjklmnpqrstvwxyz\"", "assert remove_vowels(\"ABCDEFGHIJKLMNOPQRST...
remove_vowels
def remove_vowels(s: str) -> str:
1
generic
93089b30616657ee1486fcee61c5ae58
You are given a list of integers `numbers` containing up to 10,000 elements. Your task is to implement a function `find_duplicate` that identifies all integers that appear more than once in the list. The integers in the resulting list should be ordered by their first occurrence in the original list. **Input:** - A lis...
def find_duplicate(numbers): """ Identifies all integers that appear more than once in the list. Parameters: numbers (list of int): The list of integers to check for duplicates. Returns: list of int: A list of duplicate integers ordered by their first occurrence. """ seen = set...
[ "assert find_duplicate([1, 2, 3, 4, 5]) == []", "assert find_duplicate([1, 1, 2, 2, 3, 3]) == [1, 2, 3]", "assert find_duplicate([1, 2, 3, 4, 5, 1, 2, 6, 7, 8, 9, 3]) == [1, 2, 3]", "assert find_duplicate([10, 20, 30, 40, 50, 10, 60, 70, 80, 90, 30]) == [10, 30]", "assert find_duplicate([5, 5, 5, 5, 5]) == ...
find_duplicate
def find_duplicate(numbers):
1
generic
66310cdb10d90e0ee16d9426ebb4640b
In a programming challenge, you are tasked with implementing a function `sum_of_digits(n)` that computes the sum of the digits of a positive integer `n`. The current implementation uses an iterative approach. Your goal is to refactor this function to use recursion instead. **Constraints:** - 1 ≤ n ≤ 10^9 **Sample In...
def sum_of_digits(n): """ Recursively calculates the sum of the digits of a positive integer n. Parameters: n (int): A positive integer whose digits are to be summed. Returns: int: The sum of the digits of n. """ if n < 10: return n else: return n % 10 + sum_of_digi...
[ "assert sum_of_digits(0) == 0", "assert sum_of_digits(5) == 5", "assert sum_of_digits(123) == 6", "assert sum_of_digits(456) == 15", "assert sum_of_digits(789) == 24", "assert sum_of_digits(1001) == 2", "assert sum_of_digits(9999) == 36", "assert sum_of_digits(123456789) == 45", "assert sum_of_digit...
sum_of_digits
def sum_of_digits(n):
1
generic
e1a54b0ae7eea20a72e20a4b216238d0
You are given a word and a tokenized sentence represented as a list of strings. Your task is to implement a function `find_word_occurrences(word, sentence)` that returns a list of integers indicating the positions where the specified word appears in the sentence. You are not allowed to use any built-in list methods or ...
def find_word_occurrences(word, sentence): """ Returns a list of indices where the given word appears in the sentence. :param word: A string representing the word to search for. :param sentence: A list of strings representing the tokenized sentence. :return: A list of integers representing the ...
[ "assert find_word_occurrences(\"cat\", [\"the\", \"cat\", \"sat\", \"on\", \"the\", \"cat\"]) == [1, 5]", "assert find_word_occurrences(\"dog\", [\"the\", \"dog\", \"barked\", \"at\", \"the\", \"cat\"]) == [1]", "assert find_word_occurrences(\"bird\", [\"the\", \"cat\", \"sat\", \"on\", \"the\", \"mat\"]) == []...
find_word_occurrences
def find_word_occurrences(word, sentence):
1
generic
9d1002f09ab261b84bf87652855643a1
You are tasked with implementing a function to determine the total number of employees in a hierarchical organization structure. The organization is represented as a list of nested dictionaries, where each dictionary contains the following keys: - `'name'`: A string representing the employee's name. - `'subordinates'`:...
def count_employees(employees): """ Counts the total number of employees in a hierarchical organization structure. :param employees: List of dictionaries representing the hierarchical structure of employees. :return: Integer representing the total number of employees. """ total = 0 for empl...
[ "assert count_employees([{\"name\": \"Alice\", \"subordinates\": []}]) == 1", "assert count_employees([{\"name\": \"Alice\", \"subordinates\": [{\"name\": \"Bob\", \"subordinates\": []}]}]) == 2", "assert count_employees([{\"name\": \"Alice\", \"subordinates\": [{\"name\": \"Bob\", \"subordinates\": [{\"name\":...
count_employees
def count_employees(employees):
1
generic
37ff86cd63ebc260087e5f6da026dd8f
You are given two dictionaries, `dict_a` and `dict_b`, representing inventories with item names as keys and their respective quantities as values. Your task is to merge these dictionaries into a single dictionary, `dict_merged`, adhering to the following rules: - If an item appears in both dictionaries, use the quantit...
def merge_inventory(dict_a, dict_b): """ Merges two dictionaries representing inventories into a single dictionary. Parameters: dict_a (dict): The first inventory dictionary. dict_b (dict): The second inventory dictionary. Returns: dict: A merged dictionary with lowercase string ke...
[ "assert merge_inventory({'apple': 3, 'banana': 2}, {'Banana': 5, 'orange': 4}) == {'apple': 3, 'banana': 2, 'orange': 4}", "assert merge_inventory({'Apple': 3, 'Banana': 2}, {'apple': 5, 'Orange': 4}) == {'apple': 3, 'banana': 2, 'orange': 4}", "assert merge_inventory({}, {'Banana': 5, 'orange': 4}) == {'banana...
merge_inventory
def merge_inventory(dict_a, dict_b):
1
generic
12b3da96c28b9ab2474eb487fbc9d7e8
You are given a list of integers `nums` and an integer `target`. Your task is to find the index of the first occurrence of `target` in `nums`. If `target` is not present in the list, return `-1`. **Input:** - The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the list. - The second line c...
def find_first_occurrence(nums, target): """ Returns the index of the first occurrence of the target value in the list nums. If the target is not found, returns -1. :param nums: List of integers :param target: Integer to find in the list :return: Index of the first occurrence of target or -...
[ "assert find_first_occurrence([4, 2, 7, 1, 3, 9, 5], 7) == 2", "assert find_first_occurrence([1, 2, 3, 4, 5], 3) == 2", "assert find_first_occurrence([10, 20, 30, 40, 50], 10) == 0", "assert find_first_occurrence([10, 20, 30, 40, 50], 50) == 4", "assert find_first_occurrence([1, 1, 1, 1, 1], 1) == 0", "as...
find_first_occurrence
def find_first_occurrence(nums, target):
1
algorithmic
6cd6fe516cded3076553e1fad65855fb
You are given a 2D grid `board` representing a game board, where each cell contains an integer representing a game piece. Your task is to implement a function `deep_copy` that creates and returns a deep copy of the given board. The function should manually handle the copying of each element from the original board to t...
def deep_copy(board): """ Creates a deep copy of a 2D grid without using built-in deep copy functions. :param board: A 2D list of integers representing the game board. :return: A new 2D list that is a deep copy of the original board. """ # Check if the board is empty or not a list of lists ...
[ "assert deep_copy([[1, 2], [3, 4]]) == [[1, 2], [3, 4]]", "assert deep_copy([]) == []", "assert deep_copy([[1]]) == [[1]]", "assert deep_copy([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]", "assert deep_copy([[None, None], [None, None]]) == [[None, None], [None, None]]", "assert ...
deep_copy
def deep_copy(board):
1
generic
1f7698ea694caf61888c751d54f13000
You are given a string `sentence` consisting of words separated by spaces. Your task is to implement a function `remove_duplicate_words(sentence)` that processes this string and returns a new string with all duplicate words removed, preserving the order of the first occurrence of each word. The comparison should be cas...
def remove_duplicate_words(sentence): """ Removes duplicate words from the given sentence, preserving the order of the first occurrence of each word. The comparison is case-insensitive. :param sentence: A string containing words separated by spaces. :return: A string with duplicate words removed. ...
[ "assert remove_duplicate_words(\"hello world\") == \"hello world\"", "assert remove_duplicate_words(\"Hello hello world\") == \"Hello world\"", "assert remove_duplicate_words(\"Python is great and python is fun\") == \"Python is great and fun\"", "assert remove_duplicate_words(\"a A a A\") == \"a\"", "asser...
remove_duplicate_words
def remove_duplicate_words(sentence):
1
generic
24e6e6ce5261fcb724e52e116f555bf9
You are given two sorted lists of integers, `list1` and `list2`, in ascending order. Your task is to merge these two lists into a single sorted list in descending order. You are not allowed to use any built-in sorting functions or libraries. Implement the function `merge_descending(list1, list2)` that takes in two sort...
def merge_descending(list1, list2): """ Merges two sorted lists in ascending order into a single sorted list in descending order. Parameters: list1 (List[int]): The first sorted list. list2 (List[int]): The second sorted list. Returns: List[int]: A merged list sorted in descending ...
[ "assert merge_descending([1, 3, 5], [2, 4, 6]) == [6, 5, 4, 3, 2, 1]", "assert merge_descending([], [1, 2, 3]) == [3, 2, 1]", "assert merge_descending([7, 9], [4, 5, 6, 8]) == [9, 8, 7, 6, 5, 4]", "assert merge_descending([1, 2, 3], []) == [3, 2, 1]", "assert merge_descending([], []) == []", "assert merge...
merge_descending
def merge_descending(list1, list2):
1
generic
37d68e9e0bed62f58d7c51c2f04f64ff
You are given a binary tree. Your task is to perform a level order traversal of the tree and return the result as a list of lists, where each inner list contains the values of the nodes at each level. The binary tree is represented using a `TreeNode` class. **Input:** - The input is a binary tree represented by a `Tr...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def levelOrder(root): """ Perform a level order traversal of a binary tree and return the result as a list of lists. :param root: TreeNode, the root of the b...
[ "assert levelOrder(TreeNode(1)) == [[1]]", "assert levelOrder(None) == []", "assert levelOrder(TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))) == [[3], [9, 20], [15, 7]]", "assert levelOrder(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))) == [[1], ...
levelOrder
def levelOrder(root):
1
algorithmic
525716996b86e7f7c0699530c7070c1d
You are tasked with implementing a function to generate prime numbers. Write a Python function `generate_prime_numbers` that accepts an integer `n` and returns a list containing the first `n` prime numbers. Your solution should include a helper function `_is_prime` to determine if a number is prime. The helper function...
def generate_prime_numbers(n): """Generate the first n prime numbers.""" def _is_prime(num): """Check if a number is prime.""" if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 ...
[ "assert generate_prime_numbers(0) == []", "assert generate_prime_numbers(1) == [2]", "assert generate_prime_numbers(2) == [2, 3]", "assert generate_prime_numbers(5) == [2, 3, 5, 7, 11]", "assert generate_prime_numbers(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]", "assert generate_prime_numbers(15) == [2, ...
generate_prime_numbers
def generate_prime_numbers(n):
1
generic
b81e1a3ce3ddc9c59ce8026c40b9ccd4
You are tasked with implementing a function `process_input` that processes a given string and returns a tuple. The first element of the tuple should be the numeric value of the string if it represents a valid number, considering both scientific notation and non-ASCII numeric characters (specifically Arabic numerals). T...
def process_input(input_str): """ Processes a string to determine if it represents a valid number in either scientific notation or using Arabic numerals. Returns a tuple with the numeric value and the original string. :param input_str: The string to process. :return: A tuple (number, input_str)...
[ "assert process_input(\"123\") == (123.0, \"123\")", "assert process_input(\"1.23e2\") == (123.0, \"1.23e2\")", "assert process_input(\"\\u0661\\u0662\\u0663\") == (123.0, \"\\u0661\\u0662\\u0663\")", "assert process_input(\"abc\") == (None, \"abc\")", "assert process_input(\"123abc\") == (None, \"123abc\")...
process_input
def process_input(input_str):
1
generic
3c5153b66e80b92fd8e382792a297ab2
You are given a 2D grid representing a game board of dimensions `n x m`, initially filled with zeros. Your task is to implement a function `move_game_piece` that takes the current position of a game piece `(x, y)` and a direction `d` as input. The direction `d` is an integer where `0` represents moving right, `1` repre...
def move_game_piece(grid, position, direction): """ Moves a game piece on a grid based on the given direction. Parameters: grid (list of list of int): The game board represented as a 2D grid. position (tuple of int): The current position of the game piece as (x, y). direction (int): The directi...
[ "assert move_game_piece([[0, 0, 0], [0, 0, 0], [0, 0, 0]], (1, 1), 0) == (1, 3)", "assert move_game_piece([[0, 0, 0], [0, 0, 0], [0, 0, 0]], (1, 1), 1) == (3, 1)", "assert move_game_piece([[0, 0, 0], [0, 0, 0], [0, 0, 0]], (3, 3), 2) == (3, 1)", "assert move_game_piece([[0, 0, 0], [0, 0, 0], [0, 0, 0]], (3, 3...
move_game_piece
def move_game_piece(grid, position, direction):
1
generic
7c15e45bbafa3b3ef1b3399faf4e7616
You are given an undirected graph represented by an adjacency matrix. Your task is to determine whether the graph is bipartite. A graph is bipartite if its vertices can be divided into two disjoint sets such that no two graph vertices within the same set are adjacent. **Input:** - The first line contains an integer `...
def is_bipartite(graph): """ Determines if a given graph is bipartite using BFS. :param graph: List[List[int]], an adjacency matrix representing the graph. :return: bool, True if the graph is bipartite, False otherwise. """ if not graph: return True # An empty graph is considered b...
[ "assert is_bipartite([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) == True", "assert is_bipartite([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) == False", "assert is_bipartite([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) == True", "assert is_bipartite([[0, 1], [1, 0]]) == True", "assert is_bipartite([[0]]) == True",...
is_bipartite
def is_bipartite(graph):
1
generic
923c474a512b6b7f91e7405afade9d08
Given a list of integers, write a function `filter_odd_numbers` that returns a new list containing only the odd numbers from the original list. Your implementation should utilize list comprehensions for enhanced readability. **Sample Input:** ```python [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` **Sample Output:** ```python ...
def filter_odd_numbers(numbers): """ Filters out odd numbers from a given list of integers. :param numbers: List of integers. :return: A new list containing only the odd numbers from the input list. """ return [number for number in numbers if number % 2 != 0]
[ "assert filter_odd_numbers([1, 2, 3, 4, 5]) == [1, 3, 5]", "assert filter_odd_numbers([10, 21, 32, 43, 54]) == [21, 43]", "assert filter_odd_numbers([2, 4, 6, 8, 10]) == []", "assert filter_odd_numbers([11, 13, 15, 17, 19]) == [11, 13, 15, 17, 19]", "assert filter_odd_numbers([]) == []", "assert filter_od...
filter_odd_numbers
def filter_odd_numbers(numbers):
1
algorithmic
9ca17a464b0c17410cca15f4cd8e062c
You are given a string `sentence` consisting of words separated by spaces. Your task is to write a function that returns a list of all unique words in the string, sorted in alphabetical order. Words are defined as sequences of alphanumeric characters, and the comparison should be case-insensitive. Punctuation and other...
import re def unique_sorted_words(sentence): """ Returns a list of all unique words in the given sentence, sorted alphabetically. :param sentence: A string containing words separated by spaces. :return: A list of unique words, sorted alphabetically. """ words = re.findall(r'\b\w+\b', sente...
[ "assert unique_sorted_words(\"Hello, world!\") == [\"hello\", \"world\"]", "assert unique_sorted_words(\"Python is fun, and Python is powerful.\") == [\"and\", \"fun\", \"is\", \"powerful\", \"python\"]", "assert unique_sorted_words(\"a b c d e f g\") == [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]", "as...
unique_sorted_words
def unique_sorted_words(sentence):
1
algorithmic
8f76ae8a0ab41474d49e68a34cbdfdef
You are given an integer representing a person's age in years. Your task is to write a function that calculates and returns the person's age in days, assuming a year has exactly 365 days. Your function should be written in a Pythonic style. **Sample Input:** ``` 25 ``` **Sample Output:** ``` 9125 ```
def get_age_in_days(age_years): """ Calculate the age in days given the age in years. Parameters: age_years (int): The age of a person in years. Returns: int: The age of the person in days, assuming a year has 365 days. """ return age_years * 365
[ "assert get_age_in_days(0) == 0", "assert get_age_in_days(1) == 365", "assert get_age_in_days(2) == 730", "assert get_age_in_days(10) == 3650", "assert get_age_in_days(18) == 6570", "assert get_age_in_days(50) == 18250", "assert get_age_in_days(100) == 36500", "assert get_age_in_days(0.5) == 182.5", ...
get_age_in_days
def get_age_in_days(age_years):
1
algorithmic
2d469ed6dca17252b7380b0607d397ef
You are tasked with implementing a simple calculator using Python's `argparse` module. Your program should function as a command-line interface that accepts two numbers and an arithmetic operator as input arguments. The supported operations are addition (+), subtraction (-), multiplication (*), and division (/). Your p...
import argparse def calculate(num1, num2, operator): """ Perform the specified arithmetic operation on two numbers. Parameters: num1 (float): The first number. num2 (float): The second number. operator (str): The arithmetic operator ('+', '-', '*', '/'). Returns: float: The result of ...
[ "assert calculate(10, 5, '+') == 15", "assert calculate(10, 5, '-') == 5", "assert calculate(10, 5, '*') == 50", "assert calculate(10, 5, '/') == 2.0", "assert calculate(0, 5, '+') == 5", "assert calculate(0, 5, '-') == -5", "assert calculate(0, 5, '*') == 0", "assert calculate(5, 0, '/') == \"Error: ...
calculate
def calculate(num1, num2, operator):
1
generic
de06943aa74e45d3e5afaa7ec985972b
You are given a binary tree represented as a nested dictionary in the form `{'value': <value>, 'left': <left_subtree>, 'right': <right_subtree>}`. Your task is to write a function `binary_tree_depth` that calculates the depth of the binary tree. The depth of a binary tree is defined as the number of nodes along the lon...
def binary_tree_depth(tree): """ Calculate the depth of a binary tree represented as a nested dictionary. :param tree: A dictionary representing a binary tree. :return: An integer representing the depth of the binary tree. """ if tree is None: return 0 left_depth = binary_tree_d...
[ "assert binary_tree_depth(None) == 0", "assert binary_tree_depth({'value': 1, 'left': None, 'right': None}) == 1", "assert binary_tree_depth({'value': 1, 'left': {'value': 2, 'left': None, 'right': None}, 'right': None}) == 2", "assert binary_tree_depth({'value': 1, 'left': None, 'right': {'value': 2, 'left':...
binary_tree_depth
def binary_tree_depth(tree):
1
generic
cb084cd00ae342161110dc0d1d58315b
You are given a list of integers `nums` containing `n-1` distinct numbers in the range from 1 to `n`. Your task is to find the missing number in the list. The list may not be sorted. **Input:** - A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer is in the range from 1 to n (inclusive), and exactly o...
def find_missing_number(nums): """ Finds the missing number in a list of integers from 1 to n with exactly one number missing. :param nums: List[int] - A list of integers from 1 to n with one number missing. :return: int - The missing number. """ n = len(nums) + 1 expected_sum = n * (n ...
[ "assert find_missing_number([1, 2, 4, 5, 6]) == 3", "assert find_missing_number([1, 3, 4, 5]) == 2", "assert find_missing_number([2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1", "assert find_missing_number([1, 2, 3, 4, 5, 6, 7, 8, 10]) == 9", "assert find_missing_number([10, 9, 8, 7, 6, 5, 4, 3, 2]) == 1", "assert fi...
find_missing_number
def find_missing_number(nums):
1
generic
fb1445828d9aae11299a61af63cce8ee
You are given a list of distinct elements and an integer `k`. Your task is to generate all possible combinations of `k` elements from the list. Each combination should be represented as a list. Return a list of these combinations. **Input:** - The first line contains an integer `n` (1 ≤ n ≤ 10), the number of elements...
from itertools import combinations def generate_combinations(input_list, k): """ Generate all possible combinations of k elements from the input list. :param input_list: List of distinct elements. :param k: Number of elements in each combination. :return: List of all possible combinations of k ele...
[ "assert generate_combinations([1, 2, 3], 2) == [[1, 2], [1, 3], [2, 3]]", "assert generate_combinations([1, 2, 3, 4], 2) == [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]", "assert generate_combinations([1, 2, 3, 4], 3) == [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]", "assert generate_combinations([1, 2, 3...
generate_combinations
def generate_combinations(input_list, k):
1
generic
a90e73f8fff70b7cf5a8c6da7cfe7ab7
In a web application, you need to implement a pagination feature. Given the current page number and the total number of pages, design a function that returns a list of page numbers to be displayed in the pagination scheme. The current page should be centered in the list when possible, and adjacent pages should be inclu...
def generate_pagination(current_page, total_pages, max_visible_pages=5): """ Generates a list of page numbers for a pagination scheme. Parameters: - current_page (int): The current page number. - total_pages (int): The total number of pages. - max_visible_pages (int): The maximum number of ...
[ "assert generate_pagination(1, 10) == [1, 2, 3, 4, 5]", "assert generate_pagination(5, 10) == [3, 4, 5, 6, 7]", "assert generate_pagination(10, 10) == [6, 7, 8, 9, 10]", "assert generate_pagination(3, 5) == [1, 2, 3, 4, 5]", "assert generate_pagination(1, 1) == [1]", "assert generate_pagination(2, 2) == [...
generate_pagination
def generate_pagination(current_page, total_pages, max_visible_pages=5):
1
generic
bbac70c01af7e8fc1249610780672645
In a custom time system, each day consists of 25 hours, each hour consists of 100 minutes, and each minute consists of 100 seconds. Given an integer representing the number of seconds since midnight (00:00) in this system, write a function `seconds_to_time` that returns a string formatted as "HH:MM:SS". The function sh...
def seconds_to_time(seconds): """ Convert the given number of seconds since midnight in a custom time system to a formatted string "HH:MM:SS". :param seconds: Integer representing the number of seconds since midnight. :return: String formatted as "HH:MM:SS". """ custom_seconds = seconds % 1...
[ "assert seconds_to_time(0) == \"00:00:00\"", "assert seconds_to_time(1) == \"00:00:01\"", "assert seconds_to_time(99) == \"00:00:99\"", "assert seconds_to_time(100) == \"00:01:00\"", "assert seconds_to_time(10101) == \"01:01:01\"", "assert seconds_to_time(9999) == \"00:99:99\"", "assert seconds_to_time(...
seconds_to_time
def seconds_to_time(seconds):
1
generic
df9b3cf5589ff61ef96e3c2d2ddfc52e
You are given a dictionary `shapes` where each key is a string representing a type of geometric shape ("circle" or "rectangle"), and the value is a dictionary containing the necessary attributes to compute the area of that shape. For a circle, the attributes dictionary contains a key `"radius"` with the radius value. F...
import math def calculate_total_area(shapes): """ Calculate the total area of all shapes provided in the shapes dictionary. :param shapes: A dictionary where each key is a string ("circle" or "rectangle") and each value is a dictionary with the necessary attributes to compute the area. ...
[ "assert calculate_total_area({\"circle\": {\"radius\": 1}}) == math.pi", "assert calculate_total_area({\"rectangle\": {\"width\": 3, \"height\": 4}}) == 12", "assert calculate_total_area({\"circle\": {\"radius\": 0}}) == 0", "assert calculate_total_area({\"rectangle\": {\"width\": 0, \"height\": 5}}) == 0", ...
calculate_total_area
def calculate_total_area(shapes):
1
generic
fddeb3e21582458b2f2492c9479a3044
You are given a JSON file named `config.json` located in the same directory as your script. Your task is to write a Python function that reads this file and prints the values of specific keys according to the following rules: - If the key `settings` exists and contains the key `theme`, print the value of `theme`. - If...
import json def read_config_and_print_values(filename): """ Reads a JSON file and prints the values of specific keys based on predefined rules. Args: filename (str): The name of the JSON file to read. Returns: None """ try: with open(filename, 'r') as file: ...
[ "assert read_config_and_print_values('config.json') == None # Assuming the function prints to stdout and returns None", "assert read_config_and_print_values('nonexistent.json') == None # File not found case", "assert read_config_and_print_values('invalid_json.json') == None # Invalid JSON case", "assert re...
read_config_and_print_values
def read_config_and_print_values(filename):
1
generic
02b2bc05302c419e83d610a55906a2f0
You are tasked with implementing a function `calculate_discounted_price` that computes the final price of an item after applying a given discount rate. The function should accept two parameters: `original_price` (a float representing the initial price of the item) and `discount_rate` (a float representing the discount ...
def calculate_discounted_price(original_price, discount_rate): """ Calculate the final price of an item after applying a discount. Parameters: original_price (float): The initial price of the item. discount_rate (float): The discount percentage to be applied. Returns: float: The final pric...
[ "assert calculate_discounted_price(100, 20) == 80.0", "assert calculate_discounted_price(200, 50) == 100.0", "assert calculate_discounted_price(150, 0) == 150.0", "assert calculate_discounted_price(0, 10) == 0.0", "assert calculate_discounted_price(100, 100) == 0.0", "assert calculate_discounted_price(99....
calculate_discounted_price
def calculate_discounted_price(original_price, discount_rate):
1
generic
7ad4a6333c0062eb72b365e91f3b756d
You are given a list of integers. Your task is to write a Python function that identifies the two numbers with the smallest difference between them. The function should return a tuple containing these two numbers. The solution should have a time complexity better than O(n^2). If there are multiple pairs with the same s...
def find_smallest_difference_pair(nums): """ Finds and returns a tuple of two numbers from the list with the smallest difference. :param nums: List of integers :return: Tuple containing two integers with the smallest difference """ nums.sort() min_diff = float('inf') min_pair = (Non...
[ "assert find_smallest_difference_pair([4, 1, 9, 17, 6, 3, 8, 12]) == (3, 4)", "assert find_smallest_difference_pair([1, 3, 6, 19, 20]) == (19, 20)", "assert find_smallest_difference_pair([10, 20, 30, 40, 50]) == (10, 20)", "assert find_smallest_difference_pair([5, 8, 12, 15, 16]) == (15, 16)", "assert find_...
find_smallest_difference_pair
def find_smallest_difference_pair(nums):
1
generic
3e1ca969afc4d28d4afbae43f004113d
You are given a string `S` representing a C++ code snippet. Your task is to count the occurrences of each type of brace in the string. The braces are `{`, `}`, `[`, `]`, `(`, and `)`. Output the counts in the format "Brace: Count" for each type of brace in the order they are listed. **Input:** - A single string `S` (1...
def count_braces(code_snippet): """ Counts the occurrences of each type of brace in the given C++ code snippet. Parameters: code_snippet (str): A string representing the C++ code snippet. Returns: None: Prints the count of each brace in the specified format. """ brace_counts = {'{': 0,...
[ "assert count_braces(\"int main() { if (a > b) { return a; } else { return b; } }\") == None", "assert count_braces(\"{[()]}\") == None", "assert count_braces(\"{{[[(())]]}}\") == None", "assert count_braces(\"{{[[(())]]\") == None", "assert count_braces(\"\") == None", "assert count_braces(\"int main() {...
count_braces
def count_braces(code_snippet):
1
generic
ea73ebd9d4d40705473441a9dbfff342
You are given a list of integers representing the heights of students in a class. Your task is to write a Python function `find_median_height(heights)` that calculates the median height of the students. The function should handle both even and odd numbers of heights correctly. **Input:** - A list of integers `heights`...
def find_median_height(heights): """ Calculate the median height of a list of student heights. :param heights: List of integers representing the heights of students. :return: Float representing the median height. """ sorted_heights = sorted(heights) n = len(sorted_heights) if n % 2 == 0...
[ "assert find_median_height([62, 65, 70, 55, 58]) == 62", "assert find_median_height([1, 2, 3, 4, 5, 6]) == 3.5", "assert find_median_height([100]) == 100", "assert find_median_height([1, 3, 3, 6, 7, 8, 9]) == 6", "assert find_median_height([1, 2, 3, 4, 5]) == 3", "assert find_median_height([5, 2, 1, 3, 4]...
find_median_height
def find_median_height(heights):
1
generic
82bf4ce7a97f8d7bf2c6ff80e784ff46
You are given a string `s`. Your task is to write a function `character_count` that processes the string and returns a dictionary. The dictionary should have characters as keys and their respective counts as values. The function should treat all characters as lowercase and ignore whitespace characters. **Input:** - A...
def character_count(s): """ Processes a string to return a dictionary with character counts. Parameters: s (str): The input string to process. Returns: dict: A dictionary with characters as keys and their counts as values. """ counts = {} s = s.lower() for char in s: ...
[ "assert character_count(\"Hello World!\") == {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1, '!': 1}", "assert character_count(\"Python\") == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}", "assert character_count(\"AaBbCc\") == {'a': 2, 'b': 2, 'c': 2}", "assert character_count(\"123 456 789\") =...
character_count
def character_count(s):
1
generic
e9956047a88e4cc949bae325aa83ac06
You are given a string `s` containing words separated by spaces and possibly including punctuation. Your task is to write a function `to_snake_case` that converts the string into snake case. In snake case, all words are in lowercase and separated by underscores. Additionally, all punctuation characters must be removed ...
import string def to_snake_case(input_string: str) -> str: """ Convert a given string to snake case by removing punctuation, converting to lowercase, and joining words with underscores. :param input_string: The input string containing words, spaces, and punctuation. :return: The string convert...
[ "assert to_snake_case(\"Hello World\") == \"hello_world\"", "assert to_snake_case(\"Hello, World!\") == \"hello_world\"", "assert to_snake_case(\"This is a test.\") == \"this_is_a_test\"", "assert to_snake_case(\"Python's syntax is great!\") == \"pythons_syntax_is_great\"", "assert to_snake_case(\"Multiple ...
to_snake_case
def to_snake_case(input_string: str) -> str:
1
generic
e3b054694357c7af1399872015c18444
You are given a binary tree represented as a list of lists, where each inner list corresponds to a level of the tree. Your task is to implement a function `find_max_value` that returns the maximum value present in the tree. **Input:** - A list of lists `tree` where `tree[i]` is a list containing the values of the node...
def find_max_value(tree): """ Finds and returns the maximum value in a binary tree represented as a list of lists. :param tree: List of lists where each inner list represents a level of the tree. :return: Integer representing the maximum value in the tree. """ max_value = tree[0][0] for...
[ "assert find_max_value([[1]]) == 1", "assert find_max_value([[1], [2, 3]]) == 3", "assert find_max_value([[10], [5, 20], [15, 30, 25]]) == 30", "assert find_max_value([[100], [90, 80], [70, 60, 50], [40, 30, 20, 10]]) == 100", "assert find_max_value([[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]) == 1", "assert f...
find_max_value
def find_max_value(tree):
1
generic
8f994a1db07e996c365260a54cab581a
You are tasked with implementing a function to compute the nth Fibonacci number efficiently. To achieve this, you must use a recursive approach with memoization to store previously computed Fibonacci numbers and avoid redundant calculations. Your function should return the nth Fibonacci number as an integer. **Input:*...
def fibonacci(n, memo=None): """ Calculate the nth Fibonacci number using recursion with memoization. :param n: An integer representing the position in the Fibonacci sequence. :param memo: A dictionary to store previously computed Fibonacci numbers. :return: The nth Fibonacci number as an integer. ...
[ "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
01c8203aba1bc5404c2c20af97e5b1d4
You are given a task to implement a function `send_message` that interacts with a hypothetical messaging service API. The function should accept three parameters: an authorized messaging service instance, a user's unique identifier, and a message to be sent. The function must return the sent message along with its uniq...
import uuid def send_message(messaging_service_instance, user_id, message): """ Sends a message to a user via a messaging service API. Parameters: messaging_service_instance (object): The authorized messaging service instance. user_id (str): The user's unique identifier, a 12-character alphanumeri...
[ "assert send_message(HypotheticalMessagingService(), \"1234567890ab\", {\"subject\": \"Hello\", \"body\": \"This is a test message.\"})['sent_message'] == {\"subject\": \"Hello\", \"body\": \"This is a test message.\"}", "assert send_message(HypotheticalMessagingService(), \"1234567890ab\", {\"subject\": \"Hello\...
send_message
def send_message(messaging_service_instance, user_id, message):
1
generic
508de51e95019a56a64d19328525b1cd
You are given a task to compute the factorial of a non-negative integer \( n \). The factorial of a non-negative integer \( n \) is the product of all positive integers less than or equal to \( n \). Your job is to write an iterative function to calculate the factorial instead of using recursion. Your function should h...
def factorial(n): """ Calculate the factorial of a non-negative integer n using iteration. Parameters: n (int): A non-negative integer whose factorial is to be computed. Returns: int: The factorial of the integer n. Raises: ValueError: If n is a negative integer. """ ...
[ "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(15) == 1307674368000", "assert factorial(20)...
factorial
def factorial(n):
1
generic
1f02d29b1d8b259a1d1b9850439fe994
You are given two integers, `start` and `end`. Your task is to write a function that returns a list of all prime numbers within the range `[start, end]` (inclusive). Use the Sieve of Eratosthenes algorithm to efficiently find the prime numbers. **Input:** - Two integers `start` and `end` (1 ≤ start ≤ end ≤ 10^6) **O...
def sieve_of_eratosthenes(start, end): """ Returns a list of prime numbers within the range [start, end] using the Sieve of Eratosthenes algorithm. :param start: The starting integer of the range (inclusive). :param end: The ending integer of the range (inclusive). :return: A list of prime numb...
[ "assert sieve_of_eratosthenes(10, 50) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]", "assert sieve_of_eratosthenes(1, 10) == [2, 3, 5, 7]", "assert sieve_of_eratosthenes(0, 1) == []", "assert sieve_of_eratosthenes(2, 2) == [2]", "assert sieve_of_eratosthenes(14, 16) == []", "assert sieve_of_eratosthene...
sieve_of_eratosthenes
def sieve_of_eratosthenes(start, end):
1
generic
a08dcc1c81b46448a53bf53ff619b080
You are given a list of integers `nums`. Your task is to determine the length of the longest increasing subsequence in `nums`. An increasing subsequence is defined as a sequence derived from `nums` by deleting some or no elements without changing the order of the remaining elements, where each element is strictly great...
def longest_increasing_subsequence(nums): """ Returns the length of the longest increasing subsequence in the given list of integers. :param nums: List[int] - A list of integers. :return: int - The length of the longest increasing subsequence. """ if not nums: return 0 dp = [1]...
[ "assert longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4", "assert longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == 4", "assert longest_increasing_subsequence([7, 7, 7, 7, 7, 7, 7]) == 1", "assert longest_increasing_subsequence([1, 2, 3, 4, 5]) == 5", "assert longest_increasing_subsequ...
longest_increasing_subsequence
def longest_increasing_subsequence(nums):
1
generic
9f16ab94c6d62d8ce0becc4da7b5b692
You are given a list of integers. Your task is to implement a function `calculate_average` that computes the average of all strictly positive numbers in the list. If there are no strictly positive numbers, the function should return -1. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^3), where each in...
def calculate_average(numbers): """ Calculate the average of strictly positive numbers in a list. Parameters: numbers (list of int): A list of integers. Returns: float: The average of strictly positive numbers, or -1 if no such numbers exist. """ non_negative_numbers = [num for...
[ "assert calculate_average([1, 2, 3, 4, 5]) == 3.0", "assert calculate_average([-1, -2, -3, -4, -5]) == -1", "assert calculate_average([0, 0, 0, 0]) == -1", "assert calculate_average([10, 20, 30, 40, 50]) == 30.0", "assert calculate_average([1, -1, 2, -2, 3, -3]) == 2.0", "assert calculate_average([0, 1, 2...
calculate_average
def calculate_average(numbers):
1
generic
f9ec883b0ac9528848f94b0e728d449b
You are given a string `expression` representing a mathematical expression consisting of non-negative integers, operators `+`, `-`, `*`, `/`, and parentheses `()`. Your task is to evaluate the expression and return the result as a floating-point number. The operators should follow the standard precedence and associativ...
def evaluate_expression(expression): """ Evaluates a mathematical expression given as a string and returns the result as a float. :param expression: A string representing the mathematical expression. :return: The result of the evaluated expression as a float. """ def calculate(op1, op2, ope...
[ "assert evaluate_expression(\"3 + 5\") == 8", "assert evaluate_expression(\"10 - 2\") == 8", "assert evaluate_expression(\"4 * 3\") == 12", "assert evaluate_expression(\"20 / 4\") == 5", "assert evaluate_expression(\"3 + 5 * 2\") == 13", "assert evaluate_expression(\"(3 + 5) * 2\") == 16", "assert evalu...
evaluate_expression
def evaluate_expression(expression):
1
generic
948a6203477766259ba12df5989706b9
You are given a dictionary representing a list of products with their corresponding prices. Your task is to write a Python function that sorts this dictionary by the prices in ascending order and returns a new dictionary with the sorted products. The input dictionary will have product names as keys and their prices as ...
def sort_products_by_price(products): """ Sorts a dictionary of products by their prices in ascending order. Parameters: products (dict): A dictionary with product names as keys and their prices as values. Returns: dict: A new dictionary with products sorted by price in ascending order. ""...
[ "assert sort_products_by_price({'apple': 0.99, 'banana': 0.59, 'orange': 1.29, 'pear': 0.79}) == {'banana': 0.59, 'pear': 0.79, 'apple': 0.99, 'orange': 1.29}", "assert sort_products_by_price({'milk': 2.49, 'bread': 1.99, 'eggs': 2.99}) == {'bread': 1.99, 'milk': 2.49, 'eggs': 2.99}", "assert sort_products_by_p...
sort_products_by_price
def sort_products_by_price(products):
1
algorithmic
9392e4741c89866f9e4954b73e15a9d2
You are given a string `s` and a list of characters `chars`. Your task is to implement a function `remove_chars` that removes all occurrences of the characters in `chars` from the string `s`. The function should return the modified string. If the input string `s` is empty or if the list `chars` is empty, the function s...
def remove_chars(s, chars): """ Removes all occurrences of the characters in `chars` from the string `s`. Parameters: s (str): The input string from which characters are to be removed. chars (list): A list of characters to be removed from the string `s`. Returns: str: The modified ...
[ "assert remove_chars(\"hello world\", ['l', 'o']) == \"he wrd\"", "assert remove_chars(\"abcdef\", ['a', 'e']) == \"bcdf\"", "assert remove_chars(\"python\", []) == \"python\"", "assert remove_chars(\"\", ['x', 'y']) == \"\"", "assert remove_chars(\"remove chars\", ['r', 'e']) == \"mov chas\"", "assert re...
remove_chars
def remove_chars(s, chars):
1
generic
4aa50c5f9fe843e8cd547ddc1953ce42
You are given a string `s` consisting of various characters, including parentheses. Your task is to determine if the parentheses in the string are balanced. A string with balanced parentheses means that every opening parenthesis '(' has a corresponding closing parenthesis ')' and they are correctly nested. **Input:** ...
def is_balanced_parentheses(s): """ Check if the parentheses in the string are balanced. :param s: A string that may contain various characters including parentheses. :return: True if the parentheses are balanced, False otherwise. """ stack = [] for char in s: if char == '(': ...
[ "assert is_balanced_parentheses(\"((a + b) * c) - (d / e)\") == True", "assert is_balanced_parentheses(\"((a + b) * c - (d / e)\") == False", "assert is_balanced_parentheses(\"()\") == True", "assert is_balanced_parentheses(\")(\") == False", "assert is_balanced_parentheses(\"(a + b) * (c - d)\") == True", ...
is_balanced_parentheses
def is_balanced_parentheses(s):
1
generic
8d4ce618649fa59a7b2495676c16a964
You are given a string `s` consisting of any characters, including punctuation and whitespace. Your task is to implement a function `reverse_string` that returns the reversed version of the string `s`. You are not allowed to use any built-in string methods that directly reverse the string. **Input:** - A single string...
def reverse_string(s): """ Reverses the given string s without using built-in string reversal methods. Parameters: s (str): The string to be reversed. Returns: str: The reversed string. """ reversed_s = '' for char in s: reversed_s = char + reversed_s return reversed_s ...
[ "assert reverse_string(\"Hello, World!\") == \"!dlroW ,olleH\"", "assert reverse_string(\"Python\") == \"nohtyP\"", "assert reverse_string(\"12345\") == \"54321\"", "assert reverse_string(\"!@#$%^&*()\") == \")(*&^%$#@!\"", "assert reverse_string(\"a\") == \"a\"", "assert reverse_string(\"\") == \"\"", ...
reverse_string
def reverse_string(s):
1
generic
ea35fec2af41ba78738322fc82bfad1e
You are tasked with implementing a function to manage an inventory system for a store. The inventory is represented as a dictionary where each key is a product name and the corresponding value is a list containing two integers: the quantity of the product in stock and its price per unit. Your goal is to compute the tot...
def calculate_inventory_value(inventory): """ Calculate the total value of each product in stock. Parameters: inventory (dict): A dictionary where keys are product names and values are lists of [quantity, price_per_unit]. Returns: list: A list of tuples, each containing (product_name, quantity...
[ "assert calculate_inventory_value({\"apple\": [10, 0.5], \"banana\": [20, 0.3]}) == [(\"apple\", 10, 0.5, 5.0), (\"banana\", 20, 0.3, 6.0)]", "assert calculate_inventory_value({\"orange\": [15, 0.75], \"grape\": [30, 0.2]}) == [(\"orange\", 15, 0.75, 11.25), (\"grape\", 30, 0.2, 6.0)]", "assert calculate_invent...
calculate_inventory_value
def calculate_inventory_value(inventory):
1
generic
d02fc7e304de0391e24409a16eebf03e
You are given a list of dictionaries, where each dictionary represents a book in a library. Each dictionary contains keys for the book's title, author, and publication year. Your task is to implement a function `sort_books_by_year` that sorts the list of books primarily by the publication year in ascending order. If tw...
def sort_books_by_year(books): """ Sorts a list of book dictionaries first by the publication year in ascending order. If two books have the same publication year, they are sorted by title in ascending order. :param books: List of dictionaries containing book information. :return: Sorted list o...
[ "assert sort_books_by_year([{'title': 'B', 'author': 'X', 'publication_year': 2000}, {'title': 'A', 'author': 'Y', 'publication_year': 2000}]) == [{'title': 'A', 'author': 'Y', 'publication_year': 2000}, {'title': 'B', 'author': 'X', 'publication_year': 2000}]", "assert sort_books_by_year([{'title': 'C', 'author'...
sort_books_by_year
def sort_books_by_year(books):
1
generic
573310a197cfa65a916c16548cee781a
You are given two sorted lists of tuples, `list1` and `list2`. Each tuple in the lists is of the form `(value, weight, category)`, where `value` is an integer, `weight` is a positive integer, and `category` is a string. Your task is to write a function `merge_sorted_lists(list1, list2)` that merges these two lists into...
def merge_sorted_lists(list1, list2): """ Merges two sorted lists of tuples and returns a single sorted list. Each tuple in the lists is of the form (value, weight, category). The sorting criteria are: 1. Sort by value in ascending order. 2. Sort by weight in descending order for tuples wit...
[ "assert merge_sorted_lists([(1, 2, 'a'), (3, 4, 'b')], [(1, 3, 'b'), (3, 2, 'a')]) == [(1, 3, 'b'), (1, 2, 'a'), (3, 4, 'b'), (3, 2, 'a')]", "assert merge_sorted_lists([(5, 1, 'c')], [(5, 1, 'a')]) == [(5, 1, 'a'), (5, 1, 'c')]", "assert merge_sorted_lists([(2, 2, 'x')], [(2, 2, 'y')]) == [(2, 2, 'x'), (2, 2, '...
merge_sorted_lists
def merge_sorted_lists(list1, list2):
1
generic
d5eebefdfce9df104f1cd60a238ef191
You are given a string `s`. Your task is to determine if `s` is a palindrome, considering only alphanumeric characters and ignoring cases. A string is a palindrome if it reads the same forwards and backwards. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5), which may contain uppercase and lowercase letters, digits, ...
import string def is_palindrome(s: str) -> bool: """ Determines if the given string is a palindrome, ignoring non-alphanumeric characters and case. :param s: The input string to check. :return: True if the string is a palindrome, False otherwise. """ cleaned = ''.join(char.lower() for char...
[ "assert is_palindrome(\"A\") == True", "assert is_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome(\"No 'x' in Nixon\") == True", "assert is_palindrome(\"Hello\") == False", "assert is_palindrome(\"Was it a car or a cat I saw?\") == True", "assert is_palindrome(\"Madam, in Ed...
is_palindrome
def is_palindrome(s: str) -> bool:
1
algorithmic
91fb773f6b23a8e9162bb14e9c9e72ef
You are given a string `s`. Your task is to determine if `s` is a palindrome, disregarding spaces, punctuation, and case sensitivity. Implement a function `is_palindrome(s)` that returns `True` if `s` is a palindrome and `False` otherwise. Use regular expressions to preprocess the string. **Input:** - A single string ...
import re def is_palindrome(s): """ Determines if the given string s is a palindrome, ignoring spaces, punctuation, and case sensitivity. :param s: The input string to check. :return: True if s is a palindrome, False otherwise. """ cleaned = re.sub(r'[^a-zA-Z0-9]', '', s).lower() retur...
[ "assert is_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome(\"racecar\") == True", "assert is_palindrome(\"No lemon, no melon\") == True", "assert is_palindrome(\"Was it a car or a cat I saw?\") == True", "assert is_palindrome(\"Not a palindrome\") == False", "assert is_palin...
is_palindrome
def is_palindrome(s):
1
generic
b1899bd30dfc3eec50c84b87d5a31e67
You are given a string `record_str` representing a person's record formatted as follows: - The record begins with "Record:" followed by a space. - It contains three fields: Name, Ethnicity, and Date of Birth (DOB). - Each field is separated by a semicolon and may have irregular whitespace around it. - The Name field s...
def extract_record_info(record_str): """ Extracts and returns the Name, Ethnicity, and DOB fields from a given record string. Parameters: record_str (str): The record string containing information about a person. Returns: str: A string containing the Name, Ethnicity, and DOB fields sep...
[ "assert extract_record_info(\"Record: Name: John Doe; Ethnicity: Caucasian; DOB: 01/01/1990; Additional Info\") == \"Name:JohnDoe; Ethnicity:Caucasian; DOB:01/01/1990\"", "assert extract_record_info(\"Record: Name: Jane Doe; Ethnicity: African American; DOB: 02/02/1980\") == \"Name:JaneDoe; Ethnicity:AfricanAmeri...
extract_record_info
def extract_record_info(record_str):
1
generic
b8728934d0cb93c978ea829dece3f36b
You are given a dictionary `employee_data` where each key is a unique employee ID and each value is another dictionary containing details about the employee. Your task is to implement a function `calculate_average_age(employee_data)` that computes the average age of all employees. Each employee dictionary includes an `...
def calculate_average_age(employee_data): """ Calculate the average age of all employees in the given employee_data dictionary. :param employee_data: A dictionary where keys are employee IDs and values are dictionaries containing employee details. :return: The average age of all employees as a float. R...
[ "assert calculate_average_age({}) == 0", "assert calculate_average_age({1: {'name': 'John', 'age': 30}}) == 30", "assert calculate_average_age({1: {'name': 'John', 'age': 30}, 2: {'name': 'Doe', 'age': 25}}) == 27.5", "assert calculate_average_age({1: {'name': 'John', 'age': 30}, 2: {'name': 'Doe', 'age': 25}...
calculate_average_age
def calculate_average_age(employee_data):
1
generic
dc91b5a1deb89e2719dfbb6fc1855c80
You are given a list of integers. Your task is to write a Python function that returns a list of tuples. Each tuple should consist of an integer from the list and the number of times it appears in the list. The order of tuples in the output list should match the order of first appearances of the integers in the input l...
def count_occurrences(lst): """ Returns a list of tuples, where each tuple contains an integer from the list and the count of its occurrences in the list. :param lst: List of integers :return: List of tuples (integer, count) """ occurrences = {} for num in lst: if num not in...
[ "assert count_occurrences([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) == [(1, 1), (2, 2), (3, 3), (4, 4)]", "assert count_occurrences([5, 5, 5, 5, 5]) == [(5, 5)]", "assert count_occurrences([1, 1, 2, 2, 3, 3, 4, 4]) == [(1, 2), (2, 2), (3, 2), (4, 2)]", "assert count_occurrences([]) == []", "assert count_occurrences([...
count_occurrences
def count_occurrences(lst):
1
generic
ca64dc7632a6f3247e23066cb3745ff6
You are given an array `arr` of `n` integers and an integer `k`. Your task is to rotate the elements of the array to the right by `k` steps. If `k` exceeds the length of the array, it should wrap around. Implement the function `rotate_array(arr, k)` to achieve this. **Input:** - The first argument is a list of integer...
def rotate_array(arr, k): """ Rotates the elements of the input array `arr` to the right by `k` steps. If `k` is greater than the length of the array, the rotation wraps around. :param arr: List[int] - The input array of integers. :param k: int - The number of steps to rotate the array. :return...
[ "assert rotate_array([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]", "assert rotate_array([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]", "assert rotate_array([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]", "assert rotate_array([1, 2, 3, 4, 5], 7) == [4, 5, 1, 2, 3]", "assert rotate_array([], 3) == []", "assert rotate_array([...
rotate_array
def rotate_array(arr, k):
1
generic
dfeae9aca883642586e9784a5159f9bc
You are given a list of integers. Your task is to implement a function `find_largest_prime` that identifies the largest prime number within the list. If no prime numbers are present, the function should return `-1`. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^3), where each integer `n` satisfies ...
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 find_largest_prime([10, 15, 3, 7, 11, 19, 4]) == 19", "assert find_largest_prime([2, 3, 5, 7, 11, 13, 17, 19]) == 19", "assert find_largest_prime([4, 6, 8, 9, 10]) == -1", "assert find_largest_prime([29, 15, 23, 11, 17]) == 29", "assert find_largest_prime([1, 4, 6, 8, 10]) == -1", "assert find_lar...
find_largest_prime
def find_largest_prime(numbers):
1
generic
076e72f2c7ffb74c6e7bab6282fe90c6
You are given a string `s`. Your task is to determine whether the string is a palindrome. A string is considered a palindrome if it reads the same forwards and backwards. Implement a recursive function `is_palindrome` to solve this problem. **Input:** - A single string `s` (1 ≤ |s| ≤ 1000), consisting of lowercase Eng...
def is_palindrome(s): """ Recursively checks if the given string s is a palindrome. :param s: The string to check. :return: True if s is a palindrome, False otherwise. """ if len(s) <= 1: return True elif s[0] == s[-1]: return is_palindrome(s[1:-1]) else: ret...
[ "assert is_palindrome(\"racecar\") == True", "assert is_palindrome(\"hello\") == False", "assert is_palindrome(\"a\") == True", "assert is_palindrome(\"\") == True", "assert is_palindrome(\"madam\") == True", "assert is_palindrome(\"level\") == True", "assert is_palindrome(\"noon\") == True", "assert ...
is_palindrome
def is_palindrome(s):
1
algorithmic
403c8ffca73114aaf88cdbc33a66bb91
Given two lists of integers, `list1` and `list2`, each of length `n`, representing the coordinates of two vectors in a 2D plane, compute the dot product of these vectors. Your solution must operate in constant space complexity. **Input:** - Two lists of integers, `list1` and `list2`, where `1 ≤ n ≤ 10^5` and `-10^9 ≤ ...
def vector_dot_product(list1, list2): """ Computes the dot product of two vectors represented by lists list1 and list2. Parameters: list1 (List[int]): The first vector. list2 (List[int]): The second vector. Returns: int: The dot product of the two vectors. """ dot_product =...
[ "assert vector_dot_product([1, 2, 3], [4, 5, 6]) == 32", "assert vector_dot_product([0, 0, 0], [1, 2, 3]) == 0", "assert vector_dot_product([1, -1, 1], [-1, 1, -1]) == -3", "assert vector_dot_product([10, 20, 30], [1, 2, 3]) == 140", "assert vector_dot_product([-1, -2, -3], [-4, -5, -6]) == 32", "assert v...
vector_dot_product
def vector_dot_product(list1, list2):
1
generic
8032e1f2d7ff17b1c2d3715c757efbb5
You are given a list of integers. Your task is to implement the selection sort algorithm to sort the list in descending order. Your function should modify the list in place and return it. **Input:** - A list of integers `arr` (1 ≤ len(arr) ≤ 1000), where each integer `arr[i]` satisfies -1000 ≤ arr[i] ≤ 1000. **Outpu...
def selection_sort_descending(arr): """ Sorts a list of integers in descending order using the selection sort algorithm. Parameters: arr (list): A list of integers to be sorted. Returns: list: The sorted list in descending order. """ n = len(arr) for i in range(n): ...
[ "assert selection_sort_descending([5, 2, 9, 1, 5, 6]) == [9, 6, 5, 5, 2, 1]", "assert selection_sort_descending([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]", "assert selection_sort_descending([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]", "assert selection_sort_d...
selection_sort_descending
def selection_sort_descending(arr):
1
generic
97882a98000e32626b5a678cb59976cd
In a software testing scenario, you are required to implement a function `should_clear_cache` that decides whether to clear a cache service before executing a set of tests. The function accepts two boolean parameters: `run_services` and `use_stale_data`. The cache should be cleared if and only if `run_services` is `Tru...
def should_clear_cache(run_services, use_stale_data): """ Determines whether the cache should be cleared before running tests. Parameters: run_services (bool): Indicates whether the services should be run. use_stale_data (bool): Indicates if stale data is acceptable for the tests. Returns: ...
[ "assert should_clear_cache(True, False) == True", "assert should_clear_cache(True, True) == False", "assert should_clear_cache(False, False) == False", "assert should_clear_cache(False, True) == False", "assert should_clear_cache(True, False) == True", "assert should_clear_cache(True, True) == False", "...
should_clear_cache
def should_clear_cache(run_services, use_stale_data):
1
generic
a404ffed8483a5cbcc66c687d411048a
You are given a string `s`. Your task is to implement a function `count_vowels(s)` that returns the number of vowels (a, e, i, o, u) present in the string, ignoring case sensitivity. The function should handle both uppercase and lowercase letters. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5), consisting of alphab...
def count_vowels(s): """ Counts the number of vowels in the given string, ignoring case. Parameters: s (str): The input string. Returns: int: The count of vowels in the string. """ vowels = 'aeiouAEIOU' return sum(1 for char in s if char in vowels) # Example usage input_string = "...
[ "assert count_vowels(\"The quick brown fox jumps over the lazy dog.\") == 11", "assert count_vowels(\"HELLO WORLD\") == 3", "assert count_vowels(\"Python Programming\") == 4", "assert count_vowels(\"AEIOUaeiou\") == 10", "assert count_vowels(\"\") == 0", "assert count_vowels(\"bcdfghjklmnpqrstvwxyz\") == ...
count_vowels
def count_vowels(s):
1
generic
e67a4e025dc6217699f25b57c1b4c8d6
You are given a string `s`. Your task is to determine the total number of palindromic substrings within `s`. A palindromic substring is a substring that reads the same forwards and backwards. For example, in the string `"aba"`, the palindromic substrings are `"a"`, `"a"`, `"b"`, and `"aba"`. **Input:** - A single str...
def count_palindromic_substrings(s: str) -> int: """ Counts the total number of palindromic substrings in the given string s. :param s: A string consisting of lowercase English letters. :return: The total number of palindromic substrings in s. """ n = len(s) count = 0 def expand_ar...
[ "assert count_palindromic_substrings(\"a\") == 1", "assert count_palindromic_substrings(\"aa\") == 3", "assert count_palindromic_substrings(\"aba\") == 4", "assert count_palindromic_substrings(\"abba\") == 6", "assert count_palindromic_substrings(\"racecar\") == 10", "assert count_palindromic_substrings(\...
count_palindromic_substrings
def count_palindromic_substrings(s: str) -> int:
1
generic
bb6bbcb8b9433349effaf821235bf53a
You are given a sorted list `arr` of `n` distinct integers and a target integer `target`. Your task is to implement a recursive function `binary_search` that returns the index of `target` in `arr` if it exists, otherwise return `-1`. The list `arr` is sorted in non-decreasing order. **Input:** - The first line contain...
def binary_search(arr, target, low=0, high=None): """ Perform a binary search on a sorted list to find the index of the target value. Parameters: arr (list): A sorted list of integers. target (int): The integer value to search for. low (int): The starting index of the search range. high (in...
[ "assert binary_search([1, 2, 3, 4, 5], 3) == 2", "assert binary_search([1, 2, 3, 4, 5], 1) == 0", "assert binary_search([1, 2, 3, 4, 5], 5) == 4", "assert binary_search([1, 2, 3, 4, 5], 6) == -1", "assert binary_search([], 1) == -1", "assert binary_search([1], 1) == 0", "assert binary_search([1], 2) == ...
binary_search
def binary_search(arr, target, low=0, high=None):
1
generic
3c65e720592cfa1eaa83a466527d1e20
You are given a list of integers. Your task is to implement a function `sort_by_frequency` that returns a new list sorted by the frequency of the elements in descending order. If two elements have the same frequency, they should be sorted by their value in ascending order. For example, given the input list `[4, 5, 6, 4...
def sort_by_frequency(nums): """ Sorts a list of integers by the frequency of elements in descending order. If two elements have the same frequency, they are sorted by their value in ascending order. :param nums: List of integers to be sorted. :return: A new list sorted by the specified conditi...
[ "assert sort_by_frequency([4, 5, 6, 4, 4, 7, 8, 5, 8]) == [4, 5, 8, 6, 7]", "assert sort_by_frequency([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) == [4, 3, 2, 1]", "assert sort_by_frequency([10, 20, 20, 10, 10, 30, 50, 50, 50]) == [10, 50, 20, 30]", "assert sort_by_frequency([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) == [1, 2, 3, 4...
sort_by_frequency
def sort_by_frequency(nums):
1
generic
889c108044cf81dffabad3f660841d27
You are given a list of integers. Your task is to implement a function `find_second_largest` that returns the second largest distinct integer in the list. If the list contains fewer than two distinct integers, the function should return `None`. **Input:** - A list of integers `numbers` (0 ≤ len(numbers) ≤ 10^5), wher...
def find_second_largest(numbers): """ Returns the second largest distinct integer in the list. If there are fewer than two distinct integers, returns None. :param numbers: List of integers :return: Second largest distinct integer or None """ if len(numbers) < 2: return None ...
[ "assert find_second_largest([1, 2, 3, 4, 5]) == 4", "assert find_second_largest([5, 5, 5, 5]) == None", "assert find_second_largest([10]) == None", "assert find_second_largest([]) == None", "assert find_second_largest([1, 1, 2, 2, 3, 3]) == 2", "assert find_second_largest([100, 90]) == 90", "assert find...
find_second_largest
def find_second_largest(numbers):
1
generic
08fd22297fe4a2ad39cbdad439ab3e46
You are given a dictionary `data` where each key is a string representing a date in the format "YYYY-MM-DD" and each value is an integer representing the sales amount for that date. Your task is to write a function `aggregate_sales` that aggregates the sales amounts by year. The function should return a dictionary wher...
def aggregate_sales(data): """ Aggregates sales amounts by year from a dictionary of date-sales pairs. Parameters: data (dict): A dictionary with date strings as keys and sales amounts as values. Returns: dict: A dictionary with years as keys and total sales for each year as values. """ ...
[ "assert aggregate_sales({\"2021-01-01\": 100, \"2021-02-01\": 200, \"2022-01-01\": 300}) == {\"2021\": 300, \"2022\": 300}", "assert aggregate_sales({\"2020-12-31\": 500, \"2020-11-30\": 400, \"2019-10-15\": 250}) == {\"2020\": 900, \"2019\": 250}", "assert aggregate_sales({\"2023-03-10\": 150, \"2023-04-20\": ...
aggregate_sales
def aggregate_sales(data):
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 (1 here)
domain generic or algorithmic

How it was built

Only tasks whose reference passes all its tests are kept: below that, the tests (or the reference) are wrong, and a correct solution cannot earn an all-tests-pass reward.

  • data/train-00000-of-00050.parquet of nvidia/OpenCodeInstruct: 100,000 rows
  • tests all call one function defined in the reference: 80,449
  • dataset score >= 1.0: 27,328
  • random sample (seed 0): 25,000
  • 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
41