source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
15,410
Write a Python function to reverse a given string without using any built-in reverse functions or slicing. The function should iterate through the string and construct the reversed string manually. The code should start with: ```python def reverse_string(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(string: str) -> str: """ Reverse a given string without using any built-in reverse functions or slicing. Args: string (str): The string to be reversed. Returns: str: The reversed stri...
code_exercise_27k
15,411
Write a Python function to find the minimum element in a given NumPy array. The function should handle empty arrays by raising a `ValueError`. The code should start with: ```python import numpy as np def find_minimum(arr: np.ndarray) -> np.float64: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_minimum(arr: np.ndarray) -> np.float64: """ Find the minimum element in a given NumPy array. Parameters: arr (numpy.ndarray): The input NumPy array. Returns: numpy.float64: The mini...
code_exercise_27k
15,412
Write a Python function to find the number of ways to arrange n non-attacking queens on an n x n chessboard. The function should use a backtracking approach to solve the problem. The code should start with: ```python def total_n_queens(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_safe(board, row, col): """ Check if it is safe to place a queen at board[row][col]. Args: board (list[list[int]]): The current state of the chessboard. row (int): The row index where the queen is to b...
code_exercise_27k
15,414
Write a Python function to find the indices of the maximum element in each row of a given NumPy array. The function should return a NumPy array containing the indices of the maximum elements for each row. The code should start with: ```python import numpy as np def find_max_indices_in_rows(array: np.ndarray) -> np.nda...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def find_max_indices_in_rows(array: np.ndarray) -> np.ndarray: """ Find the indices of the maximum element in each row of a given NumPy array. Args: array (numpy.ndarray): The input array for whi...
code_exercise_27k
15,417
Write a Python function to find the indices of the minimum element in each row of a given NumPy array. The function should return a NumPy array containing the indices of the minimum element in each row. The code should start with: ```python import numpy as np def min_indices_in_rows(array: np.ndarray) -> np.ndarray: ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def min_indices_in_rows(array: np.ndarray) -> np.ndarray: """ Find the indices of the minimum element in each row of a NumPy array. Parameters: array (numpy.ndarray): The input NumPy array. Retu...
code_exercise_27k
15,419
Write a Python function to find the largest and smallest elements in a given list of numbers. The function should handle the case where the input list is empty by raising a `ValueError`. The code should start with: ```python from typing import List, Tuple def find_largest_and_smallest(numbers: List[int]) -> Tuple[int,...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_largest_and_smallest(numbers: List[int]) -> Tuple[int, int]: """ Finds the largest and smallest elements in a list of numbers. Args: numbers (List[int]): A list of integers. ...
code_exercise_27k
15,422
Write a Python function to determine if a list is sorted in descending order. The function should return `True` if the list is sorted in descending order, and `False` otherwise. The code should start with: ```python from typing import List def is_list_sorted_descending(lst: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_list_sorted_descending(lst: List[int]) -> bool: """ Determine if a list is sorted in descending order. Args: lst (List[int]): The list to check. Returns: bool: True if th...
code_exercise_27k
15,423
Write a Python function to replace all negative numbers in a given NumPy array with a specified value. The function should take two parameters: the input NumPy array and the value to replace negative numbers with. The function should return the modified NumPy array. 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 replace_negative_with_value(arr: np.ndarray, value: float) -> np.ndarray: """ Replace all negative numbers in a NumPy array with a specified value. Parameters: arr (np.ndarray): Input NumPy array...
code_exercise_27k
15,425
Write a Python function to find the maximum product of a subarray within a given array. The function should efficiently handle arrays with both positive and negative integers, as well as zeros. The code should start with: ```python from typing import List def max_product_subarray(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_product_subarray(arr: List[int]) -> int: """ Returns the maximum product of a subarray within the given array. Args: arr (List[int]): The input array containing integers. Return...
code_exercise_27k
15,426
Write a Python function to remove duplicates from a given list while preserving the order of the elements. The function should return a new list with all duplicate elements removed. The code should start with: ```python from typing import List def remove_duplicates_preserve_order(lst: List[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_preserve_order(lst: List[int]) -> List[int]: """ Remove duplicates from a list while preserving the order of the elements. Args: lst (List[int]): The input list from ...
code_exercise_27k
15,427
Write a Python function to count the occurrences of a specific element in a given NumPy array. The function should efficiently handle large arrays and return the count of the specified element. The code should start with: ```python import numpy as np def count_element_occurrences(array: np.ndarray, element) -> int: ``...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def count_element_occurrences(array: np.ndarray, element) -> int: """ Count the occurrences of a specific element in a given NumPy array. Args: array (np.ndarray): The NumPy array in which to cou...
code_exercise_27k
15,430
Write a Python function to check if two strings are anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. The function should ignore case and spaces. The code should start with: ```python def are_anagrams(string1: str, string2: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def are_anagrams(string1: str, string2: str) -> bool: """ Check if two strings are anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. This function compares the sorted ...
code_exercise_27k
15,435
Write a Python function to calculate the nth element of the Fibonacci sequence using an iterative approach. The function should handle edge cases such as negative indices and return the correct Fibonacci number for non-negative indices. The code should start with: ```python def fibonacci_iterative(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci_iterative(n: int) -> int: """ Calculate the nth element of the Fibonacci sequence using an iterative approach. Parameters: n (int): The index of the element to calculate. Returns: int: The nth ele...
code_exercise_27k
15,440
Write a Python function to find the length of the longest common subsequence (LCS) between two given strings. The function should use dynamic programming to efficiently compute the result. The code should start with: ```python def longest_common_subsequence_length(str1: str, str2: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence_length(str1: str, str2: str) -> int: """ Calculates the length of the longest common subsequence of two strings. Args: str1 (str): The first string. str2 (str): The second stri...
code_exercise_27k
15,445
Write a Python function to increment all elements in a given NumPy array by a specified integer value. The function should handle both positive and negative increments. The code should start with: ```python import numpy as np def increment_array_by_value(arr: np.ndarray, increment_value: int) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def increment_array_by_value(arr: np.ndarray, increment_value: int) -> np.ndarray: """ Increments all elements in a given NumPy array by a specified integer value. Args: arr (numpy.ndarray): The ...
code_exercise_27k
15,447
Write a Python function to sort a list of numbers using the bubble sort algorithm. The function should repeatedly swap adjacent elements if they are in the wrong order until the entire list is sorted. The code should start with: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts a list of numbers using the bubble sort algorithm. Bubble sort repeatedly swaps adjacent elements if they are in the wrong order. This pro...
code_exercise_27k
15,448
Write a Python function to decrement all elements in a given NumPy array by a specified value. The function should handle both 1D and 2D arrays and return the modified array. The code should start with: ```python import numpy as np def decrement_array_by_value(arr: np.ndarray, value: int) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def decrement_array_by_value(arr: np.ndarray, value: int) -> np.ndarray: """ Decrement all elements in a NumPy array by a specified value. Parameters: arr (numpy.ndarray): The input NumPy array. ...
code_exercise_27k
15,449
Write a Python function to find the intersection of two lists, ensuring that the result contains only unique elements and is sorted in ascending order. The function should handle lists of integers and return the intersection as a sorted list. The code should start with: ```python from typing import List def find_sort...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_sorted_intersection(list1: List[int], list2: List[int]) -> List[int]: """ Find the intersection of two lists and return the result sorted in ascending order. Args: list1 (List[int])...
code_exercise_27k
15,453
Write a Python function to find the common elements between two sorted arrays efficiently. The function should return a new sorted list of common elements. The code should start with: ```python from typing import List def find_common_elements(arr1: List[int], arr2: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_common_elements(arr1: List[int], arr2: List[int]) -> List[int]: """ Find common elements between two sorted arrays. Args: arr1 (List[int]): The first sorted array. arr2 (Lis...
code_exercise_27k
15,455
Write a Python function to compute the cumulative sum of a given NumPy array. The function should take a NumPy array as input and return a new NumPy array containing the cumulative sum of the input array. The function should also handle cases where the input is not a NumPy array by raising a `ValueError`. The code sho...
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) -> np.ndarray: """ Compute the cumulative sum of a NumPy array. Parameters: arr (numpy.ndarray): The input array for which the cumulative sum is to be computed. ...
code_exercise_27k
15,458
Write a Python function to compute the Levenshtein distance (edit distance) between two strings. The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. The function should start with: ```python def levenshtein_dist...
Here is the Python code to solve the given problem in the markdown block: ```python def levenshtein_distance(str1: str, str2: str) -> int: """ Compute the Levenshtein distance (edit distance) between two strings. The Levenshtein distance is the minimum number of single-character edits (insertions, dele...
code_exercise_27k
15,459
Write a Python function to generate a list of prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. The function should efficiently mark non-prime numbers and return a list of all prime numbers up to the specified limit. 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_primes(limit: int) -> List[int]: """ Generate a list of prime numbers up to the given limit using the Sieve of Eratosthenes algorithm. Args: limit (int): The upper limit up to w...
code_exercise_27k
15,461
Write a Python function to compute the cumulative product of a given 1-dimensional NumPy array. The function should handle the following cases: 1. If the input array is empty, raise a `ValueError` with the message "Input array is empty." 2. If the input array is not 1-dimensional, raise a `ValueError` with the message ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def compute_cumulative_product(arr: np.ndarray) -> np.ndarray: """ Compute the cumulative product of a 1-dimensional NumPy array. Parameters: arr (np.ndarray): Input 1-dimensional NumPy array. R...
code_exercise_27k
15,468
Write a Python function to remove all occurrences of a specific element from a given list. The function should return a new list with all occurrences of the specified element removed. The code should start with: ```python from typing import List, Any def remove_element(lst: List[Any], element: Any) -> List[Any]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def remove_element(lst: List[Any], element: Any) -> List[Any]: """ Remove all occurrences of a specific element from a given list. Args: lst (List[Any]): The list from which to remove t...
code_exercise_27k
15,472
Write a Python function to compute the median of a given list of numbers. The function should handle both even and odd lengths of the list and should raise a `ValueError` if the input list is empty. The code should start with: ```python from typing import List def compute_median(numbers: List[float]) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def compute_median(numbers: List[float]) -> float: """ Computes the median of a given list of numbers. Parameters: numbers (List[float]): The input list of numbers. Returns: float: The ...
code_exercise_27k
15,474
Write a Python function to sort a list of numbers using the insertion sort algorithm. The function should take a list of integers as input and return the sorted list in ascending order. The code should start with: ```python from typing import List def insertion_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def insertion_sort(arr: List[int]) -> List[int]: """ Sorts a list of numbers using the insertion sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: ...
code_exercise_27k
15,475
Write a Python function to perform element-wise comparison of two NumPy arrays and return a boolean array indicating where the elements of the two arrays are equal. The function should handle arrays of any shape and ensure that the comparison is performed correctly. 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 element_wise_comparison(a: np.ndarray, b: np.ndarray) -> np.ndarray: """ Perform element-wise comparison of two NumPy arrays. Parameters: a (numpy.ndarray): First input array. b (numpy.ndarra...
code_exercise_27k
15,478
Write a Python function to find the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. The function should handle both positive and negative integers. The code should start with: ```python def gcd(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def gcd(a: int, b: int) -> int: """ Calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. Args: a (int): The first number. b (int): The second number. Returns: ...
code_exercise_27k
15,480
Write a Python function to return an array where each element at index `i` is the number of 1's in the binary representation of the number `i`. The function should efficiently compute this for all numbers from 0 to `n`. The code should start with: ```python from typing import List def count_bits(n: int) -> List[int]:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_bits(n: int) -> List[int]: """ Returns an array where each element at index i is the number of 1's in the binary representation of i. Args: n (int): The maximum number in the range...
code_exercise_27k
15,485
Write a Python function to reshape a given 2D NumPy array into a 1D array. The function should ensure that the input array is indeed 2-dimensional and raise a `ValueError` if it is not. The function should use the `ravel()` method to flatten the array. The code should start with: ```python import numpy as np def flat...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def flatten_array(array_2d: np.ndarray) -> np.ndarray: """ Reshapes a 2D NumPy array to a 1D array. Parameters: array_2d (np.ndarray): The input 2D NumPy array. Returns: np.ndarray: A 1D Num...
code_exercise_27k
15,486
Write a Python function to convert a given 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: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def decimal_to_binary(decimal: int) -> str: """ Converts a decimal number to its equivalent binary representation. Args: decimal (int): The decimal number to be converted. Must be a non-negative integer. Return...
code_exercise_27k
15,488
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]: """ Merge two sorted lists into a single sorted list. Args: list1 (List[int]): The first sorted list. list2 (...
code_exercise_27k
15,489
Write a Python function to count the number of distinct subsequences of a given string `s` that match a target string `t`. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. The code should start with: ```python de...
Here is the Python code to solve the given problem in the markdown block: ```python def count_distinct_subsequences(s: str, t: str) -> int: """ Count the number of distinct subsequences of string s that match string t. Args: s (str): The source string from which subsequences are derived. t ...
code_exercise_27k
15,492
Write a Python function to find the first non-repeating character in a given string. The function should return the character if found, otherwise return `None`. The code should start with: ```python def find_first_non_repeating_character(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_non_repeating_character(string: str) -> str: """ Find the first non-repeating character in a given string. Args: string (str): The input string to search for the first non-repeating character. Re...
code_exercise_27k
15,497
Write a Python function to perform an element-wise logical OR operation on two NumPy arrays. The function should ensure that the input arrays are of the same shape and return a new NumPy array containing the result of the element-wise logical OR operation. 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 element_wise_logical_or(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Perform element-wise logical OR operation on two NumPy arrays. Parameters: arr1 (np.ndarray): The first input array....
code_exercise_27k
15,502
Write a Python function to perform element-wise logical XOR operation on two NumPy arrays. The function should ensure that the input arrays have the same shape and return the resulting array after performing the element-wise logical XOR operation. The code should start with: ```python import numpy as np def elementwis...
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 operation on two NumPy arrays. Parameters: arr1 (np.ndarray): First input array. ...
code_exercise_27k
15,513
Write a Python function to calculate the modular exponentiation of two numbers efficiently. The function should handle large numbers and ensure that the result is computed modulo a given modulus. The function should also include input validation to ensure that the base, exponent, and modulus are positive integers, and ...
Here is the Python code to solve the given problem in the markdown block: ```python def modular_exponentiation(base: int, exponent: int, modulus: int) -> int: """ Calculates the modular exponentiation of 'base' raised to the power of 'exponent' modulo 'modulus'. Args: base (int): The base number. ...
code_exercise_27k
15,514
Write a Python function to compute the cross product of two 1-D NumPy arrays. The function should ensure that the input arrays are 1-D and have at least 3 elements. If the input arrays do not meet these criteria, the function should raise a `ValueError`. The function should return the cross product as a NumPy array. T...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def compute_cross_product(array1: np.ndarray, array2: np.ndarray) -> np.ndarray: """ Compute the cross product of two 1-D NumPy arrays. Parameters: array1 (numpy.ndarray): First input array, must be ...
code_exercise_27k
15,519
Write a Python function to generate all possible combinations of a list of numbers, including combinations of different lengths. The function should return a list of lists, where each inner list represents a combination. The code should start with: ```python from typing import List from itertools import combinations d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from itertools import combinations def find_all_combinations(numbers: List[int]) -> List[List[int]]: """ Generate all possible combinations of a list of numbers, including combinations of different lengt...
code_exercise_27k
15,523
Write a Python function to reverse the 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_words(sentence: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def reverse_words(sentence: str) -> str: """ Reverse the words in a given sentence. Args: sentence (str): The input sentence. Returns: str: The sentence with reversed words. Examples: >>>...
code_exercise_27k
15,527
Write a Python function to convert a given Roman numeral to its corresponding integer value. The function should handle the standard Roman numeral rules, where smaller numerals placed before larger numerals are subtracted, and smaller or equal numerals placed after larger numerals are added. The function should also ra...
Here is the Python code to solve the given problem in the markdown block: ```python def roman_to_integer(roman: str) -> int: """ Converts a given Roman numeral to its corresponding integer value. Args: roman (str): The Roman numeral to be converted. Returns: int: The integer value of t...
code_exercise_27k
15,531
Write a Python function to find the longest common prefix among a list of strings. The function should return the longest common prefix as a string, or an empty string if no common prefix exists. The code should start with: ```python from typing import List def longest_common_prefix(strings: List[str]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_prefix(strings: List[str]) -> str: """ Finds the longest common prefix among a list of strings. Args: strings (List[str]): A list of strings to find the longest common pre...
code_exercise_27k
15,535
Write a Python function to compute the cumulative minimum of a NumPy array. The function should take a NumPy array as input and return a new NumPy array where each element at index `i` is the minimum value from the start of the array up to index `i`. The code should start with: ```python import numpy as np def cumula...
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: """ Compute the cumulative minimum of a NumPy array. Args: arr (numpy.ndarray): The input array for which to compute the cumulative minimum....
code_exercise_27k
15,545
Write a Python function to generate all possible combinations of elements from two given NumPy arrays. Each combination should be a tuple consisting of one element from the first array and one element from the second array. The function should return a 2D NumPy array where each row represents a combination. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from itertools import product def generate_combinations(arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray: """ Generates all possible combinations of elements from two NumPy arrays. Args: arr1 (n...
code_exercise_27k
15,550
Write a Python function to convert a given decimal number to its binary representation using bitwise operations. The function should handle both positive and negative integers. The binary representation should be returned as a string. The code should start with: ```python def decimal_to_binary(decimal: int) -> str: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def decimal_to_binary(decimal: int) -> str: """ Converts a decimal number to its binary representation using bitwise operations. Args: decimal (int): The decimal number to convert. Returns: str: The bin...
code_exercise_27k
15,553
Write a Python function to check if a given string is a valid palindrome, ignoring spaces, punctuation, and case sensitivity. The function should return `True` if the string is a valid palindrome and `False` otherwise. The code should start with: ```python import re def is_valid_palindrome(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_palindrome(string: str) -> bool: """ Checks if a given string is a valid palindrome, ignoring spaces, punctuation, and case sensitivity. Args: string (str): The string to be checked. Ret...
code_exercise_27k
15,554
Write a Python function to color a cycle graph using 2 colors. A cycle graph is a graph that forms a single cycle, where each node is connected to exactly two other nodes. The function should return a dictionary mapping each node to its assigned color. The colors should alternate between 'red' and 'blue' starting from ...
Here is the Python code to solve the given problem in the markdown block: ```python def color_cycle_graph(n: int) -> dict: """ Color a cycle graph using 2 colors. Parameters: n (int): The number of nodes in the cycle graph. Returns: dict: A dictionary mapping each node to its assigned color. ...
code_exercise_27k
15,558
Write a Python function to merge overlapping intervals from a given list of intervals. Each interval is represented as a tuple containing two integers, where the first integer is the start of the interval and the second integer is the end of the interval. The function should return a list of merged intervals. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """ Merge overlapping intervals from a given list of intervals. Args: intervals: A list of tuples repre...
code_exercise_27k
15,560
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock once, given a list of daily stock prices. The function should return the maximum profit, or 0 if no profit can be made. The code should start with: ```python from typing import List def max_profit(prices: List[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit(prices: List[int]) -> int: """ Calculates the maximum profit that can be obtained by buying and selling a stock once. Args: prices (List[int]): A list of daily prices of the s...
code_exercise_27k
15,561
Write a Python function to compute the element-wise power of a given NumPy array and round each element to the nearest integer. The function should handle both positive and negative numbers in the array. The code should start with: ```python import numpy as np def element_wise_power_and_round(arr: np.ndarray) -> np.nd...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def element_wise_power_and_round(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise power of a given NumPy array and round each element to the nearest integer. Parameters: --------------- ...
code_exercise_27k
15,563
Write a Python function to determine if a number is a prime number using the Miller-Rabin primality test. The function should be efficient and handle large numbers. The code should start with: ```python import random def is_prime_miller_rabin(n: int, k: int = 5) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import random def is_prime_miller_rabin(n: int, k: int = 5) -> bool: """ Determine if a number is a prime using the Miller-Rabin primality test. Args: n (int): The number to be checked for primality. k (int...
code_exercise_27k
15,564
Write a Python function to determine if it is possible to reach the last index of a given list of non-negative integers, where each integer represents the maximum number of steps you can take from that position. The function should return `True` if it is possible to reach the last index, and `False` otherwise. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def can_jump(nums: List[int]) -> bool: """ Determine if you are able to reach the last index of the given list of non-negative integers. Args: nums (List[int]): A list of non-negative intege...
code_exercise_27k
15,568
Write a Python function to compute the inverse hyperbolic sine (arcsinh) for each element in a given NumPy array. The function should take a NumPy array as input and return a new NumPy array containing the arcsinh values of the input array's elements. The code should start with: ```python import numpy as np def comput...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def compute_arcsinh(arr: np.ndarray) -> np.ndarray: """ Compute the inverse hyperbolic sine (arcsinh) for each element in a NumPy array. Parameters: ----------- arr : numpy.ndarray Input ...
code_exercise_27k
15,573
Write a Python function to calculate the factorial of a large number using dynamic programming. The function should efficiently handle large values of `n` by storing intermediate results in a cache to avoid redundant calculations. The code should start with: ```python def factorial_dp(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_dp(n: int) -> int: """ Calculate the factorial of a non-negative integer using dynamic programming. Args: n (int): Non-negative integer to calculate the factorial for. Returns: int: The fa...
code_exercise_27k
15,576
Write a Python function to compute the element-wise arc cosine of a NumPy array. The function should take a NumPy array as input and return a new array where each element is the arc cosine of the corresponding element in the input array. The code should start with: ```python import numpy as np def elementwise_arccos(a...
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: """ Compute the element-wise arc cosine of a NumPy array. Parameters: arr (numpy.ndarray): The input array. Returns: numpy.ndarray: An ...
code_exercise_27k
15,578
Write a Python function to determine if it is possible to split a given array of integers into consecutive subsequences of length at least 3. Each subsequence must consist of consecutive integers. The function should return `True` if such a split is possible, and `False` otherwise. 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 def can_split_into_consecutive_subsequences(nums: List[int]) -> bool: """ Determines if it is possible to split the given array into consecutive subsequences of length at least 3. Args: nums...
code_exercise_27k
15,579
Write a Python function to compute the element-wise arc sine of a NumPy array. The function should take a NumPy array as input and return a new NumPy array where each element is the arc sine (inverse sine) of the corresponding element in the input array. The function should handle arrays of any shape and ensure that th...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def elementwise_arc_sine(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise arc sine of a NumPy array. Parameters: arr (numpy.ndarray): Input array where each element is within the range [-...
code_exercise_27k
15,580
Write a Python function to determine if a given number is a perfect power. A number is considered a perfect power if it can be expressed as \( \text{base}^\text{exponent} \) where both base and exponent are integers greater than 1. The function should return `True` if the number is a perfect power and `False` otherwise...
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_power(n: int) -> bool: """ Determine if a given number is a perfect power. A number is a perfect power if it can be expressed as base^exponent where both base and exponent are integers greater than 1. Ar...
code_exercise_27k
15,581
Write a Python function to color a complete graph using 4 colors. The function should return a dictionary where the keys are the vertex indices and the values are the colors assigned to each vertex. The function should handle the case where the number of vertices is less than or equal to 0 by raising a `ValueError`. T...
Here is the Python code to solve the given problem in the markdown block: ```python def color_complete_graph(num_vertices: int) -> dict: """ Colors a complete graph using 4 colors. Parameters: num_vertices (int): The number of vertices in the complete graph. Returns: dict: A dictionary...
code_exercise_27k
15,584
Write a Python function to count the number of words in a given sentence, considering various edge cases such as punctuation, multiple spaces, and empty strings. The function should handle these cases gracefully and return the correct word count. The code should start with: ```python def count_words(sentence: str) -> ...
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 input sentence. Returns: int: The number of words in the ...
code_exercise_27k
15,588
Write a Python function to compute the element-wise hyperbolic cosine of a given NumPy array. The function should ensure that the input is a NumPy array and return the element-wise hyperbolic cosine of the input array. The code should start with: ```python import numpy as np def compute_hyperbolic_cosh(arr: np.ndarray...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def compute_hyperbolic_cosh(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise hyperbolic cosine of a NumPy array. Parameters: arr (numpy.ndarray): Input NumPy array. Returns: nump...
code_exercise_27k
15,589
Write a Python function to count the number of prime numbers within a given range efficiently. The function should use a helper function to check if a number is prime. The code should start with: ```python def count_primes_in_range(start: int, end: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n: int) -> bool: """Check if a number is prime. Parameters: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if n <= 1: return False fo...
code_exercise_27k
15,590
Write a Python function to compute the element-wise hyperbolic tangent (tanh) of a given NumPy array. The function should handle arrays of any shape and return a new array with the same shape, where each element is the hyperbolic tangent of the corresponding element in the input array. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def elementwise_tanh(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise hyperbolic tangent (tanh) of a NumPy array. Parameters: arr (numpy.ndarray): The input array. Returns: numpy...
code_exercise_27k
15,593
Write a Python function to color a graph represented by an adjacency matrix using the minimum number of colors. The function should return a list where each element represents the color assigned to the corresponding node. The code should start with: ```python from typing import List def color_graph_min_colors(adj_matr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def color_graph_min_colors(adj_matrix: List[List[int]]) -> List[int]: """ Color a graph represented by an adjacency matrix using the minimum number of colors. Args: adj_matrix (List[List[int...
code_exercise_27k
15,597
Write a Python function to remove `k` digits from a given number `num` such that the resulting number is the smallest possible. The function should return the smallest possible number as a string. The code should start with: ```python def remove_k_digits(num: str, k: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_k_digits(num: str, k: int) -> str: """ Removes k digits from the given number 'num' so as to make the smallest possible number. Args: num (str): The input number from which digits need to be removed. ...
code_exercise_27k
15,600
Write a Python function to determine the weight of the last remaining stone after performing a series of stone smashing operations. Each stone has a positive integer weight. The two heaviest stones are smashed together, and if they are not of equal weight, the difference in weight becomes a new stone. This process cont...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def last_stone_weight(stones: List[int]) -> int: """ Returns the weight of the last stone remaining after performing a series of stone smashing operations. Parameters: stones (List[int]): A ...
code_exercise_27k
15,607
Write a Python function to compute the element-wise cube of a given NumPy array. The function should take a NumPy array as input and return a new NumPy array where each element is the cube of the corresponding element in the input array. The code should start with: ```python import numpy as np def elementwise_cube(arr...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def elementwise_cube(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise cube of a given NumPy array. Parameters ---------- arr : numpy.ndarray Input array for which the element-...
code_exercise_27k
15,609
Write a Python function to compute the element-wise inverse square root of a given NumPy array. The function should raise a `ValueError` if the input array contains any negative values. The code should start with: ```python import numpy as np def elementwise_inverse_sqrt(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_inverse_sqrt(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise inverse square root of a NumPy array. Parameters: arr (numpy.ndarray): Input array. Returns: numpy.n...
code_exercise_27k
15,610
Write a Python function to reverse the order of words in a given sentence. The function should handle sentences with multiple spaces between words and leading/trailing spaces. 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 input sentence to be reversed. Returns: str: The reversed sentence. """ ...
code_exercise_27k
15,614
Write a Python function to compute the element-wise reciprocal of a given NumPy array. The function should handle arrays with both positive and negative numbers, as well as zeros. If the input array contains zeros, the function should return `np.inf` for those elements. The code should start with: ```python import nump...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def element_wise_reciprocal(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise reciprocal of a given NumPy array. Parameters: arr (numpy.ndarray): The input array. Returns: numpy.n...
code_exercise_27k
15,618
Write a Python function to calculate the maximum number of units that can be loaded onto a truck given a list of box types and a truck size limit. Each box type is represented as a tuple containing the number of boxes and the number of units per box. The function should maximize the total number of units loaded onto th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def maximum_units_on_truck(box_types: List[Tuple[int, int]], truck_size: int) -> int: """ Calculate the maximum number of units that can be loaded onto a truck. Args: box_types (List[...
code_exercise_27k
15,619
Write a Python function to compute the element-wise signum (sign) of a given NumPy array. The signum function should return 1 for positive numbers, -1 for negative numbers, and 0 for zero. The function should handle both integers and floating-point numbers. 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 element_wise_signum(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise signum (sign) of a given NumPy array. The signum function returns: - 1 for positive numbers - -1 for negative ...
code_exercise_27k
15,621
Write a Python function to compute the element-wise ceiling (round up) of a given NumPy array. The function should take a NumPy array as input and return a new NumPy array where each element is rounded up to the nearest integer. The function should also handle cases where the input is not a NumPy array by raising a `Va...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def ceil_array(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise ceiling of a NumPy array. Parameters: arr (numpy.ndarray): The input array. Returns: numpy.ndarray: The array with...
code_exercise_27k
15,626
Write a Python function to compute the element-wise power of 2 of a given NumPy array. The function should take a NumPy array as input and return a new NumPy array where each element is the square of the corresponding element in the input array. The code should start with: ```python import numpy as np def element_wise...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def element_wise_power_of_2(arr: np.ndarray) -> np.ndarray: """ Computes the element-wise power of 2 of a given NumPy array. Args: arr (np.ndarray): The input NumPy array. Returns: n...
code_exercise_27k
15,636
Write a Python function to compute the element-wise exponential of each element in a NumPy array and round the result to the nearest integer. The function should handle arrays of any shape and ensure that the output array has the same shape as the input array. 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 compute_exp_and_round(arr: np.ndarray) -> np.ndarray: """ Compute the element-wise exponential of each element in a NumPy array and round to the nearest integer. Parameters: arr (numpy.ndarray): ...
code_exercise_27k
15,641
Write a Python function to insert a new interval into a list of non-overlapping intervals sorted by their start times. The function should merge the new interval with any overlapping intervals and return the updated list of intervals. The code should start with: ```python from typing import List, Tuple def insert_int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def insert_interval(intervals: List[Tuple[int, int]], new_interval: Tuple[int, int]) -> List[Tuple[int, int]]: """ Insert a new interval into a list of non-overlapping intervals sorted by their st...
code_exercise_27k
15,644
Write a Python function to find the highest occurring substring of length `k` in a given string. If there are multiple substrings with the same highest occurrence, return the first one encountered. The function should handle edge cases such as an empty string or invalid `k` values. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python def find_highest_occurring_substring(string: str, k: int) -> str: """ Finds the highest occurring substring of length k in the given string. Args: string (str): The input string. k (int): The length of the s...
code_exercise_27k
15,649
Write a Python function to generate a checkerboard pattern of 0s and 1s for a given number of rows and columns. The checkerboard pattern should alternate between 0s and 1s starting with 1 in the top-left corner. The function should return a 2D list representing the checkerboard pattern. 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 generate_checkerboard(rows: int, cols: int) -> List[List[int]]: """ Generate a checkerboard pattern of 0s and 1s. Args: rows (int): The number of rows in the checkerboard. cols (...
code_exercise_27k
15,651
Write a Python function to sort a list of numbers using the merge 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 merge_sort(arr: List[float]) -> List[float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[float]) -> List[float]: """ Sorts a list of numbers using the merge sort algorithm. Args: arr: A list of numbers (integers or floating-point numbers) to be sorted. ...
code_exercise_27k
15,652
Write a Python function to create an array with evenly spaced values between a given start and end value, inclusive. The function should handle the following constraints: 1. The number of values to generate must be at least 2. 2. The start value must be less than or equal to the end value. 3. The function should return...
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, end: float, num_values: int) -> np.ndarray: """ Create an array with evenly spaced values between the start and end values. Parameters: start (float o...
code_exercise_27k
15,656
Write a Python function to determine the minimum number of colors required to color a given graph such that no two adjacent nodes have the same color. The graph is represented as a dictionary where keys are nodes and values are lists of adjacent nodes. The function should return the minimum number of colors needed. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def min_colors_needed(graph: Dict[int, List[int]]) -> int: """ Determines the minimum number of colors needed to color a graph such that no two adjacent nodes have the same color. Args: ...
code_exercise_27k
15,658
Write a Python function to calculate the minimum number of character deletions required to make two strings anagrams of each other. An anagram of a string is another string that contains the same characters, only the order of characters can be different. The function should start with: ```python def min_deletions_to_an...
Here is the Python code to solve the given problem in the markdown block: ```python def min_deletions_to_anagram(str1: str, str2: str) -> int: """ Calculate the minimum number of deletions required to make two strings anagrams. Args: str1 (str): The first input string. str2 (str): The secon...
code_exercise_27k
15,674
Write a Python function to create a 2D array with random integers and sort each row in descending order. The function should take the number of rows, the number of columns, the minimum value for the random integers, and the maximum value for the random integers as inputs. The function should return the sorted 2D array....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def sort_rows_2d_array_desc(rows: int, cols: int, min_val: int, max_val: int) -> List[List[int]]: """ Create a 2D array with random integers and sort each row in descending order. Args...
code_exercise_27k
15,676
Write a Python function to create a 5x5 matrix filled with random integers between 0 and 9, and then replace all even numbers in the matrix with -1. The function should return the modified matrix. The code should start with: ```python import numpy as np def replace_even_with_minus_one(matrix: np.ndarray) -> np.ndarra...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def replace_even_with_minus_one(matrix: np.ndarray) -> np.ndarray: """ Replaces all even numbers in the given 5x5 matrix with -1. Args: matrix (np.ndarray): A 5x5 matrix filled with random intege...
code_exercise_27k
15,680
Write a Python function to calculate the mean of each row in a given 2-dimensional array. The function should handle arrays of any size, not just 3x3. The function should also validate that the input is a 2-dimensional array. If the input is not valid, the function should raise a `ValueError`. The code should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def calculate_mean_of_rows(arr: np.ndarray) -> np.ndarray: """ Calculates the mean value of each row in a 2-dimensional array. Args: arr (numpy.ndarray): The input 2-dimensional array. Retur...
code_exercise_27k
15,681
Write a Python function to group a list of people based on the group sizes they belong to. The function should take two lists as input: one containing the names of the people and the other containing the sizes of the groups. The function should return a list of lists, where each sublist represents a group of people. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def group_people_by_size(people: List[str], group_sizes: List[int]) -> List[List[str]]: """ Groups the given list of people based on the group size they belong to. Args: people (List[str]): ...
code_exercise_27k
15,684
Write a Python function to calculate the dot product of two given matrices. The function should handle matrices of any compatible shapes, not just (3, 4) and (4, 2). The function should raise a `ValueError` if the matrices are not compatible for dot product multiplication. The code should start with: ```python import ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def matrix_dot_product(matrix1: np.ndarray, matrix2: np.ndarray) -> np.ndarray: """ Calculate the dot product of two given matrices. Parameters: matrix1 (np.ndarray): First matrix. matrix2 (np.nd...
code_exercise_27k
15,687
Write a Python function to color a complete bipartite graph using 3 colors. The function should take two integers `n` and `m` as input, representing the number of nodes in the first and second partitions of the bipartite graph, respectively. The function should return a dictionary where the keys are the node indices an...
Here is the Python code to solve the given problem in the markdown block: ```python def color_bipartite_graph(n: int, m: int) -> dict: """ Colors a complete bipartite graph using 3 colors. Parameters: - n (int): Number of nodes in the first partition. - m (int): Number of nodes in the second pa...
code_exercise_27k
15,688
Write a Python function to generate a 2D array where each row contains numbers from 0 to the row number. The function should handle the input validation to ensure that the number of rows is a positive integer. The code should start with: ```python from typing import List def generate_2d_array(num_rows: int) -> List[Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_2d_array(num_rows: int) -> List[List[int]]: """ Generate a 2D array where each row contains numbers from 0 to the row number. Args: num_rows (int): The number of rows to generat...
code_exercise_27k
15,691
Write a Python function to determine if a given graph is a bipartite subgraph. A bipartite graph is a graph whose vertices can be divided into two disjoint sets such that no two graph vertices within the same set are adjacent. The function should take a graph represented as a dictionary where keys are nodes and values ...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque def is_bipartite_graph(graph: dict) -> bool: """ Determine if a given graph is a bipartite subgraph. Args: graph (dict): A dictionary representing the graph where keys are nodes and va...
code_exercise_27k
15,695
Write a Python function to generate a spiral matrix of size n x n. The matrix should be filled in a spiral order starting from the top-left corner and moving right, down, left, and up in a cyclic manner until all elements are filled. The function should return the generated spiral matrix. 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 generate_spiral_matrix(n: int) -> List[List[int]]: """ Generate a spiral matrix of size n x n. Parameters: n (int): The size of the spiral matrix. Returns: List[List[int]]: The gene...
code_exercise_27k
15,696
Write a Python function to check if a number is a prime number using the Sieve of Atkin algorithm. The function should be efficient and handle edge cases appropriately. The code should start with: ```python def is_prime_sieve_of_atkin(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_sieve_of_atkin(num: int) -> bool: """ Check if a number is prime using the Sieve of Atkin algorithm. Args: num (int): The number to check for primality. Returns: bool: True if the number is...
code_exercise_27k
15,697
Write a Python function to create a 2D array with random integers and sort it column-wise. The function should generate a 2D array of specified dimensions, fill it with random integers within a given range, and then sort each column of the array in ascending order. The function should return the sorted 2D array. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def create_and_sort_2d_array(rows: int, cols: int, min_val: int, max_val: int) -> List[List[int]]: """ Creates a 2D array with random integers and sorts it column-wise. Args: r...
code_exercise_27k
15,698
Write a Python function to color a ladder graph using 2 colors. The ladder graph is defined by the number of rungs `n`, where each rung is connected to the next and the previous one, forming a sequence. The function should return a dictionary where the keys are the rungs and the values are the colors assigned to each r...
Here is the Python code to solve the given problem in the markdown block: ```python def color_ladder_graph(n: int) -> dict: """ Colors a ladder graph using 2 colors. Parameters: - n: The number of rungs in the ladder graph (minimum 2). Returns: - A dictionary representing the coloring of the l...
code_exercise_27k
15,700
Write a Python function to determine if a given graph is a clique. A clique is a subset of vertices of an undirected graph such that every two distinct vertices in the subset are adjacent. The graph is represented as a dictionary where the keys are the nodes and the values are sets of neighbors for each node. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def is_clique(graph: Dict[int, Set[int]]) -> bool: """ Determine if the given graph is a clique. A clique is a subset of vertices of an undirected graph such that every two distinct vertices in...
code_exercise_27k
15,702
Write a Python function to find the first missing positive number in a given list of integers. The function should return the smallest positive integer that is not present in the list. If all positive integers up to the length of the list are present, the function should return the next positive integer. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def first_missing_positive(nums: List[int]) -> int: """ Finds the first missing positive number in a given list of integers. Args: nums (List[int]): A list of integers. Returns: ...
code_exercise_27k
15,709
Write a Python function to find the largest number in a given list of integers. If the list is empty, raise a `ValueError` with a specific message. The function should be efficient and handle various edge cases. The code should start with: ```python from typing import List def find_largest_number(numbers: List[int]) ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_number(numbers: List[int]) -> int: """ Find the largest number in a list of integers. Args: numbers (List[int]): A list of integers. Returns: int: The largest n...
code_exercise_27k
15,711
Write a Python function to find the length of the longest palindromic substring in a given string. The function should efficiently handle the problem using a dynamic programming approach or an expansion around the center method. The code should start with: ```python def longest_palindromic_substring_length(s: str) -> i...
Here is the Python code to solve the given problem in the markdown block: ```python def longest_palindromic_substring_length(s: str) -> int: """ Finds the length of the longest palindromic substring in a given string. Args: s (str): The input string. Returns: int: The length of the lon...
code_exercise_27k
15,720
Write a Python function to determine if `n` flowers can be successfully planted in a given flowerbed without violating the rule that no two flowers can be planted adjacent to each other. The flowerbed is represented by a list of integers, where `0` represents an empty plot and `1` represents a planted flower. The funct...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def can_place_flowers(flowerbed: List[int], n: int) -> bool: """ Determine if n flowers can be successfully planted in the flowerbed without violating the adjacency rule. Args: flowerbed (Li...
code_exercise_27k
15,728
Write a Python function to create a 2D array with random integers and find the maximum sum along each column. The function should take the number of rows, number of columns, minimum value, and maximum value for random integer generation as inputs. The function should return a list of maximum sums for each column. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def find_max_sum_along_columns(rows: int, cols: int, min_value: int, max_value: int) -> List[int]: """ Create a 2D array of random integers and find the maximum sum along each column. ...