source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
code_exercise_27k | 18,482 | Write a Python function to sort a list of integers using the merge sort algorithm. The function should be able to handle both ascending and descending order based on a provided boolean flag. If the flag is `True`, the list should be sorted in ascending order; if `False`, it should be sorted in descending order.
The co... | 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], ascending: bool = True) -> List[int]:
"""
Sorts a list of integers using the merge sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
... |
code_exercise_27k | 18,484 | Write a Python function to perform element-wise multiplication of two given NumPy arrays. The function should ensure that the input arrays have the same shape before performing the multiplication. If the shapes do not match, the function should raise a `ValueError`.
The code should start with:
```python
import numpy a... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_multiply(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Perform element-wise multiplication of two given NumPy arrays.
Parameters:
arr1 (numpy.ndarray): First input array.
... |
code_exercise_27k | 18,493 | Write a Python function to replace negative values in a given NumPy array with a specified replacement value. The function should allow the user to specify the replacement value, which defaults to zero if not provided. The function should handle multi-dimensional arrays and return the modified array.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def replace_negatives_with_value(arr: np.ndarray, replacement_value: float = 0.0) -> np.ndarray:
"""
Replaces negative values in a NumPy array with a specified replacement value.
Parameters:
- arr: n... |
code_exercise_27k | 18,500 | Write a Python function to extract all odd numbers from a given NumPy array. The function should return a new NumPy array containing only the odd numbers from the input array. The code should start with:
```python
import numpy as np
def extract_odd_numbers(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 extract_odd_numbers(arr: np.ndarray) -> np.ndarray:
"""
Extracts all odd numbers from a given NumPy array.
Args:
arr (np.ndarray): The input NumPy array from which odd numbers are to be extra... |
code_exercise_27k | 18,501 | Write a Python function to sort a given list of integers using the merge sort algorithm recursively. The function should split the list into two halves, sort each half recursively, and then merge the two sorted halves back together. The code should start with:
```python
from typing import List
def merge_sort(arr: List... | 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 list of integers using the merge sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
Returns:
List... |
code_exercise_27k | 18,502 | Write a Python function to calculate the sum of each row in a given 2D NumPy array. The function should return a NumPy array containing the sum of each row. The code should start with:
```python
import numpy as np
def row_sums(matrix: np.ndarray) -> np.ndarray:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def row_sums(matrix: np.ndarray) -> np.ndarray:
"""
Calculate the sum of each row in a given 2D NumPy array.
Args:
matrix (numpy.ndarray): The input 2D array.
Returns:
numpy.ndarray:... |
code_exercise_27k | 18,518 | Write a Python function to multiply each element in a given NumPy array by a scalar value. The function should handle the following:
1. Ensure the input is a NumPy array.
2. Ensure the scalar value is either an integer or a float.
3. Return the result of multiplying each element in the input array by the scalar value.
... | 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: int or float) -> np.ndarray:
"""
Multiply each element in a given NumPy array by a scalar value.
Parameters:
arr (np.ndarray): The input NumPy ar... |
code_exercise_27k | 18,520 | Write a Python function to calculate the number of ways to reach the top of a staircase with `n` steps by taking either 1 or 2 steps at a time. The function should use dynamic programming to optimize the recursive solution and avoid redundant calculations.
The code should start with:
```python
def count_ways_to_climb(... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_ways_to_climb(n: int) -> int:
"""
Calculate the number of ways to reach the top of a staircase with n steps by taking either 1 or 2 steps at a time.
Args:
n (int): The total number of steps in the staircas... |
code_exercise_27k | 18,535 | Write a Python function to check if a given string is a palindrome using a recursive approach. The function should consider only alphanumeric characters and ignore case. The function should start with:
```python
def is_palindrome_recursive(s: str) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome_recursive(s: str) -> bool:
"""
Recursively checks if a given string is a palindrome, considering only alphanumeric characters and ignoring case.
Args:
s (str): The string to check.
Returns:
... |
code_exercise_27k | 18,540 | Write a Python function to transpose a given 2D list (list of lists) without using NumPy. The function should return a new 2D list where the rows and columns of the original list are swapped. The code should start with:
```python
from typing import List
def transpose_2d_list(matrix: List[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 transpose_2d_list(matrix: List[List[int]]) -> List[List[int]]:
"""
Transposes a given 2D list (list of lists).
Parameters:
- matrix (List[List[int]]): The input 2D list to be transposed.
... |
code_exercise_27k | 18,542 | Write a Python function to calculate the Euclidean distance between two points in a multi-dimensional space using NumPy. The function should accept two NumPy arrays representing the coordinates of the points and return the Euclidean distance as a float. The code should start with:
```python
import numpy as np
def eucl... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float:
"""
Calculate the Euclidean distance between two points in a multi-dimensional space.
Args:
point1 (np.ndarray): The coord... |
code_exercise_27k | 18,547 | Write a Python function to calculate the nth term in a sequence defined by the recurrence relation \( f(n) = f(n-1) + 2 \cdot f(n-2) \). The function should use memoization to optimize the recursive calls and avoid redundant calculations. The code should start with:
```python
from typing import Dict
def calculate_sequ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def calculate_sequence_memoized(n: int, memo: Dict[int, int] = None) -> int:
"""
Calculate the nth term in the sequence defined by the recurrence relation f(n) = f(n-1) + 2*f(n-2) using memoization.
... |
code_exercise_27k | 18,549 | Write a Python function to find the common elements between two lists of integers. The function should return a list containing the common elements in sorted order. The code should start with:
```python
from typing import List
def find_common_elements(list1: List[int], list2: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_common_elements(list1: List[int], list2: List[int]) -> List[int]:
"""
Find the common elements between two lists of integers and return them in sorted order.
Args:
list1 (List[int])... |
code_exercise_27k | 18,570 | Write a Python function to calculate the number of ways to arrange `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 function should be recursive and should use a helper function to check if a position is valid for placing a q... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_n_queens_arrangements(n: int) -> int:
"""
Calculate the number of ways to arrange n queens on an n x n chessboard such that no two queens threaten each other.
Args:
n (int): The size of the chessboard and ... |
code_exercise_27k | 18,577 | Write a Python function to calculate the percentile of a given list of numbers. The function should accept a list of numbers and a single percentile value or a list of percentile values, and return the corresponding percentile(s) as a float or a list of floats. The function should handle edge cases such as an empty lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def calculate_percentile(data: List[float], q: Union[float, int, List[Union[float, int]]]) -> Union[float, List[float]]:
"""
Calculate the percentile of a given list of numbers.
Args:
... |
code_exercise_27k | 18,580 | Write a Python function to calculate the element-wise multiplication of two NumPy arrays. The function should ensure that the input arrays have the same shape and return the resulting array. The code should start with:
```python
import numpy as np
def elementwise_multiplication(array1: np.ndarray, array2: np.ndarray) ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_multiplication(array1: np.ndarray, array2: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise multiplication of two NumPy arrays.
Args:
array1 (np.ndarray): The first input... |
code_exercise_27k | 18,583 | Write a Python function to calculate the number of unique paths in a grid from the top-left to the bottom-right using dynamic programming. The grid has `m` rows and `n` columns, and you can only move right or down. The function should start with:
```python
def count_unique_paths_dp(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_unique_paths_dp(m: int, n: int) -> int:
"""
Calculate the number of unique paths in a grid from the top-left to the bottom-right using dynamic programming.
Args:
m (int): Number of rows in the grid.
... |
code_exercise_27k | 18,584 | Write a Python function to merge two given NumPy arrays element-wise. The function should take two NumPy arrays as input and return a new NumPy array where each element is the result of merging the corresponding elements from the two input arrays. The merging operation should concatenate the elements as strings.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def merge_arrays_element_wise(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Merges two NumPy arrays element-wise by concatenating corresponding elements as strings.
Args:
arr1 (np.ndarra... |
code_exercise_27k | 18,587 | Write a Python function to find the indices of the top N maximum values in a given NumPy array. The function should return an array of indices that correspond to the top N maximum values in the input array. The code should start with:
```python
import numpy as np
def find_top_n_indices(arr: np.ndarray, N: int) -> np.n... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def find_top_n_indices(arr: np.ndarray, N: int) -> np.ndarray:
"""
Find the indices of the top N maximum values in a NumPy array.
Args:
arr (np.ndarray): The input NumPy array.
N (int): T... |
code_exercise_27k | 18,596 | Write a Python function to calculate the number of ways to partition a positive integer using dynamic programming. A partition of a number is a way of writing it as a sum of positive integers, where the order of addends does not matter. For example, the partitions of 4 are: 4, 3+1, 2+2, 2+1+1, 1+1+1+1.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_partitions(n: int) -> int:
"""
Calculate the number of ways to partition a positive integer using dynamic programming.
Args:
n (int): The positive integer to partition.
Returns:
int: The numbe... |
code_exercise_27k | 18,600 | Write a Python function to determine if a given directed graph is a Directed Acyclic Graph (DAG). The function should use a recursive Depth-First Search (DFS) approach to detect cycles in the graph. The graph is represented as a dictionary where keys are vertices and values are lists of vertices that the key vertex has... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import defaultdict
def is_dag(graph: dict) -> bool:
"""
Determine if a given directed graph is a Directed Acyclic Graph (DAG).
Args:
graph (dict): A dictionary representing the directed graph, wher... |
code_exercise_27k | 18,610 | Write a Python function to generate all possible valid combinations of `k` numbers from a given list without duplication. The function should be recursive and should return a list of lists, where each inner list represents a valid combination. The code should start with:
```python
from typing import List
def generate_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_combinations(nums: List[int], k: int) -> List[List[int]]:
"""
Generate all possible valid combinations of k numbers from a given list without duplication.
Args:
nums (List[int])... |
code_exercise_27k | 18,611 | Write a Python function to perform element-wise multiplication of two NumPy arrays. The function should ensure that the input arrays have the same shape and return the element-wise product of the two arrays. The code should start with:
```python
import numpy as np
def element_wise_multiplication(array1: np.ndarray, ar... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def element_wise_multiplication(array1: np.ndarray, array2: np.ndarray) -> np.ndarray:
"""
Perform element-wise multiplication of two NumPy arrays.
Parameters:
array1 (np.ndarray): First input array.... |
code_exercise_27k | 18,617 | Write a Python function to perform element-wise subtraction of two NumPy arrays. The function should ensure that the input arrays have the same shape before performing the subtraction. If the shapes do not match, the function should raise a `ValueError`. The code should start with:
```python
import numpy as np
def ele... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_subtraction(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Perform element-wise subtraction of two NumPy arrays.
Parameters:
arr1 (numpy.ndarray): The first input array.
a... |
code_exercise_27k | 18,619 | Write a Python function to perform element-wise logical OR between two NumPy arrays. The function should ensure that the input arrays have the same shape and return the result of the element-wise logical OR operation. The code should start with:
```python
import numpy as np
def elementwise_logical_or(arr1: np.ndarray,... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_logical_or(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Perform element-wise logical OR between two NumPy arrays.
Parameters:
arr1 (numpy.ndarray): The first input array.
... |
code_exercise_27k | 18,621 | Write a Python function to find the shortest path in a weighted directed graph using Dijkstra's algorithm. The function should return the shortest path from a given start node to an end node, including the weights of the edges. If no path exists, the function should return `None`.
The code should start with:
```python... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Optional, Tuple
import heapq
def find_shortest_path(graph: Dict[str, Dict[str, int]], start: str, end: str) -> Optional[List[Tuple[str, int]]]:
"""
Find the shortest path in a weighted directed gr... |
code_exercise_27k | 18,626 | Write a Python function to perform element-wise logical OR between two NumPy arrays. The function should ensure that the two arrays have the same shape before performing the operation. If the shapes do not match, the function should raise a `ValueError`. The function should return a new NumPy array containing the eleme... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_logical_or(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Perform element-wise logical OR between two NumPy arrays.
Parameters:
arr1 (np.ndarray): The first NumPy array.
a... |
code_exercise_27k | 18,632 | Write a Python function to perform element-wise logical XOR between two NumPy arrays. The function should ensure that the input arrays are of the same shape and are NumPy arrays. If the shapes do not match or the inputs are not NumPy arrays, appropriate exceptions should be raised.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_logical_xor(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Perform element-wise logical XOR between two NumPy arrays.
Args:
arr1 (np.ndarray): First input array.
a... |
code_exercise_27k | 18,633 | Write a Python function to calculate the element-wise square of a given NumPy array. The function should handle arrays of any shape and return a new array with each element squared. The code should start with:
```python
import numpy as np
def element_wise_square(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 element_wise_square(array: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise square of a given NumPy array.
Args:
array (numpy.ndarray): The input array for which to compute the eleme... |
code_exercise_27k | 18,636 | Write a Python function to calculate the element-wise logarithm of a given NumPy array. The function should handle only positive values in the array and raise a `ValueError` if any non-positive values are found. The code should start with:
```python
import numpy as np
def elementwise_log(array: np.ndarray) -> np.ndarr... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_log(array: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise natural logarithm of a NumPy array.
Parameters:
array (np.ndarray): Input NumPy array containing only positive val... |
code_exercise_27k | 18,637 | Write a Python function to calculate the element-wise sine of a given NumPy array. The function should ensure that the input is a NumPy array and return the sine values for each element in the array. The code should start with:
```python
import numpy as np
def elementwise_sine(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 elementwise_sine(arr: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise sine of a NumPy array.
Parameters:
arr (numpy.ndarray): Input array.
Returns:
numpy.ndarray: Array contain... |
code_exercise_27k | 18,645 | Write a Python function to calculate the element-wise arcsin (inverse sine) of a given NumPy array. The function should ensure that the input is a valid NumPy array and handle the calculation efficiently. The code should start with:
```python
import numpy as np
def elementwise_arcsin(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 elementwise_arcsin(arr: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise arcsin of a given NumPy array.
Parameters:
arr (numpy.ndarray): Input array for which arcsin is calculated.
... |
code_exercise_27k | 18,648 | Write a Python function to calculate the element-wise arccosine of a given NumPy array. The function should ensure that the input array is numeric and contains values only between -1 and 1, inclusive. The function should return a new array with the same shape and data type as the input array, containing the element-wis... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_arccos(arr: np.ndarray) -> np.ndarray:
"""
Computes the element-wise arccosine of a NumPy array.
Parameters:
arr (numpy.ndarray): The input array for which element-wise arccosine is t... |
code_exercise_27k | 18,654 | Write a Python function to calculate the natural logarithm of each element in a given NumPy array. The function should handle arrays with both positive and non-positive elements. For non-positive elements, the function should return a special value, such as `None`, to indicate that the logarithm is not defined for thos... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import List, Union
def calculate_logarithm(arr: np.ndarray) -> List[Union[float, None]]:
"""
Calculates the natural logarithm of each element in a NumPy array.
Returns None for elements that a... |
code_exercise_27k | 18,656 | Write a Python function to calculate the base 10 logarithm of a NumPy array. The function should handle only positive values in the input array and return the array with base 10 logarithm values. If the input array contains any non-positive values, 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_base_10_logarithm(array: np.ndarray) -> np.ndarray:
"""
Calculate the base 10 logarithm of a NumPy array.
Parameters:
array (numpy.ndarray): The input array containing only positive val... |
code_exercise_27k | 18,657 | Write a Python function to calculate the number of ways to arrange n non-attacking queens on an nxn chessboard using a recursive approach. The function should ensure that no two queens can attack each other, meaning no two queens share the same row, column, or diagonal.
The code should start with:
```python
from typin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_n_queens_arrangements(n: int) -> int:
"""
Calculate the number of ways to arrange n non-attacking queens on an nxn chessboard.
Args:
n (int): The size of the chessboard and the num... |
code_exercise_27k | 18,666 | Write a Python function to calculate the element-wise exponential of a given NumPy array using a custom base. The function should take an array and a base as input and return a new array where each element is the result of raising the base to the power of the corresponding element in the input array.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_exponential(arr: np.ndarray, base: float = 10) -> np.ndarray:
"""
Calculate the element-wise exponential of a NumPy array using a custom base.
Parameters:
arr (np.ndarray): Input arra... |
code_exercise_27k | 18,669 | Write a Python function to create a 1D NumPy array with evenly spaced elements between two given values. The function should handle the case where the number of elements is less than 1 by raising a `ValueError`. The code should start with:
```python
import numpy as np
def create_evenly_spaced_array(start: float, stop:... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def create_evenly_spaced_array(start: float, stop: float, num_elements: int) -> np.ndarray:
"""
Create a 1D NumPy array with evenly spaced elements between two given values.
Parameters:
start (fl... |
code_exercise_27k | 18,673 | Write a Python function to calculate the cumulative product of a given NumPy array. The cumulative product of an array is an array where each element at index `i` is the product of all the elements of the original array up to index `i`. The function should handle both integer and floating-point arrays.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cumulative_product(arr: np.ndarray) -> np.ndarray:
"""
Calculate the cumulative product of a NumPy array.
Parameters:
arr (numpy.ndarray): The input NumPy array.
Returns:
numpy.n... |
code_exercise_27k | 18,677 | Write a Python function to calculate the cumulative maximum of a given NumPy array along a specified axis. The function should handle both 1D and multi-dimensional arrays and allow the user to specify the axis along which the cumulative maximum is computed. If no axis is specified, the function should compute the cumul... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cumulative_maximum(arr: np.ndarray, axis: int = None) -> np.ndarray:
"""
Calculate the cumulative maximum of a NumPy array along a specified axis.
Parameters:
arr (np.ndarray): Input array.
... |
code_exercise_27k | 18,681 | Write a Python function to calculate the cumulative minimum of a given NumPy array. The cumulative minimum at each position in the array is the minimum value encountered from the start of the array up to that position. The function should handle 1D arrays and return a new array of the same length containing the cumulat... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cumulative_minimum(arr: np.ndarray) -> np.ndarray:
"""
Calculate the cumulative minimum of a given NumPy array.
Parameters:
arr (numpy.ndarray): Input array.
Returns:
numpy.ndarray: Cumu... |
code_exercise_27k | 18,683 | Write a Python function to calculate the element-wise absolute value of a given NumPy array. The function should return a new NumPy array with the absolute values of the elements in the input array. The function should also include input validation to ensure that the input is a 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 calculate_absolute_value(array: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise absolute value of a NumPy array.
Args:
array (np.ndarray): The input NumPy array.
Returns:
... |
code_exercise_27k | 18,685 | Write a Python function to calculate the element-wise rounding of a NumPy array to a specified number of decimal places. The function should take a NumPy array and an integer representing the number of decimal places to round to, and return a new NumPy array with the rounded values.
The code should start with:
```pyth... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def round_array_to_decimal(arr: np.ndarray, decimals: int) -> np.ndarray:
"""
Round each element in a NumPy array to a specified number of decimal places.
Parameters:
- arr: NumPy array to be rounded... |
code_exercise_27k | 18,696 | Write a Python function to perform element-wise division of a NumPy array by a scalar. The function should handle the case where the scalar is zero by returning a special value (e.g., `None`). The code should start with:
```python
import numpy as np
from typing import Union
def elementwise_division(arr: np.ndarray, sc... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import Union
def elementwise_division(arr: np.ndarray, scalar: Union[int, float]) -> Union[np.ndarray, None]:
"""
Perform element-wise division of a NumPy array by a scalar.
If the scalar is ... |
code_exercise_27k | 18,708 | Write a Python function to calculate the minimum number of operations required to transform one string into another using the following operations:
- Insertion: Insert a character at any position.
- Deletion: Remove a character from any position.
- Substitution: Replace a character with another character.
The function... | Here is the Python code to solve the given problem in the markdown block:
```python
def edit_distance(str1: str, str2: str) -> int:
"""
Calculates the minimum number of operations required to transform str1 into str2 using the following operations:
- Insertion: Insert a character at any position.
-... |
code_exercise_27k | 18,711 | Write a Python function to calculate the element-wise addition of a scalar to a NumPy array. The function should take a NumPy array and a scalar as inputs and return a new NumPy array where each element is the result of adding the scalar to the corresponding element of the input array. The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def add_scalar_to_array(array: np.ndarray, scalar: float) -> np.ndarray:
"""
Add a scalar to each element of a NumPy array.
Parameters:
array (np.ndarray): Input NumPy array.
scalar (float): Scal... |
code_exercise_27k | 18,712 | Write a Python function to calculate the element-wise cumulative sum of a given NumPy array along a specified axis. The function should handle both 1D and 2D arrays and allow the user to specify the axis along which the cumulative sum is calculated. If the axis is not specified, the function should default to calculati... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import Optional
def element_wise_cumulative_sum(arr: np.ndarray, axis: Optional[int] = 0) -> np.ndarray:
"""
Calculate the element-wise cumulative sum of a NumPy array along a specified axis.
... |
code_exercise_27k | 18,717 | Write a Python function to calculate the element-wise logical AND of a NumPy array with a scalar. The function should handle both boolean and numeric arrays and return a new array with the result of the logical AND operation. The code should start with:
```python
import numpy as np
def elementwise_logical_and(arr: np.... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_logical_and(arr: np.ndarray, scalar: int) -> np.ndarray:
"""
Calculate the element-wise logical AND of a NumPy array with a scalar.
Parameters:
arr (np.ndarray): The input NumPy array... |
code_exercise_27k | 18,720 | Write a Python function to perform an element-wise logical OR operation between a NumPy array and a scalar value. The function should return a new NumPy array where each element is the result of the logical OR operation between the corresponding element in the input array and the scalar value. The logical OR operation ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_logical_or(array: np.ndarray, scalar: int) -> np.ndarray:
"""
Performs an element-wise logical OR operation between a NumPy array and a scalar value.
Parameters:
array (numpy.ndar... |
code_exercise_27k | 18,723 | Write a Python function to calculate the element-wise logical XOR of a NumPy array with a scalar. The function should handle both boolean and integer arrays, and the scalar can be either a boolean or an integer. The code should start with:
```python
import numpy as np
def elementwise_xor(array: np.ndarray, scalar: int... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_xor(array: np.ndarray, scalar: int) -> np.ndarray:
"""
Calculate the element-wise logical XOR of a NumPy array with a scalar.
Args:
array (numpy.ndarray): A NumPy array of boolean... |
code_exercise_27k | 18,724 | Write a Python function to calculate the number of ways to reach the top of a staircase by taking any number of steps from a given set of possible steps. The function should be implemented using dynamic programming to optimize the recursive solution.
The code should start with:
```python
from typing import Set
def co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Set
def count_ways_to_climb(stairs: int, steps: Set[int]) -> int:
"""
Calculate the number of ways to reach the top of a staircase by taking any number of steps from a given set.
Args:
stairs (in... |
code_exercise_27k | 18,726 | Write a Python function to calculate the element-wise maximum between two NumPy arrays. The function should handle arrays of the same shape and return a new array where each element is the maximum of the corresponding elements from the input arrays.
The code should start with:
```python
import numpy as np
def element... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_maximum(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Calculates the element-wise maximum between two NumPy arrays.
Args:
arr1 (np.ndarray): The first input array.
... |
code_exercise_27k | 18,734 | Write a Python function to calculate the cumulative sum of each row in a 2D NumPy array and return the result as a 1D NumPy array. The function should handle any size of 2D array and ensure that the cumulative sums are calculated row-wise.
The code should start with:
```python
import numpy as np
def cumulative_sum_ro... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cumulative_sum_rows(arr: np.ndarray) -> np.ndarray:
"""
Calculate the cumulative sum of each row in a 2D NumPy array and return the result as a 1D NumPy array.
Parameters:
arr (np.ndarray): The i... |
code_exercise_27k | 18,737 | Write a Python function to calculate the cumulative sum of both rows and columns in a 2D NumPy array. The function should return two separate 2D arrays: one containing the cumulative sums of the rows and the other containing the cumulative sums of the columns. The code should start with:
```python
import numpy as np
d... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cumulative_sum_2d(arr: np.ndarray) -> (np.ndarray, np.ndarray):
"""
Calculate the cumulative sum of both rows and columns in a 2D NumPy array.
Parameters:
arr (np.ndarray): A 2D NumPy array for w... |
code_exercise_27k | 18,754 | Write a Python function to perform element-wise subtraction of a scalar from each row in a 2D NumPy array. The function should return a new 2D NumPy array with the same shape as the input array, where each row has the scalar subtracted from its elements.
The code should start with:
```python
import numpy as np
def su... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def subtract_scalar_from_rows(array: np.ndarray, scalar: float) -> np.ndarray:
"""
Perform element-wise subtraction of a scalar from each row in a 2D NumPy array.
Parameters:
- array: 2D NumPy array.... |
code_exercise_27k | 18,756 | Write a Python function to calculate the element-wise negation of each element in a 2D NumPy array. The function should take a 2D NumPy array as input and return a new 2D NumPy array where each element is the negation of the corresponding element in the input array. The code should start with:
```python
import numpy as... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def element_wise_negation(arr: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise negation of each element in a 2D NumPy array.
Args:
arr (numpy.ndarray): Input 2D array.
Returns:
... |
code_exercise_27k | 18,757 | Write a Python function to generate all possible combinations of `k` numbers from a given list in lexicographic order using a recursive approach. The function should return a list of tuples, where each tuple represents a combination of `k` numbers from the input list.
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, Tuple
def generate_combinations(lst: List[int], k: int) -> List[Tuple[int, ...]]:
"""
Generate all possible combinations of k numbers from a given list in lexicographic order using a recursive approach.... |
code_exercise_27k | 18,758 | Write a Python function to calculate the element-wise absolute value of each element in a 2D NumPy array. The function should handle any 2D array, including those with negative values, and return a new array with the absolute values of the original elements. The code should start with:
```python
import numpy as np
def... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_absolute_values(arr: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise absolute value of each element in a 2D NumPy array.
Args:
arr (np.ndarray): A 2D NumPy array for whi... |
code_exercise_27k | 18,762 | Write a Python function to calculate the element-wise rounding of each element in a 2D NumPy array. The function should handle any size of 2D array and return a new array with each element rounded to the nearest integer. The code should start with:
```python
import numpy as np
def round_2d_array(arr: np.ndarray) -> np... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def round_2d_array(arr: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise rounding of each element in a 2D NumPy array.
Parameters:
arr (np.ndarray): A 2D NumPy array.
Returns:
np.nd... |
code_exercise_27k | 18,763 | Write a Python function to calculate the element-wise ceiling of each element in a 2D NumPy array. The function should return a new 2D NumPy array with the element-wise ceiling of the input array. The function should raise a `ValueError` if the input array is not 2D.
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 calculate_ceil_2d_array(arr: np.ndarray) -> np.ndarray:
"""
Calculates the element-wise ceiling of each element in a 2D NumPy array.
Parameters:
arr (np.ndarray): Input 2D NumPy array.
Retur... |
code_exercise_27k | 18,764 | Write a Python function to perform a reverse level order traversal of a binary tree without using recursion. The function should return a list containing the values of the nodes in the binary tree in reverse level order. The code should start with:
```python
from collections import deque
from typing import List, Option... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def reverse_level_o... |
code_exercise_27k | 18,786 | Write a Python function to extract the diagonal elements of a given 2-dimensional list (not a NumPy array). The function should return a list containing the diagonal elements. The code should start with:
```python
from typing import List
def extract_diagonal_elements(matrix: List[List[int]]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_diagonal_elements(matrix: List[List[int]]) -> List[int]:
"""
Extracts the diagonal elements from a given 2-dimensional list.
Args:
matrix (List[List[int]]): The input 2-dimension... |
code_exercise_27k | 18,790 | Write a Python function to find the maximum value in a given list of integers. The function should handle edge cases such as an empty list and non-integer elements. If the list is empty, the function should return `None`. If the list contains non-integer elements, the function should raise a `TypeError`. The code shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_maximum_in_list(lst: List[int]) -> Optional[int]:
"""
Find the maximum value in a given list of integers.
Args:
lst (List[int]): The input list of integers.
Returns:
... |
code_exercise_27k | 18,795 | Write a Python function to count the number of non-zero elements in a given NumPy array. The function should efficiently handle arrays of various shapes and sizes. The code should start with:
```python
import numpy as np
def count_nonzero_elements(array: np.ndarray) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def count_nonzero_elements(array: np.ndarray) -> int:
"""
Count the number of non-zero elements in a given NumPy array.
Args:
array (np.ndarray): The input NumPy array.
Returns:
int:... |
code_exercise_27k | 18,798 | Write a Python function to calculate the sum of all elements in a given list using tail recursion. Tail recursion is a special form of recursion where the recursive call is the last operation in the function. This allows for optimization by some compilers and interpreters, as it can be transformed into an iterative loo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_list_elements_tail_recursive(lst: List[int], acc: int = 0) -> int:
"""
Calculate the sum of all elements in a list using tail recursion.
Args:
lst (List[int]): The list of integers t... |
code_exercise_27k | 18,801 | Write a Python function to find the maximum element in a list using a tail-recursive approach. The function should handle an empty list by raising a `ValueError`. The code should start with:
```python
from typing import List, TypeVar
T = TypeVar('T', int, float)
def find_max_tail_recursive(arr: List[T]) -> T:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, TypeVar
T = TypeVar('T', int, float)
def find_max_tail_recursive(arr: List[T]) -> T:
"""
Finds the maximum element in a list using a tail-recursive approach.
Args:
arr (List[T]): List cont... |
code_exercise_27k | 18,802 | Write a Python function to find the indices of elements in a given list that are greater than a specified threshold value. The function should return a list of indices.
The code should start with:
```python
from typing import List
def find_indices_above_threshold(arr: List[int], threshold: int) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_indices_above_threshold(arr: List[int], threshold: int) -> List[int]:
"""
Find the indices of elements in a list that are greater than a specified threshold value.
Args:
arr (List[i... |
code_exercise_27k | 18,804 | Write a Python function to calculate the factorial of a given non-negative integer using a tail-recursive approach. The function should handle the case where the input number is negative by raising a `ValueError`. The code should start with:
```python
def factorial(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def factorial(n: int) -> int:
"""
Calculates the factorial of a given non-negative integer using a tail-recursive approach.
Args:
n (int): The non-negative integer for which the factorial needs to be calculated.
... |
code_exercise_27k | 18,807 | Write a Python function to compute the Fibonacci sequence up to a specified position using tail recursion. The function should handle non-negative integers and return the Fibonacci number at the specified position. The code should start with:
```python
def fibonacci_tail_recursive(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci_tail_recursive(n: int) -> int:
"""
Compute the Fibonacci sequence up to a specified position using tail recursion.
Args:
n (int): The position up to which the Fibonacci sequence should be computed.
... |
code_exercise_27k | 18,810 | Write a Python function to reshape a given 1-dimensional list into a 2-dimensional list of shape (4, 4). The function should ensure that the input list can be reshaped into the specified shape without any loss of data. If the input list cannot be reshaped into the specified shape, the function should return `None`.
Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def reshape_list(array: List[int]) -> Optional[List[List[int]]]:
"""
Reshapes a 1-dimensional list into a 2-dimensional list of shape (4, 4).
Args:
array (List[int]): The input 1-d... |
code_exercise_27k | 18,814 | Write a Python function to compute the dot product of two given 2-dimensional NumPy arrays. The function should check if the shapes of the arrays are compatible for the dot product calculation and raise a `ValueError` if they are not. The code should start with:
```python
import numpy as np
def compute_dot_product(arr... | 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 given 2-dimensional NumPy arrays.
Parameters:
arr1 (numpy.ndarray): First input array... |
code_exercise_27k | 18,819 | Write a Python function to concatenate two given 3-dimensional NumPy arrays along the third axis. The function should ensure that the shapes of the input arrays are compatible for concatenation and raise a `ValueError` if they are not. The code should start with:
```python
import numpy as np
def concatenate_3d_arrays(... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def concatenate_3d_arrays(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Concatenates two given 3-dimensional NumPy arrays along the third axis.
Args:
arr1 (numpy.ndarray): The first 3-di... |
code_exercise_27k | 18,821 | Write a Python function to extract the unique elements and their counts from a given list of integers. The function should return two lists: one containing the unique elements and the other containing their respective counts. The code should start with:
```python
from typing import List, Tuple
def get_unique_elements_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def get_unique_elements_and_counts(arr: List[int]) -> Tuple[List[int], List[int]]:
"""
Extract the unique elements and their counts from a given list of integers.
Args:
arr (List[int]... |
code_exercise_27k | 18,822 | Write a Python function to sort a list of integers in descending order using asynchronous programming. The function should be able to handle asynchronous operations and return the sorted list. The code should start with:
```python
from typing import List
import asyncio
async def sort_descending_async(numbers: List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import asyncio
async def sort_descending_async(numbers: List[int]) -> List[int]:
"""
Sorts a list of integers in descending order using asynchronous programming.
Args:
numbers (List[int]): A... |
code_exercise_27k | 18,825 | Write a Python function to swap two rows of a given 2-dimensional Numpy array. The function should take the array and the indices of the two rows to be swapped as inputs and return the modified array. Ensure that the function handles cases where the row indices are out of bounds by raising an `IndexError`.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def swap_rows(arr: np.ndarray, row1: int, row2: int) -> np.ndarray:
"""
Swaps two rows of a 2-dimensional numpy array.
Parameters:
arr (numpy.ndarray): The input 2-dimensional numpy array.
... |
code_exercise_27k | 18,828 | Write a Python function to find the smallest element in a list using a tail-recursive approach. The function should avoid using loops and minimize stack usage by leveraging tail recursion. The function should handle an empty list by raising a `ValueError`.
The code should start with:
```python
from typing import List,... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def find_smallest_element(lst: List[Union[int, float]]) -> Union[int, float]:
"""
Find the smallest element in a list using a tail-recursive approach.
This function uses a helper function to ... |
code_exercise_27k | 18,831 | Write a Python function to find the maximum width of a binary tree without using recursion. The function should use a level-order traversal (also known as breadth-first search) to determine the maximum width of the tree. The width of a level in a binary tree is defined as the number of nodes at that level.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import deque
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def get_max_width(root: Optiona... |
code_exercise_27k | 18,839 | Write a Python function to compute the element-wise product of two NumPy arrays and store the result in a new array. The function should ensure that the input arrays have the same shape and return the resulting array. The code should start with:
```python
import numpy as np
def elementwise_product(arr1: np.ndarray, ar... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_product(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Compute the element-wise product of two NumPy arrays.
Parameters:
arr1 (numpy.ndarray): The first input array.
arr2 ... |
code_exercise_27k | 18,843 | Write a Python function to find the indices where the elements of two given lists are equal. The function should return a list of indices where the corresponding elements in the two lists are equal. The code should start with:
```python
from typing import List
def find_equal_indices(list1: List[int], list2: List[int])... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_equal_indices(list1: List[int], list2: List[int]) -> List[int]:
"""
Finds the indices where the elements of two given lists are equal.
Args:
list1 (List[int]): The first input list.... |
code_exercise_27k | 18,845 | Write a Python function to merge two sorted lists into a single sorted list using a tail-recursive approach. The function should efficiently combine the elements of both lists while maintaining the sorted order. The code should start with:
```python
from typing import List
def merge_sorted_lists_recursive(list1: List[... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sorted_lists_recursive(list1: List[int], list2: List[int], merged_list: List[int] = None) -> List[int]:
"""
Merge two sorted lists into a single sorted list using a tail-recursive approach.
... |
code_exercise_27k | 18,860 | Write a Python function to find the n elements in a given list of numbers that are closest to a specified value. The function should return a list containing the n elements that are closest to the specified value. The code should start with:
```python
from typing import List
def find_closest_elements(arr: List[float],... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_closest_elements(arr: List[float], value: float, n: int) -> List[float]:
"""
Find the n elements in a given list of numbers that are closest to a specified value.
Args:
arr (List[fl... |
code_exercise_27k | 18,861 | Write a Python function to check if a given number is a prime number using a tail-recursive approach. The function should start with:
```python
def is_prime_recursive(n: int, divisor: int = 2) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
def is_prime_recursive(n: int, divisor: int = 2) -> bool:
"""
Check if a given number is prime using a tail-recursive approach.
Args:
n (int): The number to check for primality.
divisor (int): The current ... |
code_exercise_27k | 18,872 | Write a Python function to generate the first N prime numbers using tail recursion. The function should be able to handle the generation of prime numbers efficiently and should be implemented using tail recursion to avoid potential stack overflow issues.
The code should start with:
```python
from typing import List
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_first_n_primes(n: int) -> List[int]:
"""
Generate the first N prime numbers using tail recursion.
Args:
n (int): The number of prime numbers to generate.
Returns:
L... |
code_exercise_27k | 18,881 | Write a Python function to check if a given expression has balanced parentheses using a tail-recursive approach. The function should return `True` if the parentheses in the expression are balanced, and `False` otherwise. The function should handle expressions containing only parentheses characters `(` and `)`.
The cod... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_balanced_recursive(expression: str) -> bool:
"""
Check if a given expression has balanced parentheses using a tail-recursive approach.
Args:
expression (str): The expression to check.
Returns:
bo... |
code_exercise_27k | 18,885 | Write a Python function to generate a NumPy array of `n` random integers between a specified lower and upper bound (inclusive). The function should handle cases where `n` is zero or negative by returning an empty array. Additionally, the function should ensure that the lower bound is less than or equal to the upper bou... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def generate_random_integers(n: int, lower_bound: int, upper_bound: int) -> np.ndarray:
"""
Generates a NumPy array of n random integers between the specified lower and upper bounds (inclusive).
Args:
... |
code_exercise_27k | 18,888 | Write a Python function to perform matrix multiplication using tail recursion. The function should take two matrices as input and return the resulting matrix after multiplication. The function should be implemented using a tail-recursive helper function to ensure efficient computation.
The code should start with:
```p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def matrix_multiply_tail_recursive(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
"""
Multiplies two matrices A and B using tail recursion.
Args:
A (List[List[int]]): The first ... |
code_exercise_27k | 18,891 | Write a Python function to implement the quicksort algorithm using tail recursion. The function should sort a list of integers in ascending order. Tail recursion is a technique where the recursive call is the last operation in the function, which can help in optimizing the function to use less stack space.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def quicksort_tail_recursive(lst: List[int]) -> List[int]:
"""
Sorts a list in ascending order using the quicksort algorithm with tail recursion.
Args:
lst (List[int]): The list to be sorted... |
code_exercise_27k | 18,896 | Write a Python function to access the first three elements of a given NumPy array. If the array has fewer than three elements, the function should return an empty NumPy array. The function should not raise any exceptions.
The code should start with:
```python
import numpy as np
def get_first_three_elements(arr: np.nd... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def get_first_three_elements(arr: np.ndarray) -> np.ndarray:
"""
Returns the first three elements of a given NumPy array.
If the array has fewer than three elements, returns an empty NumPy array.
Arg... |
code_exercise_27k | 18,906 | Write a Python function to access every other element of a given NumPy array, starting from the first element. The function should return a new NumPy array containing every other element of the input array. The code should start with:
```python
import numpy as np
def access_every_other_element(arr: np.ndarray) -> np.n... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def access_every_other_element(arr: np.ndarray) -> np.ndarray:
"""
Access every other element of a given NumPy array, starting from the first element.
Args:
arr (numpy.ndarray): The input NumPy a... |
code_exercise_27k | 18,911 | Write a Python function to create a NumPy array with values from 1 to `n` in descending order. The function should take an integer `n` as input and return a NumPy array. The code should start with:
```python
import numpy as np
def create_descending_array(n: int) -> np.ndarray:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def create_descending_array(n: int) -> np.ndarray:
"""
Creates a NumPy array with values from 1 to n in descending order.
Args:
n (int): The upper limit value for the array.
Returns:
... |
code_exercise_27k | 18,912 | Write a Python function to perform a binary search on a sorted array to find the index of a target number. If the target number is not found, 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 with:
```python
from typing import Li... | 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 a target number in a sorted array.
Args:
arr (List[int]): A sorted list of integers.
... |
code_exercise_27k | 18,914 | Write a Python function to perform a binary search on a sorted array and return the index of the target number. If the target number is not found, 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 with:
```python
from typing impo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def binary_search_index(arr: List[Union[int, float]], target: Union[int, float]) -> int:
"""
Performs binary search on the given sorted array to find the index of the target number.
Args:... |
code_exercise_27k | 18,918 | Write a Python function to find the first occurrence of a target number in a sorted array with duplicates using a binary search algorithm. The function should return the index of the first occurrence of the target number if it exists in the array, otherwise it 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 first_occurrence_binary_search(arr: List[int], target: int) -> Optional[int]:
"""
Returns the index of the first occurrence of the target number in the sorted array with duplicates.
Ar... |
code_exercise_27k | 18,920 | Write a Python function to find the last occurrence of a target number in a given list of integers. If the target number is not found in the list, the function should return -1. The function should start with:
```python
from typing import List
def find_last_occurrence(numbers: 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_last_occurrence(numbers: List[int], target: int) -> int:
"""
Finds the last occurrence of the target number in a list of integers.
Args:
numbers (List[int]): A list of integers wher... |
code_exercise_27k | 18,923 | Write a Python function to find the closest element to a target number in a sorted array using a binary search algorithm. The function should return the closest element if the target is not found in the array. The code should start with:
```python
from typing import List, Union
def find_closest_element(arr: List[Union... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def find_closest_element(arr: List[Union[int, float]], target: Union[int, float]) -> Union[int, float]:
"""
Find the closest element to a target number in a sorted array using binary search.
... |
code_exercise_27k | 18,928 | Write a Python function to access the second row of a given 2D NumPy array. The function should handle cases where the input array is not 2-dimensional or does not have at least 2 rows by raising appropriate exceptions.
The code should start with:
```python
import numpy as np
def get_second_row(arr: np.ndarray) -> np... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def get_second_row(arr: np.ndarray) -> np.ndarray:
"""
Accesses the second row of a given 2D NumPy array.
Parameters:
arr (np.ndarray): The input 2D NumPy array.
Returns:
np.ndarray: The sec... |
code_exercise_27k | 18,929 | Write a Python function to find the smallest element in a rotated sorted array using a binary search algorithm. The array is guaranteed to be sorted and then rotated at some pivot point. The function should handle arrays with duplicate elements and return the smallest element efficiently.
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 find_smallest_element(arr: List[int]) -> int:
"""
Find the smallest element in a rotated sorted array using a binary search algorithm.
Args:
arr (List[int]): A rotated sorted array.
... |
code_exercise_27k | 18,931 | Write a Python function to access the last row of a given 2D NumPy array. The function should return the last row as a 1D NumPy array. The function should also handle cases where the input array is not 2-dimensional by raising a `ValueError`.
The code should start with:
```python
import numpy as np
def get_last_row(a... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def get_last_row(arr: np.ndarray) -> np.ndarray:
"""
Get the last row of a given 2D NumPy array.
Parameters:
arr (numpy.ndarray): The input 2D array.
Returns:
numpy.ndarray: The last row of ... |
code_exercise_27k | 18,933 | Write a Python function to find the largest element in a rotated sorted array efficiently. A rotated sorted array is an array that was originally sorted in ascending order and then rotated at some pivot point. For example, the array `[7, 8, 9, 10, 1, 2, 3, 4, 5, 6]` is a rotated sorted array. The function should use a ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_largest_element_in_rotated_array(arr: List[int]) -> int:
"""
Find the largest element in a rotated sorted array using a binary search approach.
Args:
arr (List[int]): The rotated so... |
code_exercise_27k | 18,934 | Write a Python function to access a specific element in a given 2D NumPy array. The function should handle the case where the row or column index is out of bounds by raising an `IndexError`. The code should start with:
```python
import numpy as np
def access_specific_element(arr: np.ndarray, row: int, col: int) -> int... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def access_specific_element(arr: np.ndarray, row: int, col: int) -> int or float:
"""
Accesses a specific element in a 2D NumPy array.
Parameters:
arr (numpy.ndarray): The input 2D array.
row (in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.