source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
22,119
Write a Python function to sort a list of book details using MergeSort based on the publication year. Each book detail is represented as a tuple containing the title, author, and publication year. The function should be able to handle lists of varying sizes and should return the sorted list of book details. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def sort_books_by_year(book_list: List[Tuple[str, str, int]]) -> List[Tuple[str, str, int]]: """ Sorts a list of book details using MergeSort based on the publication year. Args: book...
code_exercise_27k
22,123
Write a Python function to find the maximum element in a sliding window of size `k` for a given array of integers. The function should return a list of maximum elements for each sliding window as it moves from the start of the array to the end. The code should start with: ```python from typing import List def find_ma...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import deque def find_maximum_sliding_window(arr: List[int], k: int) -> List[int]: """ Find the maximum element in a sliding window of size k for a given array of integers. Args: ...
code_exercise_27k
22,136
Write a Python function to find the length of the longest substring without repeating characters in a given string. The function should efficiently handle the input string and return the length of the longest substring with unique characters. The code should start with: ```python def length_of_longest_substring(s: str...
Here is the Python code to solve the given problem in the markdown block: ```python def length_of_longest_substring(s: str) -> int: """ Calculates the length of the longest substring without repeating characters. Args: s (str): The input string. Returns: int: The length of the longest ...
code_exercise_27k
22,297
Write a Python function to generate a random sample from a given normal distribution using NumPy. The function should take three parameters: the mean of the normal distribution, the standard deviation of the normal distribution, and the size of the output array. The function should return the generated random sample as...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_random_sample(mean: float, std_dev: float, size: int or tuple) -> np.ndarray: """ Generate a random sample from a normal distribution. Parameters: mean (float): The mean of the norma...
code_exercise_27k
22,308
Write a Python function to sort a given dataset using NumPy. The dataset is a NumPy array of integers. The function should return the sorted dataset. The code should start with: ```python import numpy as np def sort_dataset(dataset: np.ndarray) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def sort_dataset(dataset: np.ndarray) -> np.ndarray: """ Sorts a given dataset using NumPy. Args: dataset (np.ndarray): The dataset to be sorted, represented as a NumPy array. Returns: ...
code_exercise_27k
22,318
Write a Python function to perform Singular Value Decomposition (SVD) on a given matrix using NumPy. The function should return the left singular vectors, the singular values, and the right singular vectors (conjugate transpose). The code should start with: ```python import numpy as np def perform_svd(matrix: np.ndarr...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def perform_svd(matrix: np.ndarray) -> tuple: """ Perform Singular Value Decomposition (SVD) on a given matrix. Args: matrix (np.ndarray): Input matrix for which SVD is to be computed. Retur...
code_exercise_27k
22,332
Write a Python function to convert a given sentence to lowercase. The function should handle any string input and return the string with all characters converted to lowercase. The code should start with: ```python def convert_to_lowercase(sentence: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_lowercase(sentence: str) -> str: """ Convert a given sentence to lowercase. Args: sentence (str): The sentence to be converted to lowercase. Returns: str: The sentence with all characters...
code_exercise_27k
22,362
Write a Python function to remove HTML tags from a given string. The function should use regular expressions to identify and remove any HTML tags, leaving only the plain text content. The code should start with: ```python import re def remove_html_tags(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def remove_html_tags(text: str) -> str: """ Removes HTML tags from the given text. Args: text (str): The text containing HTML tags. Returns: str: The text with HTML tags removed. """ ...
code_exercise_27k
22,368
Write a Python function to calculate the frequency of each word in a given paragraph and return the top N most frequent words. If `top_n` is not provided, return the frequency of all words in descending order. The function should handle case-insensitive word counting and ignore punctuation. The code should start with:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Optional import re def word_frequency(paragraph: str, top_n: Optional[int] = None) -> List[Tuple[str, int]]: """ Calculate the frequency of each word in a given paragraph and return the top N mos...
code_exercise_27k
22,371
Write a Python function to convert a given text into a bag-of-words representation. The function should return a dictionary where the keys are unique words and the values are their frequencies in the text. The function should handle text preprocessing by converting it to lowercase, removing punctuation marks and number...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import re from collections import Counter def text_to_bag_of_words(text: str) -> Dict[str, int]: """ Convert the given text into a bag-of-words representation. Args: text (str): The input te...
code_exercise_27k
22,374
Write a Python function to generate n-grams from a given text. An n-gram is a contiguous sequence of n items from a given sample of text or speech. The function should split the text into words and then generate all possible n-grams of the specified length. The code should start with: ```python from typing import List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_ngrams(text: str, n: int) -> List[str]: """ Generate n-grams from a given text. Args: text (str): The input text. n (int): The number of words in each n-gram. Retur...
code_exercise_27k
22,376
Write a Python function to initialize a Fenwick tree (also known as a Binary Indexed Tree) with given values. The Fenwick tree is a data structure that efficiently supports range sum queries and single updates. The function should take a list of integers as input and return a list representing the initialized Fenwick t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def initialize_fenwick_tree(values: List[int]) -> List[int]: """ Initializes a Fenwick tree with given values. Args: - values: A list of integers representing the initial values for the Fenwick ...
code_exercise_27k
22,459
Write a Python function to find the maximum rectangle area in a binary matrix using a Fenwick tree. The function should take a binary matrix as input and return the maximum rectangle area that can be formed using the 1s in the matrix. The matrix is represented as a 2D list of integers, where each element is either 0 or...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_rectangle_area(matrix: List[List[int]]) -> int: """ Finds the maximum rectangle area in a binary matrix using a Fenwick tree. Args: matrix: A binary matrix as a 2D list of integers, ...
code_exercise_27k
22,472
Write a Python function to remove HTML tags from a given string. The function should use regular expressions to identify and remove any HTML tags, leaving only the plain text content. The code should start with: ```python import re def remove_html_tags(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def remove_html_tags(text: str) -> str: """ Removes HTML tags from the given text using regular expressions. Args: text (str): The text containing HTML tags. Returns: str: The text with HTML ...
code_exercise_27k
22,485
Write a Python function to generate a sequence of bi-grams from a given text. A bi-gram is a pair of consecutive words in the text. The function should split the text into words and then create bi-grams by pairing each word with the next one. The function should handle cases where the input text is empty or contains on...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def generate_bi_grams(text: str) -> List[Tuple[str, str]]: """ Convert a given text into a sequence of bi-grams. Args: text (str): The input string to convert into bi-grams. Retu...
code_exercise_27k
22,507
Write a Python function to find the maximum product subarray within a given range of a Fenwick tree. The function should efficiently compute the maximum product of any contiguous subarray within the specified range. The Fenwick tree is represented as a list of integers, and the range is defined by two indices, `left` a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_product_subarray(fenwick_tree: List[int], left: int, right: int) -> int: """ Finds the maximum product subarray in a given range of a Fenwick tree. Args: fenwick_tree (List[int]): Th...
code_exercise_27k
22,552
Write a Python function to check if the parentheses, brackets, and curly braces in a given string are balanced. A string is considered balanced if every opening bracket, parenthesis, or brace has a corresponding closing bracket, parenthesis, or brace in the correct order. The code should start with: ```python def is_b...
Here is the Python code to solve the given problem in the markdown block: ```python def is_balanced(string: str) -> bool: """ Check if the parentheses, brackets, and curly braces in a given string are balanced. Parameters: string (str): The input string to check. Returns: bool: True if the par...
code_exercise_27k
22,556
Write a Python function to count the number of valid parentheses pairs in a given string. A valid parentheses pair is defined as a pair of '(' and ')' that are properly matched and nested. The function should return the total number of such pairs. The code should start with: ```python def count_valid_parentheses_pairs...
Here is the Python code to solve the given problem in the markdown block: ```python def count_valid_parentheses_pairs(input_string: str) -> int: """ Count the number of valid parentheses pairs in a given string. Args: input_string (str): The input string to search for valid parentheses pairs. ...
code_exercise_27k
22,558
Write a Python function to find the minimum and maximum values in a given time series. The function should handle empty lists and non-numerical values by raising appropriate exceptions. The code should start with: ```python from typing import List, Tuple def find_min_max_values(time_series: List[float]) -> Tuple[float...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_min_max_values(time_series: List[float]) -> Tuple[float, float]: """ Find the minimum and maximum values in a given time series. Args: time_series (List[float]): A list of nu...
code_exercise_27k
22,571
Write a Python function to calculate the rolling mean of a time series using a specified window size. The function should handle edge cases such as when the window size is larger than the length of the time series or when the window size is less than or equal to zero. The function should return a list of rolling mean v...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def rolling_mean(time_series: List[float], window_size: int) -> List[Union[float, None]]: """ Calculate the rolling mean of a time series using a specified window size. Args: time_ser...
code_exercise_27k
22,572
Write a Python function to count the maximum depth of nested parentheses in a given string. The function should handle balanced parentheses and return the maximum depth. If the parentheses are unbalanced, the function should raise a `ValueError`. The code should start with: ```python def count_max_nested_parentheses(s...
Here is the Python code to solve the given problem in the markdown block: ```python def count_max_nested_parentheses(string: str) -> int: """ Count the maximum depth of nested parentheses in a given string. Args: string (str): The input string containing parentheses. Returns: int: The ...
code_exercise_27k
22,575
Write a Python function to count the number of opening and closing parentheses in a given string. The function should return a tuple containing the counts of opening and closing parentheses respectively. The code should start with: ```python def count_parentheses(string: str) -> tuple: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_parentheses(string: str) -> tuple: """ Count the number of opening and closing parentheses in a given string. Args: string (str): The input string to count parentheses from. Returns: tuple: A ...
code_exercise_27k
22,583
Write a Python function to find the length of the longest valid parentheses substring in a given string. A valid parentheses substring is defined as a substring where every opening parenthesis '(' has a corresponding closing parenthesis ')' in the correct order. The function should handle strings containing only parent...
Here is the Python code to solve the given problem in the markdown block: ```python def longest_valid_parentheses(s: str) -> int: """ Finds the length of the longest valid parentheses substring in a given string. Parameters: s (str): The input string containing parentheses. Returns: int: The l...
code_exercise_27k
22,591
Write a Python function to calculate the sum of two integers and return the result. The function should handle both positive and negative integers. The code should start with: ```python def calculate_sum(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_sum(a: int, b: int) -> int: """ Calculates the sum of two integers. Args: a (int): The first integer. b (int): The second integer. Returns: int: The sum of the two integers. ""...
code_exercise_27k
22,595
Write a Python function to check if the parentheses, brackets, and curly braces in a given string are properly nested and ordered. The function should return `True` if all the opening characters `'('`, `'['`, `'{'` have corresponding closing characters `')'`, `']'`, `'}'` in the correct order, and `False` otherwise. T...
Here is the Python code to solve the given problem in the markdown block: ```python def check_nested_and_ordered(string: str) -> bool: """ Check if the parentheses, brackets, and curly braces in a given string are properly nested and ordered. Args: string (str): The input string to check. Retu...
code_exercise_27k
22,596
Write a Python function to determine if a given number is a prime number. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as numbers less than or equal to 1, which are not prime. 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: """ Determine if a given number is a prime number. Args: number (int): The number to be checked for primality. Returns: bool: True if the number is prime, False otherw...
code_exercise_27k
22,602
Write a Python function to count the occurrences of each element in a given list and return the result as a dictionary. The function should handle lists containing any hashable elements, such as integers, strings, and tuples. The code should start with: ```python from typing import List, Dict, Any def count_element_oc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any def count_element_occurrences(lst: List[Any]) -> Dict[Any, int]: """ Count the occurrences of each element in a given list and return the result as a dictionary. Args: lst (List[A...
code_exercise_27k
22,605
Write a Python function to find the k-th largest element in a given list of numbers. The function should efficiently handle cases where the list is empty or k is out of bounds. The code should start with: ```python from typing import List, Union def find_kth_largest_element(numbers: List[int], k: int) -> Union[int, f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_kth_largest_element(numbers: List[int], k: int) -> Union[int, float, None]: """ Find the k-th largest element in a list of numbers. Args: numbers (List[int]): A list of numbe...
code_exercise_27k
22,606
Write a Python function to find the maximum number of balanced parentheses pairs in a given string by removing the minimum number of characters. The function should return the maximum number of balanced parentheses pairs. The code should start with: ```python def max_balanced_parentheses(s: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def max_balanced_parentheses(s: str) -> int: """ Calculates the maximum number of balanced parentheses pairs in a given string by removing minimum characters. Args: s (str): The string to check for balanced parenthe...
code_exercise_27k
22,609
Write a Python function to check if a given string is a palindrome. The function should ignore spaces, punctuation, and case differences. The code should start with: ```python def is_palindrome(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(string: str) -> bool: """ Check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forwards and backwards, ignoring spaces, p...
code_exercise_27k
22,625
Write a Python function to remove the minimum number of parentheses to make a given string valid and obtain the lexicographically smallest result. A string is considered valid if every opening parenthesis '(' has a corresponding closing parenthesis ')' and they are properly nested. The function should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_min_parentheses(s: str) -> str: """ Removes the minimum number of parentheses to make a given string valid and obtains the lexicographically smallest result. Args: s (str): The input string containing par...
code_exercise_27k
22,628
Write a Python function to check if a given expression consisting of multiple parentheses patterns is a well-formed expression. A well-formed expression is defined as one where every opening parenthesis has a corresponding closing parenthesis in the correct order. The code should start with: ```python def is_well_form...
Here is the Python code to solve the given problem in the markdown block: ```python def is_well_formed(expression: str) -> bool: """ Check if a given expression consisting of multiple parentheses patterns is well-formed. Args: expression (str): The expression to be checked. Returns: bo...
code_exercise_27k
22,643
Write a Python function to determine if a given string is a valid expression containing nested square brackets and parentheses. The function should ensure that each opening bracket or parenthesis has a corresponding closing bracket or parenthesis in the correct order. The code should start with: ```python def is_valid...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_expression(expression: str) -> bool: """ Check if a given string is a valid expression containing nested square brackets and parentheses. Args: expression (str): The string to be checked for valid n...
code_exercise_27k
22,644
Write a Python function to find the nth Fibonacci number using an iterative approach. The function should handle edge cases such as non-positive integers and return the correct Fibonacci number for valid inputs. The code should start with: ```python def fibonacci(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci(n: int) -> int: """ Finds the nth Fibonacci number using an iterative approach. Parameters: n (int): The position of the Fibonacci number to be calculated. Returns: int: The nth Fibonacci number. ...
code_exercise_27k
22,647
Write a Python function to count the maximum number of opening and closing parentheses that can be removed from a given string without unbalancing it. The string contains only parentheses. The function should return a tuple where the first value represents the maximum number of opening parentheses that can be removed, ...
Here is the Python code to solve the given problem in the markdown block: ```python def count_unbalanced_parentheses(string: str) -> tuple[int, int]: """ Count the maximum number of opening and closing parentheses that can be removed from a given string without unbalancing it. Parameters: string (s...
code_exercise_27k
22,648
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 any length, including empty lists. The code should start with: ```python from typing import List def find_intersection_sorted(list1...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_intersection_sorted(list1: List[int], list2: List[int]) -> List[int]: """ Finds the intersection of two lists and returns the result as a sorted list of unique elements. Args: list1...
code_exercise_27k
22,651
Write a Python function to generate all possible balanced parentheses patterns using a given set of provided parentheses characters. The function should be able to handle different types of parentheses (e.g., `()`, `[]`, `{}`) and should return a list of all valid combinations. 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 generate_balanced_parentheses(n: int, open_paren: str, close_paren: str) -> List[str]: """ Generates all possible balanced parentheses patterns using a given set of parentheses characters. Args:...
code_exercise_27k
22,662
Write a Python function to calculate the edit distance (Levenshtein distance) between two strings. The edit distance is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. The function should be efficient and use dynamic program...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_edit_distance(str1: str, str2: str) -> int: """ Calculate the edit distance (Levenshtein distance) between two strings. The edit distance is the minimum number of single-character edits (insertions, deletions,...
code_exercise_27k
22,664
Write a Python function to count the frequency of each character in a given string, excluding spaces. The function should return a dictionary where the keys are the characters and the values are their respective counts. The code should start with: ```python from typing import Dict def count_character_frequencies(strin...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import Dict def count_character_frequencies(string: str) -> Dict[str, int]: """ Counts the frequency of each character in a given string, excluding spaces. Args: string (str): The input string to coun...
code_exercise_27k
22,665
Write a Python function to generate a random sample of size `n` from a given list without replacement. The function should handle cases where `n` is greater than the length of the list by returning the entire list in a random order. The function should also handle cases where `n` is less than or equal to zero by return...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_sample(lst: List, n: int) -> List: """ Generate a random sample of size n from a given list without replacement. Args: lst (List): The input list from which...
code_exercise_27k
22,667
Write a Python function to calculate the median of a given list of numbers. The median is the middle value in a sorted list of numbers. If the list has an even number of elements, the median is the average of the two middle numbers. The code should start with: ```python from typing import List def calculate_median(nu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_median(numbers: List[int]) -> float: """ Calculate the median of a given list of numbers. The median is the middle value in a sorted list of numbers. If the list has an even number of ...
code_exercise_27k
22,669
Write a Python function to check if two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should ignore case and spaces. The code should start with: ```python def is_ana...
Here is the Python code to solve the given problem in the markdown block: ```python def is_anagram(str1: str, str2: str) -> bool: """ Check if two strings are anagrams of each other. Args: str1 (str): The first input string. str2 (str): The second input string. Returns: bool: T...
code_exercise_27k
22,672
Write a Python function to find the longest word in a given string, considering that the string may contain punctuation and multiple spaces. The function should handle these cases by stripping punctuation and ignoring multiple spaces. The code should start with: ```python from typing import List def find_longest_word_...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List import string def find_longest_word_in_string(sentence: str) -> str: """ Finds the longest word in a given sentence, ignoring punctuation and multiple spaces. Args: sentence (str): The inp...
code_exercise_27k
22,675
Write a Python function to calculate the mode(s) of a given list of numbers. The mode is the number(s) that appear most frequently in the list. If there are multiple numbers with the same highest frequency, the function should return all of them. The function should handle an empty list by raising a `ValueError`. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_mode(lst: List[int]) -> List[int]: """ Calculate the mode(s) of a given list of numbers. The mode is the number(s) that appear most frequently in the list. If there are multiple number...
code_exercise_27k
22,677
Write a Python function to calculate the variance of a given list of numbers. The variance is a measure of how spread out the numbers in a list are. It is calculated by finding the average of the squared differences from the mean. The code should start with: ```python from typing import List def calculate_variance(nu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_variance(numbers: List[int]) -> float: """ Calculate the variance of a list of numbers. The variance is a measure of how spread out the numbers in a list are. It is calculated by findi...
code_exercise_27k
22,680
Write a Python function to check if a given string contains only digits. The function should return `True` if the string consists entirely of numeric characters, and `False` otherwise. The code should start with: ```python def contains_only_digits(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def contains_only_digits(string: str) -> bool: """ Check if a string contains only digits. Args: string (str): The string to check. Returns: bool: True if the string contains only digits, False otherwis...
code_exercise_27k
22,681
Write a Python function to perform a breadth-first search (BFS) on a graph starting from a given node. The graph is represented as a dictionary where the keys are the nodes and the values are lists of neighboring nodes. The function should return the visited nodes in the order they were visited. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque from typing import Dict, List, Any def breadth_first_search(graph: Dict[Any, List[Any]], start_node: Any) -> List[Any]: """ Perform a breadth-first search on a graph starting from a given node. ...
code_exercise_27k
22,682
Write a Python function to calculate the standard deviation of a given list of numbers. The function should handle the following: 1. Ensure the input is a non-empty list of numerical values. 2. Calculate the mean of the list. 3. Compute the sum of squared differences from the mean. 4. Calculate the variance by dividing...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def calculate_standard_deviation(numbers: List[float]) -> float: """ Calculate the standard deviation of a given list of numbers. Args: numbers (List[float]): A list of numerical...
code_exercise_27k
22,688
Write a Python function to count the number of words in a given string, considering various edge cases such as empty strings, strings with multiple spaces, and strings with 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(string: str) -> int: """ Count the number of words in a given string. This function splits the input string by whitespace and returns the number of resulting words. It handles empty strings, strings with...
code_exercise_27k
22,693
Write a Python function to perform bootstrapping on a given dataset and return the bootstrapped mean. The function should handle the following: 1. **Input Validation**: Ensure the input data is a list of numbers. 2. **Sample Size**: If the sample size is not provided, it should default to the size of the input dataset....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional import numpy as np def bootstrap_mean(data: List[float], num_iterations: int = 1000, sample_size: Optional[int] = None) -> float: """ Calculate the bootstrapped mean of a given dataset. Ar...
code_exercise_27k
22,704
Write a Python function to remove all whitespace characters from a given string, including spaces, tabs, and newline characters. The function should handle various types of whitespace characters efficiently. The code should start with: ```python def remove_all_whitespace(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def remove_all_whitespace(string: str) -> str: """ Removes all whitespace characters (spaces, tabs, and newlines) from the given string. Args: string (str): The input string from which whitespace characte...
code_exercise_27k
22,707
Write a Python function to generate a random permutation of a given list. The function should not modify the original list and should return a new list with the elements shuffled. The code should start with: ```python from typing import List import random def generate_random_permutation(lst: List) -> List: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_permutation(lst: List) -> List: """ Generate a random permutation of a given list. Args: lst (List): The list of items to be permuted. Returns: ...
code_exercise_27k
22,709
Write a Python function to find the second largest number in a given list of integers. If the list contains fewer than two elements, raise a `ValueError`. The function should be efficient and handle edge cases appropriately. The code should start with: ```python from typing import List def find_second_largest_number(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_second_largest_number(numbers: List[int]) -> int: """ Find the second largest number in a list of integers. Args: numbers (List[int]): A list of integers. Returns: int:...
code_exercise_27k
22,711
Write a Python function to find all occurrences of a word in a given string, including overlapping occurrences. The function should return a list of starting indices of all such occurrences. The code should start with: ```python from typing import List def find_all_occurrences(string: str, word: str) -> List[int]: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_occurrences(string: str, word: str) -> List[int]: """ Find all occurrences of a word in a given string, including overlapping occurrences. Args: string (str): The input string t...
code_exercise_27k
22,713
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. Args: string (str): The input string containing words to be reversed. Returns: str: A new string with ...
code_exercise_27k
22,717
Write a Python function to count the number of occurrences of each unique element in a given list. The function should return a dictionary where the keys are the unique elements from the list and the values are the counts of their occurrences. The code should start with: ```python from typing import List, Dict def co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_unique_occurrences(lst: List[int]) -> Dict[int, int]: """ Counts the number of occurrences of each unique element in a given list. Args: lst (List[int]): The list in which to...
code_exercise_27k
22,721
Write a Python function to decode a string that has been encoded using the ROT13 cipher. The ROT13 cipher is a substitution cipher that replaces each letter with the letter 13 positions after it in the alphabet. The cipher wraps around, so 'z' becomes 'm' and 'a' becomes 'n'. The function should handle both uppercase a...
Here is the Python code to solve the given problem in the markdown block: ```python def rot13_decode(encoded_string: str) -> str: """ Decode a string that has been encoded using the ROT13 cipher. The ROT13 cipher is a substitution cipher that replaces each letter with the letter 13 positions after it i...
code_exercise_27k
22,723
Write a Python function to calculate the Fibonacci sequence up to the nth term using an iterative approach. The function should return a list of Fibonacci numbers up to the nth term. If n is less than 1, the function should return an empty list. The code should start with: ```python from typing import List def fibona...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def fibonacci_sequence(n: int) -> List[int]: """ Calculate the Fibonacci sequence up to the nth term using an iterative approach. Args: n (int): The number of terms to calculate. Return...
code_exercise_27k
22,729
Write a Python function to extract all the numbers from a given string and return them as a list of integers. The function should handle various formats of numbers within the string, including single digits, multiple digits, and numbers separated by punctuation or spaces. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def extract_numbers(string: str) -> List[int]: """ Extracts all the numbers from a given string and returns them as a list of integers. Args: string (str): The input string from wh...
code_exercise_27k
22,733
Write a Python function to convert a given string to title case. Title case means that the first letter of each word in the string is capitalized, and all other letters are in lowercase. The function should handle strings with multiple spaces between words and leading/trailing spaces. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_title_case(string: str) -> str: """ Convert a given string to title case. Title case means that the first letter of each word in the string is capitalized, and all other letters are in lowercase. This fun...
code_exercise_27k
22,735
Write a Python function to find the intersection of two sorted arrays. The function should return a list of common elements between the two arrays without duplicates. The function should handle arrays of different lengths and should be efficient in terms of time complexity. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_intersection(arr1: List[int], arr2: List[int]) -> List[int]: """ Finds the intersection of two sorted arrays. Parameters: arr1 (List[int]): The first sorted array. arr2 (List[int]):...
code_exercise_27k
22,736
Write a Python function to check if a given string is a valid IPv4 address. An IPv4 address consists of four decimal numbers separated by dots, where each number ranges from 0 to 255. The function should return `True` if the string is a valid IPv4 address and `False` otherwise. The code should start with: ```python de...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_ipv4_address(ip_address: str) -> bool: """ Check if a given string is a valid IPv4 address. An IPv4 address consists of four decimal numbers separated by dots, where each number ranges from 0 to 255. A...
code_exercise_27k
22,738
Write a Python function to find the first non-repeated character in a given string. The function should return the character if it exists, otherwise return `None`. The code should start with: ```python def find_first_non_repeated_character(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_non_repeated_character(string: str) -> str: """ Finds the first non-repeated character in a given string. Args: string (str): The input string to search for the first non-repeated character. Retu...
code_exercise_27k
22,745
Write a Python function to remove punctuation marks from a given string. The function should handle various punctuation marks and return the cleaned string. The code should start with: ```python import string def remove_punctuation(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import string def remove_punctuation(text: str) -> str: """ Remove punctuation marks from a given string. Args: text (str): The input string from which punctuation marks need to be removed. Returns: st...
code_exercise_27k
22,747
Write a Python function to perform stratified sampling with replacement on a given dataset based on specified factors. The function should ensure that the sample size is proportional to the distribution of the factors in the dataset. The code should start with: ```python from typing import List import random from colle...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random from collections import Counter def stratified_sampling_with_replacement(data: List[int], factors: List[str], sample_size: int) -> List[int]: """ Perform stratified sampling with replacemen...
code_exercise_27k
22,750
Write a Python function to remove all HTML tags from a given string. The function should handle various HTML tags and return the cleaned text without any tags. The code should start with: ```python import re def remove_html_tags(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def remove_html_tags(text: str) -> str: """ Removes all HTML tags from the given input string. Args: text (str): The input string containing HTML tags. Returns: str: The input string with all...
code_exercise_27k
22,753
Write a Python function to find the first non-repeated character in a given string. If no non-repeated character is found, the function should return `None`. The function should be efficient and handle edge cases such as empty strings and strings with all characters repeated. The code should start with: ```python def ...
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_non_repeated_char(string: str) -> str: """ Find the first non-repeated character in a given string. Args: string (str): The input string to search for the first non-repeated character. Returns: ...
code_exercise_27k
22,754
Write a Python function to find the kth largest element in an unsorted list efficiently. The function should handle edge cases such as an empty list or invalid k values. The code should start with: ```python from typing import List def find_kth_largest_element(lst: List[int], k: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import heapq def find_kth_largest_element(lst: List[int], k: int) -> int: """ Find the kth largest element in an unsorted list efficiently. Args: lst (List[int]): The unsorted list of intege...
code_exercise_27k
22,759
Write a Python function to remove all consecutive duplicate characters from a given string. The function should iterate through the string and remove any character that appears consecutively more than once, leaving only one instance of that character in the resulting string. The code should start with: ```python def r...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_consecutive_duplicates(string: str) -> str: """ Removes all consecutive duplicate characters from a given string. Args: string (str): The input string from which consecutive duplicates are to be removed. ...
code_exercise_27k
22,767
Write a Python function to remove all special characters from a given string, leaving only alphanumeric characters and spaces. The function should handle various edge cases, such as empty strings, strings with only special characters, and strings with no special characters. The code should start with: ```python import ...
Here is the Python code to solve the given problem in the markdown block: ```python import re def remove_special_characters(string: str) -> str: """ Removes all special characters from a given string, leaving only alphanumeric characters and spaces. Args: string (str): The input string containing ...
code_exercise_27k
22,770
Write a Python function to perform resampling using the bootstrap method and compute the bootstrap-t confidence interval for a given dataset and a statistic function. The function should return the lower and upper bounds of the confidence interval. The code should start with: ```python import numpy as np def bootstra...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def bootstrap_t_confidence_interval(data, stat_func, num_samples=1000, alpha=0.05): """ Perform resampling using the bootstrap method and compute the bootstrap-t confidence interval. Args: data (...
code_exercise_27k
22,775
Write a Python function to find the maximum value in a given list using a rolling window of size 3. The function should return the maximum value found within any of the rolling windows. The function should handle lists with at least 3 elements and raise appropriate exceptions for invalid inputs. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_max_in_rolling_window(lst: List[Union[int, float]]) -> Union[int, float]: """ Find the maximum value in a given list using a rolling window of size 3. Args: lst (List[Union[i...
code_exercise_27k
22,778
Write a Python function to find the minimum value in a given list using a rolling window of size `k`. The function should return the minimum value found across all windows, or `None` if the list is empty or smaller than the window size. The code should start with: ```python from typing import List, Union def find_min...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_min_with_rolling_window(lst: List[int], k: int) -> Union[float, None]: """ Finds the minimum value in a given list using a rolling window of size k. Args: lst (List[int]): A ...
code_exercise_27k
22,779
Write a Python function to divide a given string into equal parts of length `n`. If the length of the string is not a multiple of `n`, the last part should be shorter than `n`. The function should handle edge cases such as an empty string, a string whose length is less than `n`, and a string whose length is exactly `n`...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def divide_string_into_parts(string: str, n: int) -> List[str]: """ Divide a given string into equal parts of length 'n'. If the length of the string is not a multiple of 'n', the last part will be s...
code_exercise_27k
22,782
Write a Python function to sort a large array of integers using the merge sort algorithm with limited memory usage. The function should be able to handle large datasets efficiently by minimizing the use of additional memory. The code should start with: ```python from typing import List def limited_memory_merge_sort(ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def limited_memory_merge_sort(arr: List[int]) -> List[int]: """ Sorts a large array of integers using the merge sort algorithm with limited memory usage. Args: arr (List[int]): The input arr...
code_exercise_27k
22,787
Write a Python function to remove all punctuation marks except periods from a given string. The function should handle various punctuation marks and ensure that only periods remain in the string. The code should start with: ```python import string def remove_punctuation_except_periods(input_string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import string def remove_punctuation_except_periods(input_string: str) -> str: """ Removes all punctuation marks except periods from the given input string. Args: input_string (str): The input string from which pun...
code_exercise_27k
22,798
Write a Python function to count the occurrences of each word in a given string, considering case sensitivity and preserving punctuation marks. The function should return a dictionary where the keys are the unique words and the values are their respective counts. The code should start with: ```python from typing impor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_words_with_case_and_punctuation(string: str) -> Dict[str, int]: """ Counts the occurrence of each word in a given string, considering case sensitivity and preserving punctuation marks. Arg...
code_exercise_27k
22,799
Write a Python function to count the number of occurrences of each element in a given list and return the result as a dictionary. The function should handle lists containing any hashable elements, such as integers, strings, or tuples. The code should start with: ```python from typing import List, Dict, Any def count_e...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any def count_elements(lst: List[Any]) -> Dict[Any, int]: """ Count the number of occurrences of each element in a given list. Args: lst (List[Any]): The input list containing element...
code_exercise_27k
22,800
Write a Python function to remove all consecutive duplicates except one from a given string. The function should iterate through the string and keep only the first occurrence of each consecutive duplicate character. The code should start with: ```python def remove_consecutive_duplicates(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_consecutive_duplicates(s: str) -> str: """ Removes all consecutive duplicates except one from a given string. Args: s (str): The input string from which consecutive duplicates are to be removed. Retu...
code_exercise_27k
22,806
Write a Python function to calculate the sum of all numbers in a given list. The function should handle both integer and floating-point numbers. The function should raise a `TypeError` if the input is not a list or if any element in the list is not a number. 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, Union def calculate_sum(numbers: List[Union[int, float]]) -> Union[int, float]: """ Calculate the sum of all numbers in a list. Args: numbers (list): A list of numbers (integers or floating...
code_exercise_27k
22,810
Write a Python function to find the maximum value from a given list of numbers. The function should handle an empty list by raising a `ValueError`. The code should start with: ```python from typing import List, Union def find_maximum(numbers: List[Union[int, float]]) -> Union[int, float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_maximum(numbers: List[Union[int, float]]) -> Union[int, float]: """ Find the maximum value from a list of numbers. Args: numbers (List[Union[int, float]]): A list of numbers....
code_exercise_27k
22,814
Write a Python function to replace all occurrences of a specific element in a list with another element. The function should handle lists containing any type of elements, including integers, strings, and other objects. The code should start with: ```python from typing import List, Any def replace_element(lst: List[Any...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def replace_element(lst: List[Any], old_element: Any, new_element: Any) -> List[Any]: """ Replaces all occurrences of an old element with a new element in a list. Args: lst (List[Any]):...
code_exercise_27k
22,815
Write a Python function to calculate the sum of all numbers in a given list, including handling nested lists. The function should recursively sum all numbers, regardless of the depth of nesting. The code should start with: ```python from typing import List, Union def recursive_sum(numbers: Union[List[Union[int, float...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def recursive_sum(numbers: Union[List[Union[int, float]], List[List[Union[int, float]]]]) -> Union[int, float]: """ Calculates the sum of all numbers in a given list, including nested lists. ...
code_exercise_27k
22,819
Write a Python function to extract all even numbers from a given list of integers. The function should return a new list containing only the even numbers from the input list. The code should start with: ```python from typing import List def extract_even_numbers(numbers: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def extract_even_numbers(numbers: List[int]) -> List[int]: """ Extracts all even numbers from a given list of integers. Args: numbers (List[int]): A list of integers from which to extract ...
code_exercise_27k
22,828
Write a Python function to remove all digits from a given string. The function should return the modified string with all digits removed. The code should start with: ```python def remove_digits(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_digits(string: str) -> str: """ Removes all digits from a given string. Args: string (str): The input string from which the digits will be removed. Returns: str: The modified string with all ...
code_exercise_27k
22,830
Write a Python function to find the longest sequence of equal values in a given list using a rolling window of size 2. The function should return the longest sequence of consecutive equal values found in the list. The code should start with: ```python from typing import List def find_longest_sequence(lst: List[int]) ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_longest_sequence(lst: List[int]) -> List[int]: """ Finds the longest sequence of equal values in a list using a rolling window of size 2. Args: lst (List[int]): A list of integers. ...
code_exercise_27k
22,833
Write a Python function to find the second smallest element in a given list. The function should handle lists with at least two elements and return the second smallest element. If the list contains fewer than two elements, the function should raise a `ValueError`. The code should start with: ```python from typing impo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_second_smallest(lst: List[Union[int, float]]) -> Union[int, float]: """ Finds the second smallest element in a given list. Parameters: lst (list): The list containing elements. ...
code_exercise_27k
22,834
Write a Python function to determine if a given string is a pangram. A pangram is a sentence that contains every letter of the alphabet at least once. The function should ignore case and non-alphabetic characters. The code should start with: ```python def is_pangram(input_string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_pangram(input_string: str) -> bool: """ Determine if the given string is a pangram. A pangram is a sentence that contains every letter of the alphabet at least once. This function ignores case and non-alphabetic ...
code_exercise_27k
22,837
Write a Python function to remove the first 'n' characters from a given string. If 'n' is greater than or equal to the length of the string, return an empty string. The function should handle edge cases such as an empty string or a negative value for 'n'. The code should start with: ```python def remove_first_n_chars(...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_first_n_chars(text: str, n: int) -> str: """ Remove the first 'n' characters from the given string. Args: text (str): The input string from which characters are to be removed. n (int): The number ...
code_exercise_27k
22,838
Write a Python function to find the intersection of two given lists, ensuring that the result contains only unique elements and is sorted in ascending order. The function should handle lists of integers and return a list of integers. The code should start with: ```python from typing import List def find_intersection_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_intersection_unique_sorted(list1: List[int], list2: List[int]) -> List[int]: """ Find the intersection of two lists, ensuring the result contains only unique elements and is sorted in ascending ...
code_exercise_27k
22,841
Write a Python function to check if a given list is sorted in non-decreasing order. The function should return `True` if the list is sorted and `False` otherwise. The function should handle lists of any length, including empty lists and lists with a single element. 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 def is_sorted_non_decreasing(lst: List[int]) -> bool: """ Check if a given list is sorted in non-decreasing order. Args: lst (List[int]): The list to be checked. Returns: bool: ...
code_exercise_27k
22,844
Write a Python function to generate the Fibonacci series up to a given number `n`. The function should return a list of all Fibonacci numbers that are less than or equal to `n`. The Fibonacci series starts with 0 and 1, and each subsequent number is the sum of the previous two numbers. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def fibonacci_series(n: int) -> List[int]: """ Generate the Fibonacci series up to a given number. Args: n (int): The maximum number up to which the Fibonacci series is generated. Retur...
code_exercise_27k
22,846
Write a Python function to remove all digits from the beginning and end of a given string. The function should return the modified string with all digits removed from the start and end, but should leave the digits in the middle of the string intact. The code should start with: ```python def remove_leading_trailing_digi...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_leading_trailing_digits(string: str) -> str: """ Remove all digits from the beginning and end of a given string. Args: string (str): The input string from which to remove leading and trailing digits. ...
code_exercise_27k
22,848
Write a Python function to count the number of vowels in a given string using recursion. The function should handle both uppercase and lowercase vowels. The code should start with: ```python def count_vowels_recursive(string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels_recursive(string: str) -> int: """ Count the number of vowels in a given string using recursion. Args: string (str): The input string to count vowels in. Returns: int: The number of vow...
code_exercise_27k
22,849
Write a Python function to find the largest power of 2 within a rolling window of size 7 for a given list of numbers. The function should return the largest power of 2 found within any 7-element subarray of the input list. The code should start with: ```python from typing import List def find_largest_power_of_2_in_wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_power_of_2_in_window(nums: List[int]) -> int: """ Find the largest power of 2 within a rolling window of size 7 for the given list of numbers. Args: nums: A list of integers...
code_exercise_27k
22,851
Write a Python function to sort a list of strings in lexicographic (dictionary) order. The function should handle lists containing only strings and raise appropriate exceptions for invalid inputs. The code should start with: ```python from typing import List def lexicographic_sort(strings: List[str]) -> List[str]: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def lexicographic_sort(strings: List[str]) -> List[str]: """ Sorts a list of strings in lexicographic (dictionary) order. Args: strings (List[str]): A list of strings to be sorted. Retu...
code_exercise_27k
22,859
Write a Python function to remove all whitespace characters except spaces from a given string. The function should return the modified string. The code should start with: ```python def remove_whitespace_except_spaces(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def remove_whitespace_except_spaces(string: str) -> str: """ Removes all whitespace characters from a string except spaces. Args: string (str): The input string from which to remove whitespace characters. Ret...
code_exercise_27k
22,860
Write a Python function to perform a binary search on a sorted list and return the index of the target element. If the target element is not found, return -1. The function should handle edge cases such as an empty list or a target element that is not present in the list. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def binary_search(arr: List[Any], target: Any) -> int: """ Perform binary search on a sorted list to find the index of the target element. Args: arr (List[Any]): A sorted list of elemen...
code_exercise_27k
22,865
Write a Python function to reverse the words in a given string while preserving the order of characters within each word. The function should handle strings with multiple spaces between words and leading/trailing spaces. The code should start with: ```python def reverse_words_preserve_order(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words_preserve_order(string: str) -> str: """ Reverses the words in a given string while preserving the order of characters within each word. Args: string (str): The input string to reverse the words in....
code_exercise_27k
22,867
Write a Python function to remove the first occurrence of a specified character from a given string. If the character is not found in the string, the function should return the original string unchanged. The function should handle edge cases such as an empty string or a string that does not contain the target character...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_first_occurrence(string: str, target: str) -> str: """ Removes the first occurrence of a specified character from the given string. Args: string (str): The input string from which the first occurrence of ...