source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
11,450
Write a Python function to count the number of vowels in a given string using a single loop. The function should be efficient and avoid nested loops. The code should start with: ```python def count_vowels_single_loop(string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels_single_loop(string: str) -> int: """ Count the number of vowels in a given string using a single loop. Args: string (str): The input string to count vowels from. Returns: int: The total...
code_exercise_27k
11,451
Write a Python function to remove all whitespace characters from a given string using functional programming concepts. The function should be able to handle various types of whitespace characters, including spaces, tabs, and newlines. The code should start with: ```python def remove_whitespace(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_whitespace(string: str) -> str: """ Remove all whitespace characters from a given string using functional programming concepts. Args: string (str): The input string from which whitespace characters are to...
code_exercise_27k
11,453
Write a Python function to check if a given list contains only non-negative numbers using the `all()` function. A non-negative number is defined as a number that is greater than or equal to zero. The function should return `True` if all elements in the list are non-negative, and `False` otherwise. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def check_non_negative_numbers(lst: List[int]) -> bool: """ Check if a given list contains only non-negative numbers. Parameters: lst (List[int]): A list of integers. Returns: bool: Tru...
code_exercise_27k
11,456
Write a Python function to find all strings in a given list that contain a specified substring using the `filter()` function. The function should be case-insensitive, meaning it should match substrings regardless of their case (e.g., "Python", "PYTHON", "python" should all be matched). The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_strings_with_substring(strings: List[str], substring: str) -> List[str]: """ Find all strings in the given list that contain the specified substring in a case-insensitive manner. Args: ...
code_exercise_27k
11,461
Write a Python function to calculate the factorial of a given number using an iterative approach. The function should handle non-negative integers only. The code should start with: ```python def factorial_iterative(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_iterative(n: int) -> int: """ Calculate the factorial of a given number using an iterative approach. Args: n (int): The number for which factorial needs to be calculated. Returns: int: The...
code_exercise_27k
11,463
Write a Python function to remove all odd numbers from a given list using the `filter()` function. The function should return a new list containing only the even numbers from the original list. The code should start with: ```python from typing import List def remove_odd_numbers(numbers: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_odd_numbers(numbers: List[int]) -> List[int]: """ Removes all odd numbers from a given list using the filter() function. Args: numbers (List[int]): A list of integers from which t...
code_exercise_27k
11,464
Write a Python function to generate Pascal's triangle up to a specified number of rows. Pascal's triangle is a triangular array of the binomial coefficients. Each number in the triangle is the sum of the two numbers directly above it. The function should return a list of lists, where each inner list represents a row in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_pascals_triangle(n: int) -> List[List[int]]: """ Generate Pascal's triangle up to the specified number of rows. Args: n (int): The number of rows in the Pascal's triangle. ...
code_exercise_27k
11,479
Write a Python function to remove all duplicates from a given list using a more efficient approach than nested loops. The function should maintain the order of the elements as they appear in the input list. The code should start with: ```python from typing import List def remove_duplicates_efficient(lst: List[int]) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_efficient(lst: List[int]) -> List[int]: """ Remove duplicates from a given list while maintaining the order of elements. Args: lst (List[int]): The input list from whic...
code_exercise_27k
11,483
Write a Python function to determine if a given number is a power of two using functional programming concepts. The function should leverage lambda functions, higher-order functions, and other functional programming techniques to achieve the solution. The code should start with: ```python def is_power_of_two_functional...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import reduce def is_power_of_two_functional(n: int) -> bool: """ Determine if a given number is a power of two using functional programming concepts. Args: n (int): The number to be checked for bein...
code_exercise_27k
11,484
Write a Python function to calculate the sum of each row and column in a given matrix. The function should return a tuple containing two lists: the first list should contain the sum of each row, and the second list should contain the sum of each column. The code should start with: ```python from typing import List, Tup...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def calculate_matrix_sums(matrix: List[List[int]]) -> Tuple[List[int], List[int]]: """ Calculate the sum of each row and column in a given matrix. Args: matrix: A 2D list representing...
code_exercise_27k
11,487
Write a Python function to merge two lists by alternating their elements using functional programming concepts. The function should handle lists of different lengths and ensure that all elements from both lists are included in the merged list. The code should start with: ```python from typing import List, Any def merg...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def merge_lists(list1: List[Any], list2: List[Any]) -> List[Any]: """ Merge two lists by alternating their elements. Args: list1 (List[Any]): The first list. list2 (List[Any]): ...
code_exercise_27k
11,488
Write a Python function to find the maximum element in a given matrix using nested loops. The matrix is represented as a list of lists, where each inner list represents a row in the matrix. The function should return the maximum element found in the matrix. The code should start with: ```python from typing import List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_element(matrix: List[List[int]]) -> int: """ Finds the maximum element in a given matrix using nested loops. Args: matrix (List[List[int]]): The matrix to search for the maximum...
code_exercise_27k
11,490
Write a Python function to find all the numbers greater than a specified threshold in a given list of integers using the `filter()` function. The function should be able to handle any integer threshold, not just 10. The code should start with: ```python from typing import List def find_numbers_greater_than(numbers: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_numbers_greater_than(numbers: List[int], threshold: int) -> List[int]: """ Find all the numbers greater than a specified threshold in the given list using filter(). Args: numbers (L...
code_exercise_27k
11,493
Create a Python decorator that prints the call stack of a recursive function, including the function name, arguments, and return values, with proper indentation to indicate the depth of recursion. The decorator should be designed to work with any recursive function. The code should start with: ```python import functoo...
Here is the Python code to solve the given problem in the markdown block: ```python import functools def print_call_stack(func): """ A decorator that prints the call stack of a recursive function, including the function name, arguments, and return values, with proper indentation. Args: func: The r...
code_exercise_27k
11,494
Write a Python function to convert a given string to uppercase using the `map()` function. The function should take a string as input and return a new string with all characters converted to uppercase. The code should start with: ```python def convert_string_to_uppercase(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def convert_string_to_uppercase(string: str) -> str: """ Converts a given string to uppercase using the map() function. Args: string (str): The input string to be converted to uppercase. Returns: str: T...
code_exercise_27k
11,497
Write a Python function to check if a given list is sorted in ascending order using the `all()` function. The function should return `True` if the list is sorted in ascending order, and `False` otherwise. The code should start with: ```python from typing import List def is_ascending(lst: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_ascending(lst: List[int]) -> bool: """ Check if a given list is sorted in ascending order. Args: lst (List[int]): The list to be checked. Returns: bool: True if the list ...
code_exercise_27k
11,500
Write a Python function to find the strings containing only lowercase characters from a given list of strings using the `filter()` function. The function should return a list of strings that meet the criteria. The code should start with: ```python from typing import List def find_lowercase_strings(string_list: List[s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_lowercase_strings(string_list: List[str]) -> List[str]: """ Finds the strings containing only lowercase characters in a given list of strings. Args: string_list (List[str]): A list ...
code_exercise_27k
11,504
Write a Python function to calculate the sum of squares of all even numbers in a given list using functional programming concepts. The function should be named `sum_of_even_squares` and should take a list of integers as input. The function should return an integer representing the sum of squares of all even numbers in ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_even_squares(numbers: List[int]) -> int: """ Calculates the sum of squares of all even numbers in a given list. Args: numbers (List[int]): A list of integers. Returns: ...
code_exercise_27k
11,509
Create a Python decorator that multiplies the output of a function by a specific value. The decorator should be flexible enough to work with any function that returns a numeric value. The code should start with: ```python def multiply_output(multiplier): ```
Here is the Python code to solve the given problem in the markdown block: ```python def multiply_output(multiplier): """ Decorator that multiplies the output of a function by a specific value. Args: multiplier (int or float): The value by which the output should be multiplied. Returns: ...
code_exercise_27k
11,510
Write a Python function to check if a given number is a palindrome using a recursive approach. The function should handle non-negative integers only. The function should return `True` if the number is a palindrome and `False` otherwise. The function should start with: ```python def is_palindrome_recursive(number: int) ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome_recursive(number: int) -> bool: """ Check if a given number is a palindrome using a recursive approach. Args: number (int): The number to check for palindrome. Returns: bool: True if t...
code_exercise_27k
11,512
Write a Python function to generate all possible combinations of a given string using nested loops. The function should return a list of all possible combinations of the characters in the string, including both single characters and substrings. The code should start with: ```python from typing import List def generate...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_combinations(string: str) -> List[str]: """ Generate all possible combinations of a given string. Args: string (str): The input string for which combinations are generated. ...
code_exercise_27k
11,513
Write a Python function to calculate the product of all even numbers in a given list of integers using the `reduce()` function from the `functools` module. The function should handle cases where the list is empty by raising a `ValueError`. The code should start with: ```python from functools import reduce from typing ...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import reduce from typing import List def calculate_product_of_even_numbers(numbers: List[int]) -> int: """ Calculates the product of all even numbers in a given list of integers. Args: numbers (List...
code_exercise_27k
11,518
Write a Python function to find the duplicate elements in a given list efficiently. The function should use a dictionary to count occurrences of each element and then return a list of elements that appear more than once. The code should start with: ```python from typing import List def find_duplicates_efficiently(arr:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_duplicates_efficiently(arr: List[int]) -> List[int]: """ Finds the duplicate elements in a given list efficiently using a dictionary. Args: arr (List[int]): The input list of intege...
code_exercise_27k
11,519
Write a Python function to remove all strings starting with a specific character from a given list using the `filter()` function. The function should be able to handle lists containing strings and other data types, and it should only remove strings that start with the specified character. Non-string elements should rem...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def remove_strings_starting_with(lst: List[Any], char: str) -> List[Any]: """ Remove all strings starting with a specific character from a given list. Args: lst (List[Any]): The list of...
code_exercise_27k
11,523
Write a Python function to capitalize the first letter of each string in a given list of strings using the `map()` function. The function should handle an empty list gracefully and return an empty list in such cases. The code should start with: ```python from typing import List def capitalize_first_letter(strings: Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def capitalize_first_letter(strings: List[str]) -> List[str]: """ Capitalizes the first letter of each string in a given list of strings using the map() function. Args: strings (List[str]): ...
code_exercise_27k
11,531
Write a Python function to merge two sorted lists and return a new sorted list using functional programming concepts. The function should avoid using explicit loops and should leverage higher-order functions and list comprehensions where possible. The function should also ensure that the input lists are sorted in ascen...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from itertools import zip_longest def merge_sorted_lists(lst1: List[int], lst2: List[int]) -> List[int]: """ Merge two sorted lists and return a new sorted list using functional programming concepts. ...
code_exercise_27k
11,534
Write a Python function to count the number of negative numbers in a given list of integers using the `filter()` function. The function should return the count of negative numbers. The code should start with: ```python from typing import List def count_negative_numbers(numbers: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_negative_numbers(numbers: List[int]) -> int: """ Count the number of negative numbers in a given list using the filter() function. Args: numbers (List[int]): A list of integers. ...
code_exercise_27k
11,542
Write a Python function to find all possible combinations of elements in two lists using nested loops. The function should return a list of tuples, where each tuple represents a combination of one element from the first list and one element from the second list. The code should start with: ```python from typing import ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_combinations(list1: List, list2: List) -> List[Tuple]: """ Find all possible combinations of elements in two lists using nested loops. Args: list1 (List): The first list. ...
code_exercise_27k
11,543
Write a Python function to filter a list of integers and return a list of numbers that fall within the range [10, 20] using the `filter()` function. The function should handle an empty list and return an empty list in that case. The code should start with: ```python from typing import List def filter_numbers_in_range(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_numbers_in_range(lst: List[int]) -> List[int]: """ Filter a list of integers to find numbers within the range [10, 20]. Args: lst (List[int]): List of integers to filter. Ret...
code_exercise_27k
11,545
Write a Python function to implement the bubble sort algorithm using nested loops. The function should sort a given list of elements in ascending order. The code should start with: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts the given list using the bubble sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: List[i...
code_exercise_27k
11,546
Write a Python function to convert a given string to uppercase using functional programming concepts. The function should take a string as input and return the uppercase version of the string. The function should be implemented using the `map` function and the `str.upper` method. The code should start with: ```python d...
Here is the Python code to solve the given problem in the markdown block: ```python def to_uppercase(string: str) -> str: """ Convert a given string to uppercase using functional programming concepts. Args: string (str): The string to be converted to uppercase. Returns: str: The upperc...
code_exercise_27k
11,550
Write a Python function to check if a given list has any duplicate elements using a set to track seen elements. The function should be efficient and avoid using the `count()` method, which can be slow for large lists. The code should start with: ```python from typing import List def has_duplicates(lst: List[int]) -> ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def has_duplicates(lst: List[int]) -> bool: """ Check if a given list has any duplicate elements using a set to track seen elements. Args: lst (List[int]): The list of integers to check for ...
code_exercise_27k
11,551
Create a Python decorator that converts the output of a function to uppercase. The decorator should be able to handle functions that return strings, lists, tuples, or dictionaries. If the function returns a dictionary, the decorator should convert all string values in the dictionary to uppercase. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, Callable, Dict, List, Tuple, Union def uppercase_output(func: Callable) -> Callable: """ Decorator that converts the output of a function to uppercase. This decorator handles functions that return s...
code_exercise_27k
11,558
Write a Python function to calculate the sum of all prime numbers in a given list using functional programming concepts. The function should be able to handle a list of integers and return the sum of all prime numbers found in the list. The code should start with: ```python from typing import List def sum_of_primes(nu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_prime(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if n <...
code_exercise_27k
11,559
Write a Python function to convert a given string to uppercase using a recursive approach. The function should take a string as input and return the string with all characters converted to uppercase. The function should be implemented recursively, meaning it should call itself to process the string. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_uppercase_recursive(string: str) -> str: """ Recursively converts a given string to uppercase. Args: string (str): The original string to be converted to uppercase. Returns: str: The conv...
code_exercise_27k
11,560
Write a Python function to count the number of vowels in a given string. The function should stop counting and return the current count if a non-alphabetic character is encountered. The function should be case-insensitive and should only count vowels from the set `{'a', 'e', 'i', 'o', 'u'}`. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels_with_break(string: str) -> int: """ Count the number of vowels in a string and stop counting if a non-alphabetic character is encountered. Args: string (str): The input string to count vowels from. ...
code_exercise_27k
11,562
Create a Python decorator that memoizes the output of a function for a specific duration. The decorator should cache the result of the function call and return the cached result if the same arguments are provided within the specified duration. If the duration has expired, the function should be re-evaluated and the new...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import wraps from datetime import datetime, timedelta def memoize_with_duration(duration: int): """ Memoize the output of a function for a specific duration. Args: duration (int): The duration in sec...
code_exercise_27k
11,566
Write a Python function to remove all strings with a length less than a given value from a given list using the `filter()` function. The function should return the modified list containing only the strings that meet the length requirement. The code should start with: ```python from typing import List def remove_short_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_short_strings(strings: List[str], length: int) -> List[str]: """ Remove all strings with a length less than the given value from the given list. Args: strings (List[str]): The lis...
code_exercise_27k
11,569
Write a Python function to find the first occurrence of a number divisible by both 2 and 3 in a given list of numbers. The function should use a `break` statement to exit the loop once a match is found. If no such number is found, the function should return `None`. The code should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_first_divisible_by_2_and_3(numbers: List[int]) -> Optional[int]: """ Finds the first occurrence of a number divisible by both 2 and 3 in a list of numbers. Args: numbers (...
code_exercise_27k
11,579
Write a Python function to check if a given number is a palindrome using functional programming concepts. The function should be implemented without using any loops or mutable state. The function should start with: ```python from typing import Callable def is_palindrome_functional(number: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable def is_palindrome_functional(number: int) -> bool: """ Check if a given number is a palindrome using functional programming concepts. Args: number: A positive integer number to check. ...
code_exercise_27k
11,583
Write a Python function to merge two lists and remove duplicates using functional programming concepts. The function should avoid using explicit loops and mutable data structures like sets or lists that are modified in place. Instead, it should use higher-order functions and immutable data structures to achieve the des...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_and_remove_duplicates(list1: List[int], list2: List[int]) -> List[int]: """ Merge two lists and remove duplicates using functional programming concepts. Args: list1 (List[int]): Th...
code_exercise_27k
11,589
Write a Python function to find the shortest string from a given list of strings using the `reduce()` function from the `functools` module. The function should handle the case where the input list is empty or contains non-string elements by raising a `ValueError`. The code should start with: ```python from functools i...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import reduce from typing import List def find_shortest_string(strings: List[str]) -> str: """ Find the shortest string from a given list of strings using the reduce() function. Args: strings (List[s...
code_exercise_27k
11,590
Write a Python function to calculate the sum of squares of all numbers in a given list using functional programming concepts. The function should be implemented using the `map` function and a lambda expression to compute the squares of the numbers, and then use the `sum` function to aggregate the results. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_squares(numbers: List[int]) -> int: """ Calculate the sum of squares of all numbers in the given list using functional programming concepts. Args: numbers (List[int]): A list of i...
code_exercise_27k
11,595
Write a Python function to check if a given number is a perfect number using an iterative approach. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). The function should start with: ```python def is_perfect_number_iterative(n: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_number_iterative(n: int) -> bool: """ Check if a given number is a perfect number using an iterative approach. A perfect number is a positive integer that is equal to the sum of its proper divisors. The p...
code_exercise_27k
11,600
Write a Python function to calculate the sum of all numbers in a list until the sum exceeds a specified threshold. Use a break statement to exit the loop once the threshold is exceeded. The function should return the sum at the point when the threshold is exceeded. The code should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_until_threshold(numbers: List[int], threshold: int) -> int: """ Calculate the sum of numbers in a list until the sum exceeds a specified threshold. Args: numbers (List[int]): A list ...
code_exercise_27k
11,602
Write a Python function to find the first element in a list that is divisible by 7 and greater than 40 using functional programming concepts. The function should return `None` if no such element is found. The code should start with: ```python from typing import List, Optional def find_first_divisible_by_seven_and_grea...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_first_divisible_by_seven_and_greater_than_40(numbers: List[int]) -> Optional[int]: """ Find the first element in a list that is divisible by 7 and greater than 40. Args: n...
code_exercise_27k
11,604
Write a Python function to determine if a given number is a prime number. The function should use a break statement to exit the loop early if the number is found to be composite. The function should handle edge cases such as negative numbers, 0, and 1. The code should start with: ```python def is_prime(n: int) -> bool...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n: int) -> bool: """ Check if a given number is prime or not. Args: n (int): The number to be checked. Returns: bool: True if the number is prime, False otherwise. """ # Handle edge...
code_exercise_27k
11,605
Write a Python function to check if a given string has all unique characters using functional programming concepts. The function should be case-insensitive and should not use any loops or list comprehensions. The code should start with: ```python def has_unique_characters(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def has_unique_characters(string: str) -> bool: """ Check if a given string has all unique characters, ignoring case. This function uses functional programming concepts in Python, specifically the map and set functions. ...
code_exercise_27k
11,608
Write a Python function to calculate the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. The function should use a loop and a break statement to exit the loop once the GCD is found. The code should start with: ```python def gcd(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def gcd(a: int, b: int) -> int: """ Calculate the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. Args: a (int): First number. b (int): Second number. Returns: ...
code_exercise_27k
11,611
Write a Python function to calculate the sum of all elements at odd indices in a given list using functional programming concepts. The function should be implemented using list comprehensions and the built-in `sum` function. The code should start with: ```python from typing import List def sum_odd_indices(lst: List[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_odd_indices(lst: List[int]) -> int: """ Calculate the sum of all elements at odd indices in a given list using functional programming concepts. Args: lst (List[int]): The input list ...
code_exercise_27k
11,612
Write a Python function to find the first occurrence of a number that is divisible by both 7 and 11 in a given list of integers. The function should use a break statement to exit the loop when a match is found. The function should return the first such number found, or `None` if no such number is found. The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_first_divisible_by_7_and_11(numbers: List[int]) -> Optional[int]: """ Finds the first occurrence of a number that is divisible by both 7 and 11 in a given list of integers. Args: ...
code_exercise_27k
11,617
Write a Python function to apply a given function to each element of a list using the `map()` function. The function should take two arguments: a list of elements and a function to apply to each element. The function should return a new list containing the results of applying the given function to each element of the i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable def apply_function_to_list(elements: List, func: Callable) -> List: """ Applies a given function to each element of a list using the map() function. Args: elements (list): A list o...
code_exercise_27k
11,622
Write a Python function to check if a given list is a palindrome using functional programming concepts. The function should be able to handle lists of any data type, including nested lists. The function should return `True` if the list is a palindrome and `False` otherwise. The code should start with: ```python from ty...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def is_palindrome_functional(lst: List[Any]) -> bool: """ Check if a given list is a palindrome using functional programming concepts. Args: lst (List[Any]): The list to be checked. ...
code_exercise_27k
11,626
Create a Python decorator that converts the output of a function to a specific data type. The decorator should be flexible enough to handle different data types and should be able to be applied to any function. The code should start with: ```python def convert_output_to(data_type): ```
Here is the Python code to solve the given problem in the markdown block: ```python def convert_output_to(data_type): """ A decorator that converts the output of a function to a specified data type. Args: data_type (type): The target data type to convert the output to. Returns: functio...
code_exercise_27k
11,630
Write a Python function to concatenate all strings in a given list with a specific delimiter using the `reduce()` function from the `functools` module. The function should handle empty lists and ensure that the delimiter is only added between strings, not at the beginning or end of the resulting string. The function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import reduce from typing import List def concatenate_strings(strings: List[str], delimiter: str) -> str: """ Concatenates all strings in a given list with a specific delimiter using the reduce() function. A...
code_exercise_27k
11,634
Write a Python function to check if a given number is a power of three using functional programming concepts. The function should be implemented without using loops or mutable state. Instead, leverage recursion and functional programming constructs. The code should start with: ```python def is_power_of_three(n: int) -...
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_three(n: int) -> bool: """ Checks if a given number is a power of three using functional programming concepts. Parameters: n (int): The number to be checked. Returns: bool: True if the number is...
code_exercise_27k
11,641
Write a Python function to calculate the sum of all numbers between 50 and 100 (inclusive) in a given list of integers using the `filter()` function. The function should be efficient and handle edge cases such as an empty list or no numbers within the specified range. The code should start with: ```python from typing ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_between_50_and_100(numbers: List[int]) -> int: """ Calculates the sum of all numbers between 50 and 100 (inclusive) in a given list of integers. Args: numbers (List[int]): A list of ...
code_exercise_27k
11,645
Write a Python function to convert a given string to title case using functional programming concepts. The function should handle various edge cases, such as strings with multiple spaces, leading and trailing spaces, and empty strings. The function should also be efficient and use Python's built-in functional programmi...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_title_case(string: str) -> str: """ Convert a given string to title case using functional programming concepts. Args: string (str): The input string to be converted to title case. Returns: ...
code_exercise_27k
11,649
Write a Python function to check if a given list is sorted in ascending order using the `all()` function. The function should return `True` if the list is sorted in ascending order, and `False` otherwise. The code should start with: ```python from typing import List def is_ascending(lst: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_ascending(lst: List[int]) -> bool: """ Check if a given list is sorted in ascending order. Parameters: lst (List[int]): The list to be checked. Returns: bool: True if the list is...
code_exercise_27k
11,668
Write a Python function to check if a given list contains only negative numbers using the `all()` function. The function should return `True` if all elements in the list are negative, and `False` otherwise. The code should start with: ```python from typing import List def contains_only_negative_numbers(lst: List[int])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def contains_only_negative_numbers(lst: List[int]) -> bool: """ Check if a given list contains only negative numbers. Args: lst (List[int]): The list of integers to be checked. Returns:...
code_exercise_27k
11,683
Write a Python function to filter a list of integers and return a new list containing only the numbers that are divisible by either 2 or 3. The function should use the `filter()` function and a lambda function to achieve this. The code should start with: ```python from typing import List def filter_divisible_by_2_or_3...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_divisible_by_2_or_3(numbers: List[int]) -> List[int]: """ Filters a list of integers to find the numbers divisible by either 2 or 3. Args: numbers (List[int]): A list of integers ...
code_exercise_27k
11,685
Write a Python function to calculate the factorial of a given non-negative integer using a recursive approach. The function should handle edge cases such as input being 0 or 1, and should raise a `ValueError` if a negative integer is provided. The code should start with: ```python def factorial(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial(n: int) -> int: """ Calculate the factorial of a given non-negative integer using a recursive approach. Args: n (int): The non-negative integer for which to calculate the factorial. Returns: ...
code_exercise_27k
11,691
Write a Python function to find the maximum of three numbers using a lambda function. The function should take three arguments and return the maximum value among them. The code should start with: ```python max_of_three = lambda num1, num2, num3: ... ```
Here is the Python code to solve the given problem in the markdown block: ```python max_of_three = lambda num1, num2, num3: num1 if num1 > num2 and num1 > num3 else (num2 if num2 > num3 else num3) """ A lambda function to find the maximum of three numbers. Parameters: - num1 (number): The first number. - num2 (number...
code_exercise_27k
11,695
Write a Python function to determine if a given number is even or odd. The function should return a string "Even" if the number is even and "Odd" if the number is odd. The function should be implemented using a lambda function. The code should start with: ```python is_even_or_odd = lambda num: ... ```
Here is the Python code to solve the given problem in the markdown block: ```python is_even_or_odd = lambda num: "Even" if num % 2 == 0 else "Odd" """ Check if a number is even or odd. Parameters: - num (int): The number to be checked. Returns: - str: Returns "Even" if num is ...
code_exercise_27k
11,704
Write a Python function to check if a given string is a palindrome. A palindrome is a string that reads the same backward as forward. The function should be case-insensitive and should ignore non-alphanumeric characters. The code should start with: ```python def is_palindrome(s: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(s: str) -> bool: """ Check if a given string is a palindrome. The function is case-insensitive and ignores non-alphanumeric characters. Args: s (str): The input string to check for palindrome ...
code_exercise_27k
11,710
Write a Python function to count the number of vowels in a given string. The function should be case-insensitive and should only consider the English vowels 'a', 'e', 'i', 'o', and 'u'. Any non-alphabetic characters should be ignored during the vowel count. The function should utilize a lambda expression and a list com...
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels(s: str) -> int: """ Count the number of vowels in a given string. Args: s (str): The input string to count vowels from. Returns: int: The total count of vowels in the string. Notes...
code_exercise_27k
11,713
Write a Python function to check if a list is empty or not. The function should be implemented using a lambda function and should return `True` if the list is empty and `False` otherwise. The function should be named `is_list_empty`. The code should start with: ```python is_list_empty = lambda lst: ... ```
Here is the Python code to solve the given problem in the markdown block: ```python is_list_empty = lambda lst: len(lst) == 0 # Docstring """ This lambda function takes a list as input and checks if it is empty or not. Parameters: - lst: The list to be checked for emptiness Returns: - True if the list is empty - Fal...
code_exercise_27k
11,717
Write a Python function to sort a list of integers in ascending order. The function should be able to handle lists of varying lengths, including empty lists. The function should return a new list that is sorted, without modifying the original list. The code should start with: ```python from typing import List def sor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_list_of_integers(lst: List[int]) -> List[int]: """ Sorts a list of integers in ascending order and returns a new sorted list. Args: lst (List[int]): The input list of integers to be...
code_exercise_27k
11,721
Write a Python function to calculate the factorial of a given non-negative integer using a recursive approach. The function should handle input validation to ensure that the input is a non-negative integer. The code should start with: ```python def factorial(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial(n: int) -> int: """ Calculate the factorial of a given non-negative integer using a recursive approach. Parameters: n (int): The non-negative integer for which the factorial needs to be calculated. Re...
code_exercise_27k
11,723
Write a Python function to reverse a given string. The function should be able to handle strings of varying lengths, including empty strings. The function should be implemented using a lambda function. The code should start with: ```python reverse_string = lambda string: ... ```
Here is the Python code to solve the given problem in the markdown block: ```python reverse_string = lambda string: string[::-1] # Docstring """ Reverses the given string. Args: string (str): The string to be reversed. Returns: str: The reversed string. """ ```
code_exercise_27k
11,726
Write a Python function to check if a number is prime or not. The function should be efficient and should only check divisibility up to the square root of the number. The function should return `True` if the number is prime and `False` otherwise. The code should start with: ```python def is_prime(number: int) -> bool: ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(number: int) -> bool: """ Check if a given number is prime. Args: number (int): The number to be checked for primality. Returns: bool: True if the number is prime, False otherwise. Exp...
code_exercise_27k
11,733
Write a Python function to check if a given string is a valid email address. The function should use a regular expression to validate the email format. The code should start with: ```python import re def is_valid_email(email: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_email(email: str) -> bool: """ Check if a given string is a valid email address. Args: email (str): The string to be checked. Returns: bool: True if the string is a valid email a...
code_exercise_27k
11,736
Write a Python function to calculate the average of a list of numbers. The function should handle lists of integers and floats, and return the average as a float. The function should also handle edge cases such as an empty list by returning `None`. The code should start with: ```python from typing import List, Optiona...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def calculate_average(numbers: List[float]) -> Optional[float]: """ Calculate the average of a list of numbers. Args: numbers (List[float]): A list of numeric values. Returns:...
code_exercise_27k
11,749
Write a Python function to calculate the sum of all even numbers in a given list. The function should be implemented using a lambda function and should filter out the even numbers before summing them. The code should start with: ```python from typing import List sum_of_even_numbers = lambda lst: sum(filter(lambda x: x...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List sum_of_even_numbers = lambda lst: sum(filter(lambda x: x % 2 == 0, lst)) """ Calculate the sum of all even numbers in a given list. Parameters: - lst (List[int]): The list of integers from which to calculate t...
code_exercise_27k
11,758
Write a Python function to check if a given string is a valid URL. The function should use a regular expression to validate the URL. The function should return a boolean indicating whether the string is a valid URL. The code should start with: ```python import re def is_valid_url(url: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_url(url: str) -> bool: """ Check if a given string is a valid URL. Args: url (str): The string to be validated as a URL. Returns: bool: True if the string is a valid URL, False o...
code_exercise_27k
11,768
Write a Python function to calculate the sum of all digits in a given number. The function should handle both positive and negative integers. The code should start with: ```python def sum_of_digits(num: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits(num: int) -> int: """ Calculate the sum of all digits in a given number. Args: num (int): The number for which the sum of digits needs to be calculated. Returns: int: The sum of all di...
code_exercise_27k
11,771
Write a Python function to convert a string to title case. The function should take a string as input and return the string with each word capitalized. The function should handle various edge cases, such as strings with leading/trailing spaces, multiple spaces between words, and special characters. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python def to_title_case(string: str) -> str: """ Converts a given string to title case, where each word is capitalized. Args: string (str): The input string to be converted to title case. Returns: str: The in...
code_exercise_27k
11,772
Write a Python function to calculate the factorial of a given number, ensuring that the function skips calculations for numbers less than or equal to 1 using the `continue` statement. The function should handle both positive and non-positive integers appropriately. The code should start with: ```python def calculate_f...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_factorial(n: int) -> int: """ Calculates the factorial of a given number, skipping calculations for numbers less than or equal to 1. Args: n (int): The number for which the factorial is to be calculate...
code_exercise_27k
11,774
Write a Python function to find the smallest number among three numbers. The function should be implemented using a lambda function and should return the smallest number. The code should start with: ```python from typing import Callable find_smallest: Callable[[int, int, int], int] = lambda a, b, c: ... ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable # Define a lambda function to find the smallest number among three numbers find_smallest: Callable[[int, int, int], int] = lambda a, b, c: min(a, b, c) """ This lambda function finds the smallest number amo...
code_exercise_27k
11,784
Write a Python function to calculate the power of a number using a lambda function. The function should take two parameters: the base and the exponent. The function should return the result of raising the base to the exponent. Additionally, provide a detailed docstring for the lambda function that explains its purpose,...
Here is the Python code to solve the given problem in the markdown block: ```python power_lambda = lambda base, exponent: base ** exponent # Docstring for the lambda function power_lambda.__doc__ = """ Calculate the power of a number. Parameters: base (numeric): The base number. exponent (numeric): The exponent to ra...
code_exercise_27k
11,789
Write a Python function to calculate the average value of a specific key in a list of dictionaries. The function should handle cases where the list is empty and return `None` in such cases. The code should start with: ```python from typing import List, Dict, Optional def calculate_average(data: List[Dict[str, int]], k...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List, Dict, Optional def calculate_average(data: List[Dict[str, int]], key: str) -> Optional[float]: """ Calculate the average value of a specific key in a list of dictionaries. Args: data (Lis...
code_exercise_27k
11,797
Write a Python function to find the common characters between two given strings. The function should return a sorted list of unique common characters. The code should start with: ```python from typing import List def find_common_characters(str1: str, str2: str) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def find_common_characters(str1: str, str2: str) -> List[str]: """ Find the common characters between two strings and return them as a sorted list. Args: str1 (str): The first string for c...
code_exercise_27k
11,811
Write a Python function to find the sum of all prime numbers in a given list of integers. The function should be efficient and handle edge cases such as an empty list or a list with non-prime numbers. The code should start with: ```python from typing import List def sum_of_prime_numbers(numbers: List[int]) -> int: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def is_prime(num: int) -> bool: """ Helper function to check if a number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the num...
code_exercise_27k
11,814
Write a Python function to find the largest prime factor of a given number. The function should be efficient and handle large numbers. The code should start with: ```python import math def largest_prime_factor(num: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import math def largest_prime_factor(num: int) -> int: """ Find the largest prime factor of a given number. Args: num (int): The number for which to find the largest prime factor. Returns: int: The lar...
code_exercise_27k
11,816
Write a Python function to calculate the factorial of a given number using recursion. The function should be implemented using a lambda function. The code should start with: ```python factorial = lambda n: ... ```
Here is the Python code to solve the given problem in the markdown block: : ```python factorial = lambda n: 1 if n == 0 else n * factorial(n-1) """ Calculate the factorial of a given number using recursion. Parameters: n (int): The number for which the factorial is to be calculated. It should be a non-negative intege...
code_exercise_27k
11,831
Write a Python function to check if a given string is a pangram. A pangram is a sentence that contains every letter of the alphabet at least once. The function should be case-insensitive and should ignore non-alphabetic characters. The code should start with: ```python import string def is_pangram(s: str) -> bool: ``...
Here is the Python code to solve the given problem in the markdown block: ```python import string def is_pangram(s: str) -> bool: """ Check if the given string is a pangram. A pangram is a sentence that contains every letter of the alphabet at least once. This function is case-insensitive and ignores ...
code_exercise_27k
11,838
Write a Python function to check if a given number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself. For example, 6 is a perfect number since the sum of its proper divisors (1, 2, 3) equals 6. The function should be implemented as a...
Here is the Python code to solve the given problem in the markdown block: ```python is_perfect_number = lambda num: sum([i for i in range(1, num) if num % i == 0]) == num """ Returns True if the given number is a perfect number, else False. A perfect number is a positive integer that is equal to the sum of its proper...
code_exercise_27k
11,842
Write a Python function to calculate the sum of elements in a binary tree. The binary tree is represented using a class `TreeNode` where each node has a value (`val`), a left child (`left`), and a right child (`right`). The function should recursively traverse the tree and compute the sum of all node values. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def sum_binary_tree(root: TreeNode) -> int: """ Calculate the sum of all elements ...
code_exercise_27k
11,851
Write a Python function to find the longest common prefix among a list of strings. The function should be efficient and handle edge cases such as an empty list or a list containing strings with no common prefix. The code should start with: ```python from typing import List def longest_common_prefix(strings: List[str])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_prefix(strings: List[str]) -> str: """ Finds the longest common prefix among a list of strings. Args: strings (List[str]): A list of strings for which to find the longest ...
code_exercise_27k
11,862
Write a Python function to calculate the number of trailing zeros in the factorial of a given number. The function should be efficient and avoid calculating the factorial directly for large numbers due to potential overflow issues. The code should start with: ```python def count_trailing_zeros_in_factorial(n: int) -> ...
Here is the Python code to solve the given problem in the markdown block: ```python def count_trailing_zeros_in_factorial(n: int) -> int: """ Calculate the number of trailing zeros in the factorial of a given number. Args: n (int): The number for which to calculate the factorial's trailing zeros. ...
code_exercise_27k
11,865
Write a Python function to check if a given number is an Armstrong number. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. The function should be implemented using a lambda function and should return a boolean value indicating whether the numb...
Here is the Python code to solve the given problem in the markdown block: ```python armstrong_check = lambda num: num == sum(int(digit)**len(str(num)) for digit in str(num)) """ Checks if a number is an Armstrong number. Parameters: num (int): The number to be checked. Returns: bool: True if the number is an...
code_exercise_27k
11,873
Write a Python function to validate if a given string is a valid credit card number using the Luhn algorithm. The function should remove any non-digit characters from the input string, check if the length of the resulting string is between 13 and 16 digits, and then apply the Luhn algorithm to validate the checksum. T...
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_credit_card_number(card_number: str) -> bool: """ Validates if a given string is a valid credit card number using the Luhn algorithm. Args: card_number (str): The credit card number to be val...
code_exercise_27k
11,876
Write a Python function to calculate the sum of all prime numbers less than a given number. The function should be efficient and use a lambda function to determine if a number is prime. The code should start with: ```python from typing import List import math def sum_of_primes_less_than(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def sum_of_primes_less_than(n: int) -> int: """ Calculate the sum of all prime numbers less than the given number n. Args: n (int): The upper limit (exclusive) for the prime numb...
code_exercise_27k
11,894
Write a Python decorator that logs the execution time of a function. The decorator should print the time taken by the function to execute in milliseconds. The code should start with: ```python import time from functools import wraps def log_execution_time(func): ```
Here is the Python code to solve the given problem in the markdown block: ```python import time from functools import wraps def log_execution_time(func): """ A decorator that logs the execution time of a function in milliseconds. Args: func: The function to be decorated. Returns: A wr...
code_exercise_27k
11,896
Write a Python function to check if a given expression has balanced parentheses. The function should ensure that each opening parenthesis '(' has a corresponding closing parenthesis ')' and that they are properly nested. The function should handle expressions with other characters (e.g., numbers, operators) and should ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_balanced_parentheses(expression: str) -> bool: """ Check if a given expression has balanced parentheses. This function uses a stack-based approach to ensure that each opening parenthesis '(' has a corresponding c...
code_exercise_27k
11,897
Create a Python decorator that ensures a function is only executed if a specified condition is met. The decorator should take a callable condition as an argument and apply it to the wrapped function. If the condition evaluates to `True`, the function should execute normally; otherwise, it should return `None`. The deco...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import wraps def execute_if(condition): """ Decorator that ensures a function is only executed if a given condition is met. Args: condition (callable): A callable object that evaluates the condition....
code_exercise_27k
11,902
Write a Python decorator that limits the maximum number of times a function can be called. The decorator should raise a `ValueError` if the function is called more than the specified number of times. The code should start with: ```python from functools import wraps def limit_calls(max_calls: int): ```
Here is the Python code to solve the given problem in the markdown block: ```python from functools import wraps def limit_calls(max_calls: int): """ Decorator to limit the maximum number of times a function can be called. Args: max_calls (int): The maximum number of times the function can be calle...
code_exercise_27k
11,905
Write a Python function to find all prime numbers between two given numbers, inclusive. The function should be efficient and handle edge cases such as when the start and end values are the same or when there are no prime numbers in the range. The function should also include input validation to ensure that the start an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def find_prime_numbers(start: int, end: int) -> List[int]: """ Find all prime numbers between the given start and end values, inclusive. Args: start (int): The starting value of ...
code_exercise_27k
11,908
Write a Python function to check if a given number is divisible by all the numbers from 1 to a specified limit `n`. The function should return `True` if the number is divisible by all these numbers, and `False` otherwise. The code should start with: ```python def is_divisible_by_1_to_n(num: int, n: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_divisible_by_1_to_n(num: int, n: int) -> bool: """ Check if a given number is divisible by all the numbers from 1 to a specified limit `n`. Args: num (int): The number to be checked. n (int): The uppe...
code_exercise_27k
11,911
Create a Python decorator that memoizes the result of a function for a given set of input arguments. The decorator should cache the results of function calls to avoid redundant computations. The code should start with: ```python from functools import wraps def memoize(function): ```
Here is the Python code to solve the given problem in the markdown block: ```python from functools import wraps def memoize(function): """ Decorator that memoizes the result of a function for a given set of input arguments. This decorator caches the results of function calls to avoid redundant computation...