source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
15,730
Write a Python function to find the index of the number closest to a specified value in a 1D array of unique values. The function should handle an empty array by raising a `ValueError`. The code should start with: ```python from typing import List def find_closest_index(arr: List[int], target: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_closest_index(arr: List[int], target: int) -> int: """ Finds the index of the number closest to the specified value in a 1D array of unique values. Args: arr (List[int]): A 1D array...
code_exercise_27k
15,732
Write a Python function to calculate the number of possible paths in a grid from the top-left to the bottom-right corner, considering that you can only move right or down. The function should handle grids of varying sizes and return the total number of unique paths. The code should start with: ```python def count_path...
Here is the Python code to solve the given problem in the markdown block: ```python def count_paths_in_grid(m: int, n: int) -> int: """ Calculates the number of possible paths in a grid from the top-left to the bottom-right corner. Args: m (int): The number of rows in the grid. n (int): The...
code_exercise_27k
15,734
Write a Python function to generate a new matrix where each row contains the largest value from the corresponding row of the given input matrix. The input matrix is a 2D list of integers. The function should start with: ```python from typing import List def generate_largest_value_matrix(matrix: List[List[int]]) -> Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_largest_value_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Generates a new matrix where each row contains the largest value from the corresponding row of the given input matrix. ...
code_exercise_27k
15,737
Write a Python function to determine if a given number is a vampire number. A vampire number is a number that can be expressed as the product of two numbers, each having half the number of digits of the original number, and the concatenation of the digits of these two numbers must exactly match the digits of the origin...
Here is the Python code to solve the given problem in the markdown block: ```python def is_vampire_number(number: int) -> bool: """ Determine if a given number is a vampire number. A vampire number is a number that can be expressed as the product of two numbers, each having half the number of digits of...
code_exercise_27k
15,738
Write a Python function to sort each row of a given 2D array in descending order. The function should return a new 2D array with the rows sorted in descending order, without modifying the original array. The code should start with: ```python from typing import List def sort_rows_descending(arr: List[List[int]]) -> Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_rows_descending(arr: List[List[int]]) -> List[List[int]]: """ Sorts each row of a 2D array in descending order and returns a new 2D array. Args: arr (List[List[int]]): A 2D array (l...
code_exercise_27k
15,741
Write a Python function to determine the size of a given NumPy array. The function should return the total number of elements in the array. If the input is not a NumPy array, the function should raise a `TypeError`. The code should start with: ```python import numpy as np def get_array_size(array: np.ndarray) -> int:...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def get_array_size(array: np.ndarray) -> int: """ Calculate the size of the given NumPy array. Parameters: array (numpy.ndarray): The NumPy array for which the size needs to be determined. Retur...
code_exercise_27k
15,743
Write a Python function to determine if a given number is a "balanced number." A balanced number is defined as a number whose sum of digits on the left side of the middle digit(s) is equal to the sum of digits on the right side. The function should accept the number as either an integer or a string representation of a ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union def is_balanced_number(num: Union[int, str]) -> bool: """ Determine if a given number is a balanced number. A balanced number is defined as a number whose sum of digits on the left side of the ...
code_exercise_27k
15,747
Write a Python function to create a NumPy array of zeros with a specific shape. The function should take a tuple representing the desired shape of the array 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.nda...
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 a specific shape. Args: shape (tuple): The desired shape of the array. Returns: numpy.ndarr...
code_exercise_27k
15,753
Write a Python function to implement a binary search algorithm that finds the index of a target element in a sorted array. If the target element is not found, the function should return -1. The function should handle edge cases such as an empty array or a target that is not present in the array. The code should start ...
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 a binary search on a sorted array to find the index of the target element. Args: arr: A sorted list of integers. ta...
code_exercise_27k
15,756
Write a Python function to determine if a given number is a power of four. The function should return `True` if the number is a power of four, and `False` otherwise. The function should handle both integer and floating-point inputs. The code should start with: ```python def is_power_of_four(num: float) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_power_of_four(num: float) -> bool: """ Determine if a given number is a power of four. Parameters: num (float): The number to be checked. Returns: bool: True if num is a power of four, False...
code_exercise_27k
15,767
Write a Python function to find the maximum value in a 1D NumPy array. The function should handle the following cases: 1. The input array is empty. 2. The input array does not have exactly one dimension. 3. The input array contains integers or floating-point numbers. The code should start with: ```python import numpy ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_max_value(arr: np.ndarray) -> np.float64: """ Find the maximum value in a 1D NumPy array. Parameters: arr (numpy.ndarray): 1D NumPy array. Returns: numpy.float64: Maximum value in t...
code_exercise_27k
15,769
Write a Python function to find the minimum value in a 1D NumPy array. The function should handle the following: 1. Ensure the input is a 1D NumPy array. 2. Use the `np.min()` function to find the minimum value. 3. Return the minimum value. The code should start with: ```python import numpy as np def find_minimum(arr...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_minimum(arr: np.ndarray) -> float: """ Finds the minimum value in a 1D NumPy array. Args: arr (np.ndarray): A 1D NumPy array. Returns: float: The minimum value in the input ...
code_exercise_27k
15,771
Write a Python function to calculate the mean of a 1D NumPy array. The function should handle arrays with different data types and ensure the mean is calculated accurately. The code should start with: ```python import numpy as np def calculate_mean(arr: np.ndarray) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_mean(arr: np.ndarray) -> float: """ Calculate the mean of a 1D NumPy array. Args: arr (numpy.ndarray): A 1D NumPy array for which the mean needs to be calculated. Returns: ...
code_exercise_27k
15,773
Write a Python function to calculate the sum of all elements in a 1D NumPy array. The function should handle arrays of any length and return the sum as a float. The code should start with: ```python import numpy as np def sum_of_array(arr: np.ndarray) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sum_of_array(arr: np.ndarray) -> float: """ Calculate the sum of all elements in a 1D NumPy array. Args: arr (numpy.ndarray): A 1D NumPy array containing the elements to be summed. Retur...
code_exercise_27k
15,777
Write a Python function to calculate the sum of all elements in a list without using built-in functions (e.g., `sum()`). The function should be able to handle lists of integers and floating-point numbers. The code should start with: ```python from typing import List, Union def calculate_sum(nums: List[Union[int, float...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def calculate_sum(nums: List[Union[int, float]]) -> Union[int, float]: """ Calculate the sum of all elements in a list without using built-in functions. Args: nums (List[Union[int, fl...
code_exercise_27k
15,780
Write a Python function to remove duplicate elements from a given list without using built-in functions like `set()` or `dict.fromkeys()`. The function should maintain the order of the first occurrence of each element. The code should start with: ```python from typing import List def remove_duplicates(lst: List[int])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(lst: List[int]) -> List[int]: """ Removes duplicate elements from a list without using built-in functions. Parameters: lst (List[int]): The input list from which duplicates...
code_exercise_27k
15,782
Write a Python function to calculate the total cost of punch cards sold, based on the number of punches needed per card and the number of cards sold. Each punch card costs the same amount, which is equal to the number of punches needed per card. The function should return the total cost as a floating-point number. The...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_punch_card_cost(punches_needed: int, cards_sold: int) -> float: """ Calculates the total cost of punch cards sold, based on the number of punches needed per card and the number of cards sold. Args: pun...
code_exercise_27k
15,783
Write a Python function to transpose a 2D list (list of lists) without using NumPy. The function should take a 2D list as input and return its transposed version. The transposed list should have its rows and columns swapped. The code should start with: ```python from typing import List def transpose_2d_list(matrix: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transpose_2d_list(matrix: List[List[int]]) -> List[List[int]]: """ Transpose a 2D list (list of lists). Parameters: matrix (List[List[int]]): The input 2D list to be transposed. Returns...
code_exercise_27k
15,784
Write a Python function to create a deep copy of a nested list, ensuring that no references to the original list or its sublists are retained. The function should handle lists containing integers, strings, and other lists. The code should start with: ```python from typing import List, Any def deep_copy_list(original_l...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List, Any def deep_copy_list(original_list: List[Any]) -> List[Any]: """ Create a deep copy of a nested list, ensuring that no references to the original list or its sublists are retained. Args: ...
code_exercise_27k
15,787
Write a Python function to swap the values of two variables without using a third variable. The function should work for any data type that supports the basic arithmetic operations (addition and subtraction) or the bitwise XOR operation. The code should start with: ```python def swap_values(x, y): ```
Here is the Python code to solve the given problem in the markdown block: ```python def swap_values(x, y): """ Swaps the values of two variables without using a third variable. This function supports swapping values for any data type that supports the basic arithmetic operations (addition and subtracti...
code_exercise_27k
15,788
Write a Python function to replace all odd values in a given NumPy array with -1. The function should return a new array with the modifications, leaving the original array unchanged. The code should start with: ```python import numpy as np def replace_odd_values(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 replace_odd_values(arr: np.ndarray) -> np.ndarray: """ Replaces all odd values in a NumPy array with -1. Args: arr (numpy.ndarray): The input NumPy array. Returns: numpy.ndarray:...
code_exercise_27k
15,789
Write a Python function to concatenate two strings without using the `+` operator. The function should handle the concatenation by using string methods or other built-in functions that do not directly involve the `+` operator. The function should also raise a `TypeError` if either of the inputs is not a string. The co...
Here is the Python code to solve the given problem in the markdown block: ```python def concatenate_strings(s1: str, s2: str) -> str: """ Concatenates two strings without using the '+' operator. Args: s1 (str): The first string to be concatenated. s2 (str): The second string to be concatena...
code_exercise_27k
15,792
Write a Python function to find the indices of non-zero elements in a given 2D NumPy array. The function should return a tuple containing two 1-D NumPy arrays, where the first array contains the row indices and the second array contains the column indices of the non-zero elements. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_nonzero_indices(arr: np.ndarray) -> tuple: """ Find the indices of non-zero elements in a 2D NumPy array. Parameters: arr (numpy.ndarray): The input 2D NumPy array. Returns: tuple: ...
code_exercise_27k
15,793
Write a Python function to reverse a given string without using built-in 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(input_str: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(input_str: str) -> str: """ Reverse a given string without using built-in functions or methods. Args: input_str (str): The string to be reversed. Returns: str: The reversed string. ...
code_exercise_27k
15,795
Write a Python function to convert a string to an integer without using built-in functions like `int()`. The function should handle both positive and negative integers. If the input string contains non-digit characters (except for the optional leading minus sign), it should raise a `ValueError`. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python def string_to_integer(string: str) -> int: """ Convert a string to an integer without using built-in functions. Parameters: string (str): The input string to be converted. Returns: int: The converted integer va...
code_exercise_27k
15,798
Write a Python function to check if a given string is a palindrome without using built-in functions like `str.lower()`, `str.isalpha()`, or `str.join()`. The function should handle case insensitivity and ignore non-alphabetic characters. The code should start with: ```python def is_palindrome_custom(string: str) -> boo...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome_custom(string: str) -> bool: """ Check if a given string is a palindrome without using built-in functions. Parameters: string (str): The input string to check. Returns: bool: Returns True if t...
code_exercise_27k
15,801
Write a Python function to calculate the dot product of two NumPy arrays. The function should handle arrays of any compatible dimensions, including vectors (1D arrays) and matrices (2D arrays). The function should raise a `ValueError` if the input arrays have incompatible dimensions. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def dot_product(array1: np.ndarray, array2: np.ndarray) -> np.ndarray: """ Calculate the dot product of two NumPy arrays. Parameters: array1 (numpy.ndarray): The first input array. array2 (numpy....
code_exercise_27k
15,804
Write a Python function to multiply each element of a given NumPy array by a specified value. The function should handle both 1D and 2D arrays and ensure that the input is a valid NumPy array. The code should start with: ```python import numpy as np def multiply_array_elements(array: np.ndarray, value: float) -> np.nd...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def multiply_array_elements(array: np.ndarray, value: float) -> np.ndarray: """ Multiply each element of the input NumPy array by the specified value. Args: array (numpy.ndarray): The input NumPy...
code_exercise_27k
15,807
Write a Python function to calculate the trace of a given 2D NumPy array. The trace of a matrix is defined as the sum of the elements on its main diagonal. The function should handle only 2D arrays and raise a `ValueError` if the input array is not 2D. The code should start with: ```python import numpy as np def calc...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_trace(arr: np.ndarray) -> int or float: """ Calculate the trace of a 2D NumPy array. The trace of a matrix is the sum of the elements on its main diagonal. Args: arr (numpy.nda...
code_exercise_27k
15,812
Write a Python function to merge two dictionaries, with the second dictionary's values taking precedence over the first dictionary's values in case of key conflicts. The function should handle any type of dictionary values, including nested dictionaries. The code should start with: ```python from typing import Dict, An...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def merge_dictionaries(dict1: Dict[Any, Any], dict2: Dict[Any, Any]) -> Dict[Any, Any]: """ Merge two dictionaries, with the second dictionary's values taking precedence over the first dictionary's ...
code_exercise_27k
15,813
Write a Python function to calculate the cumulative sum of a given list of integers without using NumPy. The function should return a new list where each element at index `i` is the sum of all elements from the original list up to index `i`. The code should start with: ```python from typing import List def cumulative...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def cumulative_sum(arr: List[int]) -> List[int]: """ Calculate the cumulative sum of a list of integers. Parameters: ----------- arr : List[int] The input list of integers. Retu...
code_exercise_27k
15,815
Write a Python function to remove specific elements from a given list. The function should take two arguments: the original list and a list of elements to be removed. The function should return a new list with all the specified elements removed. The original list should remain unchanged. 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 remove_specific_elements(elements: List, to_remove: List) -> List: """ Remove specific elements from a given list. Args: elements (List): The original list from which elements are to be ...
code_exercise_27k
15,818
Write a Python function to find the index of the maximum value in a given NumPy array. If the array is empty, raise a `ValueError`. The function should be efficient and handle both 1D and multi-dimensional arrays. The code should start with: ```python import numpy as np def find_max_index(array: np.ndarray) -> int: `...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_max_index(array: np.ndarray) -> int: """ Find the index of the maximum value in a NumPy array. Args: array (np.ndarray): Input NumPy array. Returns: int: Index of the maximu...
code_exercise_27k
15,821
Write a Python function to implement the bubble sort algorithm. The function should sort a given list of integers in ascending order. The code should start with: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts the input array in ascending order using the bubble sort algorithm. Args: arr (List[int]): The unsorted array. Returns: L...
code_exercise_27k
15,822
Write a Python function to check if all elements in a given NumPy array are non-zero. The function should return `True` if all elements are non-zero, and `False` otherwise. The code should start with: ```python import numpy as np def all_non_zero(arr: np.ndarray) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def all_non_zero(arr: np.ndarray) -> bool: """ Check if all elements in a given NumPy array are non-zero. Args: arr (numpy.ndarray): The input NumPy array. Returns: bool: True if all...
code_exercise_27k
15,826
Write a Python function to count the number of occurrences of a specific value in a given NumPy array. The function should efficiently handle large arrays and return the count of the specified value. The code should start with: ```python import numpy as np def count_occurrences(arr: np.ndarray, value) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def count_occurrences(arr: np.ndarray, value) -> int: """ Count the number of occurrences of a specific value in a NumPy array. Args: arr (numpy.ndarray): The input NumPy array. value: Th...
code_exercise_27k
15,828
Write a Python function to remove duplicate elements from a given NumPy array while preserving the order of the first occurrence of each element. The function should return a new NumPy array with the duplicates removed. The code should start with: ```python import numpy as np def remove_duplicates_preserve_order(arr:...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def remove_duplicates_preserve_order(arr: np.ndarray) -> np.ndarray: """ Remove duplicate elements from a NumPy array while preserving the order of the first occurrence of each element. Parameters: a...
code_exercise_27k
15,829
Write a Python function to sort a 1D NumPy array in descending order. The function should use the `np.sort()` function from the NumPy library and then reverse the sorted array to achieve the descending order. The code should start with: ```python import numpy as np def sort_array_descending(array: np.ndarray) -> np.nd...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sort_array_descending(array: np.ndarray) -> np.ndarray: """ Sorts a 1D NumPy array in descending order. Args: array (np.ndarray): The 1D NumPy array to be sorted. Returns: np.nda...
code_exercise_27k
15,838
Write a Python function to implement the quicksort algorithm. The function should sort a given list of integers in ascending order. The quicksort algorithm should be implemented using a recursive approach. 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 an array in ascending order using the quicksort algorithm. Args: arr (List[int]): The array to be sorted. Returns: List[int...
code_exercise_27k
15,848
Write a Python function to sort the rows of a 2D NumPy array based on the values in a specific column. The function should take a 2D NumPy array and an integer representing the column index as inputs and return the sorted 2D NumPy array. The code should start with: ```python import numpy as np def sort_2d_array_by_col...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sort_2d_array_by_column(arr: np.ndarray, column: int) -> np.ndarray: """ Sorts the rows of a 2D NumPy array based on the values in a specific column. Args: arr (np.ndarray): The 2D NumPy arra...
code_exercise_27k
15,849
Write a Python function to count the number of occurrences of each element in a given list. The function should return a dictionary where the keys are the unique elements from the list and the values are the counts of those elements. The code should start with: ```python from typing import List, Dict def count_occurr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_occurrences(lst: List[int]) -> Dict[int, int]: """ Count the number of occurrences of each element in a given list. Args: lst (List[int]): The input list of integers. Re...
code_exercise_27k
15,851
Write a Python function to determine if a given graph is a transitive subgraph. A graph is considered a transitive subgraph if for every pair of nodes (u, v) such that there is a path from u to v, there is also a direct edge from u to v. The graph is represented as a dictionary where each key is a node, and the corresp...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque def is_transitive_subgraph(graph: dict) -> bool: """ Determine if a given graph is a transitive subgraph. Args: graph (dict): A dictionary representing the graph. Each key ...
code_exercise_27k
15,858
Write a Python function to find the maximum and minimum value in a list 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[int]) -> Tuple[int, ...
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]: """ Find the maximum and minimum values in a list of numbers without using built-in functions. Args: numbers (List[int]): A li...
code_exercise_27k
15,862
Write a Python function to calculate the nth term of the Fibonacci sequence using dynamic programming. The function should efficiently compute the nth term by storing previously computed values to avoid redundant calculations. The code should start with: ```python def fibonacci_dynamic(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci_dynamic(n: int) -> int: """ Calculate the nth term of the Fibonacci sequence using dynamic programming. Args: n (int): The position in the Fibonacci sequence to compute. Returns: int: The ...
code_exercise_27k
15,863
Write a Python function to generate a 2D NumPy array filled with random integers within a specified range. The function should take three parameters: the lower bound (inclusive), the upper bound (exclusive), and the shape of the array (a tuple representing the number of rows and columns). The function should return the...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_random_array(low: int, high: int, shape: tuple) -> np.ndarray: """ Generate a 2D NumPy array filled with random integers within a specified range. Parameters: low (int): The lower bound ...
code_exercise_27k
15,865
Write a Python function to find all possible combinations of a given list of numbers. Each combination should be represented as a tuple, and the function should return a list of all such tuples. The function should consider combinations of all possible lengths, from 1 up to the length of the input list. The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import itertools def find_all_combinations(numbers: List[int]) -> List[Tuple[int, ...]]: """ Find all possible combinations of a given list of numbers. Args: numbers (List[int]): The ...
code_exercise_27k
15,869
Write a Python function to determine if a given graph is a disconnected subgraph. A disconnected subgraph is a graph that consists of two or more separate components, where no node in one component is connected to any node in another component. The graph is represented as a dictionary where keys are nodes and values ar...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque def is_disconnected_subgraph(graph: dict) -> bool: """ Determines if a given graph is a disconnected subgraph. Parameters: graph (dict): A graph represented as a dictionary where keys ...
code_exercise_27k
15,870
Write a Python function to find the minimum number of perfect squares that sum up to a given positive integer `n`. A perfect square is an integer that is the square of an integer, e.g., 1, 4, 9, 16, etc. The function should return the minimum number of such perfect squares that sum up to `n`. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def min_perfect_squares(n: int) -> int: """ Calculate the minimum number of perfect squares that sum up to a given positive integer n. Args: n (int): The input number. Retur...
code_exercise_27k
15,872
Write a Python function to convert a 2D NumPy array into a 1D array, removing the diagonal elements. The function should handle square matrices (where the number of rows equals the number of columns) and return a 1D array containing all the elements of the original 2D array except for the diagonal elements. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def remove_diagonal(arr: np.ndarray) -> np.ndarray: """ Converts a 2D NumPy array into a 1D array, removing the diagonal elements. Args: arr (np.ndarray): The input 2D array. Must be a square mat...
code_exercise_27k
15,875
Write a Python function to calculate the median of each row in a given 2-dimensional NumPy array. The function should handle only 2-dimensional arrays and return an array containing the medians of each row. If the input array is not 2-dimensional, the function should raise a `ValueError`. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_median_per_row(arr: np.ndarray) -> np.ndarray: """ Calculate the median of each row in a given 2-dimensional NumPy array. Parameters: arr (numpy.ndarray): Input array with shape (n, m),...
code_exercise_27k
15,876
Write a Python function to replace all negative values in a given NumPy array with 0. The function should ensure that the original array is not modified and should return a new array with the negative values replaced. The code should start with: ```python import numpy as np def replace_negative_with_zero(arr: np.ndarr...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def replace_negative_with_zero(arr: np.ndarray) -> np.ndarray: """ Replaces all negative values in a NumPy array with 0. Args: arr (numpy.ndarray): Input NumPy array with negative values. Re...
code_exercise_27k
15,880
Write a Python function to calculate the sum of elements in each column of a 2D NumPy array. The function should take a 2D NumPy array as input and return a NumPy array containing the sum of elements in each column. The code should start with: ```python import numpy as np def sum_of_columns(arr: np.ndarray) -> np.ndar...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sum_of_columns(arr: np.ndarray) -> np.ndarray: """ Calculates the sum of elements in each column of a 2D NumPy array. Args: arr (np.ndarray): 2D NumPy array. Returns: np.ndarray:...
code_exercise_27k
15,884
Write a Python function to calculate the absolute difference between two NumPy arrays. The function should ensure that the input arrays have the same shape and return the absolute difference as a new NumPy array. If the input arrays have different shapes, the function should raise a `ValueError`. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_absolute_difference(array1: np.ndarray, array2: np.ndarray) -> np.ndarray: """ Calculate the absolute difference between two NumPy arrays. Parameters: array1 (numpy.ndarray): The first ...
code_exercise_27k
15,895
Write a Python function to determine if two arrays can be made equal by reversing one or more subarrays. The function should check if the elements in the `arr` array can be rearranged by reversing any subarray to match the `target` array. The function should return `True` if it is possible to make the arrays equal, and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def can_be_equal(target: List[int], arr: List[int]) -> bool: """ Determines if two arrays can be made equal by reversing one or more subarrays. Args: target (List[int]): The target array to ...
code_exercise_27k
15,897
Write a Python function to calculate the mean of each row in a 2D NumPy array. The function should validate that the input array is 2D and raise a `ValueError` if it is not. The code should start with: ```python import numpy as np def calculate_row_means(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 calculate_row_means(array: np.ndarray) -> np.ndarray: """ Calculate the mean of each row in a 2D NumPy array. Parameters: array (np.ndarray): The input 2D NumPy array. Returns: np.ndarra...
code_exercise_27k
15,901
Write a Python function to determine if a given graph is a chordless cycle graph. A chordless cycle graph is a simple cycle graph where no two non-adjacent vertices are connected by an edge. The graph is represented as an adjacency list. The code should start with: ```python from typing import Dict, Set def is_chordl...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def is_chordless_cycle_graph(graph: Dict[int, Set[int]]) -> bool: """ Determine if a given graph is a chordless cycle graph. Parameters: graph (Dict[int, Set[int]]): The graph represented a...
code_exercise_27k
15,904
Write a Python function to implement the merge sort algorithm. The function should take a list of integers as input and return the sorted list. The merge sort algorithm should be implemented using a recursive approach. The function should be able to handle lists of any length, including empty lists and lists with a sin...
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 of integers using the merge sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: ...
code_exercise_27k
15,909
Write a Python function to replace all NaN values in a given NumPy array with a specified replacement value. The function should handle both the presence and absence of NaN values in the array. The code should start with: ```python import numpy as np def replace_nan_with_value(arr: np.ndarray, replacement_value: float...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def replace_nan_with_value(arr: np.ndarray, replacement_value: float) -> np.ndarray: """ Replace all NaN values in a given NumPy array with a specified replacement value. Parameters: - arr: NumPy arr...
code_exercise_27k
15,910
Write a Python function to determine if there are two distinct indices `i` and `j` in a given list of integers `nums` such that the absolute difference between `nums[i]` and `nums[j]` is at most `t`, and the absolute difference between `i` and `j` is at most `k`. The function should return `True` if such indices exist,...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def contains_nearby_almost_duplicate(nums: List[int], k: int, t: int) -> bool: """ Determine if there are two distinct indices i and j in the list `nums` such that the absolute difference between `nu...
code_exercise_27k
15,923
Write a Python function to color a graph with minimum total weight using 9 colors. The graph is represented as an adjacency matrix, where `graph[i][j]` is the weight of the edge between node `i` and node `j`. The function should return a dictionary mapping each node to its color such that the total weight of the graph ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def color_graph_with_min_weight(graph: List[List[int]]) -> Dict[int, int]: """ Colors a graph with minimum total weight using 9 colors. Args: graph (List[List[int]]): Adjacency matrix ...
code_exercise_27k
15,930
Write a Python function to compute the pairwise product of two given NumPy arrays. The function should ensure that the input arrays have the same shape and return a new NumPy array containing the pairwise product of the elements from the input arrays. The code should start with: ```python import numpy as np def pairwi...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def pairwise_product(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Compute the pairwise product of two given NumPy arrays. Parameters: arr1 (np.ndarray): First NumPy array. arr2 ...
code_exercise_27k
15,934
Write a Python function to sort a 2D NumPy array by two specified columns. The function should first sort the array by the first specified column, and then within each group of rows that have the same value in the first column, sort by the second specified column. The function should handle any size of 2D array and any...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sort_2d_array_by_columns(arr: np.ndarray, sort_column_1: int, sort_column_2: int) -> np.ndarray: """ Sorts a 2D NumPy array by two specified columns. The array is first sorted by the first specified colum...
code_exercise_27k
15,938
Write a Python function to generate all possible subsets of a given list of integers. The function should return a list of lists, where each inner list represents a subset of the input list. The code should start with: ```python from typing import List def generate_subsets(nums: List[int]) -> List[List[int]]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_subsets(nums: List[int]) -> List[List[int]]: """ Generate all possible subsets of a given list of integers. Args: nums (List[int]): A list of integers. Returns: Lis...
code_exercise_27k
15,940
Write a Python function to generate all possible combinations of a given list of elements. Each combination should be represented as a tuple, and the function should return a list of all such tuples. The function should handle lists of any length and any type of elements. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import itertools def generate_combinations(elements: List) -> List[Tuple]: """ Generate all possible combinations of a given list of elements. Args: elements (List): A list of element...
code_exercise_27k
15,942
Write a Python function to calculate the cumulative product of each row in a 2D NumPy array. The function should return a 1D NumPy array where each element is the cumulative product of the corresponding row in the input array. The code should start with: ```python import numpy as np def calculate_cumulative_product(a...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_cumulative_product(arr: np.ndarray) -> np.ndarray: """ Calculate the cumulative product of each row in a 2D NumPy array. Parameters: arr (numpy.ndarray): The 2D NumPy array. Return...
code_exercise_27k
15,948
Write a Python function to find the first unique character in a given string. A unique character is defined as a character that appears exactly once in the string. If no unique character exists, the function should return an empty string. The code should start with: ```python def first_unique_char(string: str) -> str:...
Here is the Python code to solve the given problem in the markdown block: ```python def first_unique_char(string: str) -> str: """ Find the first unique character in a given string. Args: string (str): The input string. Returns: str: The first unique character found, or an empty string...
code_exercise_27k
15,952
Write a Python function to find the index of the maximum value along each column of a given 2D NumPy array. The function should return a NumPy array containing the indices of the maximum value in each column. The code should start with: ```python import numpy as np def find_max_index_each_column(arr: np.ndarray) -> n...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_max_index_each_column(arr: np.ndarray) -> np.ndarray: """ Find the index of the maximum value along each column of a 2D NumPy array. Parameters ---------- arr : numpy.ndarray Inp...
code_exercise_27k
15,953
Write a Python function to check if a given Sudoku board is valid. The Sudoku board is represented as a 9x9 list of lists, where each element is either an integer from 1 to 9 or a period ('.') representing an empty cell. The function should ensure that each row, each column, and each of the nine 3x3 sub-grids contain a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_valid_sudoku(board: List[List[str]]) -> bool: """ Check if a given Sudoku board is valid. Args: board (List[List[str]]): The Sudoku board represented as a 9x9 list of lists, ...
code_exercise_27k
15,961
Write a Python function to compute the median of each row in a 2D NumPy array. The function should take a 2D NumPy array as input and return a 1D NumPy array containing the medians of each row. The code should start with: ```python import numpy as np def compute_row_medians(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_row_medians(arr: np.ndarray) -> np.ndarray: """ Compute the median of each row in a 2D NumPy array. Parameters: arr (np.ndarray): 2D NumPy array. Returns: np.ndarray: 1D NumPy ar...
code_exercise_27k
15,966
Write a Python function to generate all valid combinations of parentheses for a given number of pairs. Each combination should be a string consisting of '(' and ')' characters, and the parentheses must be balanced (i.e., each opening parenthesis must have a corresponding closing parenthesis, and they must be properly n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_parentheses(n: int) -> List[str]: """ Generate all valid combinations of parentheses for a given number of pairs. Args: n (int): The number of pairs of parentheses. Returns...
code_exercise_27k
15,978
Write a Python function to simulate a one-dimensional random walk of 'n' steps. Each step can be either 1 or -1 and should be chosen randomly. The function should return the final position after 'n' steps. The code should start with: ```python import random def random_walk(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import random def random_walk(n: int) -> int: """ Simulates a one-dimensional random walk of 'n' steps. Args: n (int): The number of steps in the random walk. Returns: int: The final position after 'n'...
code_exercise_27k
15,982
Write a Python function to compute the standard deviation of each row in a given 2D NumPy array. The function should handle any valid 2D NumPy array and return a 1D NumPy array containing the standard deviation for each row. The code should start with: ```python import numpy as np def row_standard_deviation(array: np....
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def row_standard_deviation(array: np.ndarray) -> np.ndarray: """ Compute the standard deviation of each row in a 2D NumPy array. Parameters: array (np.ndarray): Input 2D NumPy array. Returns: ...
code_exercise_27k
15,983
Write a Python function to simulate a biased random walk where the probabilities of moving left and right are not equal. The probability of moving right should be `p`, and that of moving left should be `1 - p`. The function should return the final position after the specified number of steps. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python import random def biased_random_walk(steps: int, p: float) -> int: """ Simulates a biased random walk where the probabilities of moving left and right are not equal. Args: steps (int): The number of steps in the ra...
code_exercise_27k
15,991
Write a Python function to simulate a random walk on a 2D lattice, considering only the four cardinal directions (up, down, left, right). Each step should move the walker in one of these directions randomly. The function should return the final position of the walker after a specified number of steps. The code should ...
Here is the Python code to solve the given problem in the markdown block: ```python import random def random_walk(n: int) -> tuple: """ Simulate a random walk on a 2D lattice. Parameters: - n: number of steps in the walk (int) Returns: - final position of the walker as a tuple (int, int) ...
code_exercise_27k
15,997
Write a Python function to calculate the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. The function should be able to handle both positive and negative integers. The code should start with: ```python def gcd(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def gcd(a: int, b: int) -> int: """ Calculate the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. Args: a (int): The first number. b (int): The second number. Returns: ...
code_exercise_27k
16,003
Write a Python function to compute the Hamming distance between two strings represented as NumPy arrays. The Hamming distance is defined as the number of positions at which the corresponding elements in the two strings are different. The function should raise a `ValueError` if the input strings have different lengths. ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def hamming_distance(string1: np.ndarray, string2: np.ndarray) -> int: """ Calculate the Hamming distance between two strings represented as NumPy arrays. The Hamming distance is the number of positions ...
code_exercise_27k
16,009
Write a Python function to solve the "Palindromic Partitioning" problem for a given string. The function should return a list of all possible palindromic partitions of the input string. A palindromic partition is a partition of the string such that every substring in the partition is a palindrome. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def palindromic_partition(s: str) -> List[List[str]]: """ Solves the Palindromic Partitioning problem for a given string. Parameters: s (str): The input string to be partitioned. Returns: ...
code_exercise_27k
16,010
Write a Python function to calculate the cumulative sum of each column in a 2D NumPy array. The function should take a 2D NumPy array as input and return a 2D NumPy array where each element in a column is the cumulative sum of all elements above it in that column, including the element itself. The code should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def cumulative_sum_of_columns(arr: np.ndarray) -> np.ndarray: """ Calculate the cumulative sum of each column in a 2D NumPy array. Parameters: arr (np.ndarray): A 2D NumPy array for which the cumulat...
code_exercise_27k
16,015
Write a Python function to calculate the weighted sum of a 1D NumPy array using given weights and indices. The function should ensure that the array, indices, and weights have the same length. If not, it should raise a `ValueError`. The code should start with: ```python import numpy as np def weighted_sum(array: np.nd...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def weighted_sum(array: np.ndarray, weights: np.ndarray, indices: np.ndarray) -> float: """ Calculate the weighted sum of a 1D NumPy array using given weights and indices. Parameters: array (nump...
code_exercise_27k
16,019
Write a Python function to find all possible combinations of k numbers from a given set of n numbers. The function should return a list of tuples, where each tuple represents a unique combination of k numbers from the input list. The code should start with: ```python from typing import List, Tuple def find_combination...
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 find_combinations(nums: List[int], k: int) -> List[Tuple[int, ...]]: """ Find all possible combinations of k numbers from a given set of n numbers. Args...
code_exercise_27k
16,020
Write a Python function to compute the sum of elements in each column of a 2D NumPy array, excluding NaN values. The function should handle arrays of any size and shape. The code should start with: ```python import numpy as np def sum_columns_without_nan(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 sum_columns_without_nan(arr: np.ndarray) -> np.ndarray: """ Compute the sum of elements in each column of a 2D NumPy array, excluding NaN values. Args: arr (numpy.ndarray): The input 2D array...
code_exercise_27k
16,030
Write a Python function to find all possible combinations of a given word, where each combination is a tuple of characters. The function should return a list of tuples, each representing a unique combination of characters from the word. The order of combinations in the list does not matter, but the order of characters ...
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 find_all_combinations(word: str) -> List[Tuple[str]]: """ Find all possible combinations of a given word. Args: word (str): The word to find com...
code_exercise_27k
16,039
Write a Python function to remove an edge between two nodes in an adjacency matrix. The function should handle both directed and undirected graphs. If the graph is undirected, the function should remove the edge in both directions. The function should also check if the nodes are within the valid range of the adjacency ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_edge(adj_matrix: List[List[int]], node1: int, node2: int, is_undirected: bool = True) -> List[List[int]]: """ Remove an edge between two nodes in an adjacency matrix. Args: adj_ma...
code_exercise_27k
16,041
Write a Python function to create a NumPy array of a specified size filled with a specified value. The function should take two parameters: the size of the array (an integer) and the value to fill the array with (a float or integer). The function should return the generated NumPy array. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_filled_array(size: int, value: float) -> np.ndarray: """ Create a NumPy array of size (size x size) filled with the specified value. Args: size (int): The size of the square array. ...
code_exercise_27k
16,043
Write a Python function to calculate the outdegree of a given node in an adjacency matrix. The adjacency matrix is represented as a 2D list where `adj_matrix[i][j]` is `1` if there is an edge from node `i` to node `j`, and `0` otherwise. The function should handle edge cases such as invalid node indices and non-square ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_outdegree(adj_matrix: List[List[int]], node: int) -> int: """ Calculate the outdegree of a given node in an adjacency matrix. Args: adj_matrix (List[List[int]]): A 2D list repr...
code_exercise_27k
16,050
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(array: 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(array: np.ndarray, scalar: float) -> np.ndarray: """ Multiply each element of a NumPy array by a specified scalar value. Args: array (np.ndarray): The input NumPy arr...
code_exercise_27k
16,055
Write a Python function to find the maximum value in a given NumPy array. The function should handle empty arrays by raising a `ValueError`. The code should start with: ```python import numpy as np def find_max_value(array: np.ndarray) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_max_value(array: np.ndarray) -> float: """ Find the maximum value in a NumPy array. Args: array (np.ndarray): The input NumPy array. Returns: float: The maximum value in the...
code_exercise_27k
16,058
Write a Python function to reverse the order of rows in a given NumPy array. The function should take a 2D NumPy array as input and return a new 2D NumPy array with the rows reversed. The original array should not be modified. The code should start with: ```python import numpy as np def reverse_rows(arr: np.ndarray) ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def reverse_rows(arr: np.ndarray) -> np.ndarray: """ Reverse the order of rows in a given 2D NumPy array. Parameters: arr (np.ndarray): The input 2D NumPy array. Returns: np.ndarray: A new 2...
code_exercise_27k
16,065
Write a Python function to get the indices of non-zero elements in a given 2D NumPy array. The function should return a tuple containing two NumPy arrays, where the first array represents the indices of non-zero elements along the row dimension, and the second array represents the indices along the column dimension. T...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def get_non_zero_indices(arr: np.ndarray) -> tuple: """ Get the indices of non-zero elements in a 2D NumPy array. Parameters: arr (np.ndarray): A 2D NumPy array from which to extract the indices of n...
code_exercise_27k
16,067
Write a Python function to normalize a given NumPy array such that it has a mean of 0 and a standard deviation of 1. The function should handle arrays of any shape and ensure that the normalization process is correctly applied. The code should start with: ```python import numpy as np def normalize_array(arr: np.ndarra...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def normalize_array(arr: np.ndarray) -> np.ndarray: """ Normalize a NumPy array to have mean 0 and standard deviation 1. Args: arr (np.ndarray): The input NumPy array to be normalized. Retur...
code_exercise_27k
16,071
Write a Python function to replace all even numbers in a given Numpy array with the value -1. The function should return the modified array. The code should start with: ```python import numpy as np def replace_even_with_minus_one(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 replace_even_with_minus_one(arr: np.ndarray) -> np.ndarray: """ Replace all even numbers in a given Numpy array with the value -1. Args: arr (numpy.ndarray): The input array. Returns: ...
code_exercise_27k
16,076
Write a Python function to sort the columns of a given 2-dimensional NumPy array based on the values in the first row. The function should return a new array with the columns sorted in ascending order based on the values in the first row. The original array should not be modified. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sort_columns_by_first_row(arr: np.ndarray) -> np.ndarray: """ Sort the columns of a 2-dimensional NumPy array based on the values in the first row. Args: arr (numpy.ndarray): A 2-dimensional ...
code_exercise_27k
16,079
Write a Python function to calculate the indegree of a given node in an adjacency matrix. The adjacency matrix represents a directed graph, where `adjacency_matrix[i][j]` is non-zero if there is a directed edge from node `i` to node `j`. The function should return the number of incoming edges (indegree) for the specifi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_indegree(adjacency_matrix: List[List[int]], node: int) -> int: """ Calculate the indegree of a given node in an adjacency matrix. Args: adjacency_matrix (List[List[int]]): The ...
code_exercise_27k
16,087
Write a Python function to solve the "N-Queens II" problem using backtracking. The function should return the total number of distinct solutions to place `n` queens on an `n x n` chessboard such that no two queens threaten each other. A queen can move horizontally, vertically, and diagonally. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python def total_n_queens(n: int) -> int: """ Solve the N-Queens II problem using backtracking. Args: n: An integer representing the number of queens and the size of the chessboard. Returns: The total number o...
code_exercise_27k
16,088
Write a Python function to count the number of occurrences of a specific value in a given list of integers. The function should be efficient and handle various edge cases, such as an empty list or a value that does not exist in the list. The code should start with: ```python from typing import List def count_occurren...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_occurrences(lst: List[int], value: int) -> int: """ Count the number of occurrences of a specific value in a given list of integers. Args: lst (List[int]): The list of integers to ...
code_exercise_27k
16,091
Write a Python function to solve the "Permutation Sequence" problem. Given two integers `n` and `k`, the function should return the `k`-th permutation sequence of numbers from 1 to `n`. The permutation sequence should be returned as a string. The code should start with: ```python def get_permutation_sequence(n: int, k...
Here is the Python code to solve the given problem in the markdown block: ```python def get_permutation_sequence(n: int, k: int) -> str: """ Returns the k-th permutation sequence of numbers from 1 to n. Parameters: n (int): The total number of elements. k (int): The position of the desired permutat...
code_exercise_27k
16,098
Write a Python function to solve the "Regular Expression Matching" problem. The function should determine if a given string matches a given regular expression pattern. The pattern supports the following special characters: - `.` (dot): Matches any single character. - `*` (asterisk): Matches zero or more of the precedin...
Here is the Python code to solve the given problem in the markdown block: ```python def is_match(s: str, p: str) -> bool: """ Check if a given string matches a given regular expression pattern. Args: s (str): The input string to match. p (str): The regular expression pattern. Returns: ...
code_exercise_27k
16,103
Implement a function to solve the "Wildcard Matching" problem using backtracking. The function should check if a given string `s` matches a pattern `p` containing wildcards `'*'` and `'?'`. The wildcard `'*'` can match any sequence of characters (including an empty sequence), and the wildcard `'?'` can match any single...
Here is the Python code to solve the given problem in the markdown block: ```python def is_match(s: str, p: str) -> bool: """ Checks if a given string `s` matches a pattern `p` containing wildcards '*' and '?'. Args: s (str): The input string. p (str): The pattern string. Retur...
code_exercise_27k
16,105
Write a Python function to compute the Hadamard product between two NumPy arrays. The Hadamard product (also known as the element-wise product) is the product of corresponding elements in two arrays of the same shape. The function should raise a `ValueError` if the input arrays have different shapes. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def hadamard_product(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Computes the Hadamard product (element-wise product) of two NumPy arrays. Args: arr1 (numpy.ndarray): The first input a...
code_exercise_27k
16,112
Write a Python function to transpose a given matrix and improve memory access patterns in high-performance computing applications. The function should take a 2D list (matrix) as input and return the transposed matrix. The transposed matrix should be structured such that the memory access patterns are optimized for high...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transpose_matrix_for_hpc(matrix: List[List[int]]) -> List[List[int]]: """ Transposes the given matrix to improve memory access patterns in high-performance computing applications. Parameters: ...