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 (` `), 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 World\") == \"Hello World\"",
"assert clean_text(\"Hello\\tWorld\") == \"Hello World\"",
"assert clean_text(\"Hello\\n\\tWorld\") == \"Hello World\"",
"assert clean_text(\"Hello \\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 |
1db47278dd3c338ccf076584a1d0443e | You are given a sorted array of integers, `arr`, and a target integer, `goal`. Your task is to find the index of the first occurrence of `goal` in `arr` using an iterative binary search algorithm. If `goal` does not exist in `arr`, return `-1`. Ensure that your algorithm performs no more than `log2(n) + 1` comparisons,... | def find_first_occurrence(arr, goal):
"""
Finds the index of the first occurrence of the target integer `goal` in the sorted array `arr`.
If `goal` is not present in `arr`, returns -1.
:param arr: List[int] - A sorted list of integers.
:param goal: int - The target integer to find.
:return:... | [
"assert find_first_occurrence([1, 2, 3, 3, 4, 5], 3) == 2",
"assert find_first_occurrence([1, 2, 3, 3, 4, 5], 1) == 0",
"assert find_first_occurrence([1, 2, 3, 3, 4, 5], 5) == 5",
"assert find_first_occurrence([1, 2, 3, 3, 4, 5], 6) == -1",
"assert find_first_occurrence([1, 2, 3, 3, 4, 5], 0) == -1",
"ass... | find_first_occurrence | def find_first_occurrence(arr, goal): | 1 | generic |
6daf86a567d8ae8f971f4f07498e4aeb | You are given a string `text`. Your task is to implement a function `count_words` that returns the number of words in the string. Words are defined as sequences of characters separated by whitespace (spaces, tabs, newlines).
**Input:**
- A single string `text` (1 ≤ len(text) ≤ 10^5).
**Output:**
- An integer represe... | def count_words(text):
"""
Counts the number of words in the given string.
Parameters:
text (str): The input string.
Returns:
int: The number of words in the string.
"""
# Split the string into words using whitespace as the delimiter
words = text.split()
# Return the nu... | [
"assert count_words(\"Hello, World! This is a test.\") == 6",
"assert count_words(\" Leading and trailing spaces \") == 4",
"assert count_words(\"Multiple spaces between words\") == 4",
"assert count_words(\"\") == 0",
"assert count_words(\"OneWord\") == 1",
"assert count_words(\"New\\nLine\\nChar... | count_words | def count_words(text): | 0.9 | generic |
e66eed867e0f9b42ce9bee6a16033293 | You are given a string `s`. Your task is to write a function `generate_palindrome` that constructs the shortest palindrome by appending characters to the end of `s`. The function should handle edge cases such as an empty string or a string that is already a palindrome.
**Input:**
- A single string `s` (0 ≤ |s| ≤ 1000)... | def generate_palindrome(s: str) -> str:
"""
Constructs the shortest palindrome by appending characters to the end of the input string `s`.
:param s: Input string
:return: Shortest palindrome formed by appending characters to `s`
"""
if s == s[::-1]: # Check if the input string is already a... | [
"assert generate_palindrome(\"race\") == \"racecar\"",
"assert generate_palindrome(\"abba\") == \"abba\"",
"assert generate_palindrome(\"\") == \"\"",
"assert generate_palindrome(\"a\") == \"a\"",
"assert generate_palindrome(\"ab\") == \"aba\"",
"assert generate_palindrome(\"abc\") == \"abcba\"",
"asser... | generate_palindrome | def generate_palindrome(s: str) -> str: | 0.9 | generic |
c457b3dc0932353837b1a91e81cc916f | You are given a list of functions, `func_list`, where each function takes a single argument `x` and returns a float. Implement the function `total_obj_f(x, func_list)` that first sorts the functions in `func_list` based on their output values at a fixed point `a=0`, and then returns the sum of the outputs of all functi... | def total_obj_f(x, func_list):
"""
Sorts the functions in `func_list` based on their output values at a fixed point `a=0`,
and returns the sum of the outputs of all functions in the sorted list when evaluated at `x`.
:param x: A float representing the point at which the functions should be evaluated.
... | [
"assert total_obj_f(1, [lambda x: x, lambda x: x**2, lambda x: x+1]) == 3",
"assert total_obj_f(2, [lambda x: x, lambda x: x**2, lambda x: x+1]) == 8",
"assert total_obj_f(0, [lambda x: x, lambda x: x**2, lambda x: x+1]) == 1",
"assert total_obj_f(-1, [lambda x: x, lambda x: x**2, lambda x: x+1]) == 1",
"as... | total_obj_f | def total_obj_f(x, func_list): | 0.4 | generic |
778659ba175cb562f4e747c7ea5bf17c | You are given a task to implement a function that converts a distance in meters to degrees of latitude at a specified latitude. The conversion factor varies linearly from 110,574 meters per degree at the equator (0 degrees latitude) to 111,694 meters per degree at the poles (90 degrees latitude). Your function should t... | def meters_to_degrees_of_latitude(meters, latitude):
"""
Converts a distance in meters to degrees of latitude at a specified latitude.
Parameters:
meters (float or int): The distance in meters.
latitude (float or int): The latitude at which the conversion should be calculated.
Returns:... | [
"assert meters_to_degrees_of_latitude(110574, 0) == 1.0",
"assert meters_to_degrees_of_latitude(111694, 90) == 1.0",
"assert meters_to_degrees_of_latitude(111694, -90) == 1.0",
"assert meters_to_degrees_of_latitude(0, 0) == 0.0",
"assert meters_to_degrees_of_latitude(55287, 0) == 0.5",
"assert meters_to_d... | meters_to_degrees_of_latitude | def meters_to_degrees_of_latitude(meters, latitude): | 0.8 | generic |
ee4d524a9914905a1daecad9ad161224 | You are given a nested dictionary `data`. Your task is to implement a function `flatten_dict` that transforms this nested dictionary into a single-level dictionary. The keys in the resulting dictionary should be formed by concatenating the keys from the original dictionary, separated by underscores. For example, if the... | def flatten_dict(data, parent_key='', sep='_'):
"""
Flattens a nested dictionary into a single-level dictionary.
Parameters:
- data (dict): The nested dictionary to flatten.
- parent_key (str): The base key string for recursion (default is an empty string).
- sep (str): The separator to use... | [
"assert flatten_dict({'a': {'b': {'c': 1, 'd': 2}}, 'e': 3}) == {'a_b_c': 1, 'a_b_d': 2, 'e': 3}",
"assert flatten_dict({'x': 1, 'y': {'z': 2}}) == {'x': 1, 'y_z': 2}",
"assert flatten_dict({'level1': {'level2': {'level3': {'level4': 5}}}}) == {'level1_level2_level3_level4': 5}",
"assert flatten_dict({}) == {... | flatten_dict | def flatten_dict(data, parent_key='', sep='_'): | 0.8 | generic |
279a695b9766c144685b72bdf2a84398 | You are given a list of dictionaries, where each dictionary contains information about a person with keys `name`, `age`, and `gender`. Your task is to implement a function that filters out people who are at least a specified age and returns a list of these people along with the count of such individuals.
**Input:**
- ... | def filter_people_by_age(people, min_age):
"""
Filters people by a minimum age and returns a list of those who meet the criteria along with the count.
:param people: List of dictionaries, each containing 'name', 'age', and 'gender' keys.
:param min_age: Integer representing the minimum age to filter by... | [
"assert filter_people_by_age([{\"name\": \"Alice\", \"age\": 25, \"gender\": \"Female\"}, {\"name\": \"Bob\", \"age\": 20, \"gender\": \"Male\"}, {\"name\": \"Charlie\", \"age\": 30, \"gender\": \"Male\"}], 25) == ([{\"name\": \"Alice\", \"age\": 25, \"gender\": \"Female\"}, {\"name\": \"Charlie\", \"age\": 30, \"g... | filter_people_by_age | def filter_people_by_age(people, min_age): | 1 | generic |
06eb74383256179ab69d8c6fd9389a77 | You are given an array of integers `numbers` and an integer `target`. Your task is to find the indices of the two distinct elements in `numbers` that sum up to `target`. It is guaranteed that there is exactly one solution, and you cannot use the same element twice. Return the indices as a tuple `(index1, index2)` where... | def two_sum(numbers, target):
"""
Finds two distinct indices in the list 'numbers' such that the numbers at those indices add up to 'target'.
:param numbers: List of integers.
:param target: Integer representing the target sum.
:return: Tuple of two integers representing the indices of the two ... | [
"assert two_sum([2, 7, 11, 15], 9) == (0, 1)",
"assert two_sum([3, 2, 4], 6) == (1, 2)",
"assert two_sum([3, 3], 6) == (0, 1)",
"assert two_sum([1, 2, 3, 4, 5], 8) == (2, 4)",
"assert two_sum([10, 15, 3, 7], 17) == (0, 2)",
"assert two_sum([1, 5, 7, -1], 6) == (0, 3)",
"assert two_sum([0, 4, 3, 0], 0) =... | two_sum | def two_sum(numbers, target): | 0.8 | generic |
bffcefe39b10cb74abff02d5a84f3886 | You are given a non-negative integer `n`. Your task is to determine the index of the most significant bit (MSB) that is set to 1 in the binary representation of `n`. The least significant bit (LSB) is considered to be at index 0. If `n` is 0, return -1.
**Constraints:**
- 0 ≤ n ≤ 10^9
**Sample Input:**
```
18
```
**... | def find_highest_bit(n):
"""
Returns the index of the highest bit set to 1 in the binary representation of n.
If n is 0, returns -1.
:param n: Integer, the number to find the highest bit for.
:return: Integer, the index of the highest bit set to 1, or -1 if n is 0.
"""
if n == 0:
... | [
"assert find_highest_bit(0) == -1",
"assert find_highest_bit(1) == 0",
"assert find_highest_bit(2) == 1",
"assert find_highest_bit(3) == 1",
"assert find_highest_bit(4) == 2",
"assert find_highest_bit(5) == 2",
"assert find_highest_bit(10) == 3",
"assert find_highest_bit(15) == 3",
"assert find_high... | find_highest_bit | def find_highest_bit(n): | 0.4 | generic |
f99ae8b59f451868d1ba7072f7698a5a | You are given a sequence of temperature readings taken at regular intervals. Each reading is represented as a tuple containing a timestamp (in milliseconds) and a temperature (in Celsius). Your task is to compute the rate of temperature change (in Celsius per second) between each consecutive pair of readings. Implement... | def calculate_rates_helper(timestamps, temperatures, index, result):
"""
Helper function to recursively calculate the rate of temperature change.
:param timestamps: List of timestamps in milliseconds.
:param temperatures: List of temperature readings in Celsius.
:param index: Current index in the l... | [
"assert calculate_rates([(0, 20.0), (1000, 22.0)]) == [2.0]",
"assert calculate_rates([(0, 20.0), (1000, 20.0)]) == [0.0]",
"assert calculate_rates([(0, 20.0), (1000, 18.0)]) == [-2.0]",
"assert calculate_rates([(0, 20.0), (1000, 22.0), (2000, 21.0)]) == [2.0, -1.0]",
"assert calculate_rates([(0, 20.0), (10... | calculate_rates | def calculate_rates(data): | 0.9 | generic |
97f9074e7a99fc86252daa6d15cc0def | You are given a list of file paths, each representing a genomic data file. These files can be of different types, such as `.bam`, `.fasta`, `.fastq`, etc. Your task is to write a function `generate_index_paths` that takes this list of file paths as input and returns a new list containing the corresponding index file pa... | import os
def generate_index_paths(file_paths):
"""
Generate a list of index file paths corresponding to the given genomic data file paths.
Parameters:
file_paths (list of str): A list of file paths for genomic data files.
Returns:
list of str: A list of index file paths.
"""
... | [
"assert generate_index_paths(['data/sample.bam']) == ['data/sample.bai']",
"assert generate_index_paths(['data/genome.fasta']) == ['data/genome.fai']",
"assert generate_index_paths(['data/sample.fastq']) == ['data/sample.idx']",
"assert generate_index_paths(['data/sample.bam', 'data/genome.fasta', 'data/sampl... | generate_index_paths | def generate_index_paths(file_paths): | 1 | generic |
8354d124699967e88019f0199f034a59 | You are given an integer `number` with up to 18 digits. Implement the function `count_digits(number)` that returns the count of distinct digits in `number` that appear an odd number of times.
**Input:**
- An integer `number` (0 ≤ number ≤ 10^18).
**Output:**
- An integer representing the count of digits that appear a... | def count_digits(number):
"""
Counts the number of distinct digits in the given number that appear an odd number of times.
:param number: An integer with up to 18 digits.
:return: An integer representing the count of digits that appear an odd number of times.
"""
num_str = str(number)
digit... | [
"assert count_digits(1122334455667788990011) == 0",
"assert count_digits(1234567890) == 10",
"assert count_digits(12233344445) == 3",
"assert count_digits(0) == 1",
"assert count_digits(111111111111111111) == 0",
"assert count_digits(9876543210) == 10",
"assert count_digits(100000000000000000) == 1",
... | count_digits | def count_digits(number): | 0.8 | generic |
2a9201e0124704b8f79148c11a9b448c | You are given a dictionary representing students and their respective grades. Your task is to compute the average grade for each student and return a new dictionary with the same keys but with the average grades as values. If a student has no grades, their average should be considered as 0.0.
**Input:**
- A dictionary... | def calculate_average_grades(students):
"""
Calculate the average grades for a dictionary of students with their grades.
Args:
students (dict): A dictionary where keys are student names and values are lists of grades.
Returns:
dict: A dictionary with students' names as keys and their average g... | [
"assert calculate_average_grades({\"Alice\": [85, 90, 78], \"Bob\": [92, 88, 90], \"Charlie\": [75, 80, 85]}) == {\"Alice\": 84.33333333333333, \"Bob\": 90.0, \"Charlie\": 80.0}",
"assert calculate_average_grades({\"Alice\": [100, 100, 100], \"Bob\": [50, 50, 50]}) == {\"Alice\": 100.0, \"Bob\": 50.0}",
"assert... | calculate_average_grades | def calculate_average_grades(students): | 0.9 | generic |
3fd6bd0af4bdc8becc060caf564aa24d | You are tasked with implementing a function `create_range_query` for a search engine API that supports range queries. The API expects range queries to be formatted as `{start_val :<= field :<= end_value}`. Your function should generate and return a string in this format given the `start_val` and `end_value` as input.
... | def create_range_query(start_val: str, end_value: str) -> str:
"""
Generates a range query string for a search engine API in the format
{start_val :<= field :<= end_value}.
Parameters:
start_val (str): The starting value of the range.
end_value (str): The ending value of the range.
Returns... | [
"assert create_range_query(\"10\", \"20\") == \"{10 :<= field :<= 20}\"",
"assert create_range_query(\"0\", \"100\") == \"{0 :<= field :<= 100}\"",
"assert create_range_query(\"-5\", \"5\") == \"{-5 :<= field :<= 5}\"",
"assert create_range_query(\"1.5\", \"2.5\") == \"{1.5 :<= field :<= 2.5}\"",
"assert cr... | create_range_query | def create_range_query(start_val: str, end_value: str) -> str: | 0.9 | generic |
6b35e98a44e81083756a06199b87e829 | You are given a list of 3D points in a Cartesian coordinate system, where each point is represented as a tuple (x, y, z). Your task is to determine the smallest cuboid (bounding box) that can enclose all the given points. The bounding box should be represented as a dictionary with keys 'min_x', 'max_x', 'min_y', 'max_y... | def get_bounding_box(points):
"""
Determines the smallest cuboid (bounding box) that can enclose all the given 3D points.
Args:
points (list of tuples): A list where each tuple represents a 3D point (x, y, z).
Returns:
dict or None: A dictionary with keys 'min_x', 'max_x', 'min_y', 'ma... | [
"assert get_bounding_box([(1, 2, 3), (4, 5, 6), (7, 8, 9)]) == {'min_x': 1, 'max_x': 7, 'min_y': 2, 'max_y': 8, 'min_z': 3, 'max_z': 9}",
"assert get_bounding_box([(0, 0, 0), (1, 1, 1), (2, 2, 2)]) == {'min_x': 0, 'max_x': 2, 'min_y': 0, 'max_y': 2, 'min_z': 0, 'max_z': 2}",
"assert get_bounding_box([(-1, -2, -... | get_bounding_box | def get_bounding_box(points): | 0.9 | generic |
b9fed2ea40e13838dd398af5633d17f1 | You are given a list of integers. Implement a function `calculate_statistics(numbers)` that computes and returns a dictionary with the following statistical measures: mean, median, mode(s), and range. If the input list is empty, the function should return `None` for each statistic.
**Input:**
- A list of integers `num... | from collections import Counter
def calculate_statistics(numbers):
"""
Calculate statistical measures for a list of numbers.
Parameters:
numbers (list): A list of integers.
Returns:
dict: A dictionary containing the mean, median, mode(s), and range of the numbers.
If the list is emp... | [
"assert calculate_statistics([1, 2, 3, 4, 5]) == {'mean': 3.0, 'median': 3, 'mode': [1, 2, 3, 4, 5], 'range': 4}",
"assert calculate_statistics([1, 1, 2, 2, 3, 3]) == {'mean': 2.0, 'median': 2, 'mode': [1, 2, 3], 'range': 2}",
"assert calculate_statistics([7, 8, 9]) == {'mean': 8.0, 'median': 8, 'mode': [7, 8, ... | calculate_statistics | def calculate_statistics(numbers): | 0.9 | generic |
2fc9b55ec53a871c0db7c0ee0f3db649 | You are developing a system for generating filenames for medical imaging data. The filenames must be constructed from three components: the imaging modality, the patient identifier, and the file extension. The system supports four predefined modalities: 'MRI', 'CT', 'PET', and 'XRAY'. The patient identifier is a string... | def generate_filename(modality, patient_id, file_extension='.img', additional_modalities=None):
"""
Generates a filename for a specific type of medical imaging data.
Parameters:
- modality: The name of the medical imaging modality.
- patient_id: The unique identifier of the patient, a string of 6 a... | [
"assert generate_filename('MRI', 'A1B2C3') == 'MRI_A1B2C3.img'",
"assert generate_filename('CT', 'X9Y8Z7', '.dat') == 'CT_X9Y8Z7.dat'",
"assert generate_filename('PET', '123456', '.raw') == 'PET_123456.raw'",
"assert generate_filename('XRAY', 'ABCDEF', '.bin') == 'XRAY_ABCDEF.bin'",
"assert generate_filenam... | generate_filename | def generate_filename(modality, patient_id, file_extension='.img', additional_modalities=None): | 0.8 | generic |
70b6ef72483e5c9f4d2632208292c989 | You are tasked with implementing a URL validator. A URL is considered valid if it meets the following conditions:
- It starts with either "http://" or "https://".
- It contains a domain name with at least one dot.
- It does not contain any spaces.
- It does not contain any of the following invalid characters: `<`, `>`,... | import re
def validate_url(url):
"""
Validates a URL based on specific criteria:
- Starts with "http://" or "https://".
- Contains a domain name with at least one dot.
- Does not contain spaces.
- Does not contain invalid characters: <, >, {, }, |, \, ^, `, ~, [, ], ;, :, ', ,, ), (, /, ?, #, @... | [
"assert validate_url(\"http://example.com\") == True",
"assert validate_url(\"https://example.co.uk\") == True",
"assert validate_url(\"ftp://example.com\") == False",
"assert validate_url(\"http://example\") == False",
"assert validate_url(\"http://example .com\") == False",
"assert validate_url(\"http:/... | validate_url | def validate_url(url): | 0.8 | generic |
b1cd0b5de689ae1967bffbf151e36202 | You are given a list of tuples, where each tuple consists of a student's name and their grade in a class. Your task is to write a Python function `sort_students_by_grade` that sorts this list in descending order based on the grades.
**Input:**
- A list of tuples, where each tuple contains a string (student's name) an... | def sort_students_by_grade(students_grades):
"""
Sorts a list of (student_name, grade) tuples in descending order by grade.
Parameters:
students_grades (list of tuple): A list where each tuple contains a student name and their grade as (name, grade)
Returns:
list of tuple: Sorted list of tuple... | [
"assert sort_students_by_grade([(\"Alice\", 88), (\"Bob\", 95), (\"Charlie\", 70), (\"David\", 90)]) == [(\"Bob\", 95), (\"David\", 90), (\"Alice\", 88), (\"Charlie\", 70)]",
"assert sort_students_by_grade([(\"Anna\", 100), (\"Tom\", 100), (\"John\", 99)]) == [(\"Anna\", 100), (\"Tom\", 100), (\"John\", 99)]",
... | sort_students_by_grade | def sort_students_by_grade(students_grades): | 1 | generic |
5892637866a93ce9141c7d09a84c8c3d | You are given a string `s` containing a sequence of words separated by spaces. Your task is to implement a function `count_words` that processes this string and returns a dictionary. The dictionary should have unique words from the string as keys and their respective counts as values. The function should be case-insens... | import string
def count_words(sentence: str) -> dict:
"""
Counts the occurrences of each unique word in a given sentence, ignoring case and punctuation.
:param sentence: A string containing words separated by spaces.
:return: A dictionary with words as keys and their counts as values.
"""
... | [
"assert count_words(\"Hello world!\") == {\"hello\": 1, \"world\": 1}",
"assert count_words(\"Python, Python, Python!\") == {\"python\": 3}",
"assert count_words(\"A quick brown fox jumps over the lazy dog.\") == {\"a\": 1, \"quick\": 1, \"brown\": 1, \"fox\": 1, \"jumps\": 1, \"over\": 1, \"the\": 1, \"lazy\":... | count_words | def count_words(sentence: str) -> dict: | 0.9 | generic |
c08807e1bacdb43cb8291778660dd947 | You are given a list of strings, where each string may contain a mix of printable and non-printable ASCII characters. Your task is to process each string and create a new list where each string only contains printable ASCII characters. Non-printable characters should be replaced with a hyphen ('-'). The printable ASCII... | def filter_special_characters(strings):
"""
Filters non-printable ASCII characters from a list of strings, replacing them with hyphens.
Counts the number of replacements made in each string.
:param strings: List of strings to be filtered.
:return: List of tuples containing the filtered string and t... | [
"assert filter_special_characters([\"hello\", \"world\"]) == [(\"hello\", 0), (\"world\", 0)]",
"assert filter_special_characters([\"h\\x00ello\", \"w\\x01orld\"]) == [(\"h-ello\", 1), (\"w-orld\", 1)]",
"assert filter_special_characters([\"\\x00\\x01\\x02\", \"abc\"]) == [\"---\", (\"abc\", 0)]",
"assert fil... | filter_special_characters | def filter_special_characters(strings): | 0.5 | generic |
323bc2a48e75baf2eddc11819b185eb9 | You are given a string `s`. Your task is to implement a function `count_frequencies` that returns a dictionary with each alphabetic character in the string as the key and its frequency as the value. The function should treat uppercase and lowercase versions of the same letter as identical. Non-alphabetic characters sho... | def count_frequencies(s):
"""
Returns a dictionary with each alphabetic character in the string as the key
and its frequency as the value. The function is case-insensitive and ignores
non-alphabetic characters.
:param s: Input string
:return: Dictionary with character frequencies
"""
s ... | [
"assert count_frequencies(\"Hello World\") == {'h': 2, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}",
"assert count_frequencies(\"AaBbCc\") == {'a': 2, 'b': 2, 'c': 2}",
"assert count_frequencies(\"Python Programming\") == {'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': ... | count_frequencies | def count_frequencies(s): | 0.6 | generic |
21ba7cc9a0ca8a66bdc57efe3b206d41 | You are given two strings, `str1` and `str2`. Your task is to implement a function `find_unique_chars(str1, str2)` that returns a string consisting of characters that are present in `str2` but not in `str1`. The characters in the output string should appear in the same order as they do in `str2`. Additionally, ensure t... | def find_unique_chars(str1, str2):
"""
Returns a string containing characters from str2 that are not in str1,
preserving the order and frequency of characters in str2.
:param str1: First input string
:param str2: Second input string
:return: String of unique characters from str2 not in str1... | [
"assert find_unique_chars(\"hello\", \"world\") == \"wrd\"",
"assert find_unique_chars(\"abc\", \"def\") == \"def\"",
"assert find_unique_chars(\"abc\", \"abc\") == \"\"",
"assert find_unique_chars(\"aabbcc\", \"ddeeff\") == \"def\"",
"assert find_unique_chars(\"xyz\", \"zyxwvut\") == \"wvut\"",
"assert f... | find_unique_chars | def find_unique_chars(str1, str2): | 0.7 | generic |
b59c85a342023d2088ec2f8bc0b42a0c | You are given a string `dna_sequence` representing a DNA sequence consisting of the nucleotides 'A', 'C', 'G', and 'T'. Your task is to implement a function `count_nucleotides` that returns a dictionary with each nucleotide as the key and its count in the sequence as the value.
**Input:**
- A single string `dna_sequen... | def count_nucleotides(dna_sequence):
"""
Counts the occurrences of each nucleotide ('A', 'C', 'G', 'T') in the given DNA sequence.
Parameters:
dna_sequence (str): A string representing a DNA sequence.
Returns:
dict: A dictionary with nucleotides as keys and their counts as values.
"""
... | [
"assert count_nucleotides(\"ACGTACGT\") == {'A': 2, 'C': 2, 'G': 2, 'T': 2}",
"assert count_nucleotides(\"AAAA\") == {'A': 4, 'C': 0, 'G': 0, 'T': 0}",
"assert count_nucleotides(\"CCCC\") == {'A': 0, 'C': 4, 'G': 0, 'T': 0}",
"assert count_nucleotides(\"GGGG\") == {'A': 0, 'C': 0, 'G': 4, 'T': 0}",
"assert ... | count_nucleotides | def count_nucleotides(dna_sequence): | 1 | generic |
7b63e333cad6e25ec61aaef6dd6f70ec | You are given a list of tweets, where each tweet is represented as a dictionary with the following keys: `user_id`, `tweet_text`, and `retweet_count`. Your task is to implement a function `top_retweeted_tweets(tweets, n)` that returns a list of the top `n` tweets sorted by `retweet_count` in descending order.
**Input:... | def top_retweeted_tweets(tweets, n):
"""
Returns a list of the top n tweets sorted by retweet_count in descending order.
:param tweets: List of dictionaries, each containing 'user_id', 'tweet_text', and 'retweet_count'.
:param n: Integer, number of top tweets to return.
:return: List of dictionarie... | [
"assert top_retweeted_tweets([{'user_id': 1, 'tweet_text': 'First tweet', 'retweet_count': 10}, {'user_id': 2, 'tweet_text': 'Second tweet', 'retweet_count': 20}, {'user_id': 3, 'tweet_text': 'Third tweet', 'retweet_count': 15}], 2) == [{'user_id': 2, 'tweet_text': 'Second tweet', 'retweet_count': 20}, {'user_id': ... | top_retweeted_tweets | def top_retweeted_tweets(tweets, n): | 1 | generic |
724e2d7ba8fd2766515cba027f0f920d | You are given a text file. Your task is to write a program that reads the file, counts the frequency of each word, and prints the words in descending order of frequency. If two words have the same frequency, they should be printed in alphabetical order. Words are defined as sequences of alphanumeric characters and are ... | from collections import Counter
import re
def read_and_count_words(filename):
"""
Reads a text file, counts the frequency of each word, and prints the words
in descending order of frequency. If two words have the same frequency,
they are printed in alphabetical order.
:param filename: str, the... | [
"assert read_and_count_words('test1.txt') == None",
"assert read_and_count_words('test2.txt') == None",
"assert read_and_count_words('empty.txt') == None",
"assert read_and_count_words('singleword.txt') == None",
"assert read_and_count_words('twowords.txt') == None",
"assert read_and_count_words('multiple... | read_and_count_words | def read_and_count_words(filename): | 0.3 | generic |
d2cafe8f40c3c23dada90fd8cb5a7be6 | You are given a time represented as a dictionary with keys "hour", "minute", and "second". Implement a function `add_minutes` that takes this dictionary and an integer `minutes` as input. The function should return a new dictionary representing the time after adding the specified number of minutes. Assume that leap sec... | def add_minutes(time, minutes):
"""
Adds a specified number of minutes to a given time and returns the new time.
Parameters:
time (dict): A dictionary with keys "hour", "minute", and "second".
minutes (int): The number of minutes to add.
Returns:
dict: A dictionary representing the... | [
"assert add_minutes({\"hour\": 23, \"minute\": 59, \"second\": 30}, 1) == {\"hour\": 0, \"minute\": 0, \"second\": 30}",
"assert add_minutes({\"hour\": 12, \"minute\": 30, \"second\": 45}, 30) == {\"hour\": 13, \"minute\": 0, \"second\": 45}",
"assert add_minutes({\"hour\": 0, \"minute\": 0, \"second\": 0}, 144... | add_minutes | def add_minutes(time, minutes): | 0.9 | generic |
fef03dbe049de237b32b8d37a1e4204d | You are given a dictionary `sales_data` representing the sales figures for a company over a series of days. Each key in the dictionary is a date in the format "YYYY-MM-DD", and each corresponding value is the total sales for that date. Your task is to implement a function `calculate_average_sales(sales_data)` that comp... | def calculate_average_sales(sales_data):
"""
Calculate the average daily sales from the given sales data.
:param sales_data: A dictionary with dates as keys and sales figures as values.
:return: The average daily sales as a float.
"""
total_sales = sum(sales_data.values())
number_of_days = ... | [
"assert calculate_average_sales({\"2023-09-01\": 1500, \"2023-09-02\": 2000, \"2023-09-03\": 2500}) == 2000.0",
"assert calculate_average_sales({\"2023-09-01\": 1000, \"2023-09-02\": 1000, \"2023-09-03\": 1000}) == 1000.0",
"assert calculate_average_sales({\"2023-09-01\": 500, \"2023-09-02\": 1500, \"2023-09-03... | calculate_average_sales | def calculate_average_sales(sales_data): | 1 | generic |
422951c445b3c2f79e88e8b843730088 | You are given a sorted list of integers and a target value. Implement a function `binary_search_recursive` that performs a binary search to find the target value in the list. The function should return the index of the target value if it exists in the list, or -1 if the target value is not present.
**Input:**
- A list... | def binary_search_recursive(arr, target):
"""
Perform a binary search on a sorted array to find the target value.
:param arr: List of sorted integers
:param target: Integer target value to search for
:return: Index of the target if found, otherwise -1
"""
def search(low, high):
if l... | [
"assert binary_search_recursive([1, 2, 3, 4, 5], 3) == 2",
"assert binary_search_recursive([1, 2, 3, 4, 5], 6) == -1",
"assert binary_search_recursive([], 1) == -1",
"assert binary_search_recursive([1], 1) == 0",
"assert binary_search_recursive([1, 3, 5, 7, 9], 7) == 3",
"assert binary_search_recursive([1... | binary_search_recursive | def binary_search_recursive(arr, target): | 1 | generic |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.