Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
32
32
problem
stringlengths
215
4.34k
reference
stringlengths
73
4.49k
tests
listlengths
10
10
function
stringlengths
1
51
signature
stringlengths
9
432
score
float64
0.3
1
domain
stringclasses
2 values
02317877068e2181c9565c1d6767ac1c
You are given a Python dictionary representing a person's information, which may include nested dictionaries. Your task is to write a function that takes this dictionary as input and returns a flattened version of the dictionary. In the flattened dictionary, all nested keys should be concatenated into a single key, sep...
def flatten_dict(d, parent_key='', sep='_'): """ Flattens a nested dictionary into a single-level dictionary with concatenated keys. :param d: The dictionary to flatten. :param parent_key: The base key string for recursion (used internally). :param sep: The separator to use between keys. :r...
[ "assert flatten_dict({\"name\": \"John\", \"info\": {\"age\": 30, \"city\": \"New York\"}}) == {\"name\": \"John\", \"info_age\": 30, \"info_city\": \"New York\"}", "assert flatten_dict({\"a\": 1, \"b\": {\"c\": 2, \"d\": {\"e\": 3}}}) == {\"a\": 1, \"b_c\": 2, \"b_d_e\": 3}", "assert flatten_dict({\"x\": {\"y\...
flatten_dict
def flatten_dict(d, parent_key='', sep='_'):
0.9
generic
8bbee8cbbf0b23330c21312172f60809
You are given a list of integers. Your task is to implement a function `reverse_list_in_place` that reverses the elements of the list in place. The function should not return anything. The list should be modified directly. **Input:** - A list of integers `lst` (1 ≤ len(lst) ≤ 10^5), where each element is an integer (-...
def reverse_list_in_place(lst): """ Reverses the elements of the list in place. Parameters: lst (list): A list of integers to be reversed. """ left_index = 0 right_index = len(lst) - 1 while left_index < right_index: lst[left_index], lst[right_index] = lst[right_index], lst[lef...
[ "assert reverse_list_in_place([1, 2, 3, 4]) is None", "assert reverse_list_in_place([1, 2, 3, 4]) == None", "lst = [1, 2, 3, 4]; reverse_list_in_place(lst); assert lst == [4, 3, 2, 1]", "lst = [1, 2, 3]; reverse_list_in_place(lst); assert lst == [3, 2, 1]", "lst = [1]; reverse_list_in_place(lst); assert lst...
reverse_list_in_place
def reverse_list_in_place(lst):
1
generic
ba748111b893a4c82f054b027eeae05b
You are given a list of integers. Your task is to write a Python function `calculate_average` that computes the average of the numbers in the list. If the list is empty, the function should return `None`. Your program should also include a main section that demonstrates the usage of the function with a sample list `[10...
def calculate_average(numbers): """ Calculate the average of a list of numbers. Parameters: numbers (list): A list of integers or floats. Returns: float or None: The average of the numbers if the list is not empty, otherwise None. """ if not numbers: # Check if the list is emp...
[ "assert calculate_average([1, 2, 3, 4, 5]) == 3.0", "assert calculate_average([10, 20, 30]) == 20.0", "assert calculate_average([5]) == 5.0", "assert calculate_average([]) == None", "assert calculate_average([100, 200, 300, 400, 500]) == 300.0", "assert calculate_average([-1, -2, -3, -4, -5]) == -3.0", ...
calculate_average
def calculate_average(numbers):
1
generic
5027b41230fa0c8e4a82590d61df04ce
You are tasked with implementing the `validate_luhn` function to verify the validity of identification numbers using the Luhn algorithm. The function should not utilize loops (for or while) or recursion. The Luhn algorithm is defined as follows: 1. Starting from the rightmost digit (the check digit) and moving left, d...
from functools import reduce def validate_luhn(n): """ Validates if the given integer n is a valid Luhn number without using loops or recursion. :param n: Integer to be validated :return: True if n is a valid Luhn number, False otherwise """ digits = [int(d) for d in str(n)[::-1]] doub...
[ "assert validate_luhn(79927398713) == True", "assert validate_luhn(1234567812345670) == False", "assert validate_luhn(4539148803436467) == True", "assert validate_luhn(49927398716) == True", "assert validate_luhn(1234567812345678) == False", "assert validate_luhn(4532015112830366) == True", "assert vali...
validate_luhn
def validate_luhn(n):
0.4
generic
330741a6df70c06fbbe27cff0ff62f8b
You are given a list of integers. Your task is to write a function `sum_even_odd(numbers)` that computes the sum of even numbers and the sum of odd numbers in the list. The function should return a tuple with the first element being the sum of even numbers and the second element being the sum of odd numbers. **Input:*...
def sum_even_odd(numbers): """ Computes the sum of even and odd numbers in a list. Parameters: numbers (list of int): A list of integers. Returns: tuple: A tuple containing the sum of even numbers and the sum of odd numbers. """ even_sum = sum(num for num in numbers if num % 2 == 0) ...
[ "assert sum_even_odd([1, 2, 3, 4, 5]) == (6, 9)", "assert sum_even_odd([2, 4, 6, 8, 10]) == (30, 0)", "assert sum_even_odd([1, 3, 5, 7, 9]) == (0, 25)", "assert sum_even_odd([]) == (0, 0)", "assert sum_even_odd([0]) == (0, 0)", "assert sum_even_odd([-2, -4, -6, -8, -10]) == (-30, 0)", "assert sum_even_o...
sum_even_odd
def sum_even_odd(numbers):
1
generic
d9fd576fd39858720c2c647c779122dd
You are tasked with implementing a function to compute the tax for a list of income amounts based on the following progressive tax brackets: - 0-10,000: 10% - 10,001-20,000: 20% - 20,001 and above: 30% Your function should take a list of integers representing income amounts and return a list of floats representing th...
def calculate_taxes(incomes): """ Calculate the taxes for a list of income amounts based on progressive tax brackets. :param incomes: List of integers representing income amounts. :return: List of floats representing the tax amounts for each income. """ taxes = [] for income in incomes: ...
[ "assert calculate_taxes([0]) == [0.0]", "assert calculate_taxes([5000]) == [500.0]", "assert calculate_taxes([10000]) == [1000.0]", "assert calculate_taxes([10001]) == [2000.2]", "assert calculate_taxes([20000]) == [3000.0]", "assert calculate_taxes([20001]) == [3000.3]", "assert calculate_taxes([5000, ...
calculate_taxes
def calculate_taxes(incomes):
0.7
generic
a7ce90bd2eeb7b0ad2cd723f2f18aeb4
You are given a dictionary `word_count` representing the frequency of each word in a text document. The keys are the words, and the values are their respective frequencies. Implement a function `most_frequent_words` that returns a list of the top 10 most frequent words in the dictionary. In the event of a tie in freque...
def most_frequent_words(word_count): """ Returns a list of the top 10 most frequent words in the given dictionary. :param word_count: A dictionary where keys are words and values are their frequencies. :return: A list of the top 10 most frequent words. """ sorted_word_count = sorted(word_co...
[ "assert most_frequent_words({'the': 20, 'and': 15, 'to': 12, 'of': 10, 'a': 9, 'in': 8, 'that': 7, 'was': 6, 'is': 5, 'on': 4, 'with': 3, 'as': 2, 'by': 1, 'for': 1, 'it': 1, 'he': 1, 'she': 1, 'they': 1, 'we': 1, 'you': 1}) == ['the', 'and', 'to', 'of', 'a', 'in', 'that', 'was', 'is', 'on']", "assert most_freque...
most_frequent_words
def most_frequent_words(word_count):
0.9
generic
84bb4fcfb9a9ce7ec372ef5732d82989
You are tasked with implementing an optimized function to compute the factorial of a given non-negative integer `n`. The function should efficiently handle large values of `n` without using recursion. Your solution should be both time and space efficient. **Input:** - A single integer `n` (0 ≤ n ≤ 100). **Output:** -...
def factorial_optimized(n): """ Calculate the factorial of a non-negative integer n using an iterative approach. Parameters: n (int): The non-negative integer to compute the factorial of. Returns: int: The factorial of the integer n. Raises: ValueError: If n is negative. ...
[ "assert factorial_optimized(0) == 1", "assert factorial_optimized(1) == 1", "assert factorial_optimized(5) == 120", "assert factorial_optimized(10) == 3628800", "assert factorial_optimized(20) == 2432902008176640000", "assert factorial_optimized(30) == 265252859812191058636308480000000", "assert factori...
factorial_optimized
def factorial_optimized(n):
0.6
generic
5a7f0bbc334a048415d36beaef50f98f
You are given two lists of time intervals, `list1` and `list2`. Each list consists of `n` and `m` intervals, respectively, where each interval is represented as a tuple of two integers `(start, end)`. Your task is to determine if there exists any partial overlap between any interval from `list1` and any interval from `...
def has_partial_overlap(list1, list2): """ Determines if there is any partial overlap between any interval from list1 and any interval from list2. :param list1: List of tuples, where each tuple represents an interval (start, end). :param list2: List of tuples, where each tuple represents an interval (s...
[ "assert has_partial_overlap([(1, 3), (5, 9), (10, 12)], [(2, 5), (8, 11)]) == True", "assert has_partial_overlap([(1, 2), (3, 4)], [(5, 6), (7, 8)]) == False", "assert has_partial_overlap([(1, 5)], [(5, 10)]) == False", "assert has_partial_overlap([(1, 5)], [(4, 10)]) == True", "assert has_partial_overlap([...
has_partial_overlap
def has_partial_overlap(list1, list2):
0.9
generic
9a0de1fa7bb4ebf21cb55b7de952d2d6
You are tasked with implementing a function named `respond` that processes a given string according to specific rules and returns an appropriate response. The function should handle the following conditions: 1. If the input string is empty after removing leading and trailing whitespace and non-alphanumeric characters ...
import re def respond(input_string: str) -> str: """ Processes a given string and returns a response based on specific conditions. Parameters: input_string (str): The input string to be processed. Returns: str: The response based on the conditions. """ # Strip leading and trai...
[ "assert respond(\" \") == \"Fine. Be that way!\"", "assert respond(\"HELLO!!!\") == \"Whoa, calm down!\"", "assert respond(\"HELLO\") == \"Whoa, calm down!\"", "assert respond(\"Is this a question?\") == \"Sure.\"", "assert respond(\"Is this a question?!\") == \"Sure.\"", "assert respond(\"Is this a qu...
respond
def respond(input_string: str) -> str:
0.5
generic
ca184ef428a469ef65b5c0debe9bd5fa
Given an integer or floating-point number, write a function to compute the product of the number and the number increased by 2. Your function should be optimized for readability and efficiency. Provide a clear docstring for your function. **Sample Input:** ``` 5 ``` **Sample Output:** ``` 35 ```
def calculate_product_with_offset(number): """ Computes the product of the given number and the number increased by 2. Parameters: number (int or float): The number to be processed. Returns: int or float: The product of the original number and the number increased by 2. """ offset_numb...
[ "assert calculate_product_with_offset(0) == 0", "assert calculate_product_with_offset(1) == 3", "assert calculate_product_with_offset(2) == 8", "assert calculate_product_with_offset(-1) == -1", "assert calculate_product_with_offset(-2) == 0", "assert calculate_product_with_offset(10) == 120", "assert ca...
calculate_product_with_offset
def calculate_product_with_offset(number):
0.9
generic
97b38ac8cb71902b8321745e118baf5b
You are given a list of tuples representing products in a store. Each tuple consists of three elements: the product name (a string), the category (a string), and the price (an integer). Your task is to sort this list of products primarily by price in ascending order. If two products have the same price, they should be ...
def sort_products(products): """ Sorts a list of products based on price in ascending order. If two products have the same price, they are sorted by product name alphabetically. :param products: List of tuples, where each tuple contains (product_name, category, price) :return: Sorted list of tuples...
[ "assert sort_products([('Laptop', 'Electronics', 1200), ('Smartphone', 'Electronics', 800), ('Blender', 'Appliances', 150), ('Toaster', 'Appliances', 50), ('Microwave', 'Appliances', 200), ('Coffee Maker', 'Appliances', 100), ('Headphones', 'Electronics', 100), ('Keyboard', 'Electronics', 150)]) == [('Coffee Maker'...
sort_products
def sort_products(products):
0.9
generic
d639918d91be8ef2a257fa7720bef8d8
You are tasked with implementing a function `count_valid_records(path)` that processes a CSV file located at the specified `path`. The function should return the count of valid records. A record is considered valid if it contains exactly three fields: a name, an age, and an email. The age must be a positive integer. Yo...
import csv def count_valid_records(path): """ Counts the number of valid records in a CSV file. A record is valid if it has exactly three fields: a name, a positive integer age, and an email. Parameters: path (str): The path to the CSV file. Returns: int: The number of valid ...
[ "assert count_valid_records(\"valid_records.csv\") == 5", "assert count_valid_records(\"empty_file.csv\") == 0", "assert count_valid_records(\"invalid_records.csv\") == 0", "assert count_valid_records(\"mixed_records.csv\") == 2", "assert count_valid_records(\"nonexistent_file.csv\") == 0", "assert count_...
count_valid_records
def count_valid_records(path):
0.7
generic
42aa3994b59c896cb6e0201ae2d38488
You are given an integer `digits`. Your task is to find the largest palindrome that can be obtained as a product of two `digits`-digit numbers. A palindrome reads the same backward as forward. For example, if `digits = 2`, the largest palindrome product is 9009, which is the product of 91 and 99. **Input:** - An integ...
def find_largest_palindrome_product(digits: int) -> int: """ Finds the largest palindrome that is a product of two `digits`-digit numbers. :param digits: An integer representing the number of digits. :return: The largest palindrome product of two `digits`-digit numbers. """ def is_palindrome(nu...
[ "assert find_largest_palindrome_product(2) == 9009", "assert find_largest_palindrome_product(1) == 9", "assert find_largest_palindrome_product(3) == 906609", "assert find_largest_palindrome_product(4) == 99000099", "assert find_largest_palindrome_product(5) == 999000999", "assert find_largest_palindrome_p...
find_largest_palindrome_product
def find_largest_palindrome_product(digits: int) -> int:
0.4
generic
9610bff99123c314ed0d19f249545d9c
You are tasked with implementing a simple voting system. Given a list of candidate names and a list of votes, where each vote is a string representing the name of a candidate, your goal is to determine the final vote counts for each candidate. The results should be returned as a dictionary sorted in descending order by...
def voting_system(candidates, votes): """ Simulates a simple voting system. Parameters: candidates (list of str): A list of candidate names. votes (list of str): A list of votes, where each vote is a candidate's name. Returns: dict: A dictionary with candidate names as keys and their vote ...
[ "assert voting_system(['Alice', 'Bob'], ['Alice', 'Bob', 'Alice']) == {'Alice': 2, 'Bob': 1}", "assert voting_system(['Alice', 'Bob'], ['Bob', 'Bob', 'Alice', 'Alice']) == {'Alice': 2, 'Bob': 2}", "assert voting_system(['Alice', 'Bob'], ['Charlie', 'Charlie']) == {'Alice': 0, 'Bob': 0}", "assert voting_system...
voting_system
def voting_system(candidates, votes):
1
generic
77bf4accdcbbdd84a4dd1e821f6ad517
You are given an `n x n` integer matrix `matrix`. Your task is to rotate the matrix 90 degrees clockwise in-place, meaning you should not use any additional storage for another matrix. The function should modify the input matrix directly. **Input:** - The first line contains an integer `n` (1 ≤ n ≤ 100), the size of t...
def rotate_matrix(matrix): """ Rotates a given n x n matrix 90 degrees clockwise in-place. :param matrix: List[List[int]] - The matrix to be rotated. """ n = len(matrix) for layer in range(n // 2): first = layer last = n - 1 - layer for i in range(first, last): ...
[ "assert rotate_matrix([[1]]) == None", "matrix = [[1, 2], [3, 4]]; rotate_matrix(matrix); assert matrix == [[3, 1], [4, 2]]", "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix(matrix); assert matrix == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14...
rotate_matrix
def rotate_matrix(matrix):
1
generic
2d0e5b513815ce748ddeea02a63c5b3f
You are given a URL as a string. Your task is to write a function `parse_url(url)` that parses the URL and returns a dictionary with the following keys: `scheme`, `netloc`, `path`, `params`, `query`, and `fragment`. The `query` key should map to a dictionary where each key is a query parameter name and each value is a ...
from urllib.parse import urlparse, parse_qs def parse_url(url): """ Parses a given URL and returns a dictionary containing the URL components. Parameters: url (str): The URL to be parsed. Returns: dict: A dictionary with keys 'scheme', 'netloc', 'path', 'params', 'query', and 'fragment'. ...
[ "assert parse_url(\"https://www.example.com/path/to/page?name=John&age=30#section1\") == {'scheme': 'https', 'netloc': 'www.example.com', 'path': '/path/to/page', 'params': '', 'query': {'name': ['John'], 'age': ['30']}, 'fragment': 'section1'}", "assert parse_url(\"http://example.com\") == {'scheme': 'http', 'ne...
parse_url
def parse_url(url):
0.9
generic
70da7b656c70fbb3f6106af9066ae01e
You are given an array of integers, `numbers`, and an integer `target`. Your task is to implement a function `find_two_sum` that identifies two distinct indices `i` and `j` such that `numbers[i] + numbers[j] = target`. The function should return a tuple `(i, j)` where `i < j`. If no such pair exists, the function shoul...
def find_two_sum(numbers, target): """ Finds two distinct indices i and j in the list 'numbers' such that numbers[i] + numbers[j] equals the 'target'. Returns a tuple (i, j) with i < j. Returns None if no such pair exists. """ num_dict = {} for index, number in enumerate(numbers): c...
[ "assert find_two_sum([2, 7, 11, 15], 9) == (0, 1)", "assert find_two_sum([3, 2, 4], 6) == (1, 2)", "assert find_two_sum([3, 3], 6) == (0, 1)", "assert find_two_sum([1, 2, 3, 4, 5], 10) == (3, 4)", "assert find_two_sum([1, 2, 3, 4, 5], 8) == (2, 4)", "assert find_two_sum([1, 2, 3, 4, 5], 11) == None", "a...
find_two_sum
def find_two_sum(numbers, target):
0.8
generic
33016285295a1cb0525418bc1588ee9f
You are tasked with refactoring a given piece of code to enhance its readability and efficiency. The function `calculate_expression` computes the result of the arithmetic expression `adder + (multiplier * multiplicand)`. Your solution should adhere to best practices, including proper documentation. Consider the followi...
def calculate_expression(adder, multiplier, multiplicand): """ Computes the result of the arithmetic expression: adder + (multiplier * multiplicand). Parameters: adder (int or float): The number to be added after the multiplication. multiplier (int or float): The number that multiplicand is multipl...
[ "assert calculate_expression(0, 0, 0) == 0", "assert calculate_expression(1, 2, 3) == 7", "assert calculate_expression(5, 5, 5) == 30", "assert calculate_expression(-1, -1, -1) == -2", "assert calculate_expression(10, 0, 100) == 10", "assert calculate_expression(0, 100, 100) == 0", "assert calculate_exp...
calculate_expression
def calculate_expression(adder, multiplier, multiplicand):
0.8
algorithmic
14aef7aa22da85c98c8f4dacb82046a5
You are tasked with implementing a function `emotion_classifier(emotion_score)` that categorizes an emotion based on a given score. The function should adhere to the following rules: - Return 'Sad' if `emotion_score` is less than -0.5. - Return 'Neutral' if `emotion_score` is between -0.5 and 0.5, inclusive. - Return ...
def emotion_classifier(emotion_score): """ Classifies the emotion based on the given emotion score and logs the result. Parameters: emotion_score (float or None): The intensity of the emotion. Returns: str or None: The emotion category ('Sad', 'Neutral', 'Happy') or None if the input is None. ...
[ "assert emotion_classifier(-1.0) == 'Sad'", "assert emotion_classifier(-0.5) == 'Neutral'", "assert emotion_classifier(0.0) == 'Neutral'", "assert emotion_classifier(0.5) == 'Neutral'", "assert emotion_classifier(0.6) == 'Happy'", "assert emotion_classifier(None) == None", "assert emotion_classifier(-0....
emotion_classifier
def emotion_classifier(emotion_score):
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
f457384205508990122a8d8e14af3f7d
You are given a target string `target` and a list of strings `wordBank`. Your task is to determine if the target string can be constructed by concatenating elements from `wordBank`. Each element in `wordBank` can be used multiple times. If the target string can be constructed, return a list of words from `wordBank` tha...
def can_form_target(target, wordBank): """ Determines if the target string can be constructed by concatenating elements from wordBank. :param target: The target string to be constructed. :param wordBank: A list of strings that can be used to construct the target. :return: A list of strings from...
[ "assert can_form_target(\"applebanana\", [\"apple\", \"banana\", \"app\", \"le\", \"ban\", \"ana\"]) == [\"apple\", \"banana\"]", "assert can_form_target(\"applebanana\", [\"apple\", \"banana\", \"app\", \"le\", \"ban\"]) == None", "assert can_form_target(\"abcdef\", [\"ab\", \"abc\", \"cd\", \"def\", \"abcd\"]...
can_form_target
def can_form_target(target, wordBank):
0.4
generic
4efc4e16042b499419a80040dfbca36d
You are given a list of non-empty strings. Your task is to determine the longest common prefix among all the strings in the list. If there is no common prefix, return an empty string. Implement the function `longest_common_prefix(strings)` to solve this problem. **Input:** - A list of strings `strings` (1 ≤ len(string...
def longest_common_prefix(strings): """ Finds the longest common prefix among all strings in the given list. :param strings: List of strings to find the common prefix for. :return: The longest common prefix as a string, or an empty string if no common prefix exists. """ if not strings: ...
[ "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(strings):
1
generic
2b8b7f56c3d5a8141d7181edf7bcf462
You are given a list of integers. Your task is to implement a function `filter_odd_numbers` that returns a new list containing only the odd numbers from the input list. Use list comprehension to accomplish this. Your function should handle any list of integers efficiently. **Sample Input:** ``` [1, 2, 3, 4, 5, 6, 7, 8...
def filter_odd_numbers(numbers): """ Filters out odd numbers from a given list of integers. Parameters: numbers (list): A list of integers. Returns: list: A list containing only the odd numbers from the input list. """ return [number for number in numbers if number % 2 != 0] # Example...
[ "assert filter_odd_numbers([1, 2, 3, 4, 5]) == [1, 3, 5]", "assert filter_odd_numbers([10, 20, 30, 40, 50]) == []", "assert filter_odd_numbers([11, 22, 33, 44, 55]) == [11, 33, 55]", "assert filter_odd_numbers([]) == []", "assert filter_odd_numbers([0, 1, 2, 3, 4, 5]) == [1, 3, 5]", "assert filter_odd_num...
filter_odd_numbers
def filter_odd_numbers(numbers):
1
generic
1a8c729923c75c54d5552d67800dce47
You are given a binary tree. Your task is to implement a function that performs a postorder traversal of the tree and returns the values of the nodes in the order they are visited. The function should not use any additional data structures or libraries other than what is provided in the standard Python library. **Inp...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def postorderTraversal(root): """ Perform a postorder traversal of a binary tree and return the values of the nodes in the order they are visited. :param roo...
[ "assert postorderTraversal(None) == []", "assert postorderTraversal(TreeNode(1)) == [1]", "assert postorderTraversal(TreeNode(1, TreeNode(2))) == [2, 1]", "assert postorderTraversal(TreeNode(1, None, TreeNode(2))) == [2, 1]", "assert postorderTraversal(TreeNode(1, TreeNode(2), TreeNode(3))) == [2, 3, 1]", ...
postorderTraversal
def postorderTraversal(root):
0.8
generic
f77632fa12b63d2fd1e99102affc6cc5
You are tasked with implementing a function `generate_fibonacci` that computes the first `n` numbers in the Fibonacci sequence. The Fibonacci sequence is defined as follows: the first number is 0, the second number is 1, and each subsequent number is the sum of the two preceding ones. Your function should return a list...
def generate_fibonacci(n): """ Generate a list of the first `n` Fibonacci numbers. Args: n (int): Number of Fibonacci numbers to generate (0 ≤ n ≤ 50) Returns: list: A list containing the first `n` Fibonacci numbers """ if n <= 0: return [] elif n == 1: retu...
[ "assert generate_fibonacci(0) == []", "assert generate_fibonacci(1) == [0]", "assert generate_fibonacci(2) == [0, 1]", "assert generate_fibonacci(3) == [0, 1, 1]", "assert generate_fibonacci(5) == [0, 1, 1, 2, 3]", "assert generate_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "assert generate_fi...
generate_fibonacci
def generate_fibonacci(n):
1
algorithmic
b27568c9b0ab6b18364f36532e6d5092
You are given a point in Cartesian coordinates `(x, y)`. Your task is to write a function `convert_to_polar` that converts this point to polar coordinates `(r, theta)`. The angle `theta` should be in radians and should lie in the range `[0, 2π)`. **Input:** - Two floating-point numbers `x` and `y` representing the Ca...
import math def convert_to_polar(x, y): """ Convert Cartesian coordinates (x, y) to polar coordinates (r, theta). Parameters: x (float): The x-coordinate in Cartesian coordinates. y (float): The y-coordinate in Cartesian coordinates. Returns: tuple: A tuple (r, theta) where r is t...
[ "assert convert_to_polar(1, 1) == (math.sqrt(2), math.pi / 4)", "assert convert_to_polar(0, 0) == (0, 0)", "assert convert_to_polar(1, 0) == (1, 0)", "assert convert_to_polar(0, 1) == (1, math.pi / 2)", "assert convert_to_polar(-1, 0) == (1, math.pi)", "assert convert_to_polar(0, -1) == (1, 3 * math.pi / ...
convert_to_polar
def convert_to_polar(x, y):
1
generic
ed9a1689405c9e7e771db3d35298ed14
You are tasked with implementing a function to generate the Fibonacci sequence. Write a Python function `generate_fibonacci` that takes an integer `n` as input and returns a list containing the first `n` Fibonacci numbers. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two prec...
def generate_fibonacci(n): """ Generate a list of the first n Fibonacci numbers. Parameters: n (int): The number of Fibonacci numbers to generate. Returns: list: A list containing the first n Fibonacci numbers. """ if n <= 0: return [] elif n == 1: return [0] el...
[ "assert generate_fibonacci(0) == []", "assert generate_fibonacci(1) == [0]", "assert generate_fibonacci(2) == [0, 1]", "assert generate_fibonacci(5) == [0, 1, 1, 2, 3]", "assert generate_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "assert generate_fibonacci(15) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
generate_fibonacci
def generate_fibonacci(n):
1
generic
68d00342b7d0ad03f1eee1f0c2c7778d
You are tasked with implementing a function to efficiently compute the term frequency (TF) of a specific term within a document from a large collection. The documents are represented as a dictionary where each key is a document ID and each value is another dictionary mapping terms to their respective frequencies. Your ...
def calculate_tf(documents: dict, doc_id: int, term: str) -> int: """ Calculate the term frequency of a specific term in a given document. :param documents: A dictionary mapping document IDs to dictionaries of term frequencies. :param doc_id: The ID of the document to search within. :param term: Th...
[ "assert calculate_tf({\"doc1\": {\"hello\": 2, \"world\": 1}}, \"doc1\", \"hello\") == 2", "assert calculate_tf({\"doc1\": {\"hello\": 2, \"world\": 1}}, \"doc1\", \"world\") == 1", "assert calculate_tf({\"doc1\": {\"hello\": 2, \"world\": 1}}, \"doc1\", \"python\") == 0", "assert calculate_tf({\"doc1\": {\"h...
calculate_tf
def calculate_tf(documents: dict, doc_id: int, term: str) -> int:
1
generic
f836144609aa16b3b0ac788ae3846ae4
You are given an integer `n`. Your task is to determine if `n` is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your program should return `True` if `n` is a prime number, and `False` otherwise. The solution should be efficient and handle edge c...
def is_prime(n): """Determine if the given integer n is a prime number. Returns True if n is a prime number, and False otherwise. """ 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 % ...
[ "assert is_prime(2) == True", "assert is_prime(3) == True", "assert is_prime(4) == False", "assert is_prime(11) == True", "assert is_prime(15) == False", "assert is_prime(17) == True", "assert is_prime(1) == False", "assert is_prime(0) == False", "assert is_prime(-7) == False", "assert is_prime(10...
is_prime
def is_prime(n):
1
generic
c2296588106b6d8fcfaa0ec2b3eb57d9
You are given a string `s`. Your task is to write a function `reverse_vowels` that returns a new string where all the vowels in the original string are reversed. The vowels are 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase). The function should handle strings of any length, including empty strings. **Sample In...
def reverse_vowels(s: str) -> str: """ Reverses the vowels in the given string s and returns the modified string. :param s: Input string :return: String with vowels reversed """ vowels = "aeiouAEIOU" s_vowels = [char for char in s if char in vowels] s_vowels.reverse() s_lis...
[ "assert reverse_vowels(\"hello world\") == \"holle werld\"", "assert reverse_vowels(\"leetcode\") == \"leotcede\"", "assert reverse_vowels(\"aA\") == \"Aa\"", "assert reverse_vowels(\"racecar\") == \"racecar\"", "assert reverse_vowels(\"AEIOU\") == \"UOIEA\"", "assert reverse_vowels(\"bcd\") == \"bcd\"", ...
reverse_vowels
def reverse_vowels(s: str) -> str:
0.8
generic
4e893da78e0a570ec1204250ffbd9a52
You are given a string `elemento` and a delimiter `delimitador`. Your task is to implement a function `split_and_filter` that splits the string into a list of elements using the provided delimiter. However, the function should only include elements in the list that meet the following criteria: - The element is not an ...
def split_and_filter(elemento, delimitador): """ Splits the input string `elemento` using the `delimitador`, treating escaped delimiters as literal characters. Returns a list of non-empty, non-whitespace elements. :param elemento: The input string to be split. :param delimitador: The delimiter ...
[ "assert split_and_filter(\"a,b,c,d,e\", \",\") == [\"a\", \"b\", \"c\", \"d\", \"e\"]", "assert split_and_filter(\"a\\\\,b,c,d\\\\,e\", \",\") == [\"a,b\", \"c\", \"d,e\"]", "assert split_and_filter(\"a,b,c,,d,e\", \",\") == [\"a\", \"b\", \"c\", \"d\", \"e\"]", "assert split_and_filter(\"a,b,c,d,e,\", \",\")...
split_and_filter
def split_and_filter(elemento, delimitador):
0.3
generic
10cae4b52b4c1adf1860f229d983aa64
You are tasked with writing a Python script that processes a CSV file to compute the average of a specified column. Your script must accept two command-line arguments: the path to the CSV file and the name of the column for which the average should be calculated. The script should handle errors gracefully, such as miss...
import sys import csv def main(): """ Main function to read a CSV file and calculate the average of a specified column. Handles command-line arguments, file reading, and error checking. """ if len(sys.argv) != 3: sys.exit("Usage: python script.py <csv_file> <column_name>") csv_file_pat...
[ "assert main([\"script.py\", \"test.csv\", \"age\"]) == \"The average of column 'age' is: 30.0\"", "assert main([\"script.py\", \"nonexistent.csv\", \"age\"]) == \"Error: The file 'nonexistent.csv' does not exist.\"", "assert main([\"script.py\", \"test.csv\", \"invalid_column\"]) == \"Error: 'invalid_column' i...
main
def main():
1
generic
7e927206e8e88f182175d8b16cd97479
You are given a binary search tree (BST) with `n` nodes. Your task is to convert this BST into a balanced binary search tree (BBST). A balanced BST is defined as a binary search tree in which the depth of the two subtrees of every node never differs by more than one. **Input:** - The root of a binary search tree (BST...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def in_order_traversal(root, result): """ Perform an in-order traversal of the BST and store the values in a list. :param root: TreeNode, the root of the BST...
[ "assert bst_to_sorted_array_bbst(None) is None", "assert bst_to_sorted_array_bbst(TreeNode(1)).val == 1", "assert bst_to_sorted_array_bbst(TreeNode(1, TreeNode(2))).val == 2", "assert bst_to_sorted_array_bbst(TreeNode(1, None, TreeNode(2))).val == 1", "assert bst_to_sorted_array_bbst(TreeNode(1, None, TreeN...
bst_to_sorted_array_bbst
def bst_to_sorted_array_bbst(root):
0.5
algorithmic
8df66a47b8bba1a4439d0db780bd0113
Given a list of integers, your task is to implement a function that returns a new list containing the unique elements from the original list, sorted in ascending order. The input list can contain any integers and may have duplicates. **Input:** - A list of integers, `input_list`. **Output:** - A list of integers, con...
def unique_sorted_elements(input_list): """ Returns a new list containing the unique elements from the original list, sorted in ascending order. :param input_list: List of integers, which may contain duplicates. :return: List of unique integers, sorted in ascending order. """ return sorted(set(...
[ "assert unique_sorted_elements([4, 6, 2, 3, 2, 6, 8, 4, 1]) == [1, 2, 3, 4, 6, 8]", "assert unique_sorted_elements([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", "assert unique_sorted_elements([1, 1, 1, 1, 1, 1]) == [1]", "assert unique_sorted_elements([]) == []", "assert unique_sorte...
unique_sorted_elements
def unique_sorted_elements(input_list):
1
generic
cc39f7c93500840391f3f17391faea8e
You are tasked with implementing a function `generate_fibonacci_sequence` that generates the Fibonacci sequence up to the nth number. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Your function should return a list containing the Fib...
def generate_fibonacci_sequence(n): """ Generate the Fibonacci sequence up to the nth number. Parameters: n (int): The number of terms in the Fibonacci sequence to generate. Returns: list: A list containing the Fibonacci sequence up to the nth number. """ if n <= 0: return [] ...
[ "assert generate_fibonacci_sequence(1) == [0]", "assert generate_fibonacci_sequence(2) == [0, 1]", "assert generate_fibonacci_sequence(5) == [0, 1, 1, 2, 3]", "assert generate_fibonacci_sequence(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "assert generate_fibonacci_sequence(0) == []", "assert generate_fibo...
generate_fibonacci_sequence
def generate_fibonacci_sequence(n):
1
generic
cfc6b6e0ff61af95860ddff716a15a10
You are tasked with implementing a function `validate_email(email)` that determines if a given string is a valid email address based on the following criteria: - The email must start with a letter or a digit. - The local part (before the '@' symbol) can include letters, digits, dots ('.'), underscores ('_'), and hyphen...
import re def validate_email(email): """ Validates an email address according to the provided rules: - Starts with a letter or a digit - Can have letters, digits, dots, underscores, or hyphens in the local part - Must include an '@' symbol followed by a domain name - Domain name must only conta...
[ "assert validate_email(\"user@example.com\") == True", "assert validate_email(\"user.name@example.co\") == True", "assert validate_email(\"user_name@example.co.uk\") == True", "assert validate_email(\"user-name@example.com\") == True", "assert validate_email(\"user@sub-domain.example.com\") == True", "ass...
validate_email
def validate_email(email):
0.8
generic
16e26e29fb72c2b58edf672947666b11
You are given a string `s` that represents a comma-separated list of integers. Your task is to write a function `sum_of_integers` that computes the sum of these integers. If the string is empty or contains any non-integer values, the function should return 0. **Input:** - A single string `s` (0 ≤ len(s) ≤ 100). **Out...
def sum_of_integers(s): """ Computes the sum of integers in a comma-separated string. Parameters: s (str): A string representing a comma-separated list of integers. Returns: int: The sum of the integers if the string is valid, otherwise 0. """ try: parts = s.split(',') ...
[ "assert sum_of_integers(\"1, 2, 3, 4\") == 10", "assert sum_of_integers(\"10, 20, 30\") == 60", "assert sum_of_integers(\"1, a, 3, 4\") == 0", "assert sum_of_integers(\"1, 2, three, 4\") == 0", "assert sum_of_integers(\"\") == 0", "assert sum_of_integers(\"100\") == 100", "assert sum_of_integers(\"0, 0,...
sum_of_integers
def sum_of_integers(s):
1
generic
4f4b8ce4bd8e0ab8b57fb3bc6bedc9a2
You are given an array of integers. Your task is to determine whether there exists a contiguous subarray whose sum is zero. Implement the function `has_zero_sum_subarray` that accepts a list of integers and returns `True` if such a subarray exists, otherwise returns `False`. **Sample Input:** ``` [3, 4, -7, 3, 1, 3, 1...
def has_zero_sum_subarray(nums): """ Determines if there exists a contiguous subarray with a sum of zero. :param nums: List of integers :return: True if a zero-sum subarray exists, False otherwise """ cumulative_sum = 0 sum_set = set() for num in nums: cumulative_sum += num ...
[ "assert has_zero_sum_subarray([1, 2, 3, 4, 5]) == False", "assert has_zero_sum_subarray([1, 2, -3, 4, 5]) == True", "assert has_zero_sum_subarray([0, 1, 2, 3]) == True", "assert has_zero_sum_subarray([1, -1]) == True", "assert has_zero_sum_subarray([1, 2, 3, -6, 4]) == True", "assert has_zero_sum_subarray...
has_zero_sum_subarray
def has_zero_sum_subarray(nums):
0.9
generic
2fd9f3c6d32a22b80de11cd70e2a4051
You are participating in a coding competition where you need to develop a function to construct a query URL for a fictional API named "RedditSearchAPI". This API enables users to retrieve comments from a specified subreddit within a defined time range. Your task is to implement the function `generate_query_url` with t...
import urllib.parse def generate_query_url(subreddit: str, after: int, before: int, size: int = 1000, sort_by: str = 'score', sort_order: str = 'desc', include_selftext: bool = False) -> str: """ Generates a query URL for the RedditSearchAPI to search for comments within a specific subreddit and time frame. ...
[ "assert generate_query_url(\"python\", 1609459200, 1612137600) == \"https://api.redditsearchapi.com/comments/python?after=1609459200&before=1612137600&size=1000&sort_by=score&sort_order=desc&include_selftext=false\"", "assert generate_query_url(\"r/learnprogramming\", 1609459200, 1612137600) == \"https://api.redd...
generate_query_url
def generate_query_url(subreddit: str, after: int, before: int, size: int = 1000, sort_by: str = 'score', sort_order: str = 'desc', include_selftext: bool = False) -> str:
0.6
generic
7b2a15a3259afea93ec3363e17cc3896
You are tasked with writing a Python program to analyze a dataset stored in a text file. The file contains a list of integers, each on a new line. Your program should read the file, compute the mean, median, and mode of the integers, and output these statistics in the format "Mean: X, Median: Y, Mode: Z". Your program ...
import statistics def calculate_statistics(file_path): """ Reads a file containing integers, calculates the mean, median, and mode, and prints them. Handles file not found, empty file, and mode computation errors. :param file_path: Path to the file containing integers. """ try: wit...
[ "assert calculate_statistics('empty.txt') == None # Assuming 'empty.txt' is an empty file", "assert calculate_statistics('nonexistent.txt') == None # Assuming 'nonexistent.txt' does not exist", "assert calculate_statistics('single_number.txt') == None # Assuming 'single_number.txt' contains only one number, ...
calculate_statistics
def calculate_statistics(file_path):
1
generic
b902d7dbc52b317ca296d96b755e20bb
You are given a list of emails, where each email is a string containing the email body. Each email body may contain a reference number, which is always preceded by the phrase "number:" and followed by a newline character. Your task is to extract the reference number from each email and store it in a dictionary, where t...
import re def extract_reference_numbers(emails): """ Extracts reference numbers from a list of emails and stores them in a dictionary. Parameters: emails (list of str): A list of email strings where each string contains an email subject and body. Returns: dict: A dictionary with email...
[ "assert extract_reference_numbers([\"Subject 1\\nnumber: 12345\\n\"]) == {\"Subject 1\": \"12345\"}", "assert extract_reference_numbers([\"Short subject\\nnumber: 67890\\n\"]) == {\"Short subject\": \"67890\"}", "assert extract_reference_numbers([\"This is a very long subject that should be truncated\\nnumber: ...
extract_reference_numbers
def extract_reference_numbers(emails):
0.7
generic
ce3db4d97ea5698663f1be6441d26a9c
You are given a string `text` that may contain newline characters (`\n`), non-breaking spaces (`&nbsp;`), and horizontal tabs (`\t`). Your task is to implement a function `clean_text` that processes this string by replacing all occurrences of these characters with a single space. Additionally, any sequence of two or mo...
import re def clean_text(text): """ Cleans the input string by replacing newline characters, non-breaking spaces, and horizontal tabs with a single space. Also replaces sequences of two or more spaces with a single space and trims leading and trailing spaces. :param text: The input string to be cleane...
[ "assert clean_text(\"Hello\\nWorld\") == \"Hello World\"", "assert clean_text(\"Hello&nbsp;World\") == \"Hello World\"", "assert clean_text(\"Hello\\tWorld\") == \"Hello World\"", "assert clean_text(\"Hello\\n\\tWorld\") == \"Hello World\"", "assert clean_text(\"Hello&nbsp;\\tWorld\") == \"Hello World\"", ...
clean_text
def clean_text(text):
1
generic
98b9d1a9c5d1e9faeb73b906ca351f24
You are tasked with implementing a function `sanitize_filename` that processes a given string to create a filename compatible with both Unix and Windows operating systems. The function should perform the following operations in sequence: 1. Normalize the string to NFD form to ensure compatibility and remove any non-ess...
import re import unicodedata def sanitize_filename(filename): """ Sanitizes a given filename to ensure compatibility across Unix and Windows systems. Parameters: filename (str): The original filename to be sanitized. Returns: str: The sanitized filename. """ # Normalize to NFD...
[ "assert sanitize_filename(\"Hello World!\") == \"hello_world\"", "assert sanitize_filename(\" Leading and trailing spaces \") == \"leading_and_trailing_spaces\"", "assert sanitize_filename(\"Multiple___underscores___\") == \"multiple_underscores\"", "assert sanitize_filename(\"Special#$%^&*()Characters\") =...
sanitize_filename
def sanitize_filename(filename):
0.9
generic
6622b2dded6515e5fea49e9e7adfd6c5
You are given a list of strings, where each string represents a sentence. Your task is to implement a function that sorts these sentences based on the number of words they contain, in ascending order. The function should return a new list with the sentences sorted accordingly. **Input:** - A list of strings, where eac...
def sort_sentences_by_word_count(sentences): """ Sorts a list of sentences by the number of words in each sentence in ascending order. :param sentences: List of strings, where each string is a sentence. :return: List of strings sorted by the number of words in each sentence. """ sentences_with_...
[ "assert sort_sentences_by_word_count([\"The quick brown fox jumps over the lazy dog\", \"Hello world\", \"A\", \"Python is fun\"]) == [\"A\", \"Hello world\", \"Python is fun\", \"The quick brown fox jumps over the lazy dog\"]", "assert sort_sentences_by_word_count([\"One\", \"Two words\", \"Three words here\", \...
sort_sentences_by_word_count
def sort_sentences_by_word_count(sentences):
0.6
generic
9d214ce73390a3684a2a56160afd6895
You are given a string `brackets` consisting of various characters, including the following types of brackets: `(`, `)`, `[`, `]`, `{`, and `}`. Your task is to determine if the brackets in the string are balanced. A string of brackets is considered balanced if: - Each opening bracket has a corresponding closing bracke...
def balance_brackets(brackets: str) -> bool: """ Determines if the brackets in the given string are balanced. :param brackets: A string containing various characters, including brackets. :return: True if the brackets are balanced, False otherwise. """ stack = [] matching_bracket = {')':...
[ "assert balance_brackets(\"([])\") == True", "assert balance_brackets(\"([)]\") == False", "assert balance_brackets(\"{[()]}\") == True", "assert balance_brackets(\"{[()]}a\") == True", "assert balance_brackets(\"a{b[c(d)e]f}g\") == True", "assert balance_brackets(\"a{b[c(d)e]f}g)\") == False", "assert ...
balance_brackets
def balance_brackets(brackets: str) -> bool:
1
generic
85fbdbfa4262c78dd61464bbb6ec3f5f
You are tasked with solving a maze navigation problem. The maze is represented as a 2D grid of size `n x m`, where each cell is either `0` (indicating an open path) or `1` (indicating a wall). The player starts at the top-left corner `(0, 0)` and aims to reach the bottom-right corner `(n-1, m-1)`. The player can only m...
def find_path(maze): """ Finds a path from the top-left corner to the bottom-right corner of a maze. :param maze: A 2D list representing the maze where 0 is an open path and 1 is a wall. :return: A list of tuples representing the path from (0, 0) to (n-1, m-1), or None if no path exists. """ ...
[ "assert find_path([[0, 0], [0, 0]]) == [(0, 0), (0, 1), (1, 1)]", "assert find_path([[0, 1], [1, 0]]) == None", "assert find_path([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]", "assert find_path([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) == None", "assert find_path([[0]]) == [(0, 0...
find_path
def find_path(maze):
0.5
generic
4193fa8728b0f7060e625052aa79c525
You are given a nested dictionary representing a person's information, including their name, age, marital status, and a list of their children, each with their own name and age. Your task is to write a Python function `convert_to_json` that takes this dictionary as input and returns a JSON string formatted with an inde...
import json def convert_to_json(nested_dict): """ Converts a nested dictionary into a JSON string with an indentation of 4 spaces. Args: nested_dict (dict): A dictionary that may contain nested dictionaries or lists. Returns: str: A JSON string representing the input dictionary, forma...
[ "assert convert_to_json({\"key\": \"value\"}) == '{\\n \"key\": \"value\"\\n}'", "assert convert_to_json({\"nested\": {\"key\": \"value\"}}) == '{\\n \"nested\": {\\n \"key\": \"value\"\\n }\\n}'", "assert convert_to_json({\"list\": [1, 2, 3]}) == '{\\n \"list\": [\\n 1,\\n 2,\\...
convert_to_json
def convert_to_json(nested_dict):
1
generic
136a27c9969373f648c5ed2fe1a2c8e6
You are tasked with implementing a function `clean_text` that processes a given string `text`. The function should handle punctuation within words, such as apostrophes in contractions, and be capable of processing Unicode characters. The function should remove all punctuation except apostrophes within words, convert al...
import unicodedata import re def clean_text(text): """ Processes a given string by removing punctuation (except apostrophes within words), converting all characters to lowercase, and returning a list of words. :param text: A string containing Unicode characters. :return: A list of words with punct...
[ "assert clean_text(\"Hello, world!\") == ['hello', 'world']", "assert clean_text(\"It's a beautiful day.\") == [\"it's\", 'a', 'beautiful', 'day']", "assert clean_text(\"Isn't it?\") == [\"isn't\", 'it']", "assert clean_text(\"Hello, world! It's a beautiful day: isn't it?\") == [\"hello\", 'world', \"it's\", ...
clean_text
def clean_text(text):
0.9
generic
9772bca2beeefafeb8532c6a6b4b6d73
You are tasked with processing a large dataset of articles, each represented as a dictionary with keys 'title', 'content', 'source', and 'date'. Your goal is to implement a function `find_keyword_articles` that identifies articles where the keyword appears as a standalone word in either the title or the content. The fu...
from collections import OrderedDict import re def find_keyword_articles(articles, keyword, limit): """ Finds a specified number of articles that contain the keyword as a whole word in the title or content. Args: articles (list of dict): The dataset of articles. keyword (str): The keyword to se...
[ "assert find_keyword_articles([{'title': 'Keyword', 'content': 'No keyword here.', 'source': 'Source1', 'date': '2001'}], 'Keyword', 1) == OrderedDict([('article_0', {'title': 'Keyword', 'content': 'No keyword here.', 'source': 'Source1', 'date': '2001'})])", "assert find_keyword_articles([{'title': 'No keyword',...
find_keyword_articles
def find_keyword_articles(articles, keyword, limit):
0.8
generic
26b485a7bb314e2332dfb1aca8abcecd
You are given a string `expression` consisting of characters '(', ')', '{', '}', '[' and ']'. Your task is to determine if the string has balanced parentheses, brackets, and braces. A string is considered balanced if each opening symbol has a corresponding closing symbol and they are correctly nested. **Input:** - A s...
def is_balanced_parentheses(expression): """ Determines if the given string has balanced parentheses, brackets, and braces. :param expression: A string consisting of '(', ')', '{', '}', '[' and ']'. :return: True if the string is balanced, False otherwise. """ matching_bracket = {')': '(', '}':...
[ "assert is_balanced_parentheses(\"()[]{}\") == True", "assert is_balanced_parentheses(\"([)]\") == False", "assert is_balanced_parentheses(\"{[()]}\") == True", "assert is_balanced_parentheses(\"((()))\") == True", "assert is_balanced_parentheses(\"(()\") == False", "assert is_balanced_parentheses(\")(\")...
is_balanced_parentheses
def is_balanced_parentheses(expression):
1
generic
899b00d3ebe5f9ac2dd2e6d57047100b
You are tasked with implementing a function for text normalization, a crucial step in natural language processing. Your function, `normalize_text`, should accept a string and perform the following transformations: 1. Convert all characters to lowercase. 2. Trim any leading or trailing whitespace. 3. Replace sequences o...
import string def normalize_text(text): """ Normalize the input text by converting it to lowercase, trimming whitespace, replacing multiple spaces with a single space, removing punctuation, and tokenizing into a list of words. :param text: The input string to be normalized. :return: A list of ...
[ "assert normalize_text(\" Hello! This is an example. It has some punctuation, and multiple\tspaces. \") == ['hello', 'this', 'is', 'an', 'example', 'it', 'has', 'some', 'punctuation', 'and', 'multiple', 'spaces']", "assert normalize_text(\"Python, Programming; Language!\") == ['python', 'programming', 'langua...
normalize_text
def normalize_text(text):
1
generic
d53f78851b28ef76181b52dce618fa22
You are given a list of integers. Your task is to write a function `process_numbers` that processes this list in a functional style using functions and higher-order functions. The function should return a new list containing only the even numbers from the original list, each multiplied by 2. **Sample Input:** ```pytho...
def process_numbers(numbers): """ Processes a list of integers by filtering out even numbers and doubling them. :param numbers: List of integers to be processed. :return: A new list containing only the even numbers from the original list, each multiplied by 2. """ return list(map(lambda x: x * ...
[ "assert process_numbers([1, 2, 3, 4, 5]) == [4, 8]", "assert process_numbers([10, 15, 20, 25, 30]) == [20, 40, 60]", "assert process_numbers([0, 1, 2, 3, 4]) == [0, 4, 8]", "assert process_numbers([-2, -3, -4, -5]) == [-4, -8]", "assert process_numbers([]) == []", "assert process_numbers([7, 11, 13, 17]) ...
process_numbers
def process_numbers(numbers):
1
algorithmic
7fb2d5ab923bf475424a8e50700693a5
You are given a list of integers. Your task is to write a Python function that returns a new list containing only the prime numbers from the original list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. **Input:** - A list of integers `numbers` (1 ≤ len(numbers...
def is_prime(n): """Check if a number is prime.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def filt...
[ "assert filter_primes([2, 3, 5, 7, 11, 13]) == [2, 3, 5, 7, 11, 13]", "assert filter_primes([4, 6, 8, 9, 10, 12]) == []", "assert filter_primes([1, 0, -1, -3, -5]) == []", "assert filter_primes([17, 19, 23, 29, 31]) == [17, 19, 23, 29, 31]", "assert filter_primes([15, 21, 22, 25, 27, 28]) == []", "assert ...
filter_primes
def filter_primes(numbers):
1
algorithmic
c2228755208c96fd0c8aee39fbeee238
You are tasked with implementing a function `extract_emails` that processes a given string and extracts all valid email addresses. The function should be robust enough to handle various email formats, including those with subdomains, special characters, and multiple occurrences. Your solution should return a list of un...
import re def extract_emails(text): """ Extracts all unique email addresses from the given text. Parameters: text (str): The input string containing potential email addresses. Returns: list: A list of unique email addresses found in the input text. """ # Regular expression pattern for...
[ "assert extract_emails(\"john.doe@example.com\") == [\"john.doe@example.com\"]", "assert extract_emails(\"jane.doe@subdomain.example.co.uk\") == [\"jane.doe@subdomain.example.co.uk\"]", "assert extract_emails(\"admin@website.net\") == [\"admin@website.net\"]", "assert extract_emails(\"support@website.net\") =...
extract_emails
def extract_emails(text):
1
generic
a4a87cb8dcad2a78879cfc1b1db539ea
You are given an integer `n`. Your task is to determine whether `n` is a palindrome number. A palindrome number is defined as a number that reads the same backward as forward. **Input:** - The first line contains an integer `n` (0 ≤ n ≤ 10^9). **Output:** - Print `True` if `n` is a palindrome number, otherwise print...
def is_palindrome(number): """ Determines if the given number is a palindrome. Args: number (int): The number to check. Returns: bool: True if the number is a palindrome, False otherwise. """ num_str = str(number) return num_str == num_str[::-1] # Test the function with th...
[ "assert is_palindrome(12321) == True", "assert is_palindrome(8) == True", "assert is_palindrome(123) == False", "assert is_palindrome(1221) == True", "assert is_palindrome(10) == False", "assert is_palindrome(1) == True", "assert is_palindrome(1234321) == True", "assert is_palindrome(1001) == True", ...
is_palindrome
def is_palindrome(number):
1
generic
dd8a957c78d4c251d813cd11cd326f91
You are given a list of dictionaries, where each dictionary represents a product with its details. Each product has a unique product ID, name, and an optional sequence number. Your task is to sort this list of dictionaries based on the sequence number in ascending order. Products without a sequence number should be pla...
def sort_products_by_sequence(products): """ Sorts a list of product dictionaries by the 'sequence_number' key in ascending order. Products without a 'sequence_number' are placed at the beginning of the list. :param products: List of dictionaries, each representing a product with 'product_id', 'name', ...
[ "assert sort_products_by_sequence([{'product_id': 1, 'name': 'Laptop', 'sequence_number': 3}, {'product_id': 2, 'name': 'Mouse'}, {'product_id': 3, 'name': 'Keyboard', 'sequence_number': 1}, {'product_id': 4, 'name': 'Monitor', 'sequence_number': 2}, {'product_id': 5, 'name': 'USB Cable'}]) == [{'product_id': 2, 'n...
sort_products_by_sequence
def sort_products_by_sequence(products):
0.4
generic
ac420c2c45abe205fc6d7a0e615c465e
You are given the lengths of the three sides of a triangle. Your task is to determine the type of triangle based on these side lengths. The possible types are "Equilateral", "Isosceles", and "Scalene". If the given side lengths do not form a valid triangle, return "Invalid Triangle". A valid triangle must satisfy the t...
def classify_triangle(a, b, c): """ Determines the type of triangle based on the lengths of its sides. Parameters: a (int): Length of the first side of the triangle. b (int): Length of the second side of the triangle. c (int): Length of the third side of the triangle. Returns: ...
[ "assert classify_triangle(3, 3, 3) == \"Equilateral\"", "assert classify_triangle(3, 4, 5) == \"Scalene\"", "assert classify_triangle(5, 5, 8) == \"Isosceles\"", "assert classify_triangle(2, 2, 3) == \"Isosceles\"", "assert classify_triangle(1, 2, 3) == \"Invalid Triangle\"", "assert classify_triangle(10,...
classify_triangle
def classify_triangle(a, b, c):
1
generic
94524d127a18bf1d2e514eaf8562b4d7
In a machine learning training scenario, you are required to compute the total number of steps taken during the training process. The training process is governed by the number of epochs, the batch size, and the dataset size. The number of steps per epoch is dynamically determined by dividing the dataset size by the ba...
import math def calculate_total_steps(epochs, batch_size, dataset_size, min_epoch): """ Calculate the total number of steps taken during the training process. Parameters: - epochs (float): The number of epochs to calculate the total number of steps for. - batch_size (int): The size of each batch. ...
[ "assert calculate_total_steps(5, 32, 1024, 3) == 160", "assert calculate_total_steps(2, 64, 2048, 4) == 128", "assert calculate_total_steps(1.5, 16, 512, 2) == 64", "assert calculate_total_steps(0, 8, 100, 1) == 12", "assert calculate_total_steps(10, 10, 100, 5) == 100", "assert calculate_total_steps(3.75...
calculate_total_steps
def calculate_total_steps(epochs, batch_size, dataset_size, min_epoch):
0.9
generic
591079dc1c6b62d31b77e426bdb55425
You are a treasure hunter on a grid-based island. The island is represented as a 2D grid of size `N x M`, where each cell can contain either a treasure (represented by `1`), a pirate (represented by `2`), or nothing (represented by `0`). Your goal is to navigate through the island and collect as many treasures as possi...
def treasure_hunt(states, grid): """ Calculate the average score of the treasure hunt based on the given states and grid. :param states: List of tuples representing the coordinates of cells on the grid. :param grid: 2D list of integers representing the island grid. :return: Float representing t...
[ "assert treasure_hunt([(0, 0), (0, 1)], [[1, 2], [0, 0]]) == 0", "assert treasure_hunt([(0, 0), (1, 1)], [[1, 0], [0, 1]]) == 20", "assert treasure_hunt([(0, 0), (0, 0)], [[1, 0], [0, 0]]) == 10", "assert treasure_hunt([(1, 1), (1, 1)], [[0, 0], [0, 1]]) == 10", "assert treasure_hunt([(0, 0), (0, 1), (1, 0)...
treasure_hunt
def treasure_hunt(states, grid):
0.6
generic
66697f1880450c5c77e21d63a6cf9fa0
You are given a list of sentences and a maximum sentence length. Your task is to write a function `filter_long_sentences` that returns a list of sentences whose lengths do not exceed the specified maximum length. **Input:** - A list of strings `sentences` where each string is a sentence. - An integer `max_length` rep...
from typing import List def filter_long_sentences(sentences: List[str], max_length: int) -> List[str]: """ Filters out sentences longer than the specified maximum length. Parameters: sentences (List[str]): A list of sentences. max_length (int): The maximum allowed length of a sentence. Return...
[ "assert filter_long_sentences([\"Hello world\", \"This is a longer sentence\"], 10) == [\"Hello world\"]", "assert filter_long_sentences([\"Short\", \"Tiny\", \"Bit\"], 4) == [\"Bit\"]", "assert filter_long_sentences([\"Equal length\", \"Equal length\"], 12) == [\"Equal length\", \"Equal length\"]", "assert f...
filter_long_sentences
def filter_long_sentences(sentences: List[str], max_length: int) -> List[str]:
0.6
generic
bffba8ee578dace972938aa00db3f406
You are given a list of integers `nums` containing `n-1` distinct integers in the range from 1 to `n`. Your task is to find and return the missing integer from the sequence. **Input:** - A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer is in the range from 1 to n, and exactly one integer is missing...
def find_missing_number(nums): """ Finds the missing number in a list of integers from 1 to n with one number missing. :param nums: List[int] - A list of integers from 1 to n with one number missing. :return: int - The missing number in the sequence. """ n = len(nums) + 1 expected_sum = n *...
[ "assert find_missing_number([1, 2, 3, 4, 6]) == 5", "assert find_missing_number([1, 3, 4, 5, 6]) == 2", "assert find_missing_number([2, 3, 4, 5, 6]) == 1", "assert find_missing_number([1, 2, 3, 4, 5, 7]) == 6", "assert find_missing_number([1, 2, 4, 5, 6, 7, 8]) == 3", "assert find_missing_number([1, 2, 3,...
find_missing_number
def find_missing_number(nums):
1
generic
7a64948d3a22c4a7f71a896ef3f99f6f
You are given a JSON object and a target key. Your task is to implement a function `find_key_value(json_obj, key)` that recursively traverses the JSON object to locate the value associated with the target key. If the key is not present in the JSON object, the function should return `None`. The JSON object can contain n...
def find_key_value(json_obj, key): """ Recursively traverses a JSON object to find the value associated with a given key. Parameters: json_obj (dict, list, or primitive): The JSON object to search within. key (str): The key to search for. Returns: The value associated with the key ...
[ "assert find_key_value({\"name\": \"John\", \"age\": 30, \"address\": {\"city\": \"New York\", \"zipcode\": \"10001\"}}, \"city\") == \"New York\"", "assert find_key_value({\"name\": \"John\", \"age\": 30, \"address\": {\"city\": \"New York\", \"zipcode\": \"10001\"}}, \"zipcode\") == \"10001\"", "assert find_k...
find_key_value
def find_key_value(json_obj, key):
1
generic
6d1a97ede3b847325c83bd4bbbeae1fb
You are given a list of strings `outer_s` and a delimiter `outersep`. Implement a function `chain_strings` that processes and joins the strings in `outer_s` using the `outersep` delimiter according to the following rules: - Discard any string in `outer_s` that is empty after stripping leading and trailing whitespace a...
import re def chain_strings(outer_s, outersep): """ Joins a list of strings using a specified delimiter after processing. Parameters: outer_s (list of str): The list of strings to be processed and joined. outersep (str): The delimiter to use between non-empty, processed strings. Retur...
[ "assert chain_strings([\" hello \", \"world!\", \" \", \"Python3.8\", \"code!\"], \"-\") == \"helloworldPython38code\"", "assert chain_strings([\" \", \" \", \" \"], \"-\") == \"\"", "assert chain_strings([], \"-\") == \"\"", "assert chain_strings([\"abc\", \"def\", \"ghi\"], \",\") == \"abc,def,ghi\"",...
chain_strings
def chain_strings(outer_s, outersep):
0.8
generic
5f7a47a03310eac32a2ba1acbf38006f
You are given a string `word` consisting of alphabetic characters. Your task is to implement a function `count_vowels(word)` that returns the number of vowels in the string. Vowels are defined as the characters 'a', 'e', 'i', 'o', 'u' and their uppercase equivalents. **Input:** - A single string `word` (1 ≤ |word| ≤ ...
def count_vowels(word): """ Counts the number of vowels in the given word. Parameters: word (str): The input string consisting of alphabetic characters. Returns: int: The number of vowels in the input string. """ vowels = "aeiouAEIOU" return sum(1 for char in word if char i...
[ "assert count_vowels(\"hello\") == 2", "assert count_vowels(\"HELLO\") == 2", "assert count_vowels(\"rhythm\") == 0", "assert count_vowels(\"aeiou\") == 5", "assert count_vowels(\"AEIOU\") == 5", "assert count_vowels(\"bcd\") == 0", "assert count_vowels(\"Python\") == 1", "assert count_vowels(\"Quick\...
count_vowels
def count_vowels(word):
1
generic
41e7a2eaacb8dafde98f79e4aeb10086
You are given an array of integers `nums`. Your task is to construct an array `result` such that `result[i]` is the product of all elements in `nums` except `nums[i]`. If `nums` contains zeros, the product at indices where `nums[i]` is zero should be the product of all non-zero elements, and the product at other indice...
def product_except_self(nums): """ Constructs an array where each element at index i is the product of all elements in the input array except the element at index i. Handles zeros appropriately. :param nums: List[int] - The input list of integers. :return: List[int] - The resulting list of prod...
[ "assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6]", "assert product_except_self([0, 1, 2, 3]) == [6, 0, 0, 0]", "assert product_except_self([1, 0, 2, 3]) == [0, 6, 0, 0]", "assert product_except_self([1, 2, 0, 3]) == [0, 0, 6, 0]", "assert product_except_self([1, 2, 3, 0]) == [0, 0, 0, 6]", "ass...
product_except_self
def product_except_self(nums):
0.9
generic
7706cf6cf08edd21160311030ffeee8b
You are given a string `s`. Your task is to write a function `filter_non_alphanumeric` that processes this string and returns a new string containing only the alphanumeric characters from the original string. Alphanumeric characters are defined as letters (both uppercase and lowercase) and digits. **Input:** - A singl...
def filter_non_alphanumeric(input_string): """ Removes all non-alphanumeric characters from the input string. Parameters: input_string (str): The string to be processed. Returns: str: A new string containing only the alphanumeric characters from the input string. """ return ''.join(cha...
[ "assert filter_non_alphanumeric(\"Hello, World!\") == \"HelloWorld\"", "assert filter_non_alphanumeric(\"Python3.8\") == \"Python38\"", "assert filter_non_alphanumeric(\"!@#$%^&*()\") == \"\"", "assert filter_non_alphanumeric(\"1234567890\") == \"1234567890\"", "assert filter_non_alphanumeric(\"abcDEF\") ==...
filter_non_alphanumeric
def filter_non_alphanumeric(input_string):
1
generic
081592126ad954c0f28e7bb76189b784
You are tasked with implementing a function `get_file_info` that processes a given file name and returns a dictionary with specific details about the file. The function should extract the file extension, determine the MIME type based on the extension, calculate the file size in bytes, and count the number of lines if t...
import os def get_file_info(file_name): """ Returns a dictionary containing the file extension, MIME type, file size in bytes, and the number of lines in the file if it is a text-based file. :param file_name: The name of the file as a string. :return: A dictionary with keys 'extension', 'mime_type...
[ "assert get_file_info('test.txt') == {'extension': '.txt', 'mime_type': 'text/plain', 'size': 10, 'line_count': 1}", "assert get_file_info('image.png') == {'extension': '.png', 'mime_type': 'image/png', 'size': 20, 'line_count': None}", "assert get_file_info('document.pdf') == {'extension': '.pdf', 'mime_type':...
get_file_info
def get_file_info(file_name):
0.3
generic
65adfeed462c4cc3ce5ee326c1564658
You are given a string `s`. Your task is to implement a function `capitalize_words` that processes this string and returns a new string where the first letter of each word is capitalized, and all other letters are in lowercase. Words are defined as sequences of alphabetic characters separated by non-alphabetic characte...
def capitalize_words(s): """ Capitalizes the first letter of each word in the given string `s`. Parameters: s (str): The input string to be processed. Returns: str: A new string with the first letter of each word capitalized and the rest in lowercase. """ result = [] capita...
[ "assert capitalize_words(\"hello world\") == \"Hello World\"", "assert capitalize_words(\"python is fun!\") == \"Python Is Fun!\"", "assert capitalize_words(\"HELLO\") == \"Hello\"", "assert capitalize_words(\"\") == \"\"", "assert capitalize_words(\"a\") == \"A\"", "assert capitalize_words(\"123abc\") ==...
capitalize_words
def capitalize_words(s):
1
generic
12d4aa4183b4c0a110a022d20a6c835a
You are given two strings `str1` and `str2`. Your task is to write a function that finds the longest common subsequence (LCS) between these two strings. The function should return the LCS as a string. If there are multiple LCSs of the same length, return any one of them. **Input:** - Two strings `str1` and `str2` (1 ≤...
def longest_common_subsequence(str1, str2): """ Finds the longest common subsequence between two strings. Parameters: str1 (str): The first string. str2 (str): The second string. Returns: str: The longest common subsequence. """ m = len(str1) n = len(str2) L = [[0] * (n + 1...
[ "assert longest_common_subsequence(\"AGGTAB\", \"GXTXAYB\") == \"GTAB\"", "assert longest_common_subsequence(\"ABC\", \"AC\") == \"AC\"", "assert longest_common_subsequence(\"ABCBDAB\", \"BDCAB\") == \"BCAB\"", "assert longest_common_subsequence(\"XMJYAUZ\", \"MZJAWXU\") == \"MJAU\"", "assert longest_common...
longest_common_subsequence
def longest_common_subsequence(str1, str2):
0.9
generic
27ddda137f760deb9d0805efde95cfb4
You are given two vectors represented as dictionaries, where keys are dimension names and values are the corresponding feature values. The vectors may contain missing values represented by `None`. Your task is to compute the Manhattan distance between these two vectors, ignoring any dimensions that contain `None` in ei...
def compute_manhattan_distance(v1, v2): """ Computes the Manhattan distance between two vectors represented as dictionaries. Parameters: v1 (dict): The first vector. v2 (dict): The second vector. Returns: int: The Manhattan distance between the two vectors, ignoring dimensions with...
[ "assert compute_manhattan_distance({'x': 1, 'y': 2}, {'x': 4, 'y': 5}) == 6", "assert compute_manhattan_distance({'x': 1, 'y': 2, 'z': 3}, {'x': 4, 'y': 5, 'z': 6}) == 9", "assert compute_manhattan_distance({'x': 1, 'y': None}, {'x': 4, 'y': 5}) == 3", "assert compute_manhattan_distance({'x': None, 'y': 2}, {...
compute_manhattan_distance
def compute_manhattan_distance(v1, v2):
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

  • 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 > 0.2: 55,590
  • 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
40