source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
16,547
Write a Python function to find the third largest number in a given list of integers. If the list does not contain at least three distinct numbers, the function should return `None`. The function should be efficient and handle edge cases such as empty lists, lists with fewer than three elements, and lists with all iden...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_third_largest(numbers: List[int]) -> Optional[int]: """ Find the third largest number in a list of integers. Args: numbers (List[int]): A list of integers. Returns: ...
code_exercise_27k
16,555
Write a Python function to merge two dictionaries into a single dictionary. If there are overlapping keys, the values from the second dictionary should overwrite the values from the first dictionary. The function should handle dictionaries with any types of keys and values. The code should start with: ```python def me...
Here is the Python code to solve the given problem in the markdown block: ```python def merge_dicts(dict1: dict, dict2: dict) -> dict: """ Merges two dictionaries into a single dictionary. If there are overlapping keys, the values from the second dictionary will overwrite the values from the first dictionar...
code_exercise_27k
16,558
Write a Python function to find the longest common prefix in a list of strings. The function should efficiently determine the longest prefix that is common to all strings in the list. If there is no common prefix, the function should return an empty string. 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 longest_common_prefix(strs: List[str]) -> str: """ Finds the longest common prefix in a list of strings. Args: strs (List[str]): A list of strings. Returns: str:...
code_exercise_27k
16,561
Write a Python function to count the occurrence of each word in a given string, considering case insensitivity and ignoring punctuation. The function should return a dictionary where the keys are the unique words (in lowercase) and the values are their respective counts. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import string def count_word_occurrences(text: str) -> Dict[str, int]: """ Count the occurrence of each word in a given string, considering case insensitivity and ignoring punctuation. Args: ...
code_exercise_27k
16,563
Write a Python function to reverse the order of words in a given paragraph. The function should handle various edge cases, such as empty paragraphs, paragraphs with multiple spaces between words, and paragraphs with leading or trailing spaces. The code should start with: ```python def reverse_words_in_paragraph(paragra...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words_in_paragraph(paragraph: str) -> str: """ Reverses the order of words in a given paragraph. Args: paragraph (str): The input paragraph to reverse. Returns: str: The paragraph with the w...
code_exercise_27k
16,565
Write a Python function to determine if two given strings are valid anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The function should ignore case and whitespace. The code should start with: ```python def ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_anagram(s1: str, s2: str) -> bool: """ Check if two strings are valid anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exa...
code_exercise_27k
16,575
Write a Python function to find the longest palindromic substring in a given string. The function should use a dynamic programming approach to efficiently determine the longest palindromic substring. The code should start with: ```python def longest_palindromic_substring(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_palindromic_substring(s: str) -> str: """ Find the longest palindromic substring in the given string using dynamic programming. Args: s (str): The input string in which to find the longest palindromic su...
code_exercise_27k
16,580
Write a Python function to create an adjacency matrix representation of a directed graph. The function should take a dictionary representing the directed graph as input, where the keys are the vertices and the values are lists of the neighboring vertices (i.e., vertices that the key vertex has outgoing edges to). The f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def create_directed_adjacency_matrix(graph: Dict[int, List[int]]) -> List[List[int]]: """ Create an adjacency matrix representation of a directed graph. Parameters: graph (dict): A diction...
code_exercise_27k
16,584
Write a Python function to find the factors of a given number efficiently. The function should return a list of all factors of the number, including 1 and the number itself. The code should start with: ```python from typing import List def find_factors(number: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def find_factors(number: int) -> List[int]: """ Find all factors of a given number efficiently. Args: number (int): The number for which to find the factors. Returns: ...
code_exercise_27k
16,587
Write a Python function to implement a linear search algorithm that finds the index of a target element in a given list. If the target element is not found, the function should return -1. The function should handle lists of any type of elements, including integers, strings, and other objects. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def linear_search(lst: List[Any], target: Any) -> int: """ Perform a linear search on a list to find the index of a target element. Args: lst (List[Any]): The list to be searched. ...
code_exercise_27k
16,590
Write a Python function to sort a list of numbers using the insertion sort algorithm. The function should be able to handle lists of integers and floating-point numbers. The code should start with: ```python from typing import List def insertion_sort(lst: List[float]) -> List[float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def insertion_sort(lst: List[float]) -> List[float]: """ Sorts a list of numbers using the insertion sort algorithm. Args: lst (List[float]): The list of numbers to be sorted. Returns: ...
code_exercise_27k
16,591
Write a Python function to calculate the sum of digits in a number. The function should handle both positive and negative integers. If the input is not an integer, the function should raise a `TypeError`. The code should start with: ```python def sum_of_digits(number: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits(number: int) -> int: """ Calculate the sum of digits in a given number. Args: number (int): The number for which the sum of digits needs to be calculated. Returns: int: The sum of digi...
code_exercise_27k
16,592
Write a Python function to find the vertex with the maximum degree in an undirected graph. The graph is represented as a dictionary where the keys are the vertices and the values are sets containing the adjacent vertices. The function should return the vertex with the maximum degree. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def find_vertex_with_max_degree(graph: Dict[int, Set[int]]) -> int: """ Finds the vertex with the maximum degree in an undirected graph. Args: graph (Dict[int, Set[int]]): The graph rep...
code_exercise_27k
16,612
Write a Python function to find the union of two sets. The union of two sets is a set that contains all the elements from both sets, without any duplicates. The function should handle sets of any size and type of elements, as long as they are hashable. The code should start with: ```python def find_union(set1: set, se...
Here is the Python code to solve the given problem in the markdown block: ```python def find_union(set1: set, set2: set) -> set: """ Returns the union of two sets. The union of two sets is a new set that contains all the elements from both sets, without any duplicates. Args: set1 (set): The fi...
code_exercise_27k
16,617
Write a Python function to solve the Subset Sum problem using backtracking. The function should find all subsets of a given list of positive integers that sum up to a specified target value. The function should return a list of all such subsets. If no such subset exists, the function should return an empty list. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def subset_sum_backtracking(numbers: List[int], target: int) -> List[List[int]]: """ Find all subsets of the given list of positive integers that sum up to the specified target. Args: number...
code_exercise_27k
16,618
Write a Python function to perform a depth-first search (DFS) on a graph. The graph is represented as a dictionary where each key is a node and its corresponding value is a list of adjacent nodes. The function should return a list of nodes visited during the search, in the order they were visited. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def depth_first_search(graph: Dict[Any, List[Any]], start_node: Any) -> List[Any]: """ Perform a depth-first search on a graph. Args: graph (Dict[Any, List[Any]]): A dictionary re...
code_exercise_27k
16,622
Write a Python function to perform a depth-first search (DFS) on a graph. The graph is represented as an adjacency list. The function should return a list of vertices visited in the order of the DFS traversal. The code should start with: ```python from typing import Dict, List, Set def depth_first_search(graph: Dict[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Set def depth_first_search(graph: Dict[str, List[str]], start: str) -> List[str]: """ Perform a Depth-First Search (DFS) on a graph. Parameters: graph (dict): The graph representation in ...
code_exercise_27k
16,625
Write a Python function to convert a decimal number to its octal representation. The function should handle both positive and zero decimal numbers. The code should start with: ```python def decimal_to_octal(decimal: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def decimal_to_octal(decimal: int) -> str: """ Convert a decimal number to its octal representation. Args: decimal (int): The decimal number to be converted. Must be a non-negative integer. Returns: s...
code_exercise_27k
16,627
Write a Python function to check if a given string is a palindrome, ignoring case and non-alphanumeric characters. The function should return `True` if the string is a palindrome and `False` otherwise. The code should start with: ```python def is_palindrome_ignore_non_alnum(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome_ignore_non_alnum(string: str) -> bool: """ Check if a given string is a palindrome, ignoring case and non-alphanumeric characters. Parameters: string (str): The string to be checked. Returns: ...
code_exercise_27k
16,631
Write a Python function to reverse the order of characters in a string using a different approach than slicing. The function should use a loop to reverse the string. The code should start with: ```python def reverse_string_loop(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string_loop(string: str) -> str: """ Reverses the order of characters in a string using a loop. Args: string (str): The input string to be reversed. Returns: str: The reversed string. ""...
code_exercise_27k
16,634
Write a Python function to determine if a given number is a power of two using bitwise operations. The function should return `True` if the number is a power of two, and `False` otherwise. The code should start with: ```python def is_power_of_two_bitwise(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_two_bitwise(num: int) -> bool: """ Determine if a given number is a power of two using bitwise operations. Parameters: num (int): The number to be checked. Returns: bool: True if num is a power ...
code_exercise_27k
16,636
Write a Python function to remove all occurrences of a specified substring from a given string. The function should handle cases where the substring might overlap within the string. The code should start with: ```python def remove_substring(string: str, substring: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_substring(string: str, substring: str) -> str: """ Removes all occurrences of a specified substring from a given string, including overlapping occurrences. Args: string (str): The input string from which ...
code_exercise_27k
16,638
Write a Python function to find the second largest number in a given list of numeric values. If the list contains fewer than two elements, raise a `ValueError`. The function should be efficient and handle both positive and negative numbers. The code should start with: ```python from typing import List, Union def find...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_second_largest_number(nums: List[Union[int, float]]) -> Union[int, float]: """ Finds the second largest number in a given list of numeric values. Args: nums (List[Union[int, ...
code_exercise_27k
16,641
Write a Python function to calculate the surface area of a cylinder. The function should take the radius and height of the cylinder as input and return the surface area. The surface area of a cylinder is calculated using the formula: \[ \text{Surface Area} = 2\pi r^2 + 2\pi rh \] where \( r \) is the radius and \( h ...
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_cylinder_surface_area(radius: float, height: float) -> float: """ Calculate the surface area of a cylinder. This function takes the radius and height of a cylinder as input and returns the surface...
code_exercise_27k
16,644
Write a Python function to check if a string is a valid palindrome, ignoring case and spaces, and considering only alphanumeric characters. The function should return `True` if the string is a valid palindrome and `False` otherwise. The code should start with: ```python def is_valid_palindrome(s: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_palindrome(s: str) -> bool: """ Check if a string is a valid palindrome, ignoring case, spaces, and non-alphanumeric characters. Args: s (str): The string to check. Returns: bool: True if t...
code_exercise_27k
16,649
Write a Python function to determine if a given undirected graph is a tree. The graph is represented as an adjacency list. A tree is defined as an undirected graph with no cycles and where every pair of vertices is connected by exactly one path. The code should start with: ```python from typing import List, Dict def ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def is_tree(graph: Dict[int, List[int]]) -> bool: """ Determine if the given undirected graph is a tree. A tree is an undirected graph with no cycles and where every pair of vertices is connec...
code_exercise_27k
16,650
Write a Python function to find the keys that are common in two dictionaries. The function should return a list of these common keys. The code should start with: ```python from typing import Dict, List def find_common_keys(dict1: Dict, dict2: Dict) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def find_common_keys(dict1: Dict, dict2: Dict) -> List[str]: """ Find the keys that are common in two dictionaries. Args: dict1 (Dict): The first dictionary. dict2 (Dict): The ...
code_exercise_27k
16,653
Write a Python function to count the occurrence of each character in a given string and return the result as a dictionary. The function should handle both uppercase and lowercase characters as distinct and should not count spaces. The code should start with: ```python def count_characters_no_spaces(string: str) -> dict...
Here is the Python code to solve the given problem in the markdown block: ```python def count_characters_no_spaces(string: str) -> dict: """ Counts the occurrence of each character in a given string, ignoring spaces. Args: string (str): The input string to count characters from. Returns: ...
code_exercise_27k
16,663
Write a Python function to generate all possible combinations of `k` elements from a given list using a recursive approach. The function should return a list of all such combinations. The code should start with: ```python from typing import List def generate_combinations(arr: List[int], k: int) -> List[List[int]]: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_combinations(arr: List[int], k: int) -> List[List[int]]: """ Generate all possible combinations of k elements from a given list using recursion. Args: arr (List[int]): The input...
code_exercise_27k
16,666
Write a Python function to calculate the Highest Common Factor (HCF) of two numbers using the Euclidean algorithm. The function should be able to handle both positive and negative integers. The code should start with: ```python def calculate_hcf(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_hcf(a: int, b: int) -> int: """ Calculates the Highest Common Factor (HCF) of two numbers using the Euclidean algorithm. Args: a (int): The first number. b (int): The second number. Return...
code_exercise_27k
16,667
Write a Python function to determine if a given directed graph is acyclic. The graph is represented using an adjacency list. The function should return `True` if the graph is acyclic and `False` otherwise. The code should start with: ```python from typing import Dict, List def is_acyclic_graph(graph: Dict[str, List[s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def is_acyclic_graph(graph: Dict[str, List[str]]) -> bool: """ Determine if a given directed graph is acyclic. Parameters: graph (Dict[str, List[str]]): A dictionary representing the direc...
code_exercise_27k
16,670
Write a Python function to find the prime factors of a given number. The function should return a list of prime factors in ascending order. The code should start with: ```python def find_prime_factors(number: int) -> list: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_prime_factors(number: int) -> list: """ Find the prime factors of a given number and return them in ascending order. Args: number (int): The number for which prime factors need to be found. Returns: ...
code_exercise_27k
16,675
Write a Python function to sort a list of numbers using the selection sort algorithm. The function should be able to handle lists of integers and floating-point numbers. The code should start with: ```python from typing import List def selection_sort(arr: List[float]) -> List[float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def selection_sort(arr: List[float]) -> List[float]: """ Sorts a list of numbers using the selection sort algorithm. Args: arr (List[float]): The input list of numbers to be sorted. Ret...
code_exercise_27k
16,678
Write a Python function to calculate the sum of even digits in a given number. The function should handle both positive and negative integers. The code should start with: ```python def sum_even_digits(number: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_even_digits(number: int) -> int: """ Calculate the sum of even digits in a given number. Args: number (int): The number for which the sum of even digits needs to be calculated. Returns: int: The...
code_exercise_27k
16,682
Write a Python function to find the kth smallest element in a given list of integers. The function should handle edge cases such as an empty list or an invalid k value. The function should be efficient and avoid sorting the entire list if possible. The code should start with: ```python from typing import List def fin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_kth_smallest(nums: List[int], k: int) -> int: """ Finds the kth smallest element in a list of integers. Args: nums (List[int]): The list of integers. k (int): The 1-based in...
code_exercise_27k
16,696
Write a Python function to find the symmetric difference between two sets. The symmetric difference between two sets is defined as the set of elements which are in either of the sets but not in both. The function should handle sets containing elements of the same type and raise a `TypeError` if the input sets are not o...
Here is the Python code to solve the given problem in the markdown block: ```python def find_symmetric_difference(set1: set, set2: set) -> set: """ Finds the symmetric difference between two sets. The symmetric difference between two sets is the set of elements which are in either of the sets but not in bo...
code_exercise_27k
16,704
Write a Python function to generate all possible palindrome partitions of a given string using backtracking. Each partition should be a list of substrings where each substring is a palindrome. The function should return a list of all such partitions. The code should start with: ```python from typing import List def p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_palindrome(s: str) -> bool: """ Check if a string is a palindrome. Args: s: Input string to check. Returns: True if the string is a palindrome, False otherwise. """ retur...
code_exercise_27k
16,705
Write a Python function to calculate the length of a string, ensuring that the function handles various edge cases such as empty strings, strings with spaces, and non-string inputs. The function should raise a `TypeError` if the input is not a string. The code should start with: ```python def calculate_string_length(s...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_string_length(string: str) -> int: """ Calculate the length of a given string. This function takes a string as input and returns its length. If the input is not a string, a TypeError is raised. Args: ...
code_exercise_27k
16,714
Write a Python function to find the sum of all prime numbers up to a given number `n` efficiently. The function should use the Sieve of Eratosthenes algorithm to identify prime numbers, which is more efficient than the trial division method used in the given code snippet. The code should start with: ```python def sum_...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_primes_sieve(n: int) -> int: """ Calculates the sum of all prime numbers up to a given number using the Sieve of Eratosthenes algorithm. Args: n (int): A positive integer specifying the limit up to which ...
code_exercise_27k
16,725
Write a Python function to calculate the product of all even numbers in a given list. If the list is empty or doesn't contain any even numbers, the function should return 1. The function should handle both integer and floating-point numbers. The code should start with: ```python from typing import List, Union def cal...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def calculate_product_of_even_numbers(numbers: List[Union[int, float]]) -> Union[int, float]: """ Calculates the product of all even numbers in a given list. Args: numbers (list): A l...
code_exercise_27k
16,732
Write a Python function to find the longest common substring among a list of strings using dynamic programming. The function should efficiently compute the longest common substring by leveraging a dynamic programming table. The code should start with: ```python from typing import List def longest_common_substring_dp(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_substring_dp(strings: List[str]) -> str: """ Finds the longest common substring among a list of strings using dynamic programming. Args: strings (List[str]): List of strin...
code_exercise_27k
16,738
Write a Python function to generate a list of random integers within a specified range and of a specified length. The function should be useful for testing functions that rely on random values. The code should start with: ```python import random def generate_random_input_data(num_elements: int, min_value: int, max_val...
Here is the Python code to solve the given problem in the markdown block: ```python import random def generate_random_input_data(num_elements: int, min_value: int, max_value: int) -> list: """ Generate a list of random integers within a specified range and of a specified length. Args: num_elements...
code_exercise_27k
16,765
Write a Python function to find the maximum independent edge set in a graph. The graph is represented as an adjacency list, where keys are nodes and values are lists of neighboring nodes. The function should return a list of edges forming the maximum independent edge set. An independent edge set is a set of edges in wh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple def maximum_independent_edge_set(graph: Dict[int, List[int]]) -> List[Tuple[int, int]]: """ Find the maximum independent edge set in a graph. Parameters: graph (dict): The graph rep...
code_exercise_27k
16,773
Write a Python function to generate all possible valid domain names of a specified length using a given set of allowed characters. The function should be recursive and should return a list of all possible domain names. The code should start with: ```python from typing import List def generate_domain_names(allowed_char...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_domain_names(allowed_chars: List[str], length: int) -> List[str]: """ Generate all possible valid domain names of a specified length using a given set of allowed characters. Args: ...
code_exercise_27k
16,788
Write a Python function to check if a given string contains only whitespace characters. The function should return `True` if the string is empty or contains only whitespace characters, and `False` otherwise. The code should start with: ```python def is_string_whitespace(input_str: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_string_whitespace(input_str: str) -> bool: """ Check if a string is empty or contains only whitespace characters. Args: input_str (str): The input string to be checked. Returns: bool: A boolean v...
code_exercise_27k
16,797
Write a Python function to find the maximum number in a given list of numbers. The function should handle an empty list by returning `None`. The code should start with: ```python from typing import List, Optional def find_maximum(numbers: List[int]) -> Optional[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_maximum(numbers: List[int]) -> Optional[int]: """ Finds and returns the maximum number from a given list of numbers. Args: numbers (List[int]): A list of numbers for which...
code_exercise_27k
16,802
Write a Python function to generate all possible combinations of k numbers from the range 1 to n using a backtracking approach. The function should return a list of all such combinations. The code should start with: ```python from typing import List def combinations(n: int, k: int) -> List[List[int]]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def combinations(n: int, k: int) -> List[List[int]]: """ Generates all combinations of k numbers from the range 1 to n using backtracking. Args: n (int): The upper limit of the range (inclus...
code_exercise_27k
16,808
Write a Python function to calculate the average of a given list of numbers. The function should handle empty lists by returning `None` and should raise a `TypeError` if the input is not a list. The code should start with: ```python from typing import List, Optional def calculate_average(numbers: List[float]) -> Optio...
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 given list of numbers. Args: numbers (List[float]): A list of numbers. Returns: ...
code_exercise_27k
16,812
Write a Python function to find the maximum area of an island in a given grid using backtracking. The grid is represented as a 2D list where `1` represents land and `0` represents water. The function should return the maximum area of an island, where the area of an island is defined as the number of connected land cell...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_area_of_island(grid: List[List[int]]) -> int: """ Finds the maximum area of an island in a grid using backtracking. Args: grid (List[List[int]]): The grid representing the island, wh...
code_exercise_27k
16,818
Write a Python function to find the minimum broadcast time in a graph represented as an adjacency list. The minimum broadcast time is defined as the maximum number of edges that need to be traversed to reach all vertices from any starting vertex. The function should return the minimum broadcast time as an integer. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def find_minimum_broadcast_time(graph: Dict[int, Set[int]]) -> int: """ Find the minimum broadcast time in a graph represented as an adjacency list. Args: graph (Dict[int, Set[int]]): T...
code_exercise_27k
16,819
Write a Python function to filter out even numbers from a given list of integers and return a new list containing only the even numbers. 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_even_numbers(numbers: List[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_even_numbers(numbers: List[int]) -> List[int]: """ Filter even numbers from a list of integers. This function takes a list of integers as input and returns a new list containing only ...
code_exercise_27k
16,821
Write a Python function to remove duplicates from a given list while preserving the order of the elements. The function should take a list as input and return a new list with all duplicate elements removed, maintaining the first occurrence of each element. 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 remove_duplicates_preserve_order(lst: List[int]) -> List[int]: """ Removes duplicates from a given list while preserving the order of the elements. Args: lst (List[int]): The list from w...
code_exercise_27k
16,838
Write a Python function to determine if two given lists have at least one common element. The function should return `True` if there is at least one common element between the two lists, and `False` otherwise. The function should be efficient and handle lists of any size. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def have_common_element(list1: List[int], list2: List[int]) -> bool: """ Determine if two lists have at least one common element. Args: list1 (List[int]): The first list. list2 (List...
code_exercise_27k
16,842
Write a Python function to count the number of occurrences of each character in a given string and return the result as a dictionary. The function should handle any string input, including empty strings and strings with special characters. The code should start with: ```python def count_character_occurrences(string: st...
Here is the Python code to solve the given problem in the markdown block: ```python def count_character_occurrences(string: str) -> dict: """ Count the number of occurrences of each character in a given string. Args: string (str): The input string to count character occurrences. Returns: ...
code_exercise_27k
16,851
Write a Python function to find the longest common prefix among a list of strings using backtracking. The function should return the longest common prefix found among the strings. If no common prefix is found, the function should return an empty string. The code should start with: ```python from typing import List de...
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: """ Find the longest common prefix from a list of strings using backtracking. Args: strings (List[str]): A list of strings. Returns...
code_exercise_27k
16,855
Write a Python function to find the most frequent character in a given string. If there are multiple characters with the same highest frequency, return the character that appears first in the string. The function should handle empty strings by returning an empty string. The code should start with: ```python def find_m...
Here is the Python code to solve the given problem in the markdown block: ```python def find_most_frequent_character(string: str) -> str: """ Find the most frequent character in a given string. If there are multiple characters with the same highest frequency, return the character that appears first in the s...
code_exercise_27k
16,856
Write a Python function to generate all possible valid combinations of k pairs of parentheses using a recursive approach. Each combination should be a string consisting of '(' and ')' characters, and the function should return a list of all such valid combinations. 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 generate_parentheses(k: int) -> List[str]: """ Generate all possible valid combinations of k pairs of parentheses using a recursive approach. Args: k (int): Number of pairs of parenthese...
code_exercise_27k
16,877
Write a Python function to find the largest sum of any two distinct elements in a given list of integers. The function should handle lists with at least two elements and return the largest sum. If the list contains fewer than two elements, the function should raise a `ValueError`. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_sum_of_two_distinct_elements(lst: List[int]) -> int: """ Finds the largest sum of any two distinct elements in a given list of integers. Args: lst (List[int]): A list of int...
code_exercise_27k
16,878
Write a Python function to find all possible combinations of a given set of positive numbers that sum up to a specified target. Each number in the set can be used multiple times. The function should return a list of all unique combinations that sum up to the target. The code should start with: ```python from typing im...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_combinations(candidates: List[int], target: int) -> List[List[int]]: """ Find all possible combinations from the candidates that sum up to the target. Args: candidates (List[int]): ...
code_exercise_27k
16,887
Write a Python function to remove all duplicates from a given list while preserving the order of the elements. The function should return a new list containing the unique elements in the order they first appeared in the input list. The code should start with: ```python from typing import List def remove_duplicates_pr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_preserve_order(lst: List) -> List: """ Removes duplicates from a given list while preserving the order of the elements. Args: lst (list): The input list from which dupl...
code_exercise_27k
16,890
Write a Python function to count the number of words in a given string, considering various edge cases such as multiple spaces, leading and trailing spaces, and punctuation. The function should handle these cases gracefully and return the correct count of words. The code should start with: ```python def count_words(st...
Here is the Python code to solve the given problem in the markdown block: ```python def count_words(string: str) -> int: """ Count the number of words in a given string, handling various edge cases. Parameters: string (str): The string to count the words in. Returns: int: The number of words i...
code_exercise_27k
16,906
Write a Python function to find the largest prime number smaller than a given number. The function should be efficient and handle edge cases such as when the given number is less than or equal to 2. The code should start with: ```python def find_largest_prime(smaller_than: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python 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 <= 1: return False ...
code_exercise_27k
16,909
Write a Python function to calculate the sum of digits raised to the power of their position in a given number. The position of the digit is determined by its place in the number, starting from 1 for the rightmost digit. The function should handle positive integers only and raise a `ValueError` for non-positive integer...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits_power_position(num: int) -> int: """ Calculates the sum of digits raised to the power of their position in a given number. Parameters: num (int): The number whose digits we want to calculate th...
code_exercise_27k
16,916
Write a Python function to determine 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). The function should return `True` if the number is perfect and `False` otherwise. The code should start with: ```python def is...
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_number(number: int) -> bool: """ Determine 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 ...
code_exercise_27k
16,923
Write a Python function to determine if a given number is a happy number. A number is considered happy if, by repeatedly replacing it with the sum of the squares of its digits, it eventually reaches 1. If it enters a cycle that does not include 1, it is not a happy number. The code should start with: ```python def is_...
Here is the Python code to solve the given problem in the markdown block: ```python def is_happy_number(num: int) -> bool: """ Determine if a given number is a happy number. A number is considered happy if, by repeatedly replacing it with the sum of the squares of its digits, it eventually reaches 1. I...
code_exercise_27k
16,936
Write a Python function to find the longest common prefix in a list of strings. The function should return an empty string if there is no common prefix. The code should start with: ```python from typing import List def longest_common_prefix(strs: List[str]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_prefix(strs: List[str]) -> str: """ Finds the longest common prefix in a list of strings. Args: strs (List[str]): A list of strings. Returns: str: The longest...
code_exercise_27k
16,937
Write a Python function to find the first non-repeating character in a given string. The function should return the character if found, otherwise return `None`. The code should start with: ```python def find_first_non_repeating_char(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_non_repeating_char(string: str) -> str: """ Find the first non-repeating character in a given string. Args: string (str): The input string to search for the first non-repeating character. Returns...
code_exercise_27k
16,940
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given list of integers using backtracking. The function should return the length of the LIS. The code should start with: ```python from typing import List def longest_increasing_subsequence(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_increasing_subsequence(nums: List[int]) -> int: """ Finds the length of the longest increasing subsequence in a given list of integers using backtracking. Args: nums (List[int]):...
code_exercise_27k
16,946
Write a Python function to find the largest product of three elements in a given list of integers. The function should handle both positive and negative integers and ensure that the list contains at least three elements. If the list contains fewer than three elements, the function should raise a `ValueError`. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_product_of_three(nums: List[int]) -> int: """ Finds the largest product of three elements in a given list of integers. Args: nums (List[int]): The list of integers. Ret...
code_exercise_27k
16,952
Write a Python function to determine if a given list of numbers forms a valid arithmetic progression. An arithmetic progression is a sequence of numbers in which the difference between consecutive terms is constant. The function should return `True` if the list is a valid arithmetic progression, and `False` otherwise. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_arithmetic_progression(numbers: List[int]) -> bool: """ Determines if a given list of numbers forms a valid arithmetic progression. An arithmetic progression is a sequence of numbers in which...
code_exercise_27k
16,954
Write a Python function to calculate the number of ways to climb a staircase of a given number of steps, where a person can climb either 1 or 2 steps at a time. The function should use dynamic programming to efficiently compute the result. The code should start with: ```python def count_ways_to_climb(n: int) -> int: `...
Here is the Python code to solve the given problem in the markdown block: ```python def count_ways_to_climb(n: int) -> int: """ Calculate the number of ways to climb a staircase of n steps, where a person can climb either 1 or 2 steps at a time. Args: n (int): The number of steps in the staircase. ...
code_exercise_27k
16,957
Write a Python function to convert a decimal number to its Roman numeral representation. The function should handle decimal numbers in the range from 1 to 3999. The code should start with: ```python def decimal_to_roman(decimal_num: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def decimal_to_roman(decimal_num: int) -> str: """ Converts a decimal number to a Roman numeral. Args: decimal_num (int): The decimal number to be converted, must be within the range 1-3999. Returns: st...
code_exercise_27k
16,959
Write a Python function to determine if a given graph is a split hypergraph. A split hypergraph is defined as a graph where every node has at least two neighbors, and each pair of neighbors of a node has at least one common neighbor. The graph is represented as a dictionary where keys are nodes and values are sets of n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def is_split_hypergraph(graph: Dict[int, Set[int]]) -> bool: """ Determine if a given graph is a split hypergraph. A split hypergraph is a graph where every node has at least two neighbors, ...
code_exercise_27k
16,960
Write a Python function to find the maximum sum of a contiguous subsequence (subarray) in a given list of integers. The function should efficiently handle cases where the list contains both positive and negative numbers. The code should start with: ```python from typing import List def max_subarray_sum(nums: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: """ Find the maximum sum of a contiguous subsequence (subarray) in a given list of integers. Args: nums (List[int]): A list of integers. Re...
code_exercise_27k
16,963
Write a Python function to perform the binary search algorithm on a given sorted list. The function should return the index of the target element if it is found in the list, otherwise, it should return -1. The function should also raise a `ValueError` if the input list is not sorted in ascending order. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def binary_search(arr: List[Any], target: Any) -> int: """ Perform binary search on a given sorted list. Args: arr (List[Any]): The sorted list to search. target (Any): The item...
code_exercise_27k
16,966
Write a Python function to count the number of connected components in an undirected graph using Depth-First Search (DFS). The graph is represented as an adjacency list. The function should start with: ```python from typing import Dict, Set def count_connected_components_dfs(graph: Dict[int, Set[int]]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def dfs(graph: Dict[int, Set[int]], node: int, visited: Set[int]) -> None: """ Perform DFS traversal in a graph starting from a given node. Args: graph (dict): The graph represented...
code_exercise_27k
16,970
Write a Python function to determine if a given number is a perfect power. A perfect power is a positive integer that can be expressed as an integer power of another positive integer. For example, 8 is a perfect power because it can be expressed as \(2^3\). The function should start with: ```python def is_perfect_powe...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_perfect_power(n: int) -> bool: """ Determine if a given number is a perfect power. A perfect power is a positive integer that can be expressed as an integer power of another positive integer. Args: ...
code_exercise_27k
16,977
Write a Python function to find the next greater element for each element in a given list of integers. The function should return a new list where each element is the next greater element for the corresponding element in the input list. If no greater element exists, the function should return `-1` for that element. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_next_greater_elements(lst: List[int]) -> List[int]: """ Returns a new list with the next greater element for each element in the input list. Args: lst (List[int]): The input list of ...
code_exercise_27k
16,979
Write a Python function to find the shortest path from a source vertex to all other vertices in an unweighted graph using Breadth-First Search (BFS). The graph is represented as an adjacency list. The function should return the shortest path distances from the source to all other vertices and the shortest paths themsel...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List from collections import deque def bfs_shortest_path_unweighted(graph: Dict[str, List[str]], source: str) -> (Dict[str, int], Dict[str, List[str]]): """ Find the shortest path from a source vertex t...
code_exercise_27k
16,981
Write a Python function to determine if a given graph is a permutation bipartite graph. A permutation bipartite graph is a graph where the vertices can be divided into two sets such that every edge connects a vertex from one set to a vertex from the other set. The function should take an adjacency list representation o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_permutation_bipartite(graph: List[List[int]]) -> bool: """ Determine if a given graph is a permutation bipartite graph. Parameters: graph (List[List[int]]): An adjacency list representing...
code_exercise_27k
16,985
Write a Python function to detect if a directed graph contains a cycle using Depth First Search (DFS). The graph is represented as an adjacency list. The function should return `True` if the graph contains a cycle, and `False` otherwise. The code should start with: ```python from typing import Dict, List def has_cycl...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def has_cycle_dfs(graph: Dict[int, List[int]]) -> bool: """ Detects if a directed graph contains a cycle using Depth First Search (DFS). Args: graph: A dictionary representing the dire...
code_exercise_27k
16,986
Write a Python function to find the longest palindromic substring in a given string. The function should return the longest palindromic substring found in the input string. If there are multiple palindromic substrings of the same maximum length, return any one of them. The code should start with: ```python def longest...
Here is the Python code to solve the given problem in the markdown block: ```python def longest_palindromic_substring(s: str) -> str: """ Find the longest palindromic substring in a given string. Args: s (str): The input string. Returns: str: The longest palindromic substring. """ ...
code_exercise_27k
16,989
Write a Python function to count the number of islands in a given 2D matrix using Depth-First Search (DFS). The matrix contains 0s and 1s, where 0 represents water and 1 represents land. An island is defined as a group of 1s (land) connected horizontally or vertically. The function 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 def count_islands(matrix: List[List[int]]) -> int: """ Counts the number of islands in a given 2D matrix using Depth-First Search (DFS). Args: matrix: A 2D list containing 0s and 1s, where 0...
code_exercise_27k
16,992
Write a Python function to find the smallest missing positive integer that cannot be obtained from a given list of numbers. The function should efficiently determine the smallest positive integer that is not present in the list. The code should start with: ```python from typing import List def find_smallest_missing_po...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_smallest_missing_positive(nums: List[int]) -> int: """ Finds the smallest positive integer that is missing from the given list of numbers. Args: nums (List[int]): The list of number...
code_exercise_27k
16,994
Write a Python function to determine if a given number is a perfect square without using the `sqrt()` function. The function should efficiently check if the number can be expressed as the square of an integer. The code should start with: ```python def is_perfect_square(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_square(num: int) -> bool: """ Determine if a given number is a perfect square without using the sqrt() function. Args: num (int): The number to check. Returns: bool: True if the number is...
code_exercise_27k
16,999
Write a Python function to check if a given string is a valid IPv4 address. An IPv4 address consists of four decimal numbers, each ranging from 0 to 255, separated by dots. The function should handle edge cases such as empty strings, strings with invalid characters, and strings with incorrect number of parts. The code...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_ipv4(ip_address: str) -> bool: """ Check if the provided string is a valid IPv4 address. Args: ip_address (str): The string to be checked. Returns: bool: True if the string is a valid IPv4 ...
code_exercise_27k
17,006
Write a Python function to count the number of reachable nodes from a given source node within a certain number of steps using Breadth-First Search (BFS). The graph is represented as an adjacency list. The function should start with: ```python from typing import Dict, List, Set def count_reachable_nodes(graph: Dict[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Set from collections import deque def count_reachable_nodes(graph: Dict[int, List[int]], source: int, steps: int) -> int: """ Counts the number of reachable nodes from a given source node within a...
code_exercise_27k
17,010
Write a Python function to check if an undirected graph is bipartite using Depth First Search (DFS). A bipartite graph is a graph whose vertices can be divided into two disjoint and independent sets such that no two graph vertices within the same set are adjacent. The function should take a dictionary representing the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def check_bipartite_dfs(graph: Dict[str, List[str]]) -> bool: """ Check if an undirected graph is bipartite using Depth First Search (DFS). Args: graph (Dict[str, List[str]]): A dictio...
code_exercise_27k
17,013
Write a Python function to find the connected components in an undirected graph using Depth-First Search (DFS). The graph is represented as an adjacency list. Each key in the dictionary represents a node, and the corresponding value is a list of nodes connected to that key. The function should return a list of connecte...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def dfs(graph: Dict[str, List[str]], node: str, visited: set, component: List[str]) -> None: """ Perform Depth-First Search (DFS) traversal on the given graph starting from the specified node. ...
code_exercise_27k
17,014
Write a Python function to check if a given string is a valid IPv6 address. The function should adhere to the IPv6 address format as specified in RFC 4291. An IPv6 address consists of eight groups of four hexadecimal digits, separated by colons. Each group represents 16 bits of the address. The function should handle t...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_ipv6_address(address: str) -> bool: """ Check if a given string is a valid IPv6 address. Args: address (str): The address string to be checked. Returns: bool: True if the address is a valid...
code_exercise_27k
17,015
Write a Python function to find the maximum biclique in a hypergraph. A hypergraph is represented as a dictionary where the keys are vertices and the values are sets of hyperedges that contain each vertex. A biclique in a hypergraph is a set of vertices such that every pair of vertices in the set is connected by a hype...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def find_max_biclique(hypergraph: Dict[int, Set[int]]) -> Set[int]: """ Find the maximum biclique in a hypergraph. Args: hypergraph (Dict[int, Set[int]]): Dictionary representing the hy...
code_exercise_27k
17,016
Write a Python function to perform a breadth-first search (BFS) on a graph. The graph is represented as an adjacency list, where each key in the dictionary represents a node in the graph, and the corresponding value is a list of neighbors for that node. The function should return the nodes visited during the BFS traver...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque def bfs(graph, start): """ Perform a breadth-first search (BFS) on a graph. Parameters: graph (dict): The graph represented as an adjacency list. Each key in the dictiona...
code_exercise_27k
17,018
Write a Python function to perform a Depth First Search (DFS) traversal on a given graph and return the visited nodes in the order they were visited. The graph is represented as a dictionary where keys are nodes and values are lists of neighboring nodes. The function should start from a specified node and traverse the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def dfs_traversal(graph: Dict[Any, List[Any]], start: Any) -> List[Any]: """ Perform a Depth First Search traversal on a graph and return the visited nodes in order. Args: graph (...
code_exercise_27k
17,034
Write a Python function to perform a Depth-First Search (DFS)-based topological sort on a directed acyclic graph (DAG). The function should take a dictionary representing the DAG as input, where each key is a node and the corresponding value is a list of its neighboring nodes. The function should return a list represen...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def topological_sort(graph: Dict[str, List[str]]) -> List[str]: """ Perform a DFS-based topological sort on a directed acyclic graph (DAG). Args: graph (dict): A dictionary representin...
code_exercise_27k
17,037
Write a Python function to add a new vertex to an existing directed graph represented as a dictionary. The function should ensure that the new vertex does not already exist in the graph. If the vertex already exists, the function should raise a `KeyError`. The function should return the updated graph with the new verte...
Here is the Python code to solve the given problem in the markdown block: ```python def add_vertex(graph: dict, vertex: str) -> dict: """ Adds a new vertex to an existing directed graph. Args: graph (dict): The existing directed graph in the format {vertex: [outgoing_vertices]}. vertex (str...
code_exercise_27k
17,038
Write a Python function to remove a vertex from an existing graph represented as an adjacency list. The function should handle the removal of the vertex and any references to it in the neighbor lists of other vertices. The function should also raise a `KeyError` if the specified vertex does not exist in the graph. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def remove_vertex(graph: Dict[Any, List[Any]], vertex: Any) -> Dict[Any, List[Any]]: """ Remove a vertex from an existing graph represented as an adjacency list. Args: graph (Dict...
code_exercise_27k
17,042
Write a Python function to find the connected components in an undirected graph using Depth First Search (DFS). The graph is represented as a dictionary of adjacency lists. The function should return a list of lists, where each inner list represents a connected component. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def find_connected_components(graph: Dict[int, List[int]]) -> List[List[int]]: """ Find the connected components in an undirected graph using Depth First Search (DFS). Parameters: graph (d...
code_exercise_27k
17,050
Write a Python function to find the shortest path between two nodes in a graph using Depth-First Search (DFS). The graph is represented as a dictionary where each key is a node and the value is a list of adjacent nodes. The function should return the shortest path as a list of nodes from the start node to the end node....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any, Optional def find_shortest_path_dfs(graph: Dict[Any, List[Any]], start: Any, end: Any) -> Optional[List[Any]]: """ Find the shortest path between two nodes in a graph using Depth-First Search...
code_exercise_27k
17,052
Write a Python function to determine if a directed graph contains a cycle. The graph is represented as an adjacency list using a dictionary where each key is a node and the value is a list of nodes that the key node points to. The function should return `True` if the graph contains a cycle and `False` otherwise. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict def is_cyclic(graph: dict) -> bool: """ Determine if a directed graph contains a cycle. Args: graph (dict): The directed graph represented as an adjacency list. Returns: ...
code_exercise_27k
17,054
Write a Python function to find the shortest path between two vertices in an unweighted graph using Breadth-First Search (BFS). The graph is represented as an adjacency list. The function should return the shortest path as a list of vertices, including both the start and end vertices. If no path exists, the function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque from typing import Dict, List, Union def find_shortest_path(graph: Dict[Union[int, str], List[Union[int, str]]], start: Union[int, str], end: Union[int, str]) -> List[Union[int, str]]: """ Find the...