source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
18,936
Write a Python function to find a peak element in an unsorted array using a binary search algorithm. A peak element is defined as an element that is greater than its neighbors. If the array has multiple peaks, the function should return the index of any one of them. The function should handle edge cases such as an empt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_peak_element(arr: List[int]) -> Optional[int]: """ Find a peak element in an unsorted array using binary search. A peak element is defined as an element that is greater than its n...
code_exercise_27k
18,937
Write a Python function to access all elements in the lower triangle of a square 2D NumPy array. The function should return a 1D NumPy array containing all elements in the lower triangle, excluding the diagonal elements. The code should start with: ```python import numpy as np def access_lower_triangle(arr: np.ndarray...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def access_lower_triangle(arr: np.ndarray) -> np.ndarray: """ Access all elements in the lower triangle of a square 2D NumPy array, excluding the diagonal elements. Parameters: - arr (numpy.ndarray):...
code_exercise_27k
18,939
Write a Python function to access all elements in the upper triangle of a square 2D NumPy array. The function should return a flattened 1D array containing the elements of the upper triangle. The code should start with: ```python import numpy as np def access_upper_triangle(arr: np.ndarray) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def access_upper_triangle(arr: np.ndarray) -> np.ndarray: """ Access all elements in the upper triangle of a square 2D NumPy array. Parameters: arr (numpy.ndarray): The input 2D square array. Re...
code_exercise_27k
18,945
Write a Python function to multiply each element of a given NumPy array by a specified scalar value. The function should handle both positive and negative scalar values. The code should start with: ```python import numpy as np def multiply_array_by_scalar(arr: np.ndarray, scalar: float) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def multiply_array_by_scalar(arr: np.ndarray, scalar: float) -> np.ndarray: """ Multiply each element of a given NumPy array by a specified scalar value. Parameters: arr (np.ndarray): Input NumPy arr...
code_exercise_27k
18,946
Write a Python function to find the kth smallest element in two sorted arrays using a binary search algorithm. The function should efficiently determine the kth smallest element by leveraging the properties of sorted arrays. The code should start with: ```python from typing import List def find_kth_smallest_element(ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_kth_smallest_element(arr1: List[int], arr2: List[int], k: int) -> int: """ Find the kth smallest element in two sorted arrays using a binary search algorithm. Args: arr1 (List[int])...
code_exercise_27k
18,948
Write a Python function to replace all negative elements of a given NumPy array with 0. The function should handle any shape of the input array and return a new array with the same shape, where all negative values are replaced by 0. The code should start with: ```python import numpy as np def replace_negatives_with_ze...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def replace_negatives_with_zero(arr: np.ndarray) -> np.ndarray: """ Replaces all negative elements of a given NumPy array with 0. Args: arr (np.ndarray): Input NumPy array. Returns: ...
code_exercise_27k
18,957
Write a Python function to access the first element of each row in each 2D sub-array of a given 3D NumPy array. The function should return a 2D NumPy array containing the first element of each row in each 2D sub-array of the input. The code should start with: ```python import numpy as np def get_first_elements(arr: np...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def get_first_elements(arr: np.ndarray) -> np.ndarray: """ Access the first element of each row in each 2D sub-array of a given 3D NumPy array. Args: arr (numpy.ndarray): The input 3D NumPy array...
code_exercise_27k
18,961
Write a Python function to compute the mean of each column in a given 2D NumPy array. The function should return a 1D NumPy array containing the mean values of each column. The code should start with: ```python import numpy as np def compute_mean_of_columns(arr: np.ndarray) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def compute_mean_of_columns(arr: np.ndarray) -> np.ndarray: """ Computes the mean value of each column in a 2D NumPy array. Parameters: arr (numpy.ndarray): A 2D NumPy array. Returns: numpy....
code_exercise_27k
18,963
Write a Python function to find the indices of the maximum value in each row of a given 2D NumPy array. The function should handle only 2D arrays and return a 1D NumPy array containing the indices of the maximum value in each row. The code should start with: ```python import numpy as np def find_max_indices(arr: np.nd...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_max_indices(arr: np.ndarray) -> np.ndarray: """ Find the indices of the maximum value in each row of the input 2D NumPy array. Parameters: arr (numpy.ndarray): Input 2D NumPy array. Ret...
code_exercise_27k
18,964
Write a Python function to find the minimum number in a sorted and rotated array with duplicates using a binary search algorithm. The array is sorted in ascending order and then rotated at some pivot unknown to you beforehand. The function should efficiently find the minimum element in O(log n) time complexity. The co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_minimum_in_rotated_array(arr: List[int]) -> int: """ Finds the minimum number in a sorted and rotated array with duplicates using binary search. Args: arr (List[int]): The sorted an...
code_exercise_27k
18,966
Write a Python function to simulate an asynchronous recommendation system that trains on given data and generates recommendations for a user. The function should use `asyncio` to handle asynchronous operations. The recommendation system should have two main methods: `train` and `recommend`. The `train` method should si...
Here is the Python code to solve the given problem in the markdown block: ```python import asyncio class RecommendationSystem: async def train(self, data): """ Simulate the training process of the recommendation system. Args: data (str): The training data for the recommendation...
code_exercise_27k
18,967
Write a Python function to sum the values of each row in a given 2D NumPy array. The function should return a 1D NumPy array containing the sums of each row. The code should start with: ```python import numpy as np def sum_rows(array: np.ndarray) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sum_rows(array: np.ndarray) -> np.ndarray: """ Sum the values of each row in a 2D NumPy array. Parameters: array (np.ndarray): The input 2D NumPy array. Returns: np.ndarray: A 1D NumPy a...
code_exercise_27k
18,968
Write a Python function to find the intersection of two sorted arrays using a binary search approach. The function should efficiently determine the common elements between the two arrays by leveraging the binary search algorithm. The code should start with: ```python from typing import List def find_intersection_of_so...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search(arr: List[int], target: int) -> int: """ Perform binary search on a sorted array. Parameters: arr (list): The sorted array to search. target (int): The target value to find...
code_exercise_27k
18,970
Write a Python function to compute the element-wise multiplication of two 2D NumPy arrays. The function should ensure that the input arrays are 2D and have the same shape before performing the multiplication. If the input arrays do not meet these criteria, the function should raise a `ValueError`. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def element_wise_multiplication(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Compute the element-wise multiplication of two 2D NumPy arrays. Parameters: arr1 (np.ndarray): The first input 2...
code_exercise_27k
18,971
Write a Python function to find the union of two sorted arrays. The union of two arrays is a new array that contains all the unique elements from both arrays, sorted in ascending order. The function should handle arrays with duplicate elements and ensure that the resulting union array does not contain any duplicates. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_union_of_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]: """ Finds the union of two sorted arrays. Parameters: - arr1 (List[int]): The first sorted array. - arr2 (List...
code_exercise_27k
18,972
Write a Python function to compute the dot product of two 2D NumPy arrays. The function should check if the arrays are compatible for the dot product operation and raise a `ValueError` if they are not. The code should start with: ```python import numpy as np def compute_dot_product(arr1: np.ndarray, arr2: np.ndarray) ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def compute_dot_product(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Compute the dot product of two 2D NumPy arrays. Args: arr1 (numpy.ndarray): The first 2D array. arr2 (numpy....
code_exercise_27k
18,983
Write a Python function to find the largest number less than or equal to a given target number in a sorted array using a binary search algorithm. The function should return the largest number found or `None` if no such number exists. The code should start with: ```python from typing import List, Union def find_larges...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_largest_number_le_target(array: List[Union[int, float]], target: Union[int, float]) -> Union[int, float, None]: """ Find the largest number less than or equal to a given target number in ...
code_exercise_27k
18,995
Write a Python function to find the target number in a sorted matrix using binary search. The matrix is a 2D list of integers sorted in non-decreasing order both row-wise and column-wise. The function should return the row and column indices of the target number if found, otherwise return `None`. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Optional def search_in_sorted_matrix(matrix: List[List[int]], target: int) -> Optional[Tuple[int, int]]: """ Finds the target number in a sorted matrix using binary search. Args: mat...
code_exercise_27k
18,997
Write a Python function to find the shortest path between two nodes in a graph using the breadth-first search (BFS) algorithm. The graph is represented as an adjacency list. The function should return the shortest path as a list of nodes, including both the start and goal nodes. If no path exists, the function should r...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque def find_shortest_path(graph: dict, start: str, goal: str) -> list: """ Find the shortest path between two nodes in a graph using breadth-first search. Args: graph (dict): The graph re...
code_exercise_27k
19,003
Write a Python function to perform a binary search on a row-wise sorted matrix to find the target number. The matrix is a 2-dimensional list where each row is sorted in ascending order, and the first element of each row is greater than the last element of the previous row. The function should return the row and column ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def binary_search_matrix(matrix: List[List[int]], target: int) -> Tuple[int, int] or None: """ Perform a binary search to find the target number in a row-wise sorted matrix. Args: mat...
code_exercise_27k
19,009
Write a Python function to find the row and column indices of a target number in a row-wise sorted matrix. If the target number is not found, return `(-1, -1)`. The matrix is a 2D list where each row is sorted in ascending order. The function should start with: ```python from typing import List, Tuple def find_number_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_number_in_matrix(matrix: List[List[int]], target: int) -> Tuple[int, int]: """ Find the row and column indices of a target number in a row-wise sorted matrix. Args: matrix: A...
code_exercise_27k
19,016
Write a Python function to find the largest number in each row of a row-wise sorted matrix. The matrix is a 2D list where each row is sorted in ascending order. The function should return a list containing the largest number in each row. The code should start with: ```python from typing import List def find_largest_i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_in_each_row(matrix: List[List[int]]) -> List[int]: """ Find the largest number in each row of a row-wise sorted matrix. Args: matrix: A 2D list representing the row-wise sor...
code_exercise_27k
19,031
Write a Python function to find the minimum absolute difference between a target number and any element in a sorted array using a binary search algorithm. The function should return the minimum absolute difference. If the array is empty, the function should raise a `ValueError`. 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 List def find_min_abs_diff(arr: List[int], target: int) -> int: """ Finds the minimum absolute difference between a target number and any element in a sorted array. Args: arr (List[int]): The sor...
code_exercise_27k
19,038
Write a Python function to find the smallest element greater than a given target number in a sorted array using a binary search algorithm. If no such element exists, the function should return `None`. The code should start with: ```python from typing import List, Union def find_smallest_greater(arr: List[Union[int, f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_smallest_greater(arr: List[Union[int, float]], target: Union[int, float]) -> Union[int, float, None]: """ Find the smallest element greater than the target in a sorted array using binary ...
code_exercise_27k
19,039
Write a Python function to find the largest element smaller than a given target number in a sorted list. The function should efficiently handle the search using a binary search approach. If no such element exists or the list is empty, the function should return `None`. The code should start with: ```python from typing...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_largest_smaller_element(arr: List[int], target: int) -> Optional[int]: """ Find the largest element in a sorted list that is smaller than a given target number. Args: arr ...
code_exercise_27k
19,040
Write a Python function to count the number of elements in a sorted matrix that are less than a given target number using a binary search algorithm. The matrix is sorted in such a way that each row is sorted in ascending order, and each column is also sorted in ascending order. The function should efficiently count the...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_numbers_less_than(matrix: List[List[int]], target: int) -> int: """ Count the number of elements in a sorted matrix that are less than a target number. Args: matrix (List[List[int]...
code_exercise_27k
19,048
Write a Python function to find the sum of all elements in a bitonic sequence using a binary search approach. A bitonic sequence is a sequence of numbers that first increases monotonically and then decreases monotonically. The function should start with: ```python from typing import List def sum_bitonic_sequence(arr: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search_peak(arr: List[int], start: int, end: int) -> int: """ Perform binary search to find the peak index in a bitonic sequence. Args: arr: A bitonic sequence (increasing followe...
code_exercise_27k
19,050
Write a Python function to find the sum of all elements in a bitonic sequence with duplicates. A bitonic sequence is a sequence that first increases monotonically and then decreases monotonically. The function should handle sequences with duplicate elements. The code should start with: ```python from typing import Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_bitonic_sequence(arr: List[int]) -> int: """ Calculate the sum of all elements in a bitonic sequence with duplicates. Args: arr (List[int]): The input array containing the bitonic se...
code_exercise_27k
19,070
Write a Python function to count the number of elements in a sorted matrix that fall within a specified range `[low, high]` using a binary search algorithm. The matrix is a 2D list where each row and column is sorted in ascending order. The function should return the count of such elements. 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 count_elements_in_range(matrix: List[List[int]], low: int, high: int) -> int: """ Counts the number of elements in a sorted matrix that fall within the specified range [low, high]. Args: ...
code_exercise_27k
19,078
Write a Python function to find the maximum product of k numbers in an unsorted array. The function should handle cases where k is greater than the length of the array and should consider both positive and negative numbers to maximize the product. The code should start with: ```python from typing import List def find_...
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], k: int) -> int: """ Finds the maximum product of k numbers in an unsorted array. Args: numbers (List[int]): The unsorted array of numbers. k ...
code_exercise_27k
19,101
Write a Python function to concatenate three given NumPy arrays along axis 0. The function should ensure that the arrays have compatible shapes for concatenation along the specified axis. The code should start with: ```python import numpy as np def concatenate_arrays_along_axis_0(arr1: np.ndarray, arr2: np.ndarray, ar...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays_along_axis_0(arr1: np.ndarray, arr2: np.ndarray, arr3: np.ndarray) -> np.ndarray: """ Concatenates three NumPy arrays along axis 0. Parameters: arr1 (np.ndarray): First NumPy a...
code_exercise_27k
19,106
Write a Python function to find the largest number with the same digits after rearranging a given number. The function should take an integer as input and return the largest possible number that can be formed using the same digits. The code should start with: ```python def find_largest_same_digits(num: int) -> int: ```...
Here is the Python code to solve the given problem in the markdown block: ```python def find_largest_same_digits(num: int) -> int: """ Finds the largest number with the same digits after rearranging a given number. Args: num (int): The input number to rearrange. Returns: int: The large...
code_exercise_27k
19,114
Write a Python function to concatenate two 1-dimensional NumPy arrays of different data types. The function should ensure that the resulting array has a data type that can accommodate both input arrays' data types. The code should start with: ```python import numpy as np def concatenate_arrays_with_dtype(arr1: np.ndar...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays_with_dtype(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Concatenates two 1-dimensional NumPy arrays of different data types. The function ensures that the resulting array...
code_exercise_27k
19,119
Write a Python function to find the minimum number of times a sorted array is rotated. The array is rotated in such a way that the elements are shifted to the right, and the last element becomes the first. The function should efficiently determine the number of rotations using a binary search approach. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_min_rotations(arr: List[int]) -> int: """ Finds the minimum number of times a sorted array is rotated. Args: arr (List[int]): The sorted array that has been rotated. Returns: ...
code_exercise_27k
19,121
Write a Python function to perform a depth-first search (DFS) on a graph represented as an adjacency matrix, starting from a specified node, and return the order of visited nodes. The function should use an iterative approach with a stack instead of recursion. The code should start with: ```python from typing import L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def dfs_adjacency_matrix(graph: List[List[int]], start_node: int) -> List[int]: """ Perform a depth-first search (DFS) on a graph represented as an adjacency matrix. Args: graph (List[List[i...
code_exercise_27k
19,124
Write a Python function to perform a depth-first search (DFS) on a given graph represented as an adjacency list, starting from a specified node. The function should return the order of visited nodes during the DFS traversal. The code should start with: ```python from typing import Dict, List, Any def dfs_traversal(gr...
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]: """ Performs a depth-first search (DFS) on a graph represented as an adjacency list. Args: graph (Dict[Any...
code_exercise_27k
19,137
Write a Python function to calculate the shortest path between two nodes in an unweighted directed graph using the Breadth-First Search (BFS) algorithm. The function should return the shortest path as a list of nodes from the start node to the end node. If no path exists, an empty list should be returned. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any from collections import deque def shortest_path_bfs(graph: Dict[Any, List[Any]], start: Any, end: Any) -> List[Any]: """ Calculates the shortest path between two nodes in an unweighted directe...
code_exercise_27k
19,138
Write a Python function to concatenate multiple lists into a single list using a loop. The function should handle lists of integers, strings, or mixed types. The code should start with: ```python from typing import List, Union def concatenate_lists(lists: List[List[Union[int, str]]]) -> List[Union[int, str]]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def concatenate_lists(lists: List[List[Union[int, str]]]) -> List[Union[int, str]]: """ Concatenates multiple lists into a single list using a loop. Args: lists (list of lists): List ...
code_exercise_27k
19,140
Write a Python function to find all the connected components (subgraphs) in an undirected graph represented as an adjacency list. Each connected component is a list of nodes that are reachable from each other. The function should return a list of these connected components. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def find_connected_components(adjacency_list: Dict[int, List[int]]) -> List[List[int]]: """ Find all connected components in an undirected graph represented as an adjacency list. Args: ...
code_exercise_27k
19,153
Write a Python function to find the shortest path between two nodes in a weighted directed graph using Dijkstra's algorithm. The graph is represented as an adjacency list where each key is a node and the corresponding value is a list of edges. Each edge is represented as a list containing the destination node and the w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Union import heapq def find_shortest_path(graph: Dict[str, List[List[Union[str, float]]]], start: str, end: str) -> List[str]: """ Find the shortest path between two nodes in a weighted directed g...
code_exercise_27k
19,157
Write a Python function to concatenate two NumPy arrays along a specified axis using slicing and indexing techniques. The function should handle arrays of different dimensions and ensure that the arrays are compatible for concatenation along the specified axis. The code should start with: ```python import numpy as np ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays(arr1: np.ndarray, arr2: np.ndarray, axis: int = 0) -> np.ndarray: """ Concatenates two NumPy arrays along a specified axis using slicing and indexing techniques. Args: arr1...
code_exercise_27k
19,159
Write a Python function to detect whether there is a cycle in an undirected graph 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_cycle_in_graph(graph: Dict[int, List[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def has_cycle_in_graph(graph: Dict[int, List[int]]) -> bool: """ Detects whether an undirected graph represented as an adjacency list contains a cycle. Args: graph (Dict[int, List[int]...
code_exercise_27k
19,169
Write a Python function to concatenate multiple Numpy arrays along the first axis (axis=0) using the `np.concatenate()` function. The function should ensure that all input arrays have compatible shapes (i.e., the same shape except for the first dimension). The code should start with: ```python from typing import List i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import numpy as np def concatenate_multiple_arrays(arrays: List[np.ndarray]) -> np.ndarray: """ Concatenates multiple Numpy arrays along the first axis (axis=0) using the np.concatenate() function. ...
code_exercise_27k
19,195
Write a Python function to find the maximum flow in a directed graph using the Ford-Fulkerson method with the Edmonds-Karp algorithm. The function should take a directed graph represented as an adjacency matrix, a source node, and a sink node as inputs, and return the maximum flow from the source to the sink. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import deque def bfs(graph: List[List[int]], source: int, sink: int, parent: List[int]) -> bool: """ Breadth-first search (BFS) algorithm to find the shortest path from the source to the...
code_exercise_27k
19,209
Write a Python function to concatenate a list of NumPy arrays along a specified axis. The function should handle the case where the axis is negative and ensure that the arrays are compatible for concatenation. The code should start with: ```python import numpy as np from typing import List def concatenate_arrays(array...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List def concatenate_arrays(arrays: List[np.ndarray], axis: int) -> np.ndarray: """ Concatenates the given NumPy arrays along a specified axis. Args: arrays (List[np.ndarray]):...
code_exercise_27k
19,212
Write a Python function to find all connected components in an undirected graph. The graph is represented as a dictionary where the keys are nodes and the values are sets of adjacent nodes. The function should return a list of lists, where each inner list represents a connected component in the graph. The code should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Set def find_connected_components(graph: Dict[int, Set[int]]) -> List[List[int]]: """ Find all connected components in an undirected graph. Parameters: graph (dict): An undirected graph r...
code_exercise_27k
19,217
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given array using a binary search approach. The function should efficiently determine the length of the LIS by maintaining an active list of potential subsequences and using binary search to update this list. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search(arr: List[int], target: int) -> int: """ Perform binary search to find the index of the first element greater than or equal to the target. Args: arr: The sorted array t...
code_exercise_27k
19,218
Write a Python function to determine if a given undirected graph is connected. The graph is represented as a dictionary where keys are vertices and values are lists of adjacent vertices. The function should return `True` if the graph is connected (i.e., there is a path between any two vertices) and `False` otherwise. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def is_graph_connected(graph: Dict[int, List[int]]) -> bool: """ Determine if a given undirected graph is connected. Args: graph (Dict[int, List[int]]): A dictionary representing the g...
code_exercise_27k
19,219
Write a Python function to concatenate multiple NumPy arrays along a specified axis. The function should handle the case where the axis is specified as a parameter and ensure that the shapes of the arrays match along all other axes. The code should start with: ```python import numpy as np from typing import List def c...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List def concatenate_arrays_along_axis(arrays: List[np.ndarray], axis: int) -> np.ndarray: """ Concatenates multiple NumPy arrays along a specified axis. Args: arrays (List[np....
code_exercise_27k
19,224
Write a Python function to find the maximum sum of a subsequence in an array such that no two elements are adjacent. The function should use a dynamic programming approach to solve the problem efficiently. The code should start with: ```python from typing import List def max_sum_non_adjacent(arr: List[int]) -> int: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_sum_non_adjacent(arr: List[int]) -> int: """ Finds the maximum sum of a subsequence in an array such that no two elements are adjacent. Parameters: arr (List[int]): The input array of in...
code_exercise_27k
19,226
Write a Python function to find the number of islands in a 2D matrix. An island is defined as a group of connected '1's (land) in the matrix, where connections are considered only in horizontal and vertical directions. The matrix consists of '1's and '0's, where '1' represents land and '0' represents water. The functio...
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 2D matrix. An island is defined as a group of connected '1's (land) in the matrix, where connections are ...
code_exercise_27k
19,237
Write a Python function to concatenate a list of NumPy arrays along a specified axis. The function should handle both positive and negative axis values. If the axis value is negative, it should be interpreted as counting from the last dimension. The function should also validate that all arrays have the same number of ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List def concatenate_arrays(arrays: List[np.ndarray], axis: int) -> np.ndarray: """ Concatenates a list of NumPy arrays along a specified axis. Parameters: arrays (List[np.ndarray]...
code_exercise_27k
19,241
Write a Python function to count the number of islands of similar characters in a given matrix of characters. An island is defined as a group of adjacent cells (horizontally or vertically) that contain the same character. The function should traverse the matrix and use Depth-First Search (DFS) to identify and count the...
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[str]]) -> int: """ Count the number of islands of similar characters in a matrix. Args: matrix (List[List[str]]): A 2D matrix of characters. Returns:...
code_exercise_27k
19,244
Write a Python function to find the number of connected components in an undirected graph. The graph is represented as an adjacency list. The function should return the number of connected components in the graph. The code should start with: ```python from typing import Dict, List def count_connected_components(graph...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def count_connected_components(graph: Dict[int, List[int]]) -> int: """ Counts the number of connected components in an undirected graph. Args: graph (Dict[int, List[int]]): A dictiona...
code_exercise_27k
19,245
Write a Python function to calculate the minimum number of towers required to cover all given widths within a specified maximum distance. Each tower can cover a range of widths up to the specified maximum distance. The function should start with: ```python from typing import List def min_towers_to_cover_widths(widths:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def min_towers_to_cover_widths(widths: List[int], max_distance: int) -> int: """ Calculate the minimum number of towers required to cover all given widths within a specified maximum distance. Args: ...
code_exercise_27k
19,253
Write a Python function to count the number of groups of connected 1s in a given binary matrix. A group of connected 1s is defined as a set of 1s where each 1 is adjacent to at least one other 1 in the group (either horizontally or vertically). The function should handle matrices of varying sizes and ensure that all ro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_connected_groups(matrix: List[List[int]]) -> int: """ Counts the number of groups of connected 1s in a binary matrix. Parameters: matrix (List[List[int]]): The input matrix containing ...
code_exercise_27k
19,254
Write a Python function to count the maximum number of different ways to climb `n` steps, where you can either climb 1 step or 2 steps at a time. The function should use a dynamic programming approach to efficiently compute the result. The code should start with: ```python def count_ways_to_climb_steps(n: int) -> int:...
Here is the Python code to solve the given problem in the markdown block: ```python def count_ways_to_climb_steps(n: int) -> int: """ Count the maximum number of different ways to climb n steps, where you can either climb 1 step or 2 steps at a time. Args: n (int): The total number of steps to clim...
code_exercise_27k
19,259
Write a Python function to find the minimum number of different ways to climb `n` steps, where you can either climb 1 or 2 steps at a time. The function should return the minimum number of ways to reach the top of the stairs. The code should start with: ```python def count_min_ways_to_climb(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_min_ways_to_climb(n: int) -> int: """ Calculate the minimum number of different ways to climb n steps, where you can either climb 1 or 2 steps at a time. Args: n (int): The total number of steps to climb. ...
code_exercise_27k
19,260
Write a Python function to concatenate multiple Numpy arrays along the first dimension (axis=0) without specifying the axis parameter explicitly. The function should handle a list or tuple of Numpy arrays and return the concatenated Numpy array. The input arrays must have the same shape along the second and higher dime...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List, Tuple def concatenate_arrays(arrays: List[np.ndarray]) -> np.ndarray: """ Concatenates multiple Numpy arrays along the first dimension (axis=0) without specifying the axis parameter e...
code_exercise_27k
19,261
Write a Python coroutine that takes a list of integers as input and yields the sum of the squares of the numbers. The coroutine should be designed to handle an arbitrary number of integers in the list. The code should start with: ```python import asyncio from typing import List async def sum_of_squares_coroutine(numbe...
Here is the Python code to solve the given problem in the markdown block: ```python import asyncio from typing import List async def sum_of_squares_coroutine(numbers: List[int]): """ Coroutine that receives a list of integers and yields the cumulative sum of their squares. Args: numbers (List[int]...
code_exercise_27k
19,269
Write a Python function to find the minimum number of coins required to reach a given target value using the provided coin denominations. The function should handle invalid inputs by raising appropriate exceptions. The code should start with: ```python from typing import List def min_number_of_coins(target_val: int, ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def min_number_of_coins(target_val: int, coins: List[int]) -> int: """ Calculate the minimum number of coins required to reach a given target value using the provided coin denominations. Args: ...
code_exercise_27k
19,275
Write a Python coroutine that receives a string and yields all the consonants in the string. A consonant is any alphabetic character that is not a vowel (i.e., not 'a', 'e', 'i', 'o', 'u'). The coroutine should be case-insensitive and should ignore non-alphabetic characters. The code should start with: ```python async...
Here is the Python code to solve the given problem in the markdown block: ```python async def find_consonants(string: str): """Coroutine that receives a string and yields all the consonants in the string. Args: string (str): The input string. Yields: str: The consonants in the string. ...
code_exercise_27k
19,276
Write a Python function to count the number of connected components of empty cells in a given 2D grid. Each cell in the grid can be either empty ('E') or occupied ('O'). A connected component is defined as a group of empty cells ('E') that are adjacent to each other either horizontally or vertically. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_connected_components(grid: List[List[str]]) -> int: """ Counts the number of connected components of empty cells in a grid. Args: grid (List[List[str]]): A 2D grid represented as a...
code_exercise_27k
19,277
Write a Python function to implement the Bubble Sort algorithm on a given list of integers. The function should sort the list in ascending order and return the sorted list. The code should start with: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts the given list using the Bubble Sort algorithm. Args: arr (List[int]): The input list to be sorted. Returns: List[int]: T...
code_exercise_27k
19,278
Write a Python function to concatenate multiple small Numpy arrays along a specified axis. The function should handle arrays of different shapes and ensure that the concatenation is performed correctly. The function should also include input validation to ensure that the arrays are compatible for concatenation along th...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List def concatenate_arrays(arrays: List[np.ndarray], axis: int = 0) -> np.ndarray: """ Concatenate multiple small Numpy arrays along a specified axis. Parameters: - arrays (List[n...
code_exercise_27k
19,282
Write a Python function to sort a list in descending order using the Bubble Sort algorithm. The function should modify the input list in place and return the sorted list. The code should start with: ```python from typing import List def bubble_sort_descending(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_descending(arr: List[int]) -> List[int]: """ Sorts a list in descending order using the Bubble Sort algorithm. Args: arr (List[int]): The list of integers to be sorted. ...
code_exercise_27k
19,285
Write a Python coroutine that receives a list of strings and returns the number of strings that have more than 5 characters. The coroutine should be asynchronous and should be able to handle large lists efficiently. The code should start with: ```python import asyncio from typing import List async def count_strings_wi...
Here is the Python code to solve the given problem in the markdown block: ```python import asyncio from typing import List async def count_strings_with_more_than_5_chars(string_list: List[str]) -> int: """ Coroutine that receives a list of strings and returns the number of strings with more than 5 characters. ...
code_exercise_27k
19,297
Write a Python function to perform a partial bubble sort on a given list. The function should stop sorting once the list is partially sorted, meaning no more swaps are needed in the current pass. The code should start with: ```python from typing import List def bubble_sort_partial(lst: 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_partial(lst: List[int]) -> List[int]: """ Perform a partial bubble sort on the given list, stopping when no more swaps are needed in a pass. Args: lst (List[int]): The list t...
code_exercise_27k
19,313
Write a Python function to find the maximum flow between two vertices in a flow network using the Edmonds-Karp algorithm. The flow network is represented as an adjacency matrix where `graph[i][j]` represents the capacity of the edge from vertex `i` to vertex `j`. The function should return the maximum flow value from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import deque def find_maximum_flow(graph: List[List[int]], source: int, sink: int) -> int: """ Finds the maximum flow between two vertices in a flow network using the Edmonds-Karp algori...
code_exercise_27k
19,319
Write a Python function to perform Bubble Sort on a list of dictionaries based on a specific value stored in each dictionary. The function should sort the list in ascending order based on the specified key. The code should start with: ```python from typing import List, Dict def bubble_sort_dicts(lst: List[Dict[str, an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def bubble_sort_dicts(lst: List[Dict[str, any]], key: str) -> List[Dict[str, any]]: """ Sorts a list of dictionaries based on a specific key using the Bubble Sort algorithm. Args: lst ...
code_exercise_27k
19,322
Write a Python function to concatenate two NumPy arrays along a specified axis, ensuring that the resulting array preserves the negative numbers from both input arrays. The function should handle arrays of different shapes and dimensions, and it should raise an error if the arrays cannot be concatenated along the speci...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import Union def concatenate_arrays(arr1: np.ndarray, arr2: np.ndarray, axis: Union[int, None] = None) -> np.ndarray: """ Concatenates two NumPy arrays along a specified axis, preserving negative ...
code_exercise_27k
19,327
Write a Python function to concatenate two NumPy arrays containing positive numbers. The function should validate that both arrays are not empty and do not contain any negative numbers before performing the concatenation. If any of these conditions are violated, the function should raise a `ValueError`. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_positive_arrays(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Concatenates two NumPy arrays containing positive numbers. Parameters: arr1 (numpy.ndarray): The first array con...
code_exercise_27k
19,338
Write a Python function to concatenate two 1D NumPy arrays, each consisting of exactly two elements, using the `np.concatenate()` function. The function should validate the input arrays to ensure they are 1D and have exactly two elements. If the input arrays do not meet these criteria, the function should raise a `Valu...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Concatenates two 1D NumPy arrays, each consisting of exactly two elements. Parameters: arr1 (np.ndarray): First input 1D ...
code_exercise_27k
19,343
Write a Python function to concatenate two NumPy arrays along a specified axis. The function should handle arrays of any shape and ensure that the arrays have the same number of dimensions before concatenation. If the arrays do not have the same number of dimensions, the function should raise a `ValueError`. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import Union def concatenate_arrays_along_axis(arr1: np.ndarray, arr2: np.ndarray, axis: Union[int, None] = None) -> np.ndarray: """ Concatenates two NumPy arrays along a specified axis. Para...
code_exercise_27k
19,346
Write a Python function to concatenate two NumPy arrays along a specified axis. The function should handle arrays of any shape and number of dimensions, ensuring that the arrays have the same shape and number of dimensions before concatenation. The code should start with: ```python import numpy as np def concatenate_a...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays(arr1: np.ndarray, arr2: np.ndarray, axis: int = 0) -> np.ndarray: """ Concatenates two NumPy arrays along a specified axis. Args: arr1 (numpy.ndarray): The first array to c...
code_exercise_27k
19,354
Write a Python function to sort a list of strings lexicographically, ignoring the case of characters. The function should handle lists of strings and return the sorted list. The function should not raise any exceptions or use any object-oriented programming constructs. The code should start with: ```python from typing ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_strings_lexicographically(strings: List[str]) -> List[str]: """ Sorts a list of strings lexicographically, ignoring the case of characters. Args: strings (List[str]): The list of st...
code_exercise_27k
19,363
Implement a hybrid sorting algorithm that uses Bubble Sort for small sublists and Merge Sort for larger sublists. The function should be able to handle lists of any size and efficiently sort them by switching between the two algorithms based on the size of the sublist. The code should start with: ```python from typing...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def hybrid_sort(arr: List[int], threshold: int = 10) -> List[int]: """ Sorts the given array using a hybrid sorting algorithm. Small sublists (size <= threshold) are sorted using Bubble Sort, while l...
code_exercise_27k
19,376
Write a Python function to implement an optimized Bubble Sort algorithm that reduces the number of comparisons and swaps by using a custom comparison function. The custom comparison function should be designed to minimize unnecessary comparisons and swaps, especially for partially sorted arrays. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort_optimized(arr: List[int]) -> List[int]: """ Sorts a given array using an optimized Bubble Sort algorithm. The optimization reduces the number of comparisons and swaps by using a cust...
code_exercise_27k
19,377
Write a Python coroutine to calculate the median of a list of integers asynchronously. The coroutine should handle the case where the input list is empty by raising a `ValueError`. The code should start with: ```python from typing import List import asyncio async def calculate_median(numbers: List[int]) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import asyncio async def calculate_median(numbers: List[int]) -> float: """ Calculate the median of a list of integers asynchronously. Args: numbers (List[int]): A list of integers. Ret...
code_exercise_27k
19,380
Write a Python function to sort a list of dates in ascending order using the Bubble Sort algorithm. The dates are provided as strings in the format "yyyy-mm-dd". The function should return a new list of sorted dates without modifying the original list. The function should also handle invalid date formats by raising a `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_dates_with_bubble_sort(dates: List[str]) -> List[str]: """ Sorts a list of dates in ascending order using the Bubble Sort algorithm. Args: dates (List[str]): A list of date strings ...
code_exercise_27k
19,388
Write a Python function to find the intersection of two lists of integers. The function should return a list containing the common elements between the two input lists. The function should handle cases where the input lists are not of type `list` or contain elements that are not integers by raising a `TypeError`. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_intersection(list1: List[int], list2: List[int]) -> List[int]: """ Find the intersection of two lists of integers. Parameters: - list1 (List[int]): The first list of integers. - list...
code_exercise_27k
19,389
Write a Python function to sort a matrix (2-dimensional list) based on a specific criterion using Bubble Sort. The function should allow sorting by rows or columns and can sort in ascending or descending order. The code should start with: ```python from typing import List def bubble_sort_matrix(matrix: List[List[int]]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort_matrix(matrix: List[List[int]], sort_by: str = 'rows', criterion: str = 'asc') -> List[List[int]]: """ Sorts a matrix (2-dimensional list) based on a specific criterion using Bubble Sort....
code_exercise_27k
19,391
Write a Python function to concatenate two one-dimensional NumPy arrays of sixteen values each. The function should ensure that both input arrays are valid before performing the concatenation. If either array is invalid, the function should raise a `ValueError`. The code should start with: ```python import numpy as np ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays(array1: np.ndarray, array2: np.ndarray) -> np.ndarray: """ Concatenates two one-dimensional NumPy arrays of sixteen values each. Args: array1 (np.ndarray): The first one-di...
code_exercise_27k
19,403
Write a Python function to implement Bubble Sort as a stable sorting algorithm using an external key-value container. The container is a list of dictionaries, where each dictionary contains a 'key' and a 'value'. The 'key' is used for sorting, and the 'value' represents the actual value associated with the key. The fun...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def bubble_sort_stable(container: List[Dict[str, any]]) -> List[Dict[str, any]]: """ Sorts the container in ascending order using Bubble Sort as a stable sorting algorithm. Args: conta...
code_exercise_27k
19,404
Write a Python function to concatenate two 1-dimensional NumPy arrays of equal size. The function should ensure that the input arrays are 1-dimensional and of the same size before performing the concatenation. If the input arrays do not meet these criteria, the function should raise appropriate exceptions. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def concatenate_arrays(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Concatenates two 1-dimensional NumPy arrays of equal size. Parameters: arr1 (numpy.ndarray): First 1-dimensional array to...
code_exercise_27k
19,406
Write a Python function to find the number of connected components in an undirected graph. The graph is represented as a dictionary where keys are nodes and values are lists of adjacent nodes. The function should use Depth-First Search (DFS) to traverse the graph and count the connected components. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def count_connected_components(graph: Dict[str, List[str]]) -> int: """ Find the number of connected components in an undirected graph. Args: graph (Dict[str, List[str]]): A dictionary...
code_exercise_27k
19,407
Write a Python function to sort a list of strings that contain numbers based on their numeric values using the Bubble Sort algorithm. The function should handle both integers and floating-point numbers. The code should start with: ```python from typing import List def bubble_sort_numeric_strings(lst: List[str]) -> Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort_numeric_strings(lst: List[str]) -> List[str]: """ Sorts a list of strings containing numbers based on their numeric values using the Bubble Sort algorithm. Args: lst (List[st...
code_exercise_27k
19,409
Write a Python function to sort a list of integers using the Bubble Sort algorithm. The function should prevent common optimization attacks like time delay or memory consumption by ensuring that the algorithm stops early if the list is already sorted. The function should also avoid modifying the original list. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(nums: List[int]) -> List[int]: """ Sorts a list of integers using the Bubble Sort algorithm. Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order until the e...
code_exercise_27k
19,443
Write a Python function to create a NumPy array of zeros with a specified shape. The function should take a tuple representing the shape of the array as input and return a NumPy array filled with zeros of that shape. The code should start with: ```python import numpy as np def create_zeros_array(shape: tuple) -> np.nd...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_zeros_array(shape: tuple) -> np.ndarray: """ Create a NumPy array of zeros with the specified shape. Parameters: - shape: Tuple specifying the shape of the array. For example, shape=(2, 4)...
code_exercise_27k
19,446
Write a Python function to create a numpy array with a sequence of numbers from a given start value to a given stop value (exclusive). The function should handle cases where the start value is greater than or equal to the stop value by returning an empty array. The code should start with: ```python import numpy as np ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_sequence_array(start: int, stop: int) -> np.ndarray: """ Creates a numpy array with a sequence of numbers from the given start to stop values (exclusive). Args: start (int): The st...
code_exercise_27k
19,453
Write a Python function to find the maximum independent set in an undirected graph. An independent set is a set of vertices in a graph, no two of which are adjacent. The function should return the maximum independent set, which is a list of vertices. The code should start with: ```python from typing import Dict, List ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def find_max_independent_set(graph: Dict[str, List[str]]) -> List[str]: """ Finds the maximum independent set in an undirected graph. Parameters: - graph: A dictionary representing an undi...
code_exercise_27k
19,459
Write a Python function to reshape a given 1D list into a 2D list with specified number of rows and columns. The function should ensure that the reshaping is possible based on the length of the input list and the specified dimensions. If the reshaping is not possible, the function should return `None`. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def reshape_list(arr: List[int], rows: int, cols: int) -> Optional[List[List[int]]]: """ Reshapes a 1D list into a 2D list with specified number of rows and columns. Args: arr (Lis...
code_exercise_27k
19,463
Write a Python function to perform an in-place bubble sort on a given list of integers using bitwise operations for swapping elements. The function should return the sorted list. The code should start with: ```python from typing import List def bubble_sort_bitwise(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_bitwise(arr: List[int]) -> List[int]: """ Perform an in-place bubble sort on the input array using bitwise operations for swapping elements. Args: arr (List[int]): The input ...
code_exercise_27k
19,464
Write a Python function to multiply each element of a given 2D array by a specified scalar value. The function should handle arrays of any size, including empty arrays. The code should start with: ```python from typing import List def multiply_2d_array_by_scalar(arr: List[List[int]], scalar: int) -> List[List[int]]: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_2d_array_by_scalar(arr: List[List[int]], scalar: int) -> List[List[int]]: """ Multiply each element of a 2D array by a specified scalar value. Args: arr (List[List[int]]): The i...
code_exercise_27k
19,470
Write a Python coroutine to find the largest prime number in a given list of integers. The coroutine should raise a `ValueError` if the list is empty or if no prime number is found. The code should start with: ```python from typing import List import asyncio async def find_largest_prime(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import asyncio async def find_largest_prime(nums: List[int]) -> int: """ Coroutine that receives a list of integers and returns the largest prime number. Args: nums (List[int]): A list of in...
code_exercise_27k
19,476
Write a Python function to filter out the odd numbers from a given array of integers. The function should return a new list containing only the odd numbers from the input array. The code should start with: ```python from typing import List def filter_odd_numbers(array: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def filter_odd_numbers(array: List[int]) -> List[int]: """ Filter out the odd numbers from the given array. Args: array (List[int]): The input array of integers. Returns: List...
code_exercise_27k
19,478
Write a Python function to create a diagonal matrix with given diagonal elements. The function should return a NumPy array representing the diagonal matrix. The code should start with: ```python import numpy as np def create_diagonal_matrix(diagonal_elements: list) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_diagonal_matrix(diagonal_elements: list) -> np.ndarray: """ Create a diagonal matrix with the given diagonal elements. Parameters: - diagonal_elements (list): A list of numbers representin...
code_exercise_27k
19,483
Write a Python function to find the indices of non-zero elements in a given list. The function should return a list of indices where the corresponding elements are non-zero. The code should start with: ```python from typing import List def find_nonzero_indices(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 find_nonzero_indices(arr: List[int]) -> List[int]: """ Find the indices of non-zero elements in the given list. Args: arr (List[int]): The input list of integers. Returns: L...
code_exercise_27k
19,490
Write a Python function to sort a list of datetime objects using the Bubble Sort algorithm. The function should take a list of datetime objects as input and return the sorted list. The code should start with: ```python from datetime import datetime from typing import List def sort_datetime_list(datetime_list: List[dat...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime from typing import List def sort_datetime_list(datetime_list: List[datetime]) -> List[datetime]: """ Sorts a list of datetime objects using the Bubble Sort algorithm. Args: datetime_li...
code_exercise_27k
19,494
Write a Python function to transpose a 2-dimensional array. The function should handle rectangular arrays where the number of columns in each row may vary. If the input array is not rectangular (i.e., not all rows have the same number of columns), the function should return `None`. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def transpose_array(array: List[List[int]]) -> Optional[List[List[int]]]: """ Transpose a 2-dimensional array. Args: array (List[List[int]]): The 2-dimensional array to be transpos...