source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
23,193
Write a Python function to calculate the overall rating of a bookmark based on user ratings and reviews. The function should take two lists as input: one containing numerical ratings and the other containing user reviews. The overall rating should be calculated by first computing the average of the numerical ratings an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_overall_rating(ratings: List[float], reviews: List[str]) -> float: """ Calculate the overall rating of a bookmark based on user ratings and reviews. Args: ratings (List[float])...
code_exercise_27k
23,194
Write a Python function to find the maximum number of overlapping intervals from a given list of intervals. Each interval is represented as a tuple of start and end values. The function should efficiently determine the maximum number of intervals that overlap at any point. The code should start with: ```python from ty...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_max_overlapping_intervals(intervals: List[Tuple[int, int]]) -> int: """ Finds the maximum number of overlapping intervals from a given list of intervals. Args: intervals (Lis...
code_exercise_27k
23,197
Write a Python function to calculate the sum of the digits of a given number. The function should handle both positive and negative integers. If the number is negative, the function should ignore the negative sign and calculate the sum of the digits. The code should start with: ```python def sum_of_digits(number: int)...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits(number: int) -> int: """ Calculate the sum of the digits of a given number. Args: number (int): The number for which the sum of digits needs to be calculated. Returns: int: The sum of ...
code_exercise_27k
23,199
Write a Python function to implement the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit. The function should return a list of all prime numbers up to the specified limit. The code should start with: ```python from typing import List def find_primes_up_to(limit: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_primes_up_to(limit: int) -> List[int]: """ Find all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. Args: limit (int): The upper limit to find all prime...
code_exercise_27k
23,200
Write a Python function to reverse a given string. The function should take a string as input and return the reversed string. 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. Args: string (str): The input string to be reversed. Returns: str: The reversed string. """ # Use slicing to reverse the str...
code_exercise_27k
23,205
Write a Python function to concatenate all elements in a given list of strings with a specified delimiter. The function should handle an empty list by returning an empty string. The code should start with: ```python from typing import List def concatenate_strings_with_delimiter(string_list: List[str], delimiter: str) ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_strings_with_delimiter(string_list: List[str], delimiter: str) -> str: """ Concatenates all elements in a given list of strings using the specified delimiter. Args: string_li...
code_exercise_27k
23,206
Write a Python function to arrange a given list of integers in a wave-like pattern. A wave-like pattern is defined such that every second element is greater than its adjacent elements. The function should start with: ```python from typing import List def arrange_in_wave_pattern(nums: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def arrange_in_wave_pattern(nums: List[int]) -> List[int]: """ Arranges a given list of integers in a wave-like pattern. A wave-like pattern is defined such that every second element is greater than...
code_exercise_27k
23,211
Write a Python function to find the pair of elements with the maximum sum in a given list of integers. The function should return a tuple containing the pair of elements with the maximum sum. If the list contains fewer than two elements, the function should raise a `ValueError`. The code should start with: ```python f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_max_sum_pair(nums: List[int]) -> Tuple[int, int]: """ Finds the pair of elements with the maximum sum in a given list of integers. Args: nums: A list of integers. Return...
code_exercise_27k
23,213
Write a Python function to find the maximum product of any three elements in a given list of integers. The function should handle lists with both positive and negative integers, and it should return the maximum product efficiently. The code should start with: ```python from typing import List def max_product_of_three...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_product_of_three(arr: List[int]) -> int: """ Finds the maximum product of any three elements in a given list of integers. Args: arr (List[int]): A list of integers. Returns: ...
code_exercise_27k
23,216
Write a Python function to sort a list of numbers in descending order using the merge sort algorithm. The function should be efficient and handle edge cases such as an empty list or a list with a single element. The code should start with: ```python from typing import List def merge_sort_descending(numbers: List[int])...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def merge_sort_descending(numbers: List[int]) -> List[int]: """ Sorts a list of numbers in descending order using the merge sort algorithm. Args: numbers (List[int]): A list of numbers to ...
code_exercise_27k
23,218
Write a Python function to check whether a given list is a valid max-heap or not. A max-heap is a binary tree where each parent node has a value greater than or equal to its child nodes. In the list representation of a max-heap, for any given index `i`, the left child can be found at `2*i + 1` and the right child can b...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_valid_max_heap(lst: List[int]) -> bool: """ Check if the given list is a valid max-heap. A max-heap is a binary tree where each parent node has a value greater than or equal to its child ...
code_exercise_27k
23,220
Write a Python function to determine if a given number is a perfect square. A perfect square is a number that can be expressed as the square of an integer. The function should handle both positive and negative integers. The code should start with: ```python def is_perfect_square(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_square(num: int) -> bool: """ Determine if a given number is a perfect square. Args: num (int): The number to check. Returns: bool: True if the number is a perfect square, False otherwise...
code_exercise_27k
23,224
Write a Python function to count the number of set bits (1s) in a given binary number. The function should handle only non-negative integers and should not use any built-in functions or libraries that directly count bits. The code should start with: ```python def count_set_bits(binary_num: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_set_bits(binary_num: int) -> int: """ Counts the number of set bits (1s) in a given binary number. Args: binary_num (int): The binary number to count the set bits from. Must be a non-negative integer. ...
code_exercise_27k
23,230
Write a Python function to find the maximum number of overlapping intervals in a given list of intervals. Each interval is represented as a tuple of two integers, where the first integer is the start time and the second integer is the end time. The function should return the maximum number of intervals that overlap at ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def max_overlapping_intervals(intervals: List[Tuple[int, int]]) -> int: """ Find the maximum number of overlapping intervals in a given list of intervals. Args: intervals (List[Tuple[...
code_exercise_27k
23,231
Write a Python function to find the maximum occurring character in a given string. If there are multiple characters with the same maximum occurrence, return the first one encountered in the string. The function should handle non-empty strings only. The code should start with: ```python def find_max_occuring_char(strin...
Here is the Python code to solve the given problem in the markdown block: ```python def find_max_occuring_char(string: str) -> str: """ Find the maximum occurring character in a given string. Args: string (str): The input string. Returns: str: The maximum occurring characte...
code_exercise_27k
23,235
Write a Python function to find the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. The function should handle only positive integers and should not raise any exceptions. 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: """ Find the Greatest Common Divisor (GCD) of two positive integers using the Euclidean algorithm. Args: a (int): The first positive integer. b (int): The second positive inte...
code_exercise_27k
23,240
Write a Python function to implement a binary search algorithm that searches for a target element in a sorted list of integers. The function should return the index of the target element if it is found, or -1 if the target element is not present in the list. 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 binary_search(arr: List[int], target: int) -> int: """ Perform binary search on a sorted list of integers to find the target element. Args: arr (List[int]): The sorted list of integers t...
code_exercise_27k
23,244
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given list of numbers. The function should efficiently compute the length of the LIS using dynamic programming. The code should start with: ```python from typing import List def longest_increasing_subsequence_length(nums: List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_increasing_subsequence_length(nums: List[int]) -> int: """ Computes the length of the longest increasing subsequence in a given list of numbers. Args: - nums: A list of integers or f...
code_exercise_27k
23,246
Write a Python function to find the longest common subsequence (LCS) between two given strings. The function should return the LCS as a string. The code should start with: ```python def longest_common_subsequence(str1: str, str2: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence(str1: str, str2: str) -> str: """ Find the longest common subsequence between two strings. Args: str1 (str): The first input string. str2 (str): The second input string. R...
code_exercise_27k
23,248
Write a Python function to find the number of ways to reach the bottom-right corner from the top-left corner of a rectangular grid, moving only down or right, while avoiding obstacles represented by blocked cells. The grid is represented as a 2D list where each cell is either `1` (obstacle/block) or `0` (empty cell). ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_paths_with_obstacles(grid: List[List[int]]) -> int: """ Find the number of ways to reach the bottom-right corner from the top-left corner of a rectangular grid, moving only down or right, w...
code_exercise_27k
23,249
Write a Python function to check whether a given string is a valid palindrome using dynamic programming. The function should return `True` if the string is a palindrome and `False` otherwise. The function should handle strings of any length, including empty strings. The code should start with: ```python def is_palindr...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome_dp(s: str) -> bool: """ Check if a given string is a valid palindrome using dynamic programming. Args: s (str): The input string to check. Returns: bool: True if the string is a valid ...
code_exercise_27k
23,253
Write a Python function to calculate the surface area of a cube given its side length. The function should handle non-negative side lengths and return the correct surface area. The code should start with: ```python def calculate_cube_surface_area(side_length: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_cube_surface_area(side_length: float) -> float: """ Calculate the surface area of a cube given its side length. Args: side_length (float): The length of one side of the cube. Returns: floa...
code_exercise_27k
23,256
Write a Python function to implement the merge sort algorithm. The function should take a list of integers as input and return the sorted list. The merge sort algorithm should be implemented using a recursive approach. The function should handle edge cases such as an empty list or a list with a single element. Addition...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts a given list of integers using the merge sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: ...
code_exercise_27k
23,271
Write a Python function to find the largest rectangle area in a histogram represented as a list of heights. The function should efficiently compute the maximum area of the rectangle that can be formed using the bars of the histogram. The code should start with: ```python from typing import List def largest_rectangle_a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def largest_rectangle_area(heights: List[int]) -> int: """ Finds the largest rectangle area in a histogram represented as a list of heights. Args: heights (list): A list of positive inte...
code_exercise_27k
23,273
Write a Python function to find the nth Fibonacci number using dynamic programming. The function should efficiently compute the Fibonacci number by storing previously computed values in a list to avoid redundant calculations. The code should start with: ```python def fibonacci_dynamic(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci_dynamic(n: int) -> int: """ Calculate the nth Fibonacci number using dynamic programming. Args: n (int): The index of the Fibonacci number to calculate. Returns: int: The nth Fibonacci num...
code_exercise_27k
23,274
Write a Python function to generate a personalized newsletter or email digest of recommended bookmarks for a user. The function should take a dictionary containing user data, including preferences and bookmark recommendations, and return a formatted string representing the newsletter content. The function should ensure...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def generate_newsletter(user_data: Dict) -> str: """ Generates a personalized newsletter or email digest of recommended bookmarks. Args: user_data (dict): A dictionary containing user data, ...
code_exercise_27k
23,277
Write a Python function to calculate the area of a parallelogram given its base and height. The function should handle non-negative inputs and return the area as a float. If either the base or height is negative, the function should raise a `ValueError`. The code should start with: ```python def calculate_parallelogra...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_parallelogram_area(base: float, height: float) -> float: """ Calculate the area of a parallelogram given its base and height. Args: base (float): The length of the parallelogram's base. Must be non-neg...
code_exercise_27k
23,283
Write a Python function to convert a given text to lowercase and remove all non-alphabetic characters. The function should handle various edge cases, such as empty strings, strings with only non-alphabetic characters, and strings with mixed alphabetic and non-alphabetic characters. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python def clean_and_convert_to_lowercase(text: str) -> str: """ Converts the given text to lowercase and removes all non-alphabetic characters. Args: text (str): The text to be cleaned and converted. Returns: ...
code_exercise_27k
23,291
Write a Python function to tokenize a given text into words, handling punctuation and case sensitivity. The function should remove punctuation from the words and convert them to lowercase. The code should start with: ```python from typing import List import string def tokenize_text(text: str) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import string def tokenize_text(text: str) -> List[str]: """ Tokenize a given text into a list of words, removing punctuation and converting to lowercase. Args: text (str): The input text to...
code_exercise_27k
23,297
Write a Python function to find the smallest missing positive integer 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 from 1 to the length of the list are present, the function should return the next positive integer. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_smallest_missing_positive_integer(nums: List[int]) -> int: """ Finds the smallest missing positive integer in a given list of integers. Args: nums (List[int]): A list of integers. ...
code_exercise_27k
23,298
Write a Python function to calculate the area of an ellipse given its major and minor axes lengths. The function should handle non-positive axes lengths by raising a `ValueError`. The code should start with: ```python import math def calculate_ellipse_area(major_axis: float, minor_axis: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_ellipse_area(major_axis: float, minor_axis: float) -> float: """ Calculates the area of an ellipse given its major and minor axes lengths. Parameters: major_axis (float): The length of...
code_exercise_27k
23,306
Write a Python function to implement the Bag-of-Words representation for a given text, considering case insensitivity and ignoring punctuation. The function should return a dictionary where the keys are unique words in the text (in lowercase) and the values are the corresponding word frequencies. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import string def bag_of_words(text: str) -> Dict[str, int]: """ Converts a given text into a Bag-of-Words representation, considering case insensitivity and ignoring punctuation. Args: text...
code_exercise_27k
23,308
Write a Python function to find the maximum sum of any subarray with a given length `k` in a given list of integers. The function should handle edge cases such as when `k` is greater than the length of the list or when the list is empty. The function should start with: ```python from typing import List def find_max_su...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_subarray_sum(arr: List[int], k: int) -> int: """ Find the maximum sum of a subarray with length k in a given list. Args: arr (List[int]): The input list of integers. k (...
code_exercise_27k
23,318
Write a Python function to find the smallest missing positive integer in a given list of integers. The function should return the smallest positive integer that is missing from the list. The list may contain duplicates and negative numbers, but the function should only consider positive integers starting from 1. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_smallest_missing_positive(nums: List[int]) -> int: """ Finds the smallest missing positive integer in a given list of integers. Args: nums (List[int]): A list of integers which may ...
code_exercise_27k
23,336
Write a Python function to filter and display bookmarks added by users based on their level of expertise or experience. The function should take a dictionary of bookmarks and a string representing the expertise level as input, and return a list of bookmarks that match the specified expertise level. The dictionary keys ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def filter_bookmarks_by_expertise(bookmarks: Dict[str, List[Dict[str, str]]], expertise: str) -> List[Dict[str, str]]: """ Filter and display bookmarks added by users based on their level of expert...
code_exercise_27k
23,341
Write a Python function to calculate the factorial of a given non-negative integer using an iterative approach. The function should handle edge cases such as zero and should not accept negative integers. The code should start with: ```python def factorial(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial(n: int) -> int: """ Calculate the factorial of a non-negative integer. Args: n (int): The non-negative integer for which factorial needs to be calculated. Returns: int: The factorial of th...
code_exercise_27k
23,342
Write a Python function to generate the Fibonacci series up to a given term `n`. The function should return a list containing the Fibonacci sequence up to the `n`-th term. If `n` is less than or equal to 0, the function should return an empty list. The code should start with: ```python from typing import List def gen...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_fibonacci_series(n: int) -> List[int]: """ Generate the Fibonacci series up to the given term. Args: n (int): The term up to which to generate the Fibonacci series. Returns...
code_exercise_27k
23,346
Write a Python function to count the number of occurrences of each element in a given list and return the result as a dictionary where the keys are the elements and the values are their respective counts. The code should start with: ```python from typing import List, Dict def count_elements(arr: List[int]) -> Dict[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_elements(arr: List[int]) -> Dict[int, int]: """ Count the number of occurrences of each element in a given list. Args: arr (List[int]): The input list of integers. Retur...
code_exercise_27k
23,350
Write a Python function to sort a list of integers in descending order using the merge sort algorithm. The merge sort algorithm should be implemented from scratch without using Python's built-in `sorted` function or any other sorting functions. The function should start with: ```python from typing import List def merg...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def merge_sort_descending(lst: List[int]) -> List[int]: """ Sorts a list of integers in descending order using the merge sort algorithm. Args: lst (List[int]): The list of integers to be s...
code_exercise_27k
23,353
Write a Python function to filter and display bookmarks based on the occupation or profession provided. The function should take a list of bookmark dictionaries and an occupation string as input, and return a list of bookmark dictionaries that match the provided occupation. Each bookmark dictionary contains information...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def display_bookmarks_by_occupation(bookmarks: List[Dict[str, str]], occupation: str) -> List[Dict[str, str]]: """ Filter and display bookmarks based on the occupation or profession provided. ...
code_exercise_27k
23,355
Write a Python function to perform sentiment analysis on a given text using an ensemble of multiple models. Each model in the ensemble will predict a sentiment score for the text, and the function should return the most common sentiment score among all the predictions. The code should start with: ```python from typing ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict from collections import Counter def ensemble_sentiment_analysis(text: str, models: List[Dict[str, str]]) -> str: """ Perform sentiment analysis on the given text using an ensemble of multiple model...
code_exercise_27k
23,361
Write a Python function to determine if a given number is a perfect square. A perfect square is a number that can be expressed as the square of an integer. The function should handle both positive and negative integers, as well as zero. The code should start with: ```python def is_perfect_square(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_square(num: int) -> bool: """ Determine if a given number is a perfect square. Args: num (int): The number to check. Returns: bool: True if the number is a perfect square, False otherwise...
code_exercise_27k
23,364
Write a Python function to swap two elements in a list without modifying the original list. The function should return a new list with the elements swapped. The indices to be swapped should be checked for validity, and if either index is out of range, the function should return the original list without any changes. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def swap_elements_in_new_list(lst: List, index1: int, index2: int) -> List: """ Swaps the elements at the given indices in a new list without modifying the original list. Args: lst (list): T...
code_exercise_27k
23,365
Write a Python function to find the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. The function should handle the case where the second number is greater than the first by swapping the numbers. The code should start with: ```python def find_gcd(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_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
23,376
Write a Python function to sort a list using the 3-way quicksort algorithm. The function should handle duplicate elements efficiently and return the sorted list. The code should start with: ```python from typing import List import random def quicksort_3way(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def quicksort_3way(arr: List[int]) -> List[int]: """ Sorts a list using the 3-way quicksort algorithm. This algorithm is similar to the regular quicksort, but it handles duplicate elem...
code_exercise_27k
23,378
Write a Python function to perform binary search on a sorted list and return the index of the target value. If the target value is not found, return -1. The function should handle edge cases such as an empty list or a target value that is not present in the list. 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 List def binary_search(arr: List[int], target: int) -> int: """ Perform binary search on a sorted list to find the index of a target value. Args: arr (List[int]): The sorted list to search in. ...
code_exercise_27k
23,381
Write a Python function to perform a 3-way quicksort on a given list of integers. The function should partition the list into three parts: elements less than the pivot, elements equal to the pivot, and elements greater than the pivot. The function should then recursively sort the "less than" and "greater than" partitio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def three_way_quicksort(arr: List[int]) -> List[int]: """ Sorts a list of integers using a 3-way quicksort algorithm. Parameters: - arr (List[int]): The list of integers to be sorted. Retur...
code_exercise_27k
23,384
Write a Python function to sort a list of strings in lexicographically increasing order using the 3-way quicksort algorithm. The function should handle lists with duplicate strings efficiently. The code should start with: ```python from typing import List def quicksort_3way(arr: List[str]) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def quicksort_3way(arr: List[str]) -> List[str]: """ Sorts a list of strings in lexicographically increasing order using the 3-way quicksort algorithm. Args: arr (List[str]): A list of strin...
code_exercise_27k
23,387
Write a Python function to generate a list of random numbers within a specified range and count how many times each number appears in the list. The function should return a dictionary where the keys are the numbers from the range and the values are the counts of how many times each number appears in the list. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List import random def generate_random_counts(start: int, end: int, size: int) -> Dict[int, int]: """ Generate a list of random numbers within a specified range and count how many times each number appe...
code_exercise_27k
23,393
Write a Python function to sort a list of tuples based on a specific element using the 3-way quicksort algorithm. The function should handle both integer and string keys. The code should start with: ```python from typing import List, Tuple, Union def sort_tuples_by_key(lst: List[Tuple[Union[int, str], ...]], key: Unio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Union def sort_tuples_by_key(lst: List[Tuple[Union[int, str], ...]], key: Union[int, str]) -> List[Tuple[Union[int, str], ...]]: """ Sorts a list of tuples based on a specific element using the 3...
code_exercise_27k
23,395
Write a Python function to generate a random color name from a given list of colors. The function should handle the case where the list is empty by raising a `ValueError`. The code should start with: ```python from typing import List import random def generate_random_color(colors: List[str]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_color(colors: List[str]) -> str: """ Generate a random color name from a given list of colors. Args: colors (List[str]): A list of color names. Returns...
code_exercise_27k
23,402
Write a Python function to generate a list of unique random integers within a given range. The function should ensure that the generated integers are unique and within the specified range. The code should start with: ```python from typing import List import random def generate_unique_random_integers(start: int, end: i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_unique_random_integers(start: int, end: int, num_elements: int) -> List[int]: """ Generates a list of unique random integers within a given range. Args: start (int...
code_exercise_27k
23,412
Write a Python function to simulate flipping a coin a given number of times and count the number of heads and tails. The function should return the counts of heads and tails as a tuple. The code should start with: ```python import random def simulate_coin_flips(num_flips: int) -> tuple: ```
Here is the Python code to solve the given problem in the markdown block: ```python import random def simulate_coin_flips(num_flips: int) -> tuple: """ Simulates flipping a coin for a given number of times and counts the number of heads and tails. Args: num_flips (int): The number of times to flip...
code_exercise_27k
23,414
Write a Python function to shuffle a given list of elements using the Fisher-Yates algorithm. The function should ensure that the original list is not modified and a new shuffled list is returned. The code should start with: ```python from typing import List import random def shuffle_list(lst: List[int]) -> List[int]:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_list(lst: List[int]) -> List[int]: """ Shuffles a given list of elements using the Fisher-Yates algorithm. Args: lst (List[int]): The list to be shuffled. Retu...
code_exercise_27k
23,415
Write a Python function to find the kth smallest element in a list using the 3-way quicksort algorithm. The function should handle the partitioning of the list into three parts: elements less than the pivot, elements equal to the pivot, and elements greater than the pivot. The function should then recursively narrow do...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_kth_smallest(arr: List[int], k: int) -> int: """ Returns the kth smallest element in the given list using the 3-way quicksort algorithm. Args: arr (List[int]): The list of integers ...
code_exercise_27k
23,422
Write a Python function to find the maximum sum of a subarray in a given array using Kadane's algorithm. The function should return the maximum sum, the starting index, and the ending index of the subarray with the maximum sum. The code should start with: ```python from typing import List, Tuple def max_subarray_sum(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def max_subarray_sum(arr: List[int]) -> Tuple[int, int, int]: """ Finds the maximum sum of a subarray in an array using Kadane's algorithm. Args: arr (List[int]): An array of integers...
code_exercise_27k
23,428
Write a Python function to find all possible subsets of a given list of integers, including the empty subset. The function should return a list of lists, where each sublist represents a subset of the input list. The code should start with: ```python from typing import List def find_all_subsets(nums: List[int]) -> List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_subsets(nums: List[int]) -> List[List[int]]: """ Find all possible subsets of a given list of integers. Parameters: nums (List[int]): List of integers. Returns: List[List[i...
code_exercise_27k
23,433
Write a Python function to generate all possible subsets from a given list of characters. Each subset should be a unique combination of the characters from the input list. The function should return a list of lists, where each inner list represents a subset. 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_subsets(char_list: List[str]) -> List[List[str]]: """ Generates all possible subsets from a given list of characters. Args: char_list (List[str]): The list of characters from wh...
code_exercise_27k
23,440
Write a Python function to find all subsets of a given length from a list of characters. The function should return a list of tuples, where each tuple represents a subset of the specified length. The function should handle edge cases such as invalid lengths (less than or equal to zero, or greater than the length of the...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_subsets_of_length(characters: List[str], length: int) -> List[Tuple[str]]: """ Find all subsets of a given length from a list of characters. Args: characters (List[str]): The...
code_exercise_27k
23,461
Write a Python function to find all subsets of a given length from a list of strings. The function should return a list of tuples, where each tuple represents a subset of the specified length. The code should start with: ```python from typing import List, Tuple from itertools import combinations def find_subsets(strin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple from itertools import combinations def find_subsets(strings: List[str], length: int) -> List[Tuple[str]]: """ Find all subsets of a given length from a list of strings. Args: strings ...
code_exercise_27k
23,462
Write a Python function to generate a random number from a normal (Gaussian) distribution using the Box-Muller transform method. The function should take two parameters: `mu` (the mean of the distribution) and `sigma` (the standard deviation of the distribution). The function should return a random number from the spec...
Here is the Python code to solve the given problem in the markdown block: ```python import random import math def generate_random_number(mu: float, sigma: float) -> float: """ Generate a random number from a normal (Gaussian) distribution using the Box-Muller transform method. Parameters: mu (float): ...
code_exercise_27k
23,463
Write a Python function to calculate the average of a list of numbers. The function should handle the case where the list is empty by returning `None` instead of raising an exception. The code should start with: ```python from typing import List, Optional def calculate_average(lst: List[float]) -> Optional[float]: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def calculate_average(lst: List[float]) -> Optional[float]: """ Calculate the average of a list of numbers. Args: lst (List[float]): A list of numbers. Returns: Option...
code_exercise_27k
23,465
Write a Python function to remove all occurrences of a specified element from a given list. The function should return the modified list. 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 specified element from a list. Args: lst (List[Any]): The list from which the element shou...
code_exercise_27k
23,469
Write a Python function to generate all subsets of a given list of positive integers in descending order. The function should return a list of subsets, where each subset is also sorted in descending order. The code should start with: ```python from typing import List def generate_descending_subsets(nums: List[int]) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_descending_subsets(nums: List[int]) -> List[List[int]]: """ Generate all subsets of a given list of positive integers in descending order. Args: nums (List[int]): A list of posi...
code_exercise_27k
23,474
Write a Python function to calculate the power of a number, ensuring that the function handles both positive and negative bases and integer exponents. The function should raise a `ValueError` if the base is negative and the exponent is not an integer. The code should start with: ```python def calculate_power(base: floa...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_power(base: float, exponent: int) -> float: """ Calculate the power of a number. Parameters: - base (float): The base number. - exponent (int): The exponent. Returns: - float: The result of ra...
code_exercise_27k
23,481
Write a Python function to find all the factors of a given positive integer. The function should return a list of all the factors, including 1 and the number itself. The code should start with: ```python from typing import List def find_factors(num: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_factors(num: int) -> List[int]: """ Find all the factors of a given positive integer. Args: num (int): The positive integer to find the factors of. Returns: List[int]: ...
code_exercise_27k
23,490
Write a Python function to find all subsets of a given list of strings that contain only palindromic strings. A palindromic string is a string that reads the same backward as forward. The function should return a list of all such subsets. The code should start with: ```python from typing import List def find_palindro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_palindrome(s: str) -> bool: """ Check if a string is a palindrome. Parameters: s (str): The string to check. Returns: bool: True if the string is a palindrome, False otherwise. ...
code_exercise_27k
23,500
Write a Python function to check if a given string contains only digits and does not contain any other characters, including spaces, punctuation, or alphabetic characters. The function should return `True` if the string meets the criteria and `False` otherwise. The code should start with: ```python def is_string_only_...
Here is the Python code to solve the given problem in the markdown block: ```python def is_string_only_digits(s: str) -> bool: """ Check if a given string contains only digits and no other characters. Args: s (str): The string to be checked. Returns: bool: True if the string contains o...
code_exercise_27k
23,505
Write a Python function to implement a random sorting algorithm, which repeatedly shuffles the elements of a list until the list is sorted. The function should return the sorted list. Additionally, write a helper function to check if a list is sorted in non-decreasing order. The code should start with: ```python impor...
Here is the Python code to solve the given problem in the markdown block: ```python import random from typing import List def random_sort(arr: List[int]) -> List[int]: """ Sorts a list `arr` using the random sort algorithm. The random sort algorithm works by repeatedly shuffling the elements of the li...
code_exercise_27k
23,513
Write a Python function to check if a given string is a valid URL. The function should validate the URL based on the following criteria: 1. The URL must start with either "http://" or "https://". 2. The URL must contain a valid domain name (e.g., "www.example.com"). 3. The URL may optionally include a port number (e.g....
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_url(url: str) -> bool: """ Checks if a given string is a valid URL. Args: url (str): The string representing the URL. Returns: bool: True if the URL is valid, False otherwise. ...
code_exercise_27k
23,514
Write a Python function to find the sum of all odd numbers in a given list of integers. The function should iterate through the list, check if each number is odd, and accumulate the sum of these odd numbers. The code should start with: ```python from typing import List def sum_of_odd_numbers(numbers: List[int]) -> int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_odd_numbers(numbers: List[int]) -> int: """ Computes the sum of all odd numbers in a given list of integers. Args: numbers (List[int]): A list of integers. Returns: i...
code_exercise_27k
23,517
Write a Python function to remove all whitespace characters from a given string. The function should handle various types of whitespace characters, including spaces, tabs, newlines, and carriage returns. The code should start with: ```python def remove_whitespace(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def remove_whitespace(string: str) -> str: """ Remove all whitespace characters from a given string. Args: string (str): The original string from which to remove whitespace characters. Returns: str: T...
code_exercise_27k
23,521
Write a Python function to count the number of occurrences of each character in a given string and return the result as a dictionary where the keys are characters and the values are their respective counts. The function should handle any string input, including empty strings. The code should start with: ```python from...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_character_occurrences(string: str) -> Dict[str, int]: """ Count the number of occurrences of each character in a given string. Args: string (str): The input string to count charact...
code_exercise_27k
23,532
Write a Python function to find the minimum spanning tree (MST) of a graph using the Prim's algorithm. The graph is represented as an adjacency list where each node points to a dictionary of its neighbors and the corresponding edge weights. The function should return the MST as a dictionary where each key is a node and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple import heapq def prim_min_spanning_tree(graph: Dict[str, Dict[str, int]]) -> Dict[str, Tuple[str, int]]: """ Find the minimum spanning tree of a graph using Prim's algorithm. Args: gr...
code_exercise_27k
23,541
Write a Python function to find the reachable vertices from a given vertex in a graph using the Bellman-Ford algorithm. The function should return a list of reachable vertices from the start vertex, excluding the start vertex itself. The graph is represented as a dictionary where the keys are vertices and the values ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple from sys import maxsize def find_reachable_vertices(graph: Dict[str, List[Tuple[str, int]]], start_vertex: str) -> List[str]: """ Finds the reachable vertices from a given vertex in a graph ...
code_exercise_27k
23,547
Write a Python function to calculate the sum of all numbers in a given range, including both the start and end values. The function should handle both positive and negative integers, and the range can be in any order (i.e., the start value can be greater than the end value). The code should start with: ```python def s...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_range(start: int, end: int) -> int: """ Calculate the sum of all numbers in a given range, including both the start and end values. Args: start (int): The starting number of the range (inclusive). ...
code_exercise_27k
23,550
Write a Python function to count the number of uppercase and lowercase letters in a given string. The function should return a tuple containing the count of uppercase and lowercase letters respectively. The code should start with: ```python def count_letters(string: str) -> tuple: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_letters(string: str) -> tuple: """ Count the number of uppercase and lowercase letters in a given string. Args: string (str): The input string to count the letters in. Returns: tuple: A tuple ...
code_exercise_27k
23,553
Write a Python function to remove all duplicate characters from a given string while preserving the order of the first occurrence of each character. The function should handle any string input, including empty strings and strings with all unique characters. The code should start with: ```python def remove_duplicates_pr...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_duplicates_preserve_order(string: str) -> str: """ Removes all duplicate characters from a string while preserving the order of their first occurrence. This function takes a string as input and returns a new stri...
code_exercise_27k
23,554
Write a Python function to find the minimum cost to reach a destination vertex from a given source vertex using the Bellman-Ford algorithm. The function should return the minimum cost and the shortest path as a dictionary. If there is no path from the source to the destination, the function should return `None`. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Union from collections import defaultdict def bellman_ford_shortest_path(graph: Dict[str, Dict[str, int]], source: str, destination: str) -> Union[Dict[str, Union[int, List[str]]], None]: """ Find...
code_exercise_27k
23,561
Write a Python function to calculate the sum of the digits of a given number. The function should handle both positive and negative integers. If the number is negative, the function should ignore the negative sign and calculate the sum of the digits of the absolute value of the number. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits(number: int) -> int: """ Calculates the sum of the digits of a given number. Args: number (int): The number for which the sum of digits needs to be calculated. Returns: int: The sum of...
code_exercise_27k
23,570
Write a Python function to find the factors of a given number using a loop. The function should return a list of all factors of the number, including 1 and the number itself. The code should start with: ```python from typing import List def find_factors(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_factors(n: int) -> List[int]: """ Find all factors of a given number. Args: n (int): The number for which factors need to be found. Returns: List[int]: A list of all fa...
code_exercise_27k
23,585
Write a Python function to remove the nth element from a given list. If the index `n` is out of bounds, the function should return the original list without any changes. The function should handle both positive and negative indices. The code should start with: ```python from typing import List def remove_nth_element(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_nth_element(lst: List[int], n: int) -> List[int]: """ Removes the nth element from a given list. If the index is out of bounds, the original list is returned without any changes. Args...
code_exercise_27k
23,592
Write a Python function to count the occurrence of a specific value in a JSON array. The JSON array is represented as a list of elements, which can be of any type (integers, strings, lists, dictionaries, etc.). The function should recursively count the occurrences of the specified value in the entire JSON array, includ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, List def count_occurrence_recursive(json_array: List[Any], value: Any) -> int: """ Count the occurrence of a specific value in a JSON array, including nested structures. Args: json_array (Li...
code_exercise_27k
23,594
Write a Python function to calculate the sum of the digits of a given number using recursion. The function should handle both positive and negative integers. If the input number is negative, the function should return the sum of the digits of the absolute value of the number. The code should start with: ```python def ...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits(number: int) -> int: """ Calculate the sum of the digits of a given number using recursion. Args: number (int): The number whose digits sum needs to be calculated. Returns: int: The su...
code_exercise_27k
23,597
Write a Python function to check 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_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_descending(lst: List[int]) -> bool: """ Check if a list is sorted in descending order. Parameters: lst (List[int]): Input list to be checked. Returns: bool: True if the list is s...
code_exercise_27k
23,607
Write a Python function to count the number of trailing zeros in the factorial of a given number `n`. The function should efficiently compute the number of trailing zeros without calculating the factorial itself, which can be very large for even moderately large `n`. The code should start with: ```python def count_tra...
Here is the Python code to solve the given problem in the markdown block: ```python def count_trailing_zeros(n: int) -> int: """ Count the number of trailing zeros in the factorial of a given number n. Args: n (int): The number whose factorial's trailing zeros are to be counted. Returns: ...
code_exercise_27k
23,608
Write a Python function to find the most frequently occurring value in a specific attribute of a JSON array of objects. The function should handle cases where the attribute might not exist in some objects and should return `None` if the JSON array is empty or if no attribute values are found. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any, Optional from collections import Counter def find_most_frequent(json_array: List[dict], attribute: str) -> Optional[Any]: """ Find the most frequently occurring value in a specific attribute of a J...
code_exercise_27k
23,617
Write a Python function to find the largest and smallest numbers in a given list of integers. The function should return a tuple containing the largest and smallest numbers. If the input list is empty, the function should raise a `ValueError` with the message "List should not be empty." 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 def find_largest_smallest(numbers: List[int]) -> Tuple[int, int]: """ Find the largest and smallest numbers in a list of integers. Args: numbers (List[int]): A list of integers. ...
code_exercise_27k
23,620
Write a Python function to optimize the placement of nodes in a graph using the Bellman-Ford algorithm. The function should return the minimum distances from the source node to all other nodes in the graph. If the graph contains a negative cycle, the function should raise a `ValueError`. The code should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict from sys import maxsize def optimize_placement(graph: Dict[str, Dict[str, int]], source: str) -> Dict[str, int]: """ Optimize the placement of nodes in a graph using the Bellman-Ford algorithm. Args...
code_exercise_27k
23,624
Write a Python function to find the unique values in a specific attribute of a JSON array of objects. The function should handle the following: - Accept a JSON array of objects and an attribute name as input. - Return a set containing the unique values of the specified attribute. - Raise a `ValueError` if the input JSO...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Set def find_unique_values(json_array: List[Dict], attribute: str) -> Set: """ Find the unique values in a specific attribute of a JSON array of objects. Args: json_array (List[Dict])...
code_exercise_27k
23,627
Write a Python function to determine if a given number is a narcissistic number. A narcissistic number (also known as a pluperfect number, an Armstrong number, or a plus perfect number) is a number that is equal to the sum of its own digits, each raised to the power of the number of digits. The code should start with:...
Here is the Python code to solve the given problem in the markdown block: ```python def is_narcissistic_number(num: int) -> bool: """ Determine if a given number is a narcissistic number. A narcissistic number is a number that is equal to the sum of its own digits, each raised to the power of the numbe...
code_exercise_27k
23,632
Write a Python function to remove all duplicate elements from a given list while preserving the order of the elements. The function should return a new list with unique elements in the order they first appear in the original list. The code should start with: ```python from typing import List def remove_duplicates_pre...
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 duplicate elements from a list while preserving the order of the elements. Args: lst (List[int]): The input list...
code_exercise_27k
23,638
Write a Python function to check if a given string contains only uppercase letters. The function should return `True` if the string contains only uppercase letters, and `False` otherwise. The function should handle strings with spaces and special characters, returning `False` if any character is not an uppercase letter...
Here is the Python code to solve the given problem in the markdown block: ```python def is_all_uppercase(string: str) -> bool: """ Check if a string contains only uppercase letters. Args: string (str): The string to be checked. Returns: bool: True if the string contains only uppercase ...
code_exercise_27k
23,657
Write a Python function to check if the elements of a list are in strictly ascending order. A list is considered strictly ascending if each element is greater than the previous element. The function should return `True` if the list is strictly ascending, and `False` otherwise. The code should start with: ```python fro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_strictly_ascending(lst: List[int]) -> bool: """ Check if the elements of a list are in strictly ascending order. Args: lst (List[int]): A list of integers to be checked. Returns:...
code_exercise_27k
23,660
Write a Python function to find the sum of all numeric values in a given dictionary. The dictionary may contain keys of any type, but all values must be numeric (either integers or floats). If any value is not numeric, the function should raise a `ValueError`. The function should also raise a `TypeError` if the input i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sum_of_numeric_values(dictionary: Dict) -> float: """ Calculate the sum of all numeric values in the given dictionary. Args: dictionary (dict): A dictionary with numeric values. Ret...
code_exercise_27k
23,666
Write a Python function to check if a given number is a palindrome using recursion. The function should take an integer as input and return a boolean indicating whether the number is a palindrome. A number is considered a palindrome if it reads the same backward as forward. The code should start with: ```python def is...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome_recursive(n: int) -> bool: """ Check if a given number is a palindrome using recursion. Args: n (int): The number to be checked. Returns: bool: True if the number is a palindrome, Fals...
code_exercise_27k
23,678
Write a Python function to find the common elements between three lists. The function should return a list containing the common elements between the three input lists. The code should start with: ```python from typing import List def find_common_elements(list1: List[int], list2: List[int], list3: List[int]) -> List[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_common_elements(list1: List[int], list2: List[int], list3: List[int]) -> List[int]: """ Find the common elements between three lists. Args: list1 (List[int]): The first list. ...
code_exercise_27k
23,680
Write a Python function to count the number of vowels and consonants in a given string. The function should be case-insensitive and should only count alphabetic characters. The function should return a tuple containing the count of vowels and consonants respectively. The code should start with: ```python def count_vow...
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels_consonants(string: str) -> tuple: """ Count the number of vowels and consonants in a given string. Args: string (str): The input string. Returns: tuple: A tuple containing the count of ...
code_exercise_27k
23,684
Write a Python function to calculate the sum of all elements in a given multidimensional list. The function should handle lists of any depth and structure, including nested lists. The code should start with: ```python from typing import List def sum_multidimensional_list(my_list: List) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def sum_multidimensional_list(my_list: List) -> int: """ Calculate the sum of all elements in a given multidimensional list. Args: my_list (list): The input multidimensional list. ...
code_exercise_27k
23,756
Write a Python function to find the maximum length subarray with equal number of 0s and 1s in a given binary array. The function should use a hash map (dictionary) to achieve this efficiently. The code should start with: ```python from typing import List def max_length_subarray_with_equal_0s_1s(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_length_subarray_with_equal_0s_1s(arr: List[int]) -> int: """ Find the maximum length subarray with equal number of 0s and 1s in a given binary array. Args: arr (List[int]): A list of...