source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
code_exercise_27k | 16,115 | Write a Python function to calculate the required padding to align a given memory size to a specified alignment value. The function should ensure that the alignment value is a power of 2 and return the necessary padding to achieve the alignment.
The code should start with:
```python
def calculate_memory_alignment(size... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_memory_alignment(size: int, alignment: int) -> int:
"""
Calculate the padding required to align a given memory size to a specified alignment value.
Args:
size (int): Size of the data structure in bytes... |
code_exercise_27k | 16,120 | Write a Python function to determine if a given Sudoku board is valid. A valid Sudoku board must satisfy the following conditions:
1. Each row must contain the digits 1-9 without repetition.
2. Each column must contain the digits 1-9 without repetition.
3. Each of the nine 3x3 sub-grids (or boxes) must contain the digi... | 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:
"""
Determine if a given Sudoku board is valid.
Args:
board (List[List[str]]): A 9x9 list representing the Sudoku board.
... |
code_exercise_27k | 16,121 | Write a Python function to create an adjacency list from a directed graph. The function should take a dictionary representing the directed graph as input and return a list of lists, where each inner list represents the adjacency list of a vertex. The adjacency list for a vertex should contain the indices of the vertice... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def create_adjacency_list(graph: Dict[str, List[str]]) -> List[List[int]]:
"""
Generate an adjacency list from a directed graph.
Parameters:
graph (dict): A dictionary representing a direc... |
code_exercise_27k | 16,124 | Write a Python function to compute the cumulative sum of a NumPy array along a specific axis. The function should handle multi-dimensional arrays and ensure that the axis provided is valid for the given array. The code should start with:
```python
import numpy as np
def cumulative_sum(arr: np.ndarray, axis: int) -> np... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cumulative_sum(arr: np.ndarray, axis: int) -> np.ndarray:
"""
Compute the cumulative sum of a NumPy array along a specific axis.
Parameters:
arr (np.ndarray): Input NumPy array.
axis ... |
code_exercise_27k | 16,128 | Write a Python function to create an adjacency list from an undirected graph. The undirected graph is represented as a dictionary where each key is a node and the value is a list of nodes that are connected to the key node. The function should return a dictionary where each key is a node and the value is a list of node... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def create_undirected_adjacency_list(graph: Dict[int, List[int]]) -> Dict[int, List[int]]:
"""
Create an adjacency list from an undirected graph.
Args:
graph (dict): A dictionary repre... |
code_exercise_27k | 16,131 | Write a Python function to calculate the indegree of a given node in a directed graph. The graph is represented as a dictionary where the keys are nodes and the values are lists of nodes to which there is an outgoing directed edge from the key node. The function should return the indegree of the specified node. If the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Union
def calculate_indegree(graph: Dict[str, List[str]], node: str) -> int:
"""
Calculate the indegree of a given node in a directed graph.
Args:
graph (Dict[str, List[str]]): A dict... |
code_exercise_27k | 16,134 | Write a Python function to calculate the outdegree of a given node in a directed graph. The directed graph is represented as a dictionary where each key is a node and the corresponding value is a list of its outgoing edges. The function should return the outdegree of the specified node. If the node is not present in th... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_outdegree(graph: dict, node: str) -> int:
"""
Calculates the outdegree of a given node in a directed graph.
Args:
graph (dict): The directed graph represented as a dictionary, where each key is a node ... |
code_exercise_27k | 16,135 | Write a Python function to generate all possible subsets of a given set of numbers. The function should return a list of lists, where each inner list represents a subset. The function should handle sets of any size, including empty sets. The code should start with:
```python
from typing import List
def generate_subset... | 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 set of numbers.
Args:
nums (List[int]): A list of numbers from which to generate subset... |
code_exercise_27k | 16,136 | Write a Python function to convert a CIE color value to an RGB color value using a given transformation matrix. The function should take a 1-dimensional NumPy array representing the CIE color value and a 3x3 NumPy array representing the transformation matrix. The function should return a 1-dimensional NumPy array repre... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def cie_to_rgb(cie_color: np.ndarray, xyz_to_rgb_matrix: np.ndarray) -> np.ndarray:
"""
Convert a CIE color value to an RGB color value using a given transformation matrix.
Args:
cie_color (np.nd... |
code_exercise_27k | 16,139 | Write a Python function to shuffle the rows of a given 2D NumPy array randomly. The function should return the shuffled array with the same shape as the input array. The code should start with:
```python
import numpy as np
def shuffle_rows(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 shuffle_rows(arr: np.ndarray) -> np.ndarray:
"""
Shuffle the rows of a given 2D NumPy array randomly.
Args:
arr (numpy.ndarray): The input array with shape (m, n), where m is the number of ro... |
code_exercise_27k | 16,146 | Write a Python function to find the longest common subsequence (LCS) of two given strings using dynamic programming. The function should return the length of the LCS and the LCS itself as a tuple. The code should start with:
```python
from typing import Tuple
def longest_common_subsequence(str1: str, str2: str) -> Tup... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def longest_common_subsequence(str1: str, str2: str) -> Tuple[int, str]:
"""
Find the longest common subsequence of two strings using dynamic programming.
Args:
str1 (str): The first string... |
code_exercise_27k | 16,168 | Write a Python function to compute the Sigmoid activation function for a given NumPy array. The Sigmoid function is defined as \( \sigma(x) = \frac{1}{1 + e^{-x}} \). The function should handle multi-dimensional arrays and apply the Sigmoid function element-wise. The function should also validate the input to ensure it... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def sigmoid_activation(x: np.ndarray) -> np.ndarray:
"""
Compute the Sigmoid activation function for a NumPy array.
The Sigmoid function is defined as:
\[
\sigma(x) = \frac{1}{1 + e^{-x}}
\]
... |
code_exercise_27k | 16,172 | Write a Python function to compute the sum of all elements in a given 2D NumPy array using an optimized memory access pattern. The function should iterate over the columns first and then the rows to minimize cache misses and improve performance. The code should start with:
```python
import numpy as np
def optimized_su... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def optimized_sum(x: np.ndarray) -> float:
"""
Compute the sum of all elements in a given 2D NumPy array using an optimized memory access pattern.
Args:
x (np.ndarray): A 2D NumPy array.
Ret... |
code_exercise_27k | 16,180 | Write a Python function to compute the Levenshtein distance between two strings using a dynamic programming approach. The function should use a 2D NumPy array to store intermediate distances and should be efficient in terms of both time and space complexity. 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 levenshtein_distance(s1: str, s2: str) -> int:
"""
Compute the Levenshtein distance between two strings using a dynamic programming approach.
Parameters:
s1 (str): The first string.
s2 (str):... |
code_exercise_27k | 16,187 | Write a Python function to find the longest increasing subsequence (LIS) in a given list of integers using dynamic programming. The function should return the length of the LIS.
The code should start with:
```python
from typing import List
def longest_increasing_subsequence_length(nums: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_increasing_subsequence_length(nums: List[int]) -> int:
"""
Calculate the length of the longest increasing subsequence in a given list of integers.
Args:
nums: A list of integers ... |
code_exercise_27k | 16,198 | Write a Python function to calculate the sum of all multiples of 3 or 5 below a given number `n`. The function should efficiently compute the sum without including the number `n` itself. The code should start with:
```python
def sum_of_multiples(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_multiples(n: int) -> int:
"""
Calculate the sum of all multiples of 3 or 5 below a given number.
Args:
n (int): The upper limit (exclusive) for the multiples.
Returns:
int: The sum of all mul... |
code_exercise_27k | 16,204 | Write a Python function to count the number of unique paths in a maze from the top-left corner to the bottom-right corner. The maze is represented as a 2D grid where `0` represents an open path and `1` represents an obstacle. The function should start with:
```python
from typing import List
def count_unique_paths(maze... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_unique_paths(maze: List[List[int]]) -> int:
"""
Counts the number of unique paths in a maze from the top-left corner to the bottom-right corner.
Args:
maze (List[List[int]]): The m... |
code_exercise_27k | 16,207 | Write a Python function to check whether a given number is prime or not. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as numbers less than 2, which are not prime by definition.
The code should start with:
```python
def is_prime(number: int) ... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(number: int) -> bool:
"""
Check if a given number is prime.
Parameters:
number (int): The number to be checked.
Returns:
bool: True if the number is prime, False otherwise.
"""
# Return Fal... |
code_exercise_27k | 16,211 | Write a Python function to calculate the minimum number of coins needed to make a given amount using a defined set of coin denominations. If it is not possible to make the amount with the given coins, return -1. The function should start with:
```python
from typing import List
def min_coins(coins: List[int], amount: i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def min_coins(coins: List[int], amount: int) -> int:
"""
Calculate the minimum number of coins needed to make a given amount using a defined set of coin denominations.
Args:
coins (List[int]... |
code_exercise_27k | 16,221 | Write a Python function to count the number of words in a given sentence, considering various edge cases such as sentences with multiple spaces, leading/trailing spaces, and punctuation. The function should handle these cases gracefully and return the correct word count.
The code should start with:
```python
def count... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_words(sentence: str) -> int:
"""
Count the number of words in a given sentence, handling various edge cases.
Args:
sentence (str): The sentence to count words in.
Returns:
int: The total numbe... |
code_exercise_27k | 16,223 | Write a Python function to create and return a one-dimensional NumPy array with a specified number of random integers within a given range. The function should also print the array.
The code should start with:
```python
import numpy as np
def create_random_integer_array(length: int, low: int, high: int) -> np.ndarray... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def create_random_integer_array(length: int, low: int, high: int) -> np.ndarray:
"""
Creates and returns a one-dimensional NumPy array with random integers within a specified range.
Also prints the array.... |
code_exercise_27k | 16,228 | Write a Python function to add two arrays element-wise. The function should handle both lists and numpy arrays. If the input arrays are lists, they must have the same length. If the input arrays are numpy arrays, they must have the same shape. The function should return the resulting array after adding the two input ar... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
import numpy as np
def add_arrays(arr1: Union[list, np.ndarray], arr2: Union[list, np.ndarray]) -> Union[list, np.ndarray]:
"""
Add two arrays element-wise.
Parameters:
arr1 (list or numpy.ndar... |
code_exercise_27k | 16,230 | Write a Python function to randomly shuffle the elements of a given array using the Fisher-Yates shuffle algorithm. The function should return the shuffled array. The code should start with:
```python
from typing import List
import random
def shuffle_array(arr: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def shuffle_array(arr: List[int]) -> List[int]:
"""
Shuffles the elements of a given array using the Fisher-Yates shuffle algorithm.
Args:
arr (List[int]): The input array to b... |
code_exercise_27k | 16,231 | Write a Python function to solve the N-Queens problem and return the total number of distinct solutions for a given size of the chessboard `n`. The N-Queens problem is a classic combinatorial problem where `n` queens must be placed on an `n x n` chessboard such that no two queens threaten each other. This means no two ... | Here is the Python code to solve the given problem in the markdown block:
```python
def solve_n_queens(n: int) -> int:
"""
Solve the N-Queens problem and return the total number of distinct solutions.
Args:
n (int): The number of queens and size of the chessboard.
Returns:
int: The tot... |
code_exercise_27k | 16,233 | Write a Python function to check whether two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The function should ignore case and non-alphabetic characters.
The code should start with:
```p... | Here is the Python code to solve the given problem in the markdown block:
```python
def are_anagrams(str1: str, str2: str) -> bool:
"""
Check whether two given strings are anagrams of each other.
An anagram is a word or phrase formed by rearranging the letters of another word or phrase,
using all t... |
code_exercise_27k | 16,236 | Write a Python function to find the shortest path between two nodes in a network using Dijkstra's algorithm. The function should return the shortest distance and the shortest path as a list of nodes. The network is represented as a dictionary where the keys are the nodes and the values are dictionaries of neighboring n... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple, Optional
import heapq
def find_shortest_path(graph: Dict[str, Dict[str, int]], start_node: str, end_node: str) -> Optional[Tuple[int, List[str]]]:
"""
Find the shortest path between two nod... |
code_exercise_27k | 16,237 | Write a Python function to implement the merge sort algorithm to sort a given array. The function should be able to handle arrays of integers and return the sorted array. The code should start with:
```python
from typing import List
def merge_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 merge_sort(arr: List[int]) -> List[int]:
"""
Sorts the given array using the merge sort algorithm.
Args:
arr (List[int]): The unsorted array of integers.
Returns:
List[int]:... |
code_exercise_27k | 16,247 | Write a Python function to calculate the sum of each column in a two-dimensional array. The function should take a list of lists (representing a 2D array) as input and return a list containing the sum of each column. If the input array is empty or contains rows of different lengths, the function should return an empty ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_columns(arr: List[List[int]]) -> List[int]:
"""
Calculate the sum of each column in a two-dimensional array.
Args:
arr (List[List[int]]): The input two-dimensional array.
Ret... |
code_exercise_27k | 16,260 | Write a Python function to calculate the transpose of a given matrix. The transpose of a matrix is obtained by swapping its rows with its columns. The function should handle matrices of any size, including non-square matrices. The code should start with:
```python
from typing import List
def transpose_matrix(matrix: L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Calculates the transpose of a given matrix.
Args:
matrix (List[List[int]]): The matrix to transpose.
Returns:
... |
code_exercise_27k | 16,262 | Write a Python function to find the longest common substring between two given strings using dynamic programming. The function should return the longest common substring as a string. The code should start with:
```python
def longest_common_substring_dp(s1: str, s2: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def longest_common_substring_dp(s1: str, s2: str) -> str:
"""
Find the longest common substring between two strings using dynamic programming.
Args:
s1 (str): The first string.
s2 (str): The second string.
... |
code_exercise_27k | 16,265 | Write a Python function to convert a given decimal number into its binary representation. The function should handle both positive and zero decimal numbers. The code should start with:
```python
def decimal_to_binary(decimal_num: int) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def decimal_to_binary(decimal_num: int) -> str:
"""
Convert a decimal number to its binary representation.
Args:
decimal_num (int): The decimal number to be converted.
Returns:
str: The binary represent... |
code_exercise_27k | 16,272 | Write a Python function to find the unique elements of an array while preserving the order of their first appearance. The function should handle lists and tuples as input. The code should start with:
```python
from typing import List, Tuple, Union
def find_unique_elements_preserving_order(arr: Union[List, Tuple]) -> L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Union
def find_unique_elements_preserving_order(arr: Union[List, Tuple]) -> List:
"""
Find the unique elements of an array while preserving the order of their first appearance.
Parameters:
... |
code_exercise_27k | 16,274 | Write a Python function to calculate the element-wise square root of a given list of non-negative integers. The function should handle lists of varying lengths and ensure that the input list contains only non-negative integers. If the input list contains any negative integers, the function should return an empty list.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def elementwise_square_root(numbers: List[int]) -> List[float]:
"""
Calculate the element-wise square root of a given list of non-negative integers.
Args:
numbers (List[int]): A ... |
code_exercise_27k | 16,278 | Write a Python function to calculate the mean of each column in a given two-dimensional list (list of lists). The function should handle any size of two-dimensional list and return a list containing the mean of each column. The code should start with:
```python
from typing import List
def calculate_column_means(matrix... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_column_means(matrix: List[List[float]]) -> List[float]:
"""
Calculates the mean of each column in a given two-dimensional list.
Args:
matrix (List[List[float]]): A two-dimensio... |
code_exercise_27k | 16,287 | Write a Python function to generate all valid permutations of parentheses for a given number of pairs with restrictions. The restrictions are that each permutation must start with an opening parenthesis '(' and end with a closing parenthesis ')'. The function should return a list of strings, where each string represent... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_valid_parentheses(n: int) -> List[str]:
"""
Generate all valid permutations of parentheses for a given number of pairs with restrictions.
Args:
n (int): Number of pairs of paren... |
code_exercise_27k | 16,301 | Write a Python function to calculate the element-wise difference between two lists of integers. The function should ensure that both lists have the same length before performing the calculation. If the lists have different lengths, the function should return `None`. The code should start with:
```python
from typing imp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def element_wise_difference(list1: List[int], list2: List[int]) -> Optional[List[int]]:
"""
Calculate the element-wise difference between two lists of integers.
Args:
list1 (List[i... |
code_exercise_27k | 16,303 | Write a Python function to create a Numpy array with `n` evenly spaced values between a given `start` and `stop` range. The function should handle cases where `n` is less than 2 by returning an empty array. The code should start with:
```python
import numpy as np
def create_evenly_spaced_array(start: float, stop: floa... | 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, n: int) -> np.ndarray:
"""
Creates a Numpy array with `n` evenly spaced values between `start` and `stop`.
Args:
start (float): The start... |
code_exercise_27k | 16,308 | Write a Python function to remove duplicate elements from a given list while preserving the order of the first occurrence of each element. The function should handle lists containing integers, strings, and other comparable data types. The code should start with:
```python
from typing import List, Any
def remove_duplic... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def remove_duplicates_preserve_order(arr: List[Any]) -> List[Any]:
"""
Removes duplicate elements from a list while preserving the order of their first occurrence.
Args:
arr (List[Any])... |
code_exercise_27k | 16,318 | Write a Python function to calculate the sum of an arbitrary number of numeric inputs. The function should accept a variable number of arguments and return their sum. The function should handle both integers and floating-point numbers. The code should start with:
```python
from typing import Union, Tuple
def sum_numbe... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union, Tuple
def sum_numbers(*args: Union[int, float]) -> Union[int, float]:
"""
Calculate the sum of an arbitrary number of numeric inputs.
Args:
*args: A variable number of numeric inputs (int ... |
code_exercise_27k | 16,322 | 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 their respective counts. The function should handle lists of any type of elements, including integers, strings, and ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_element_occurrences(arr: List) -> Dict:
"""
Count the number of occurrences of each element in a given list.
Args:
arr (List): The input list containing elements of any type.... |
code_exercise_27k | 16,323 | Write a Python function to calculate the factorial of a given non-negative integer using an iterative approach. The function should handle edge cases such as zero and should not use recursion. The code should start with:
```python
def factorial_iterative(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def factorial_iterative(n: int) -> int:
"""
Calculate the factorial of a given non-negative integer using an iterative approach.
Parameters:
n (int): The non-negative integer for which to calculate the factorial.
R... |
code_exercise_27k | 16,325 | Write a Python function to check if a given number is prime. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as negative numbers, 0, and 1, which are not prime numbers. The function should also efficiently check for primality by testing divisibi... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(n: int) -> bool:
"""
Check if a given number is prime.
Parameters:
n (int): The number to be checked.
Returns:
bool: True if the number is prime, False otherwise.
"""
# Handle edge cases: ... |
code_exercise_27k | 16,327 | Write a Python function to find the maximum value among a list of numbers. The function should be able to handle any number of inputs, not just three. The code should start with:
```python
from typing import List
def find_max_value(numbers: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_max_value(numbers: List[int]) -> int:
"""
Find the maximum value among a list of numbers.
Args:
numbers (List[int]): A list of integers from which to find the maximum value.
Re... |
code_exercise_27k | 16,330 | Write a Python function to compute the element-wise square of a given list of integers. The function should return a new list containing the squared values of the input list. The code should start with:
```python
from typing import List
def element_wise_square(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 element_wise_square(arr: List[int]) -> List[int]:
"""
Compute the element-wise square of a given list of integers.
Args:
arr (List[int]): The input list of integers.
Returns:
... |
code_exercise_27k | 16,332 | Write a Python function to extract all prime numbers from a given NumPy array. The function should take a NumPy array as input and return a new NumPy array containing only the prime numbers from the input array. The function should be efficient and handle arrays of various sizes.
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 extract_prime_numbers(n: np.ndarray) -> np.ndarray:
"""
Extracts prime numbers from a given NumPy array.
Args:
n (np.ndarray): The input NumPy array.
Returns:
np.ndarray: An arra... |
code_exercise_27k | 16,336 | Write a Python function to convert a decimal number to its binary representation. The function should handle both positive and zero decimal numbers. The code should start with:
```python
def decimal_to_binary(decimal_num: int) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def decimal_to_binary(decimal_num: int) -> str:
"""
Converts a decimal number to its binary representation.
Args:
decimal_num (int): The decimal number to convert.
Returns:
str: The binary representatio... |
code_exercise_27k | 16,347 | Write a Python function to perform element-wise division of two lists of floats. The function should handle cases where the lists have different lengths by padding the shorter list with the last element of the longer list until both lists have the same length. The function should return a list of the same length as the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def element_wise_division(arr1: List[float], arr2: List[float]) -> List[float]:
"""
Perform element-wise division of two lists of floats.
If the lists have different lengths, the shorter list is pad... |
code_exercise_27k | 16,348 | Write a Python function to count the number of vowels in a given string, considering both uppercase and lowercase vowels. The function should be case-insensitive and should return the total count of vowels in the string.
The code should start with:
```python
def count_vowels(s: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_vowels(s: str) -> int:
"""
Counts the number of vowels in a given string.
This function iterates through each character in the input string, checks if it is a vowel,
and counts the total number of vowels found... |
code_exercise_27k | 16,349 | Write a Python function to solve the N-Queens problem using bit manipulation. The function should count the number of possible solutions for placing `n` queens on an `n x n` chessboard such that no two queens threaten each other. The function should use bitwise operations to track the positions of the queens and should... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_n_queens_bitwise(n: int) -> int:
"""
Count the number of possible solutions to the N-Queens problem using bit manipulation.
Args:
n (int): The size of the chessboard and the number of queens.
Returns:... |
code_exercise_27k | 16,352 | Write a Python function to find the sum of all even numbers in a given list. The function should be able to handle both positive and negative integers, as well as an empty list. The code should start with:
```python
from typing import List
def sum_even_numbers(numbers: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_even_numbers(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in a given list.
Args:
numbers (List[int]): A list of integers.
Returns:
int: The sum ... |
code_exercise_27k | 16,363 | Write a Python function to find the index positions of the top 3 maximum values in a given list of integers. If the list contains fewer than 3 elements, the function should return the indices of all elements in descending order of their values. The function should handle lists with duplicate values and return the corre... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_top3_indices(arr: List[int]) -> List[int]:
"""
Find the index positions of the top 3 maximum values in a given list of integers.
If the list contains fewer than 3 elements, return the indic... |
code_exercise_27k | 16,369 | Write a Python function to remove duplicates from a given list while preserving the order of the elements. The function should take a list as input and return a new list with all duplicate elements removed, maintaining the first occurrence of each element in the original order.
The code should start with:
```python
fr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_duplicates_preserve_order(input_list: List[int]) -> List[int]:
"""
Removes duplicates from a given list while preserving the order of the elements.
Args:
input_list (List[int]): T... |
code_exercise_27k | 16,373 | Write a Python function to find the second largest number in a given list. The function should handle edge cases such as an empty list or a list with fewer than two elements by returning `None`. The function should also correctly identify the second largest number even if there are duplicate values in the list.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_second_largest(numbers: List[int]) -> Optional[int]:
"""
Finds the second largest number in a given list of numbers.
Args:
numbers (List[int]): A list of integers.
Re... |
code_exercise_27k | 16,376 | Write a Python function to calculate the sum of all digits in a given number. The function should handle both positive and negative integers. The code should start with:
```python
def sum_of_digits(number: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_digits(number: int) -> int:
"""
Calculates the sum of all digits in a given number.
Args:
number (int): The number for which the sum of digits needs to be calculated.
Returns:
int: The sum of... |
code_exercise_27k | 16,379 | Write a Python function to find the transpose of a given matrix. The function should handle matrices with rows of equal length and return the transposed matrix. The function should raise a `ValueError` if the input matrix is empty or contains rows of different lengths.
The code should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Find the transpose of a given matrix.
Parameters:
- matrix (List[List[int]]): The matrix for which the transpose needs to be... |
code_exercise_27k | 16,381 | Write a Python function to convert a given string to title case, ensuring that each word in the string starts with an uppercase letter and the rest of the letters are in lowercase. The function should handle various edge cases, such as strings with multiple spaces, leading/trailing spaces, and special characters.
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_to_title_case(string: str) -> str:
"""
Converts a given string to title case, ensuring each word starts with an uppercase letter and the rest are lowercase.
Args:
string (str): The input string to be con... |
code_exercise_27k | 16,386 | Write a Python function to find the elements in an array that are not present in another array. The function should efficiently handle large arrays and return the missing elements in a new list. The code should start with:
```python
from typing import List
def find_missing_elements(arr1: List[int], arr2: List[int]) ->... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_missing_elements(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Find the elements in arr1 that are not present in arr2.
Args:
arr1 (List[int]): The first array.
arr2 (L... |
code_exercise_27k | 16,387 | Write a Python function to implement the binary search algorithm. The function should take a sorted list of elements and a target value as input, and return the index of the target value in the list if it exists, or `None` if it does not. The function should be efficient and work in O(log n) time complexity.
The code ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def binary_search(arr: List[int], target: int) -> Optional[int]:
"""
Perform binary search on a sorted list to find the index of a target value.
Args:
arr (List[int]): A sorted lis... |
code_exercise_27k | 16,392 | Write a Python function to compute the element-wise absolute value of a given list of integers. The function should handle both positive and negative integers and return a new list containing the absolute values of the input list. The code should start with:
```python
from typing import List
def elementwise_abs(arr: L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def elementwise_abs(arr: List[int]) -> List[int]:
"""
Compute the element-wise absolute value of a given list of integers.
Args:
arr (List[int]): The input list of integers.
Returns:
... |
code_exercise_27k | 16,393 | Write a Python function to determine the number of unique paths in a maze from the top-left corner to the bottom-right corner, considering obstacles. The maze is represented as a 2D list where `0` represents an empty cell and `1` represents an obstacle. The function should return the number of unique paths from the sta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def unique_paths_with_obstacles(maze: List[List[int]]) -> int:
"""
Determine the number of unique paths in a maze from the top-left corner to the bottom-right corner with obstacles.
Args:
ma... |
code_exercise_27k | 16,396 | Write a Python function to sort a given list using the bubble sort algorithm. The function should be optimized to stop early if no swaps are made during a pass, indicating that the list is already sorted. The code should start with:
```python
from typing import List
def optimized_bubble_sort(lst: List[int]) -> List[in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def optimized_bubble_sort(lst: List[int]) -> List[int]:
"""
Sorts a list using the optimized bubble sort algorithm.
The algorithm stops early if no swaps are made during a pass, indicating that the ... |
code_exercise_27k | 16,399 | Write a Python function to implement the merge sort algorithm on a given list. The function should recursively divide the list into halves until each sublist contains only one element, and then merge the sorted sublists back together to produce the final sorted list. The code should start with:
```python
from typing im... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Implements the merge sort algorithm to sort a given list of integers.
Args:
arr (List[int]): The list of integers to be sorted.
Returns:... |
code_exercise_27k | 16,400 | Write a Python function to calculate the Kronecker product of two given matrices. The Kronecker product of two matrices \( A \) (of size \( m \times n \)) and \( B \) (of size \( p \times q \)) is a block matrix of size \( (m \times p) \times (n \times q) \). Each element of matrix \( A \) is multiplied by the entire m... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def kronecker_product(matrix1: List[List[int]], matrix2: List[List[int]]) -> List[List[int]]:
"""
Calculate the Kronecker product of two matrices.
Args:
matrix1 (List[List[int]]): The first ... |
code_exercise_27k | 16,408 | Write a Python function to count the number of nonzero elements in a given array. The function should efficiently handle arrays of various sizes and types of elements. The code should start with:
```python
from typing import List
def count_nonzero_elements(arr: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_nonzero_elements(arr: List[int]) -> int:
"""
Counts the number of nonzero elements in a given array.
Args:
arr (List[int]): The array containing elements to count.
Returns:
... |
code_exercise_27k | 16,409 | Write a Python function to perform element-wise multiplication of two lists of integers. The function should ensure that both lists have the same length before performing the multiplication. If the lists have different lengths, the function should raise a `ValueError`. The code should start with:
```python
from typing ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def elementwise_multiply(list1: List[int], list2: List[int]) -> List[int]:
"""
Perform element-wise multiplication of two lists of integers.
Args:
list1 (List[int]): The first list of intege... |
code_exercise_27k | 16,410 | Write a Python function to implement Dijkstra's algorithm on a given graph. The graph is represented as a dictionary where keys are nodes and values are dictionaries of connected nodes and their edge weights. The function should return a dictionary of shortest paths from a given start node to all other nodes in the gra... | Here is the Python code to solve the given problem in the markdown block:
```python
import heapq
from typing import Dict, Any
def dijkstra_shortest_paths(graph: Dict[Any, Dict[Any, int]], start: Any) -> Dict[Any, int]:
"""
Dijkstra's algorithm to find the shortest paths from a given start node to all other nod... |
code_exercise_27k | 16,420 | Write a Python function to find the maximum of three numbers using a different approach than the given code snippet. Instead of using conditional statements, use the built-in `max` function to determine the maximum value. The function should be able to handle both integers and floating-point numbers.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_maximum(num1: float, num2: float, num3: float) -> float:
"""
Finds the maximum of three numbers using the built-in max function.
Parameters:
num1 (float): The first number.
num2 (float): The second number.
... |
code_exercise_27k | 16,422 | Write a Python function to reverse a string. The function should handle only string inputs and return the reversed string. If the input is not a string, the function should raise a `TypeError`.
The code should start with:
```python
def reverse_string(input_string: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_string(input_string: str) -> str:
"""
Reverse a given string.
Args:
input_string (str): The string to be reversed.
Returns:
str: The reversed string.
Raises:
TypeError: If the i... |
code_exercise_27k | 16,429 | Write a Python function to calculate the element-wise modulus of two arrays. The function should take two numpy arrays as input and return a new numpy array containing the element-wise modulus of the input arrays. The function should raise a `ValueError` if the input arrays do not have the same shape.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def element_wise_modulus(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise modulus of two numpy arrays.
Parameters:
- arr1 (numpy.ndarray): The first input array.
... |
code_exercise_27k | 16,436 | Write a Python function to reverse the columns of a 2-dimensional NumPy array. The function should take a NumPy array as input and return a new array with its columns reversed. The code should start with:
```python
import numpy as np
def reverse_columns(arr: np.ndarray) -> np.ndarray:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def reverse_columns(arr: np.ndarray) -> np.ndarray:
"""
Reverse the columns of a 2-dimensional NumPy array.
Parameters:
arr (numpy.ndarray): The 2-dimensional array to reverse its columns.
Retur... |
code_exercise_27k | 16,438 | Write a Python function to count the number of vowels in a given string, considering both uppercase and lowercase vowels. The function should be case-insensitive and should return the total count of vowels in the string.
The code should start with:
```python
def count_vowels(string: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_vowels(string: str) -> int:
"""
Counts the number of vowels in a given string.
This function takes a string as input and returns the number of vowels present in the string.
The function is case-insensitive, me... |
code_exercise_27k | 16,443 | Write a Python function to perform element-wise exponentiation of two NumPy arrays. The function should take two arrays as input and return a new array where each element is the result of raising the corresponding element in the first array to the power of the corresponding element in the second array. The function sho... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_exponentiation(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
"""
Perform element-wise exponentiation of two NumPy arrays.
Parameters:
arr1 (numpy.ndarray): The first input array.... |
code_exercise_27k | 16,448 | Write a Python function to remove duplicates from a given list while preserving the order of the elements. The function should return a new list with all duplicate elements removed. The code should start with:
```python
from typing import List
def remove_duplicates(lst: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_duplicates(lst: List[int]) -> List[int]:
"""
Removes duplicates from a list while preserving the order of the elements.
Args:
lst (List[int]): The list containing duplicate elemen... |
code_exercise_27k | 16,453 | Write a Python function to merge two sorted lists into a single sorted list. The function should efficiently combine the elements from both lists while maintaining the sorted order. The code should start with:
```python
from typing import List
def merge_sorted_lists(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 merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]:
"""
Merges two sorted lists into a single sorted list.
Args:
list1 (List[int]): The first sorted list.
list2 ... |
code_exercise_27k | 16,463 | Write a Python function to reverse the order of words in a given string. The function should handle strings with multiple spaces between words and leading/trailing spaces. The code should start with:
```python
def reverse_words_in_string(string: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_words_in_string(string: str) -> str:
"""
Reverses the order of words in a given string.
This function splits the input string into words, reverses the order of the words,
and then joins them back into a sing... |
code_exercise_27k | 16,466 | Write a Python function to calculate the Frobenius norm of a given 2D array (matrix). The Frobenius norm of a matrix is defined as the square root of the sum of the absolute squares of its elements. The function should handle only 2D arrays and raise a `ValueError` if the input is not a 2D numpy array.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_frobenius_norm(array: np.ndarray) -> float:
"""
Calculate the Frobenius norm of a given 2D array.
The Frobenius norm is defined as the square root of the sum of the absolute squares of its ... |
code_exercise_27k | 16,469 | Write a Python function to check if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. The function should handle various edge cases, such as empty strings, strings with only non-alphanumeric characters, and strings with mixed characters.
The code should start with:
```p... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_valid_palindrome(input_str: str) -> bool:
"""
Check if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases.
Args:
input_str (str): The input string to be checked.... |
code_exercise_27k | 16,475 | Write a Python function to find the longest substring without repeating characters in a given string. The function should return the longest substring that contains no repeated characters. If the input string is empty, the function should raise a `ValueError`.
The code should start with:
```python
def longest_substrin... | Here is the Python code to solve the given problem in the markdown block:
```python
def longest_substring_without_repeating_chars(s: str) -> str:
"""
Finds the longest substring without repeating characters in a given string.
Args:
s (str): The input string.
Returns:
str: The longest s... |
code_exercise_27k | 16,477 | Write a Python function to calculate the Greatest Common Divisor (GCD) of two non-negative integers using the Euclidean algorithm. The function should handle the case where either of the numbers is zero and should not accept negative numbers. The code should start with:
```python
def gcd(num1: int, num2: int) -> int:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
def gcd(num1: int, num2: int) -> int:
"""
Calculates the Greatest Common Divisor (GCD) of two non-negative integers using the Euclidean algorithm.
Args:
num1 (int): The first non-negative integer.
num2 (int)... |
code_exercise_27k | 16,478 | Write a Python function to calculate the trace of a square matrix. The trace of a matrix is defined as the sum of the elements on its main diagonal. The function should raise a `ValueError` if the input matrix is not square.
The code should start with:
```python
from typing import List
def calculate_trace(matrix: Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_trace(matrix: List[List[int]]) -> int:
"""
Calculate the trace of a square matrix.
The trace of a matrix is the sum of the elements on its main diagonal.
Args:
matrix (Lis... |
code_exercise_27k | 16,480 | Write a Python function to check if a given number is a prime number. The function should handle special cases and efficiently determine the primality of the number. The code should start with:
```python
def is_prime(number: int) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(number: int) -> bool:
"""
Check if a given number is a prime number.
Parameters:
number (int): The number to be checked for primality.
Returns:
bool: True if the number is prime, False otherwise.
... |
code_exercise_27k | 16,482 | Write a Python function to implement binary search in a sorted list. The function should return the index of the target value if it exists in the list, otherwise return -1. The function should also raise a `ValueError` if the provided list is not sorted.
The code should start with:
```python
from typing import List, A... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def binary_search(sorted_list: List[Any], target: Any) -> int:
"""
Perform binary search on a sorted list to find the index of the target value.
Args:
sorted_list (List[Any]): A list of... |
code_exercise_27k | 16,484 | Write a Python function to swap the rows and columns of a given 2D NumPy array. The function should handle arrays of any size, not just 3x3. The code should start with:
```python
import numpy as np
def swap_rows_columns(arr: np.ndarray) -> np.ndarray:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def swap_rows_columns(arr: np.ndarray) -> np.ndarray:
"""
Swaps the rows and columns of a given 2D NumPy array.
Args:
arr (np.ndarray): The input 2D NumPy array.
Returns:
np.ndarray:... |
code_exercise_27k | 16,486 | Write a Python function to sort a list of numbers using the bubble sort algorithm. The function should be able to handle lists of integers and floating-point numbers. The code should start with:
```python
from typing import List
def bubble_sort(numbers: List[float]) -> List[float]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def bubble_sort(numbers: List[float]) -> List[float]:
"""
Sorts a list of numbers using the bubble sort algorithm.
Args:
numbers (List[float]): List of numbers to be sorted.
Returns:
... |
code_exercise_27k | 16,487 | Write a Python function to calculate the Fibonacci sequence up to a given number efficiently using an iterative approach. The function should return a list of Fibonacci numbers that are less than or equal to the given number. The code should start with:
```python
from typing import List
def fibonacci_sequence(num: int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def fibonacci_sequence(num: int) -> List[int]:
"""
Calculates the Fibonacci sequence up to a given number using an iterative approach.
Args:
num (int): The upper limit for the Fibonacci sequ... |
code_exercise_27k | 16,489 | Write a Python function to calculate the L1 norm of a given array. The L1 norm, also known as the Manhattan distance or taxicab norm, is the sum of the absolute values of the elements in the array. The function should handle both lists and numpy arrays. The code should start with:
```python
from typing import Union
imp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
import numpy as np
def l1_norm(arr: Union[list, np.ndarray]) -> float:
"""
Calculates the L1 norm (Manhattan distance) of a given array.
The L1 norm is defined as the sum of the absolute values of ... |
code_exercise_27k | 16,500 | Write a Python function to find the intersection of two sets, ensuring that the function handles cases where one or both sets are empty. The function should return an empty set if either set is empty. The code should start with:
```python
def find_intersection(set1: set, set2: set) -> set:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def find_intersection(set1: set, set2: set) -> set:
"""
Finds the intersection of two sets.
Args:
set1 (set): The first set.
set2 (set): The second set.
Returns:
set: The intersection of set1 an... |
code_exercise_27k | 16,501 | Write a Python function to split a given 2D NumPy array of shape (2, 4) horizontally into two equal-sized arrays. The function should return a tuple containing the two resulting arrays. Ensure that the function raises a `ValueError` if the input array does not have the expected shape.
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 split_array_horizontally(arr: np.ndarray) -> tuple:
"""
Splits a 2D NumPy array of shape (2, 4) horizontally into two equal-sized arrays.
Parameters:
arr (np.ndarray): Input 2D NumPy array of... |
code_exercise_27k | 16,503 | Write a Python function to find the rank of a given matrix using elementary row operations. The rank of a matrix is defined as the maximum number of linearly independent rows or columns in the matrix. The function should implement the Gaussian elimination method to reduce the matrix to row echelon form and then count t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def matrix_rank(matrix: List[List[float]]) -> int:
"""
Calculate the rank of a given matrix using Gaussian elimination.
Parameters:
matrix (List[List[float]]): The matrix for which to calculate ... |
code_exercise_27k | 16,505 | Write a Python function to calculate the element-wise sine of a given array using the `numpy` library. The function should handle both 1D and 2D arrays and return the sine values for each element in the array. The code should start with:
```python
import numpy as np
def elementwise_sine(array: np.ndarray) -> np.ndarra... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def elementwise_sine(array: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise sine of a given array using numpy.
Args:
array (numpy.ndarray): The input array for which to compute the sine... |
code_exercise_27k | 16,511 | Write a Python function to calculate the Hamming distance between two arrays. The Hamming distance is defined as the number of positions at which the corresponding symbols in the two arrays are different. The function should raise a `ValueError` if the lengths of the two arrays do not match.
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 hamming_distance(array1: List, array2: List) -> int:
"""
Calculate the Hamming distance between two arrays.
The Hamming distance is a measure of how many elements differ between two equal-length... |
code_exercise_27k | 16,518 | Write a Python function to calculate the element-wise arctangent of a given array. The function should handle both 1D and 2D arrays and return the result as a numpy array. The function should also include input validation to ensure that the input is a numpy array. The code should start with:
```python
import numpy as n... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def element_wise_arctan(arr: np.ndarray) -> np.ndarray:
"""
Calculate the element-wise arctangent of a given numpy array.
Parameters:
arr (numpy.ndarray): The input array for which to calculate the e... |
code_exercise_27k | 16,520 | Write a Python function to convert a decimal number to its binary representation. The function should handle only positive integers and return the binary representation as a string. If the input is not a positive integer, the function should raise a `ValueError`.
The code should start with:
```python
def decimal_to_bi... | Here is the Python code to solve the given problem in the markdown block:
```python
def decimal_to_binary(decimal_number: int) -> str:
"""
Convert a decimal number to its binary representation.
Args:
decimal_number (int): The decimal number to convert. Must be a positive integer.
Returns:
... |
code_exercise_27k | 16,526 | Write a Python function to find the longest increasing subsequence (LIS) with distinct numbers and unique subsequences with the minimum sum. The function should use backtracking to explore all possible subsequences and return the one that meets the criteria.
The code should start with:
```python
from typing import Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_increasing_subsequence_with_min_sum(nums: List[int]) -> List[int]:
"""
Finds the longest increasing subsequence with distinct numbers and unique subsequences with the minimum sum.
Args:
... |
code_exercise_27k | 16,527 | Write a Python function to find the k-th smallest number in a list of integers. The function should handle edge cases such as an empty list or a k value that is out of bounds. The code should start with:
```python
from typing import List
def find_kth_smallest_number(numbers: List[int], k: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_kth_smallest_number(numbers: List[int], k: int) -> int:
"""
Find the k-th smallest number in a list of integers.
Args:
numbers (List[int]): A list of integers.
k (int): The ... |
code_exercise_27k | 16,532 | Write a Python function to calculate the surface area of a sphere given its radius. The function should be able to handle both positive and zero radius values. The code should start with:
```python
import math
def calculate_sphere_surface_area(radius: float) -> float:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_sphere_surface_area(radius: float) -> float:
"""
Calculate the surface area of a sphere given its radius.
Args:
radius (float): The radius of the sphere. Must be non-negative.
Returns... |
code_exercise_27k | 16,538 | Write a Python function to reverse the order of words in a given sentence. The function should handle sentences with varying lengths, including empty sentences and sentences with multiple spaces between words. The code should start with:
```python
def reverse_sentence(sentence: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_sentence(sentence: str) -> str:
"""
Reverses the order of words in a given sentence.
Args:
sentence (str): The sentence to be reversed.
Returns:
str: The sentence with the order of words rev... |
code_exercise_27k | 16,539 | Write a Python function to calculate the factorial of a given non-negative integer using recursion. The function should handle the base case where the factorial of 0 or 1 is 1, and the recursive case where the factorial of a number `n` is `n` multiplied by the factorial of `n-1`. The function should also raise a `Value... | Here is the Python code to solve the given problem in the markdown block:
```python
def factorial(n: int) -> int:
"""
Calculate the factorial of a given non-negative integer using recursion.
Parameters:
n (int): The number to calculate the factorial of.
Returns:
int: The factorial of the given... |
code_exercise_27k | 16,542 | Write a Python function to remove all occurrences of a specified element from a given list. The function should return a new list with all instances of the specified element removed, while preserving the order of the remaining elements. The code should start with:
```python
from typing import List, Any
def remove_all_... | Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List, Any
def remove_all_occurrences(lst: List[Any], elem: Any) -> List[Any]:
"""
Remove all occurrences of a specified element from a given list.
Args:
lst (List[Any]): The input list from whi... |
code_exercise_27k | 16,545 | Write a Python function to split a given 2D NumPy array into two equal-sized arrays horizontally. The function should ensure that the input array has an even number of columns. If the input array does not meet this requirement, the function should raise a `ValueError`. The function should return a tuple containing the ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def split_array_horizontally(arr: np.ndarray) -> tuple:
"""
Splits a 2D NumPy array into two equal-sized arrays horizontally.
Parameters:
arr (numpy.ndarray): The input 2D array to be split horizonta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.