source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
17,955
Write a Python function to implement the A* algorithm with a maximum number of iterations or depth limit. The function should take the starting state, goal state, heuristic function, successors function, cost function, and an optional maximum number of iterations as parameters. The function should return the path from ...
Here is the Python code to solve the given problem in the markdown block: ```python def astar_with_limit(start, goal, heuristic, successors, cost, max_iterations=None): """ A* algorithm with a maximum number of iterations or depth limit. Parameters: start: The starting state of the search. goal: Th...
code_exercise_27k
17,962
Write a Python function to find all possible paths between two vertices in an undirected graph. The graph is represented as a dictionary where keys are vertices and values are lists of adjacent vertices. The function should return a list of all possible paths from the start vertex to the end vertex, where each path is ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def find_all_paths(graph: Dict[Any, List[Any]], start_vertex: Any, end_vertex: Any) -> List[List[Any]]: """ Find all possible paths between two vertices in an undirected graph. Args: ...
code_exercise_27k
17,967
Write a Python function to perform a topological sort on a directed acyclic graph (DAG) using Kahn's algorithm. The function should return the topological ordering of the vertices. If the graph contains a cycle, the function should raise a `ValueError`. The code should start with: ```python from collections import def...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict, deque from typing import Dict, List def topological_sort(graph: Dict[str, List[str]]) -> List[str]: """ Perform topological sort on a directed acyclic graph using Kahn's algorithm. Args...
code_exercise_27k
17,974
Write a Python function to find the shortest path between two vertices in a weighted graph using Dijkstra's algorithm. The graph is represented as a dictionary where the keys are the vertices, and the values are lists of tuples representing neighboring vertices and their distances. The function should return a list of ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple from heapq import heappop, heappush def find_shortest_path(graph: Dict[str, List[Tuple[str, int]]], source: str, target: str) -> List[str]: """ Find the shortest path between two vertices in...
code_exercise_27k
17,978
Write a Python function to determine if a given graph is planar or not. A graph is planar if it can be drawn in a plane without any edges crossing. The graph is represented as a dictionary where keys are vertices and values are lists of vertices that each vertex is connected to. The code should start with: ```python f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def is_planar(graph: Dict[int, List[int]]) -> bool: """ Determine if a given graph is planar. A graph is planar if it can be drawn in a plane without any edges crossing. Parameters: g...
code_exercise_27k
17,983
Write a Python function to check if a given directed graph contains a cycle or not. The graph is represented as a dictionary where the keys are the nodes of the graph, and the values are lists of nodes that the key node points to. The function should return `True` if the graph contains a cycle, and `False` otherwise. ...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict def has_cycle(graph: dict) -> bool: """ Check if a given directed graph contains a cycle or not. Args: graph (dict): A dictionary representing the directed graph. The keys are th...
code_exercise_27k
18,003
Write a Python function to find all reachable nodes from a given vertex in a directed graph using Depth-First Search (DFS). The graph is represented as a dictionary where keys are vertices and values are sets of adjacent vertices. The function should return a set of all reachable nodes from the given starting vertex. I...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set, Any def find_reachable_nodes(graph: Dict[Any, Set[Any]], start: Any) -> Set[Any]: """ Find all reachable nodes from a given vertex in a directed graph using DFS. Args: graph (Dict[Any,...
code_exercise_27k
18,008
Write a Python function to perform a depth-first search (DFS) on a given graph represented as an adjacency list. The function should return the order in which nodes were visited. The code should start with: ```python from typing import Dict, List, Any def depth_first_search(graph: Dict[Any, List[Any]], start_node: Any...
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 represented as an adjacency list. Args: graph (Dict[...
code_exercise_27k
18,013
Write a Python function to detect if an undirected graph contains a bipartite cycle. A bipartite cycle is a cycle in which the vertices can be divided into two disjoint sets such that no two vertices within the same set are adjacent. The function should return `True` if the graph contains a bipartite cycle, and `False`...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict def is_bipartite_cycle(graph: dict) -> bool: """ Check if an undirected graph contains a bipartite cycle. Parameters: graph (dict): An undirected graph represented as a dictionary, ...
code_exercise_27k
18,017
Write a Python function to find the largest clique in a given graph. A clique is a subset of nodes in the graph where every pair of nodes is connected. The graph is represented as a dictionary where the keys are nodes and the values are lists of nodes that are connected to the key node. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List from itertools import combinations def find_largest_clique(graph: Dict[int, List[int]]) -> List[int]: """ Finds the largest clique in a graph. Args: graph (Dict[int, List[int]]): A dic...
code_exercise_27k
18,027
Write a Python function to find the maximum element in an array of integers. The function should handle an empty array by raising a `ValueError`. The code should start with: ```python from typing import List def find_maximum(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_maximum(arr: List[int]) -> int: """ Find the maximum element in an array of integers. Args: arr (List[int]): A list of integers. Returns: int: The maximum element in th...
code_exercise_27k
18,029
Write a Python function to sort an array of integers in ascending order using the bubble sort algorithm. The function should be able to handle arrays with duplicate elements and should return the sorted array. 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 an array of integers in ascending order using the bubble sort algorithm. Parameters: arr (List[int]): The array to be sorted. Returns...
code_exercise_27k
18,036
Write a Python function to reverse a given string without using any built-in reverse functions or methods. The function should iterate through the string and construct the reversed string manually. The code should start with: ```python def reverse_string(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(s: str) -> str: """ Reverses a given string without using any built-in reverse functions or methods. Args: s (str): The string to be reversed. Returns: str: The reversed string. "...
code_exercise_27k
18,040
Write a Python function to merge two sorted arrays into a single sorted array. The function should efficiently combine the elements from both arrays while maintaining the sorted order. The code should start with: ```python from typing import List def merge_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]: """ Merge two sorted arrays into a single sorted array. Args: arr1 (List[int]): The first sorted array. arr2 (...
code_exercise_27k
18,043
Write a Python function to check if a given number is a prime number. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as numbers less than or equal to 1, which are not prime. The code should start with: ```python def is_prime(num: int) -> bool: ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Check if a given number is a prime number. Parameters: num (int): The number to be checked for primality. Returns: bool: True if the number is prime, False otherwise. """...
code_exercise_27k
18,047
Write a Python function to determine if a given graph is 3-colorable. A graph is 3-colorable if it is possible to assign one of three colors to each node such that no two adjacent nodes share the same color. The graph is represented as an adjacency list using a dictionary where keys are nodes and values are sets of nei...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict def is_3_colorable(graph: dict) -> bool: """ Determine if a given graph is 3-colorable. Parameters: graph (dict): A dictionary representing the adjacency list of the graph. ...
code_exercise_27k
18,049
Write a Python function to calculate the nth Fibonacci number using an iterative approach. The function should efficiently compute the Fibonacci number for any non-negative integer `n`. The code should start with: ```python def fibonacci(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using an iterative approach. Args: n (int): The index of the Fibonacci number to calculate. Returns: int: The nth Fibonacci number. ...
code_exercise_27k
18,056
Write a Python function to remove duplicates from a given list while preserving the order of the elements. The function should return a new list with all duplicate elements removed. The code should start with: ```python from typing import List def remove_duplicates_preserve_order(lst: List) -> 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) -> 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
18,059
Write a Python function to determine whether two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should be case-insensitive and should ignore spaces. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python def are_anagrams(str1: str, str2: str) -> bool: """ Determines whether two strings are anagrams of each other. Args: str1 (str): The first string. str2 (str): The second string. Returns: bool: T...
code_exercise_27k
18,068
Write a Python function to determine the most frequently occurring element in a given array. If there are multiple elements with the same highest frequency, return the first one encountered in the array. The function should handle empty arrays by returning `None`. The code should start with: ```python from typing impor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_most_frequent_element(arr: List[int]) -> Optional[int]: """ Determine the most frequently occurring element in a given array. Args: arr (List[int]): The input array of int...
code_exercise_27k
18,078
Write a Python function to perform a binary search on a sorted list to find the index of a target element. The function should return the index of the target element if it is found in the list, or -1 if the target element is not found. The code should start with: ```python from typing import List, Union def binary_sea...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def binary_search(arr: List[Union[int, float, str]], target: Union[int, float, str]) -> int: """ Perform a binary search on a sorted list to find the index of a target element. Args: ...
code_exercise_27k
18,090
Write a Python function to sort an array of integers using the insertion sort algorithm. The function should modify the input array in place and return the sorted array. The code should start with: ```python from typing import List def insertion_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 insertion_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers using the insertion sort algorithm. The function modifies the input array in place and returns the sorted array. ...
code_exercise_27k
18,093
Write a Python function to determine if a given string contains any duplicate characters. The function should return `True` if there are any duplicate characters in the string, and `False` otherwise. The function should be efficient and should handle both lowercase and uppercase characters as distinct. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python def has_duplicate_chars(string: str) -> bool: """ Determines if a given string contains any duplicate characters. Args: string (str): The input string to be checked for duplicate characters. Returns: bo...
code_exercise_27k
18,095
Write a Python function to find the largest continuous sum in an array of integers. The function should handle both positive and negative integers and return the largest sum of any contiguous subarray. If the array is empty, the function should return 0. The code should start with: ```python from typing import List d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_continuous_sum(arr: List[int]) -> int: """ Finds the largest continuous sum in an array of integers. Args: arr (List[int]): A list of integers. Returns: int: Th...
code_exercise_27k
18,096
Write a Python function to find all simple paths between two vertices in a directed graph. The function should return a list of all possible paths from the start vertex to the end vertex, where each path is represented as a list of vertices. The graph is represented as a dictionary where keys are vertices and values ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def find_all_paths(graph: Dict[Any, List[Any]], start: Any, end: Any) -> List[List[Any]]: """ Finds all simple paths between two vertices in a directed graph. Args: graph (Dict[An...
code_exercise_27k
18,099
Write a Python function to remove all occurrences of a specified element from a given list and return the modified list. The function should handle lists of any data type and should not modify the original list. The code should start with: ```python from typing import List, Any def remove_element(array: List[Any], ele...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def remove_element(array: List[Any], element: Any) -> List[Any]: """ Remove all occurrences of a specified element from a given list and return the modified list. Args: array (List[Any]...
code_exercise_27k
18,103
Write a Python function to find the common elements between two given lists. The function should return a list of these common elements, sorted in ascending order. The code should start with: ```python from typing import List def find_common_elements(list1: List[int], list2: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_common_elements(list1: List[int], list2: List[int]) -> List[int]: """ Find the common elements between two lists and return them sorted in ascending order. Args: list1 (List[int]): ...
code_exercise_27k
18,125
Write a Python function to determine whether 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: """ Determines whether a given number is a power of two using bitwise operations. Parameters: num (int): The number to check. Returns: bool: True if the nu...
code_exercise_27k
18,127
Write a Python function to implement the merge sort algorithm for sorting a list. The function should recursively divide the list into halves until each sublist contains only one element, and then merge the sorted sublists back together. The code should start with: ```python from typing import List def merge_sort(arr:...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts a given list using the merge sort algorithm. Args: arr (List[int]): The list to be sorted. Returns: List[int]: The sorte...
code_exercise_27k
18,133
Write a Python function to determine whether a given string is balanced with respect to parentheses, brackets, and curly braces. A string is considered balanced if every opening symbol (i.e., `(`, `[`, `{`) has a corresponding closing symbol (i.e., `)`, `]`, `}`) in the correct order. The function should return `True` ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_balanced_parentheses(s: str) -> bool: """ Check if a given string is balanced with respect to parentheses, brackets, and curly braces. Args: s (str): The string to be checked. Returns: bool: True...
code_exercise_27k
18,136
Write a Python function to determine if a given number is a perfect square. The function should handle both integer and floating-point inputs. If the input is a floating-point number, it should be checked if it is a perfect square of an integer. The function should return `True` if the number is a perfect square, and `...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_perfect_square(number: float) -> bool: """ Determine if the given number is a perfect square. Args: number (float): The number to check. Returns: bool: True if the number is a perfec...
code_exercise_27k
18,143
Write a Python function to determine whether a given string is a valid IPv4 address. An IPv4 address consists of four decimal numbers separated by dots, where each number ranges from 0 to 255. The function should handle edge cases such as leading zeros, non-numeric characters, and incorrect number of parts. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_ipv4(address: str) -> bool: """ Check if the given string is a valid IPv4 address. Parameters: address (str): The string to be checked. Returns: bool: True if the string is a valid IPv4 address, Fa...
code_exercise_27k
18,148
Write a Python function to find the kth smallest element in an unsorted array efficiently. The function should handle edge cases such as an empty array or an out-of-bounds k value. The code should start with: ```python from typing import List def find_kth_smallest(nums: List[int], k: int) -> int: ```
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 an unsorted array using the Quickselect algorithm. Args: nums (List[int]): The unsorted array of ...
code_exercise_27k
18,154
Write a Python function to determine whether a given list of integers is in non-decreasing order. The function should return `True` if the list is in non-decreasing order, and `False` otherwise. The code should start with: ```python from typing import List def is_non_decreasing_order(numbers: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_non_decreasing_order(numbers: List[int]) -> bool: """ Determine whether a given list of integers is in non-decreasing order. Args: numbers (List[int]): A list of integers to be checke...
code_exercise_27k
18,161
Implement Dijkstra's algorithm to find the shortest path from a given starting node to all other nodes in a weighted graph. The graph is represented as an adjacency list where each key is a node and the value is a dictionary of its neighbors and the corresponding edge weights. The code should start with: ```python fro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple import heapq def dijkstra_shortest_path(graph: Dict[int, Dict[int, int]], start: int) -> Dict[int, int]: """ Find the shortest path from a starting node to all other nodes in a weighted grap...
code_exercise_27k
18,167
Write a Python function to generate all possible combinations of a given list of numbers for a specified combination length. The function should return a list of tuples, where each tuple represents a combination of the specified length. The code should start with: ```python from typing import List, Tuple from itertools...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple from itertools import combinations def generate_combinations(numbers: List[int], length: int) -> List[Tuple[int, ...]]: """ Generate all possible combinations of a given list of numbers for a spec...
code_exercise_27k
18,171
Write a Python function to perform a breadth-first search (BFS) traversal on a graph starting from a given node. The graph is represented as a dictionary where each key is a node and the corresponding value is a list of neighboring nodes. The function should return the order of visited nodes in BFS traversal. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque def breadth_first_search(graph: dict, start: any) -> list: """ Perform breadth-first search traversal on a graph starting from a given node. Args: graph (dict): A dictionary representi...
code_exercise_27k
18,180
Write a Python function to implement the selection sort algorithm for sorting a list in descending order. The function should take a list of comparable elements as input and return the sorted list in descending order. The code should start with: ```python from typing import List def selection_sort_descending(lst: List...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def selection_sort_descending(lst: List[int]) -> List[int]: """ Sorts a list in descending order using the selection sort algorithm. Args: lst (List[int]): The list of comparable elements ...
code_exercise_27k
18,191
Write a Python function to determine if a given number is a happy number. A happy number is defined by the following process: - Starting with any positive integer, replace the number by the sum of the squares of its digits. - Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_happy_number(num: int) -> bool: """ Determines if a given number is a happy number. A happy number is defined by the following process: - Starting with any positive integer, replace the number by the sum of the s...
code_exercise_27k
18,196
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given array. The function should return the length of the LIS. The code should start with: ```python from typing import List def longest_increasing_subsequence(arr: 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(arr: List[int]) -> int: """ Calculate the length of the longest increasing subsequence in an array. Args: arr (List[int]): The input array. Returns: ...
code_exercise_27k
18,203
Write a Python function to determine whether a given string is a valid mathematical expression. The expression can contain digits, the operators `+`, `-`, `*`, `/`, and parentheses `(` and `)`. The function should ensure that the parentheses are properly balanced and nested, and that the expression contains only valid ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_math_expr(s: str) -> bool: """ Determine whether a given string is a valid mathematical expression. Parameters: s (str): The input string to be checked. Returns: bool: True if the string is...
code_exercise_27k
18,207
Write a Python function to find the k closest points to a given target point in a set of 2D coordinates. The function should return the k closest points based on Euclidean distance. The code should start with: ```python from typing import List, Tuple import math def find_k_closest_points(points: List[Tuple[float, floa...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import math def find_k_closest_points(points: List[Tuple[float, float]], k: int, target: Tuple[float, float]) -> List[Tuple[float, float]]: """ Finds the k closest points to a given target point i...
code_exercise_27k
18,217
Write a Python function to find the length of the longest common subsequence (LCS) between two given strings. The function should return the length of the LCS, not the subsequence itself. The code should start with: ```python def longest_common_subsequence_length(str1: str, str2: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence_length(str1: str, str2: str) -> int: """ Calculate the length of the longest common subsequence between two strings. Args: str1 (str): The first input string. str2 (str): The s...
code_exercise_27k
18,218
Write a Python function to find the cut vertices (articulation points) in a connected undirected graph. The graph is represented as a dictionary where keys are vertices and values are lists of adjacent vertices. The function should return a list of cut vertices. 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 Dict, List from collections import defaultdict def find_cut_vertices(graph: Dict[int, List[int]]) -> List[int]: """ Find cut vertices (articulation points) in a connected undirected graph. Args: ...
code_exercise_27k
18,220
Write a Python function to solve the 0/1 Knapsack problem using dynamic programming. The function should take three parameters: a list of item weights, a list of item values, and the total capacity of the knapsack. The function should return the maximum value that can be obtained by selecting items such that the total ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def knapsack_max_value(weights: List[int], values: List[int], capacity: int) -> int: """ Solve the 0/1 Knapsack problem using dynamic programming. Args: weights (List[int]): List of item wei...
code_exercise_27k
18,225
Write a Python function to determine if two given graphs are isomorphic. The graphs are represented as adjacency lists. The function should check if there exists a one-to-one correspondence between the nodes of the two graphs such that the adjacency relationships are preserved. The code should start with: ```python fr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def are_graphs_isomorphic(graph1: Dict[int, List[int]], graph2: Dict[int, List[int]]) -> bool: """ Determine if two graphs are isomorphic. Args: graph1 (Dict[int, List[int]]): The firs...
code_exercise_27k
18,227
Write a Python function to determine if a given number is a perfect cube. The function should handle both positive and negative integers. The code should start with: ```python def is_perfect_cube(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_cube(num: int) -> bool: """ Determine if a given number is a perfect cube. Args: num (int): The number to be checked. Returns: bool: True if the number is a perfect cube, False otherwise....
code_exercise_27k
18,240
Write a Python function to find the longest palindromic substring in a given string. A palindromic substring is a substring that reads the same forwards and backwards. The function should return the longest such substring found in the input string. The code should start with: ```python def longest_palindromic_substrin...
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 found in ...
code_exercise_27k
18,257
Write a Python function to find the top k most frequent elements in a given array. The function should return a list of the top k elements in descending order of their frequency. If there are ties in frequency, the elements should be returned in the order they first appear in the array. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import Counter def top_k_frequent_elements(arr: List[int], k: int) -> List[int]: """ Finds the top k most frequent elements in the given array. Args: arr (List[int]): The in...
code_exercise_27k
18,260
Write a Python function to remove all occurrences of a specified number from a given set. The function should return the modified set after removing the specified number. If the number is not present in the set, the function should return the original set unchanged. The code should start with: ```python def remove_num...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_number_from_set(my_set: set, number: int) -> set: """ Removes all occurrences of a specified number from a given set. Args: my_set (set): The set from which the number will be removed. number (int...
code_exercise_27k
18,264
Write a Python function to find the length of a given set. The function should validate that the input is indeed a set and raise a `TypeError` if it is not. The code should start with: ```python def get_set_length(input_set: set) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def get_set_length(input_set: set) -> int: """ Calculate the length of a given set. Args: input_set (set): The input set whose length is to be calculated. Returns: int: The length of the input set. ...
code_exercise_27k
18,268
Write a Python function to find the intersection of two sets `set1` and `set2`. The intersection of two sets is a set containing all elements that are present in both sets. The function should be efficient and handle any size of input sets. The code should start with: ```python def intersection(set1: set, set2: set) -...
Here is the Python code to solve the given problem in the markdown block: ```python def intersection(set1: set, set2: set) -> set: """ Finds the intersection of two sets. The intersection of two sets is a new set that contains all elements that are present in both sets. Args: set1 (set): The f...
code_exercise_27k
18,269
Write a Python function to check if a given set is empty or not. The function should return `True` if the set is empty and `False` otherwise. The code should start with: ```python def is_set_empty(my_set: set) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_set_empty(my_set: set) -> bool: """ Check if a given set is empty. Args: my_set (set): The set to be checked for emptiness. Returns: bool: True if the set is empty, False otherwise. """ #...
code_exercise_27k
18,276
Write a Python function to check if a specific element is present in a given set. The function should return `True` if the element is found in the set, and `False` otherwise. The code should start with: ```python def is_element_in_set(element: str, input_set: set) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_element_in_set(element: str, input_set: set) -> bool: """ Check if a specific element is present in the given set. Args: element (str): The element to check for in the set. input_set (set): A set of s...
code_exercise_27k
18,278
Write a Python function to find the intersection of two lists, i.e., the elements that are present in both lists. The function should return a list containing these common elements, sorted in ascending order. The code should start with: ```python from typing import List def find_intersection(list1: List[int], list2: L...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def find_intersection(list1: List[int], list2: List[int]) -> List[int]: """ Find the intersection of two lists and return the common elements sorted in ascending order. Args: list1 (List[i...
code_exercise_27k
18,279
Write a Python function to determine whether a given string can be segmented into meaningful words using a given dictionary. The function should return `True` if the string can be segmented into words that are present in the dictionary, and `False` otherwise. The code should start with: ```python def can_segment_string...
Here is the Python code to solve the given problem in the markdown block: ```python def can_segment_string(string: str, dictionary: set) -> bool: """ Determines whether a given string can be segmented into meaningful words using a given dictionary. Args: string (str): The input string to be segment...
code_exercise_27k
18,281
Write a Python function to find the common elements between two given sets and return them as a new set. The function should handle cases where one or both sets are empty. The code should start with: ```python def find_common_elements(set1: set, set2: set) -> set: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_common_elements(set1: set, set2: set) -> set: """ Find and return the common elements between two sets. Args: set1 (set): The first set. set2 (set): The second set. Returns: set: A new ...
code_exercise_27k
18,286
Write a Python function to check if all the elements in a given list `list1` are present in another list `list2`. The function should return `True` if all elements in `list1` are found in `list2`, and `False` otherwise. The function should handle lists of any length, including empty lists. The code should start with: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def check_all_elements_present(list1: List[int], list2: List[int]) -> bool: """ Check if all the elements in list1 are present in list2. Args: list1 (List[int]): The first list of integers. ...
code_exercise_27k
18,288
Write a Python function to find the symmetric difference between two sets, which is defined as the set of elements that are in either of the sets but not in both. The function should return a new set containing the symmetric difference. The code should start with: ```python def symmetric_difference(set1: set, set2: se...
Here is the Python code to solve the given problem in the markdown block: ```python def symmetric_difference(set1: set, set2: set) -> set: """ Compute the symmetric difference between two sets. The symmetric difference is defined as the set of elements that are in either of the sets but not in both. ...
code_exercise_27k
18,292
Write a Python function to find the maximum value in a given collection of numbers. The collection can be a list, set, or tuple. The function should handle empty collections by raising a `ValueError`. The code should start with: ```python from typing import Union, List, Set, Tuple def find_max_value(numbers: Union[Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union, List, Set, Tuple def find_max_value(numbers: Union[List[Union[int, float]], Set[Union[int, float]], Tuple[Union[int, float], ...]]) -> Union[int, float]: """ Find the maximum value in a given collectio...
code_exercise_27k
18,295
Write a Python function to find all the unique vowels present in a given set of letters. The input can be either a list of characters or a string. The function should return a set of unique vowels found in the input. The code should start with: ```python from typing import List, Union def find_unique_vowels(letters: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_unique_vowels(letters: Union[List[str], str]) -> set: """ Find all the unique vowels present in a given set of letters. Args: letters (Union[List[str], str]): A list of chara...
code_exercise_27k
18,296
Write a Python function to find the symmetric difference between two sets `set1` and `set2`. The symmetric difference is defined as the set of elements which are in either of the sets, but not in their intersection. The code should start with: ```python def find_symmetric_difference(set1: set, set2: set) -> set: ```
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 is the set of elements which are in either of the sets, but not in their intersec...
code_exercise_27k
18,297
Write a Python function to check if two sets have any elements in common. The function should return `True` if there is at least one common element between the two sets, and `False` otherwise. The code should start with: ```python def has_common_elements(set1: set, set2: set) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def has_common_elements(set1: set, set2: set) -> bool: """ Check if two sets have any elements in common. Args: set1 (set): The first set. set2 (set): The second set. Returns: bool: True if the ...
code_exercise_27k
18,298
Write a Python function to shuffle a given list using the Fisher-Yates algorithm. The function should return a new list that is a shuffled version of the input list, without modifying the original list. The code should start with: ```python from typing import List import random def shuffle_list(lst: List[int]) -> List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_list(lst: List[int]) -> List[int]: """ Shuffle a list using the Fisher-Yates algorithm. Args: lst (List[int]): The list to be shuffled. Returns: List[i...
code_exercise_27k
18,300
Write a Python function to remove duplicate elements from a given list while preserving the order of the first occurrence of each element. The function should use a set to track seen elements and a list to maintain the order of elements. The code should start with: ```python from typing import List def remove_duplicat...
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 duplicate elements from a list while preserving the order of the first occurrence of each element. Args: lst (list): Th...
code_exercise_27k
18,303
Write a Python function to determine whether a given string is a valid palindrome, with the option to ignore casing and non-alphanumeric characters. The function should return `True` if the string is a valid palindrome, and `False` otherwise. The function should handle both cases where the casing is ignored and where i...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_palindrome(string: str, ignore_case: bool = False) -> bool: """ Determines whether a given string is a valid palindrome, with the option to ignore casing and non-alphanumeric characters. Args: string (s...
code_exercise_27k
18,304
Write a Python function to generate all possible combinations of elements from two given sets `set1` and `set2`. Each combination should be a tuple where the first element is from `set1` and the second element is from `set2`. The function should return a set of these combinations. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Set, Tuple def generate_combinations(set1: Set[int], set2: Set[int]) -> Set[Tuple[int, int]]: """ Generate all possible combinations of elements from two sets. Args: set1 (Set[int]): The first se...
code_exercise_27k
18,306
Write a Python function to find the maximum product of two distinct numbers in a given list of integers. The function should handle the case where the list contains at least two elements. If the list contains fewer than two elements, the function should raise a `ValueError`. The code should start with: ```python from ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_product(numbers: List[int]) -> int: """ Find the maximum product of two distinct numbers in a given list of integers. Args: numbers (List[int]): A list of integers. Returns...
code_exercise_27k
18,307
Write a Python function to find the maximum and minimum values in a given list of numbers without using built-in functions like `max()` and `min()`. The function should handle an empty list by raising a `ValueError`. The code should start with: ```python from typing import List, Tuple def find_max_min(numbers: List[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_max_min(numbers: List[int]) -> Tuple[int, int]: """ Finds the maximum and minimum values in a list of numbers without using built-in functions. Args: numbers (List[int]): A l...
code_exercise_27k
18,312
Write a Python function to check if a given number is a prime palindrome. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A palindrome number reads the same backward as forward. The function should return `True` if the number is both prime and a palindrome, and `...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_palindrome(number: int) -> bool: """ Check if a given number is both a prime number and a palindrome. Args: number (int): The number to check. Returns: bool: True if the number is both prim...
code_exercise_27k
18,313
Write a Python function to find and return a set of elements that occur more than once in a given list. The function should efficiently track the elements that have been seen and identify duplicates. The code should start with: ```python from typing import List, Set def find_duplicates(lst: List[int]) -> Set[int]: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Set def find_duplicates(lst: List[int]) -> Set[int]: """ Find and return a set of elements that occur more than once in the given list. Args: lst (List[int]): The input list of integers. ...
code_exercise_27k
18,324
Write a Python function to find the intersection of multiple sets using a loop. The function should take a list of sets as input and return a set containing the elements that are common to all sets in the list. The code should start with: ```python from typing import List def find_intersection(sets: List[set]) -> set:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_intersection(sets: List[set]) -> set: """ Find the intersection of multiple sets. Parameters: sets (list): A list of sets. Returns: set: The intersection of all sets in the inp...
code_exercise_27k
18,325
Write a Python function to filter out and return a set containing only the even numbers from a given set of integers. The function should handle sets of any size, including empty sets. The code should start with: ```python def get_even_numbers(nums: set) -> set: ```
Here is the Python code to solve the given problem in the markdown block: ```python def get_even_numbers(nums: set) -> set: """ Returns a set containing only the even numbers from the given set of integers. Args: nums (set): The set of integers to filter. Returns: set: A set containing...
code_exercise_27k
18,328
Write a Python function to determine whether a given string is a valid IPv6 address. An IPv6 address consists of exactly 8 parts separated by colons (:), where each part is a 16-bit hexadecimal number. The function should validate the following: 1. The address must have exactly 8 parts. 2. Each part must be non-empty a...
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 string to be checked. Returns: bool: True if the address is a valid IPv6 ad...
code_exercise_27k
18,330
Write a Python function to find the length of the longest common subarray between two given arrays. A subarray is a contiguous sequence of elements within an array. The function should use dynamic programming to efficiently compute the result. The code should start with: ```python from typing import List def longest_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_subarray_length(arr1: List[int], arr2: List[int]) -> int: """ Finds the length of the longest common subarray between two arrays. Args: arr1 (List[int]): The first array. ...
code_exercise_27k
18,332
Write a Python function to calculate the factorial of a given non-negative integer using a set. The function should handle the case where the input number is negative by raising a `ValueError`. The code should start with: ```python def factorial_with_set(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_with_set(n: int) -> int: """ Calculate the factorial of a non-negative integer using a set. Parameters: - n (int): The non-negative integer for which factorial needs to be calculated. Returns: - i...
code_exercise_27k
18,336
Write a Python function to sort a given set of numbers in ascending order using the selection sort algorithm. The function should not use any built-in sorting functions or methods. The code should start with: ```python from typing import List def selection_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 selection_sort(arr: List[int]) -> List[int]: """ Sorts a given set of numbers in ascending order using the selection sort algorithm. Args: arr (List[int]): The list of numbers to be sort...
code_exercise_27k
18,339
Write a Python function to generate a set of prime numbers between two given numbers `start` and `end`. The function should efficiently determine if a number is prime and return the set of prime numbers within the specified range. The code should start with: ```python def get_prime_numbers(start: int, end: int) -> set...
Here is the Python code to solve the given problem in the markdown block: ```python def get_prime_numbers(start: int, end: int) -> set: """ Generate a set of prime numbers between the given `start` and `end` numbers. Args: start (int): The starting number for the range. end (int): The endin...
code_exercise_27k
18,343
Write a Python function to generate the power set of a given set, which is the set of all possible subsets including the empty set and the set itself. The function should return a set of frozensets to ensure immutability and hashability. The code should start with: ```python from typing import Set def generate_power_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Set def generate_power_set(s: Set[int]) -> Set[frozenset]: """ Generate the power set of a given set. The power set is the set of all possible subsets of the input set, including the empty set and the se...
code_exercise_27k
18,351
Write a Python function to find the first non-repeating character in a given string. If no non-repeating character exists, the function should return `None`. The function should be efficient and handle edge cases such as empty strings and strings with all repeating characters. The code should start with: ```python def...
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_non_repeating_char(input_string: str) -> str: """ Find and return the first non-repeating character in a given string. Args: input_string (str): The input string to search for the first non-repeating ...
code_exercise_27k
18,367
Write a Python function to determine if a given number is a power of three. The function should return `True` if the number is a power of three, and `False` otherwise. The function should handle edge cases such as non-positive numbers and should be efficient. The code should start with: ```python def is_power_of_three...
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_three(number: int) -> bool: """ Determine if a given number is a power of three. Args: number (int): The number to be checked. Returns: bool: True if the number is a power of three, Fals...
code_exercise_27k
18,375
Write a Python function to find the maximum element in a given list using a recursive approach. The function should handle both non-empty and empty lists. For an empty list, the function should return `None`. The code should start with: ```python from typing import List, Optional def find_max_recursive(lst: List[int])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_max_recursive(lst: List[int]) -> Optional[int]: """ Recursive function to find the maximum element in a given list. Args: lst (List[int]): The list in which the maximum el...
code_exercise_27k
18,378
Write a Python function to reverse a given string using recursion. The function should take a string as input and return the reversed string. The code should start with: ```python def reverse_string(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def reverse_string(string: str) -> str: """ Reverses a given string using recursion. Args: string (str): The string to be reversed. Returns: str: The reversed string. """ # Base case: if the s...
code_exercise_27k
18,382
Write a Python function to calculate the sum of digits in a given number using recursion. The function should handle both positive and negative integers. If the input number is negative, the function should treat it as a positive number for the purpose of summing the digits. The code should start with: ```python def s...
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 using recursion. Args: number (int): The number for which to calculate the sum of digits. Returns: int: The sum o...
code_exercise_27k
18,393
Write a Python function to remove all duplicates from a given list of integers while maintaining the order of the first occurrence of each element. The function should return a new list containing only the unique elements in the order they appeared in the original list. The code should start with: ```python from typin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(numbers: List[int]) -> List[int]: """ Remove duplicates from a list of integers and return the modified list. Parameters: numbers (list): A list of integers. Returns: ...
code_exercise_27k
18,397
Write a Python function to compute the factorial of a given number using a recursive approach. The function should handle non-negative integers only. If the input number is negative, the function should raise a `ValueError`. The code should start with: ```python def factorial_recursive(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_recursive(n: int) -> int: """ Compute the factorial of a given number using a recursive approach. Parameters: n (int): The number to compute the factorial for. Returns: int: The factorial of the i...
code_exercise_27k
18,400
Write a Python function to determine if a given number is a prime number. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as numbers less than or equal to 1, which are not prime. The function should also be efficient by only checking divisors up...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime(num: int) -> bool: """ Determines if a given number is a prime number. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False oth...
code_exercise_27k
18,409
Write a Python function to merge two sorted arrays into a single sorted array. The function should efficiently combine the elements from both arrays while maintaining the sorted order. The code should start with: ```python from typing import List def merge_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]: """ Merge two sorted arrays into a single sorted array. Args: arr1 (List[int]): The first sorted array. arr2 (...
code_exercise_27k
18,412
Write a Python function to find the second largest number in a given list of integers. If the list has fewer than two elements, raise a `ValueError`. The function should handle duplicate values correctly and return the second largest distinct number. The code should start with: ```python from typing import List def f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_second_largest(numbers: List[int]) -> int: """ Find the second largest number in a given list of integers. Args: numbers (List[int]): The list of integers from which to find the sec...
code_exercise_27k
18,414
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 from typing import Dict def count_charact...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_character_occurrences(string: str) -> Dict[str, int]: """ Counts the number of occurrences of each character in a given string. Args: string (str): The input string to count charac...
code_exercise_27k
18,415
Write a Python function to calculate the sum of all numbers from 1 to n using recursion. The function should handle the case where n is less than 1 by raising a `ValueError`. The code should start with: ```python def sum_of_n(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def sum_of_n(n: int) -> int: """ Calculate the sum of all numbers from 1 to n using recursion. Args: n (int): The upper limit of the range. Returns: int: The sum of all numbers from 1 to n. Raise...
code_exercise_27k
18,419
Write a Python function to compute the power of a number using a recursive approach. The function should handle both positive and negative integer exponents. The code should start with: ```python def recursive_power(base: float, exponent: int) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def recursive_power(base: float, exponent: int) -> float: """ Computes the power of a number using a recursive approach. Args: base (float or int): The base number. exponent (int): The exponent. Returns...
code_exercise_27k
18,420
Write a Python function to find the largest sum subarray in a given array. The function should return a tuple consisting of the start index, end index, and the sum of the largest sum subarray. The code should start with: ```python from typing import List, Tuple def find_largest_sum_subarray(arr: List[int]) -> Tuple[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_largest_sum_subarray(arr: List[int]) -> Tuple[int, int, int]: """ Finds the largest sum subarray in a given array. Args: arr (List[int]): The input array. Returns: ...
code_exercise_27k
18,423
Write a Python function to find the longest common subsequence (LCS) between two given strings. The function should return the LCS as a string. The code should start with: ```python def longest_common_subsequence(str1: str, str2: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence(str1: str, str2: str) -> str: """ Finds the longest common subsequence between two strings. Args: str1 (str): The first input string. str2 (str): The second input string. ...
code_exercise_27k
18,428
Write a Python function to find the most frequently occurring element in a given list of integers. If there are multiple elements with the same highest frequency, return the smallest element among them. The function should be efficient and handle edge cases such as an empty list. 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_most_frequent_element(arr: List[int]) -> int: """ Find the most frequently occurring element in a given list of integers. If there are multiple elements with the same highest frequency, retu...
code_exercise_27k
18,431
Write a Python function to merge overlapping intervals in a given list of intervals. Each interval is represented as a tuple of start and end points. The function should return a list of merged intervals. The code should start with: ```python from typing import List, Tuple def merge_intervals(intervals: List[Tuple[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """ Merge overlapping intervals in a list. Args: intervals (List[Tuple[int, int]]): A list of intervals...
code_exercise_27k
18,451
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given array. The function should return the length of the LIS, not the subsequence itself. The code should start with: ```python from typing import List def longest_increasing_subsequence_length(arr: 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_length(arr: List[int]) -> int: """ Calculate the length of the longest increasing subsequence in a given array. Args: arr (List[int]): The input array. ...
code_exercise_27k
18,465
Write a Python function to determine if a given string is a valid parenthesis sequence using a recursive approach. The string should only contain the characters '(' and ')'. The function should return `True` if the string is a valid parenthesis sequence, and `False` otherwise. A valid parenthesis sequence is defined as...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_parenthesis_recursive(seq: str) -> bool: """ Determine if a given string is a valid parenthesis sequence using a recursive approach. Args: seq (str): The input string to check. Returns: boo...
code_exercise_27k
18,473
Write a Python function to sort a list of integers using the quicksort algorithm. The function should be able to handle lists of any size, including empty lists and lists with duplicate elements. The code should start with: ```python from typing import List def quicksort(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 quicksort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the quicksort algorithm. Args: arr (List[int]): List of integers to be sorted. Returns: List[int]:...
code_exercise_27k
18,474
Write a Python function to count the number of occurrences of a target value in a nested list using recursion. The function should handle lists that contain other lists, which may themselves contain more lists, and so on. The function should return the total count of the target value in all levels of the nested list. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, List def count_occurrences(target: Any, nested_list: List[Any]) -> int: """ Recursively counts the number of occurrences of a target value in a nested list. Args: target (Any): The value to ...