source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
python_sharegpt_23k
5,699
Write a Python function to flatten a given array of lists and filter out the elements that are divisible by both 2 and 3. The function should return a list containing only the elements that meet the criteria. The code should start with: ```python from typing import List def flatten_and_filter_divisible_by_two_and_thr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flatten_and_filter_divisible_by_two_and_three(lst: List[List[int]]) -> List[int]: """ Flattens a given array of lists and filters out the elements that are divisible by both 2 and 3. Args: ...
python_sharegpt_23k
5,703
Write a Python function to calculate the nth Fibonacci number, where n is a prime number greater than 2. The function should raise a `ValueError` if the input is not a prime number or if it is less than or equal to 2. The code should start with: ```python def get_nth_fibonacci_prime(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def get_nth_fibonacci_prime(n: int) -> int: """ Calculate the nth Fibonacci number for a prime number greater than 2. Args: n (int): The position in the Fibonacci sequence, which must be a prime number greater than ...
python_sharegpt_23k
5,705
Write a Python function to check if a given string has all unique characters. The function should have a time complexity of O(n) and a space complexity of O(1). The function should handle strings with ASCII characters only. The code should start with: ```python def has_unique_chars(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def has_unique_chars(string: str) -> bool: """ Check if a given string has all unique characters. Args: string (str): The input string to check for unique characters. Returns: bool: True if the string h...
python_sharegpt_23k
5,709
Write a Python function to calculate the sum of the numbers in a given list with the following constraints: - The solution should have a time complexity of O(n), where n is the length of the list. - The solution should not use any built-in Python functions or libraries that directly calculate the sum of a list. - The s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_list(numbers: List[int]) -> int: """ Calculate the sum of the numbers in the given list. Args: numbers (List[int]): The list of integers to sum. Returns: int: The sum...
python_sharegpt_23k
5,711
Write a Python function to count the number of unique elements in a given list. An element is considered unique if it appears exactly once in the list. The function should return a list of these unique elements. The code should start with: ```python from typing import List def count_unique_elements(my_list: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_elements(my_list: List[int]) -> List[int]: """ Counts the number of unique elements in a given list. An element is considered unique if it appears exactly once in the list. Args: ...
python_sharegpt_23k
5,714
Write a Python function to collect unique values from a list of dictionaries based on the "key" field. The "key" field must be a string with at least 3 characters. The function should return the unique values in descending order based on the "price" field. If two values have the same price, they should be sorted in asc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def collect_unique_values(lst: List[Dict[str, Union[str, int, float]]]) -> List[str]: """ Collects unique values from a list of dictionaries based on the "key" field. The "key" field mus...
python_sharegpt_23k
5,717
Write a Python function to generate a specified number of unique random integers within a given range. The function should ensure that each generated number is unique and not already present in a provided list of existing numbers. The code should start with: ```python from typing import List import random def generat...
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_numbers(existing_numbers: List[int], range_start: int, range_end: int, desired_count: int) -> List[int]: """ Generates a specified number of unique random integer...
python_sharegpt_23k
5,718
Write a Python function to find the most common element in a given list without using any built-in functions or methods that directly solve the problem, such as the `collections` module or the `Counter` class. You must implement your own logic to solve the problem. The function 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, Any def find_most_common_element(lst: List[Any]) -> Any: """ Finds the most common element in a given list without using built-in functions or methods. Args: lst (List[Any]): The list of el...
python_sharegpt_23k
5,720
Write a Python function to format a given number to a specified number of decimal places. The function should take two parameters: the number to be formatted and the desired number of decimal places. The function should return the formatted number as a string. The code should start with: ```python def format_number_to...
Here is the Python code to solve the given problem in the markdown block: ```python def format_number_to_decimal_places(number: float, decimal_places: int) -> str: """ Formats a given number to a specified number of decimal places. Args: number (float): The number to be formatted. decimal_p...
python_sharegpt_23k
5,723
Write a Python function to generate a list of odd numbers within a specified range `[start, end]`. The function should handle cases where `start` and `end` are not necessarily odd, and should include both `start` and `end` if they are odd. The code should start with: ```python from typing import List def generate_odd_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_odd_numbers(start: int, end: int) -> List[int]: """ Generate a list of odd numbers within the specified range [start, end]. Args: start (int): The starting value of the range (i...
python_sharegpt_23k
5,727
Write a Python function to reverse an array of integers and return a new array without modifying the original array. The function should take a list of integers as input and return a new list with the elements in reverse order. The original list should remain unchanged. The code should start with: ```python from typin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array(nums: List[int]) -> List[int]: """ Reverses an array of integers and returns a new array without modifying the original array. Args: nums (List[int]): The original array of...
python_sharegpt_23k
5,733
Write a Python function to check if a given string contains a specified substring. The function should return `True` if the substring is found within the main string, and `False` otherwise. The function should have a time complexity of O(n), where n is the length of the main string, and a space complexity of O(1). The...
Here is the Python code to solve the given problem in the markdown block: ```python def substring_check(haystack: str, needle: str) -> bool: """ Check if the given string `haystack` contains the substring `needle`. Args: haystack (str): The main string to search within. needle (str): The su...
python_sharegpt_23k
5,737
Write a Python function to determine if a given number \( N \) is a prime number. The function should return `True` if \( N \) is prime and `False` otherwise. The function should be efficient and handle edge cases such as \( N \) being less than 2. The code should start with: ```python import math def is_prime(N: int...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime(N: int) -> bool: """ Determine if a given number N is a prime number. Args: N (int): The number to check for primality. Returns: bool: True if N is prime, False otherwise. ...
python_sharegpt_23k
5,744
Write a Python function to count the occurrences of a given item in a list, including nested lists and dictionaries. The function should recursively traverse the list and any nested structures to count all occurrences of the item. The code should start with: ```python from typing import Any, List, Dict def count_occu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, List, Dict def count_occurrences(lst: List[Any], item: Any) -> int: """ Counts the occurrences of a given item in a list, including nested lists and dictionaries. Args: lst (List[Any]): The ...
python_sharegpt_23k
5,746
Write a Python function to remove and return an element from a given list at a specified index without using the built-in `pop()` function or slicing. The function should handle negative indices and ensure the list is modified in place. The code should start with: ```python from typing import List, Any def custom_pop...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def custom_pop(lst: List[Any], index: int = -1) -> Any: """ Remove and return an element from the list at the specified index without using the built-in `pop()` function or slicing. Args: ...
python_sharegpt_23k
5,747
Write a Python function to reverse the order of elements in a given list without using any built-in functions or methods that directly reverse a list (e.g., `reverse()` or slicing with negative steps). You can only use basic operations and control flow statements. 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 def reverse_list(lst: List[int]) -> List[int]: """ Reverses the order of elements in a given list without using built-in reverse functions or slicing. Args: lst (List[int]): The list to be r...
python_sharegpt_23k
5,751
Write a Python function to convert a binary string to its decimal equivalent without using built-in functions or libraries for conversion. The function should handle binary strings of up to 1000 characters and only contain '0's and '1's. The code should start with: ```python def binary_to_decimal(binary_string: str) ->...
Here is the Python code to solve the given problem in the markdown block: ```python def binary_to_decimal(binary_string: str) -> int: """ Converts a binary string to its decimal equivalent without using built-in conversion functions. Args: binary_string (str): The binary string to convert, containi...
python_sharegpt_23k
5,753
Write a Python function to group students into classes based on their major. Each student is represented by a dictionary with keys "name" (string) and "major" (string). The function should take a list of such student dictionaries and return a dictionary where the keys are the major names and the values are lists of stu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def group_students(student_list: List[Dict[str, str]]) -> Dict[str, List[str]]: """ Groups students into classes based on their major. Args: student_list (List[Dict[str, str]]): A list...
python_sharegpt_23k
5,754
Write a Python function to calculate the sum of the squares of three integers and return the result. The function should take three integers as input and return their sum of squares. The code should start with: ```python def sum_of_squares(a: int, b: int, c: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_squares(a: int, b: int, c: int) -> int: """ Calculate the sum of the squares of three integers. Args: a (int): The first integer. b (int): The second integer. c (int): The third integer. ...
python_sharegpt_23k
5,755
Write a Python function that takes a list of numbers and an optional argument specifying the number of decimal places for rounding. The function should return a dictionary where the keys are the numbers from the list and the values are their square roots rounded to the specified number of decimal places. The function s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union import math def square_root_dict(numbers: List[Union[int, float]], decimal_places: int = 2) -> Dict[Union[int, float], float]: """ Returns a dictionary where the keys are the numbers from th...
python_sharegpt_23k
5,758
Write a Python function to implement a recursive sorting algorithm for a given array of unique positive integers. The implementation should not use any built-in sorting functions or libraries. The function should start with: ```python from typing import List def recursive_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def recursive_sort(arr: List[int]) -> List[int]: """ Sorts a given array of unique positive integers using a recursive merge sort algorithm. Args: arr (List[int]): The array of unique positi...
python_sharegpt_23k
5,759
Write a Python function to reverse a given string without using any built-in string manipulation functions or methods. The function should have a complexity of O(n), where n is the length of the string. The function should handle edge cases such as empty strings and single-character strings. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(s: str) -> str: """ Reverses a given string without using any built-in string manipulation functions or methods. Args: s (str): The input string to be reversed. Returns: str: The reve...
python_sharegpt_23k
5,760
Write a Python function to remove all occurrences of a given substring from a string. The function should handle cases where the substring is an empty string or the input string is empty. The function should also be efficient and avoid unnecessary operations. The code should start with: ```python def remove_all_occurr...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_all_occurrences(input_string: str, substring: str) -> str: """ Removes all occurrences of a given substring from the input string. Args: input_string (str): The original string from which to remove the su...
python_sharegpt_23k
5,761
Write a Python function to calculate the sum of all the values in a given array, which may contain both positive and negative integers. The function should handle arrays of any length, including empty arrays. The code should start with: ```python from typing import List def calculate_array_sum(arr: List[int]) -> int: ...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def calculate_array_sum(arr: List[int]) -> int: """ Calculate the sum of all the values in the given array. Args: arr (List[int]): The array of integers to sum. Returns: int: ...
python_sharegpt_23k
5,762
Write a Python function to calculate the sum of the ages of all people in a given dictionary whose names start with the letter 'J' and are above 18 years old. The dictionary will have the following structure: ```python dictionary = { 'name': ['John', 'Jane', 'Jake'], 'age': [25, 22, 19] } ``` The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def sum_of_ages_starting_with_j(data: Dict[str, List[str]]) -> int: """ Calculate the sum of the ages of all people in the given dictionary whose names start with the letter 'J' and are above 18 ye...
python_sharegpt_23k
5,763
Write a Python function to generate a multiplication table up to 12 for a given number `n`. The function should return a list of lists where each inner list represents a row in the multiplication table. Each row should contain the products of the numbers from 1 to `n` multiplied by the row index (starting from 1). The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_multiplication_table(n: int) -> List[List[int]]: """ Generates a multiplication table up to 12 for a given number n. Args: n (int): The number up to which the multiplication tab...
python_sharegpt_23k
5,771
Write a Python function to detect if an array contains duplicate values and keep track of the indices of the duplicate values. The function should return a list of tuples where each tuple contains a duplicate value and its first occurrence index. The algorithm should be optimized to have a time complexity of O(n), wher...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_duplicates(nums: List[int]) -> List[Tuple[int, int]]: """ Detects duplicate values in the given list and returns a list of tuples where each tuple contains a duplicate value and its first...
python_sharegpt_23k
5,772
Write a Python function to merge two sorted lists into one sorted list in descending order. The function should efficiently merge the lists without using the built-in `sort` method. The code should start with: ```python from typing import List def merge_sorted_lists_descending(list1: List[int], list2: List[int]) -> Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_lists_descending(list1: List[int], list2: List[int]) -> List[int]: """ Merges two sorted lists into one sorted list in descending order. Args: list1 (List[int]): The first s...
python_sharegpt_23k
5,773
Write a Python function to determine if a given string is a valid URL based on specific criteria. The function should check if the input string satisfies the following conditions: - The string starts with either "http://" or "https://". - The string contains at least one dot (".") after the prefix. - The string does no...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_url(url: str) -> bool: """ Determines if a given string is a valid URL based on specific criteria. Args: url (str): The string to be validated as a URL. Returns: bool: True if the string is...
python_sharegpt_23k
5,775
Write a Python function to sort a given list in increasing order without using any built-in sorting functions or methods. The function should implement a sorting algorithm manually. The code should start with: ```python from typing import List def custom_sort(my_list: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def custom_sort(my_list: List[int]) -> List[int]: """ Sorts a given list in increasing order using a custom implementation of the Selection Sort algorithm. Args: my_list (List[int]): The lis...
python_sharegpt_23k
5,779
Write a Python function to filter and return a list of strings from a given list that have a length greater than 5 characters. The function should only consider items that are strings and ignore any other data types. The code should start with: ```python from typing import List def filter_long_strings(items: List[obj...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_long_strings(items: List[object]) -> List[str]: """ Filters and returns a list of strings from the given list that have a length greater than 5 characters. Args: items (List[objec...
python_sharegpt_23k
5,780
Write a Python function to find all indices of a specified element in a given list. The list may contain duplicates, and the element may appear multiple times. The function should return a list of all indices where the element is found. The code should start with: ```python from typing import List def find_all_indice...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_indices(my_list: List[str], target: str) -> List[int]: """ Find all indices of a specified element in a given list. Args: my_list (List[str]): The list in which to search for th...
python_sharegpt_23k
5,783
Write a Python function to convert a string to a list of characters without using any built-in string or list manipulation functions or methods (e.g., `split()`, `list()`, etc.). The function should have a time complexity of O(n), where n is the length of the string. The code should start with: ```python def string_to_...
Here is the Python code to solve the given problem in the markdown block: ```python def string_to_list(string: str) -> list: """ Converts a string to a list of characters without using built-in string or list manipulation functions. Args: string (str): The input string to be converted. Returns...
python_sharegpt_23k
5,785
Write a Python function to create a dictionary of the declared states of India, sorted in alphabetical order by state names. Each state should be a key, and its value should be a list of the top 5 major cities in that state. The function should return the sorted dictionary. 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 Dict, List def create_sorted_state_city_dict() -> Dict[str, List[str]]: """ Creates a dictionary of the declared states of India, sorted in alphabetical order by state names. Each state is a key, and its ...
python_sharegpt_23k
5,786
Write a Python function to determine if two given strings are anagrams, considering the following requirements: 1. The function should be case-sensitive. 2. The function should ignore spaces and special characters. 3. The function should return `True` if the strings are anagrams, otherwise `False`. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python def is_anagram(str1: str, str2: str) -> bool: """ Determine if two strings are anagrams, considering case sensitivity and ignoring spaces and special characters. Args: str1 (str): The first string to compare. ...
python_sharegpt_23k
5,787
Write a Python function to round each number in a given list to 4 decimal places, maintaining the original order of the list. The input list can contain duplicate numbers. The function should return a new list with the rounded numbers. The code should start with: ```python from typing import List def round_numbers_to...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def round_numbers_to_four_decimals(numbers: List[float]) -> List[float]: """ Rounds each number in the input list to 4 decimal places and returns a new list with the rounded numbers. Args: n...
python_sharegpt_23k
5,789
Write a Python function to generate the Cartesian product of two sets. The Cartesian product of two sets \( A \) and \( B \) is defined as the set of all possible ordered pairs \( (a, b) \) where \( a \) is an element of \( A \) and \( b \) is an element of \( B \). The function should take two sets as input and return...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Set def cartesian_product(A: Set, B: Set) -> Set: """ Generate the Cartesian product of two sets A and B. The Cartesian product of two sets A and B is defined as the set of all possible ordered pairs (a,...
python_sharegpt_23k
5,793
Write a Python function to sort a list of positive integers in ascending order and ensure the list contains only positive integers. The function should raise a `ValueError` if any element in the list is not a positive integer. The code should start with: ```python from typing import List def sort_positive_integers(ls...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_positive_integers(lst: List[int]) -> List[int]: """ Sorts a list of positive integers in ascending order. Args: lst (List[int]): The list of integers to be sorted. Returns: ...
python_sharegpt_23k
5,797
Write a Python function to filter and return a list of strings from a given array of strings that have a length greater than a specified integer `n`, while maintaining the order of the original array. The function should start with: ```python from typing import List def filter_strings_by_length(data: List[str], n: int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_strings_by_length(data: List[str], n: int) -> List[str]: """ Filters and returns a list of strings from the given array that have a length greater than the specified integer `n`. Args: ...
python_sharegpt_23k
5,803
Write a Python function to convert a given integer to its binary representation. The function should handle both positive and zero integers. The code should start with: ```python def decimal_to_binary(number: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def decimal_to_binary(number: int) -> str: """ Converts a given non-negative integer to its binary representation. Args: number (int): The non-negative integer to be converted. Returns: str: The binar...
python_sharegpt_23k
5,805
Write a Python function to implement a binary search algorithm that finds the index of a specific target value in a sorted list. If the target value is not found, the function should return -1. The function should be efficient and handle edge cases such as an empty list or a target value that is not present in the 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 a binary search to find the index of a target value in a sorted list. Args: arr (List[int]): A sorted list of integers. ...
python_sharegpt_23k
5,808
Write a Python function to generate a specified number of random integers between a given range, ensuring that none of the generated numbers are divisible by a specified divisor. The function should return a list of the generated numbers. The code should start with: ```python from typing import List import random def...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_numbers(count: int, lower_bound: int, upper_bound: int, divisor: int) -> List[int]: """ Generate a specified number of random integers between a given range, ensuring th...
python_sharegpt_23k
5,810
Write a Python function to convert a list of integers into a comma-separated string representation of the integers. The function should handle lists of varying lengths, including empty lists. The code should start with: ```python from typing import List def list_to_string(lst: List[int]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def list_to_string(lst: List[int]) -> str: """ Converts a list of integers into a comma-separated string representation. Args: lst (List[int]): The list of integers to be converted. Ret...
python_sharegpt_23k
5,811
Write a Python function to filter a list of integers and return a new list containing only the elements that are greater than a specified target integer. The function should be efficient and handle edge cases such as an empty list or a target integer that is greater than all elements in the list. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_greater_than_target(numbers: List[int], target: int) -> List[int]: """ Filters a list of integers and returns a new list containing only the elements that are greater than the specified target...
python_sharegpt_23k
5,814
Write a Python function to sort an array in ascending order using the bubble sort algorithm. The function should correctly handle the provided code snippet's error and implement the sorting algorithm as intended. The code should start with: ```python from typing import List def sort_array(arr: List[int]) -> List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_array(arr: List[int]) -> List[int]: """ Sorts an array in ascending order using the bubble sort algorithm. Args: arr (List[int]): The array to be sorted. Returns: List[...
python_sharegpt_23k
5,816
Write a Python function to find the minimum and maximum values from a given list of integers in one line, ensuring a time complexity of O(n log n) and a space complexity of O(1). The function should return a tuple containing the minimum and maximum values. 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, Tuple def get_min_max_efficient(nums: List[int]) -> Tuple[int, int]: """ Find the minimum and maximum values from a list of integers in one line, ensuring a time complexity of O(n log n) and a space...
python_sharegpt_23k
5,817
Write a Python function that takes in a list of words as input and returns a dictionary where the keys are the words and the values are the lengths of the words. The function should manually calculate the length of each word without using dictionary comprehension or any built-in Python functions like `len()`. The code...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def word_length_dict(words: List[str]) -> Dict[str, int]: """ Creates a dictionary where the keys are words from the input list and the values are the lengths of the words. The length of each w...
python_sharegpt_23k
5,819
Write a Python function to implement a binary search algorithm that works with a list of integers. The function should return the index of the target number if it is present in the list, otherwise, it should return -1. The list is guaranteed to be sorted in ascending order. 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 binary_search(arr: List[int], target: int) -> int: """ Perform a binary search on a sorted list of integers to find the index of the target number. Args: arr (List[int]): A sorted list o...
python_sharegpt_23k
5,821
Write a Python function to implement binary search in a sorted array. The function should return `True` if the target element is found in the array, and `False` otherwise. The input array is guaranteed to be sorted in ascending order and can contain duplicate elements. The maximum length of the input array is 10^6. Th...
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) -> bool: """ Implements binary search to determine if a target element is present in a sorted array. Args: arr (List[int]): A sorted list of in...
python_sharegpt_23k
5,824
Write a Python function to create a nested dictionary with specified key-value pairs. The dictionary should include simple integer values for keys "a", "b", and "c". Additionally, it should include nested dictionaries for keys "d" and "e". The nested dictionary for key "d" should contain the key-value pairs "x": 10 and...
Here is the Python code to solve the given problem in the markdown block: ```python def create_nested_dictionary() -> dict: """ Creates a nested dictionary with specified key-value pairs. Returns: dict: A dictionary containing simple integer values for keys "a", "b", and "c", and nest...
python_sharegpt_23k
5,826
Write a Python function to sort a given list of integers in descending order using the insertion sort algorithm. The function should modify the list in place and return the sorted list. The code should start with: ```python from typing import List def insertion_sort_descending(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def insertion_sort_descending(arr: List[int]) -> List[int]: """ Sorts the given list of integers in descending order using the insertion sort algorithm. Args: arr (List[int]): The list of in...
python_sharegpt_23k
5,827
Write a Python function to calculate the minimum value of a given set of numbers using a recursive algorithm. The function should split the list into two halves, recursively find the minimum value in each half, and then return the smaller of the two minimum values. 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 def find_min_recursive(numbers: List[int]) -> int: """ Calculate the minimum value of a given set of numbers using a recursive algorithm. Args: numbers (List[int]): A list of integers from w...
python_sharegpt_23k
5,829
Write a Python function to compute the Euclidean distance between two points in a 2D plane. The function should handle inputs in the form of decimal numbers and provide the output rounded to two decimal places. The code should start with: ```python from typing import Tuple import math def euclidean_distance(p1: Tuple[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple import math def euclidean_distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float: """ Compute the Euclidean distance between two points in a 2D plane. Args: p1 (Tuple[float, fl...
python_sharegpt_23k
5,832
Write a Python function to calculate the running average of numbers in a given array that are divisible by 3. Any numbers not divisible by 3 should be excluded from the calculation. The function should handle cases where no numbers are divisible by 3 by returning 0. The code should start with: ```python from typing im...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def running_average_divisible_by_3(arr: List[int]) -> float: """ Calculate the running average of numbers in a given array that are divisible by 3. Args: arr (List[int]): The array of intege...
python_sharegpt_23k
5,837
Write a Python function to find the longest common contiguous subarray between two sorted integer arrays. The function should have a time complexity of O(n) and a space complexity of O(1). The function should return the longest common contiguous subarray as a list. 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 find_longest_common_subarray(arr1: List[int], arr2: List[int]) -> List[int]: """ Find the longest common contiguous subarray between two sorted integer arrays. Args: arr1 (List[int]): Th...
python_sharegpt_23k
5,838
Write a Python function to generate a list that contains only the non-unique elements from a given list. The function should have a time complexity of O(n^2) and should not use any built-in functions or libraries for counting or checking membership. The code should start with: ```python from typing import List def ge...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_non_unique_elements(lst: List[int]) -> List[int]: """ Generate a list that contains only the non-unique elements from the given list. Args: lst (List[int]): The input list from which...
python_sharegpt_23k
5,839
Write a Python function to categorize a given list of integers into odd and even numbers, and return the results in ascending order. The function should only use a single loop for efficiency. The code should start with: ```python from typing import List, Tuple def categorize_numbers(numbers: List[int]) -> Tuple[List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def categorize_numbers(numbers: List[int]) -> Tuple[List[int], List[int]]: """ Categorizes a given list of integers into odd and even numbers, and returns the results in ascending order. Args...
python_sharegpt_23k
5,843
Write a Python function to determine if a given number is a palindrome. The function should work for numbers of any size and should have a time complexity of O(log n), where n is the number of digits in the input number. The function should not convert the number to a string. The code should start with: ```python def ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome_number(num: int) -> bool: """ Determines if a given number is a palindrome without converting it to a string. Args: num (int): The number to check for palindrome property. Returns: boo...
python_sharegpt_23k
5,845
Write a Python function to find all duplicate elements in a given list and return them in ascending order. The function should efficiently track elements that have been seen before and avoid adding duplicates to the result list more than once. The code should start with: ```python from typing import List def find_dup...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_duplicates(arr: List[int]) -> List[int]: """ Find all duplicate elements in the given list and return them in ascending order. Args: arr (List[int]): The list of integers to search ...
python_sharegpt_23k
5,854
Write a Python function to create a frequency table from a list of integers. The function should return a dictionary where the keys are the unique integers from the list, and the values are the number of times each integer appears in the list. The function should be optimized for performance, especially for large input...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def create_frequency_table(lst: List[int]) -> Dict[int, int]: """ Creates a frequency table from a list of integers. Args: lst (List[int]): A list of integers for which to create the f...
python_sharegpt_23k
5,856
Write a Python function to merge two given sorted arrays and remove duplicates. The merged array should be sorted in ascending order. The function should meet the following requirements: - Time Complexity: O(n log n), where n is the total number of elements in the merged array. - Space Complexity: O(n), where n is the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_and_remove_duplicates(arr1: List[int], arr2: List[int]) -> List[int]: """ Merge two sorted arrays and remove duplicates. The merged array is sorted in ascending order. Args: arr1 (...
python_sharegpt_23k
5,862
Write a Python function to print the elements of a given list in descending order. The function should take a list of integers as input and print each element in descending order without using any built-in sorting functions. The code should start with: ```python from typing import List def print_descending_order(numbe...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def print_descending_order(numbers: List[int]) -> None: """ Prints the elements of the given list in descending order. Args: numbers (List[int]): The list of integers to be printed in desc...
python_sharegpt_23k
5,864
Write a Python function to multiply two matrices. The input matrices can have different dimensions, but they will always be compatible for multiplication. The function should return the resulting matrix. The function signature should be: ```python from typing import List def matrix_multiply(matrixA: List[List[int]], m...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def matrix_multiply(matrixA: List[List[int]], matrixB: List[List[int]]) -> List[List[int]]: """ Multiplies two matrices and returns the resulting matrix. Args: matrixA (List[List[int]]): The...
python_sharegpt_23k
5,865
Write a Python function to output the Unicode value of a given character. The function should take a single character as input and return its Unicode value as an integer. If the input is not a single character, the function should return `None`. The code should start with: ```python def get_unicode_value(character: st...
Here is the Python code to solve the given problem in the markdown block: ```python def get_unicode_value(character: str) -> int: """ Returns the Unicode value of a given character. Args: character (str): The character for which to find the Unicode value. Returns: int: The Unicode valu...
python_sharegpt_23k
5,866
Write a Python function to find all common elements between two lists, ignoring duplicates in both lists, and return the common elements in ascending order along with the count of common elements. The input lists can contain both positive and negative integers and can have a maximum length of 1000 elements. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_common_elements(list1: List[int], list2: List[int]) -> Tuple[List[int], int]: """ Find all common elements between two lists, ignoring duplicates in both lists, and return the common ...
python_sharegpt_23k
5,870
Write a Python function to create a NumPy array filled with zeros, where the size of the array is a multiple of 5. The array should then be reshaped into a 2D array with exactly 5 columns. The function should handle any valid multiple of 5 as the input size. The code should start with: ```python import numpy as np de...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_zero_array(size: int) -> np.ndarray: """ Create a NumPy array filled with zeros and reshape it into a 2D array with 5 columns. Args: size (int): The size of the array, which must be a ...
python_sharegpt_23k
5,872
Write a Python function to generate an array containing the squares of numbers from `n` to `m` (inclusive). The function should validate that both `n` and `m` are positive integers and ensure that `m` is greater than or equal to `n`. If the input is invalid, the function should return an appropriate error message. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def generate_squares(n: int, m: int) -> Union[List[int], str]: """ Generate an array containing the squares of numbers from n to m (inclusive). Args: n (int): The starting number (inc...
python_sharegpt_23k
5,873
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 2, which are not prime by definition. The code should start with: ```python def is_prime(num: int) ->...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Determines if a given number is a prime number. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. "...
python_sharegpt_23k
5,874
Write a Python function to calculate the sum of all positive elements in a given list of integers. The function should exclude any negative numbers from the summation. The code should start with: ```python from typing import List def sum_positive_elements(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_positive_elements(arr: List[int]) -> int: """ Calculate the sum of all positive elements in a given list of integers. Args: arr (List[int]): The list of integers from which to sum th...
python_sharegpt_23k
5,876
Write a Python function to find the two smallest prime numbers in a given array such that their sum equals a specified value. The array will only contain positive integers. If no such pair exists, return a message indicating that no pair was found. The code should start with: ```python from typing import List, Union ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def is_prime(num: int) -> bool: """ Check if a number is prime. Args: num (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """...
python_sharegpt_23k
5,877
Write a Python function to determine whether a given string is a valid IPv4 address. An IPv4 address consists of four decimal numbers (each between 0 and 255) separated by dots. Leading zeros in each octet are not allowed. The code should start with: ```python def is_valid_ipv4(ip_address: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_ipv4(ip_address: str) -> bool: """ Determine whether the given string is a valid IPv4 address. Args: ip_address (str): The string to be checked for IPv4 validity. Returns: bool: True if the...
python_sharegpt_23k
5,878
Write a Python function to sort an array of integers in descending order using the bubble sort algorithm. The function should have a time complexity of O(n^2) in the worst case and a space complexity of O(1). You are not allowed to use any built-in sorting functions or libraries. The code should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort_descending(arr: List[int]) -> List[int]: """ Sorts an array of integers in descending order using the bubble sort algorithm. Args: arr (List[int]): The array of integers to b...
python_sharegpt_23k
5,881
Write a Python function to find the longest palindrome substring within a given string that contains only lowercase alphabets. The function should return the starting and ending indices of the longest palindrome substring. If there are multiple longest palindromes with the same length, the function should return the on...
Here is the Python code to solve the given problem in the markdown block: ```python def find_longest_palindrome(string: str) -> tuple: """ Find the longest palindrome substring within a given string and return its starting and ending indices. Args: string (str): The input string containing only low...
python_sharegpt_23k
5,886
Write a Python function to safely convert a string to a float, handling potential errors such as invalid numeric formats. If the conversion fails, the function should return `None`. The code should start with: ```python def safe_float_conversion(string_number: str) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def safe_float_conversion(string_number: str) -> float: """ Safely converts a string to a float, handling invalid numeric formats. Args: string_number (str): The string to be converted to a float. Returns: ...
python_sharegpt_23k
5,894
Write a Python function to concatenate two given strings with a specified delimiter and return the resulting string. The function should handle cases where the delimiter is an empty string. The code should start with: ```python def concatenate_strings_with_delimiter(str1: str, str2: str, delimiter: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def concatenate_strings_with_delimiter(str1: str, str2: str, delimiter: str) -> str: """ Concatenates two strings with a specified delimiter and returns the resulting string. Args: str1 (str): The first string to co...
python_sharegpt_23k
5,901
Write a Python function to convert an integer to a string, ensuring that the resulting string contains only numeric characters and has a length of exactly 5 digits. If the input is not an integer or contains non-numeric characters, return an error message. If the length of the integer string is less than 5, pad it with...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_fixed_length_string(integer: int) -> str: """ Converts an integer to a string with exactly 5 digits. Args: integer (int): The integer to be converted. Returns: str: A string of exactly 5 ...
python_sharegpt_23k
5,906
Write a Python function to remove leading zeros from a string, but only if they are followed by a non-zero digit. The function should not remove zeros that are followed by another zero or a non-digit character. The code should start with: ```python def remove_leading_zeros(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_leading_zeros(string: str) -> str: """ Removes leading zeros from a string, but only if they are followed by a non-zero digit. Args: string (str): The input string from which to remove leading zeros. ...
python_sharegpt_23k
5,907
Write a Python function to calculate the average score of students based on their immutable student records. The student records are stored in a dictionary where the keys are tuples representing the student's ID and name, and the values are their scores. The function should handle cases where the dictionary might be em...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple def calculate_average_score(student_records: Dict[Tuple[int, str], int]) -> float: """ Calculate the average score of students based on their immutable student records. Args: student_...
python_sharegpt_23k
5,909
Write a Python function to concatenate two given strings with a specified separator and return the resulting string. The function should handle cases where the separator is an empty string. The code should start with: ```python def concatenate_strings(string1: str, string2: str, separator: str = " ") -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def concatenate_strings(string1: str, string2: str, separator: str = " ") -> str: """ Concatenates two strings with a specified separator and returns the resulting string. Args: string1 (str): The first string to co...
python_sharegpt_23k
5,912
Write a Python function to add two matrices. The function should take two matrices represented as lists of lists of integers and return a new matrix that is the sum of the two input matrices. The matrices will have the same dimensions, meaning they will have the same number of rows and the same number of columns in eac...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def add_matrices(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: """ Adds two matrices represented as lists of lists of integers. Args: a (List[List[int]]): The first matrix. ...
python_sharegpt_23k
5,915
Write a Python function to find the minimum element in a given list of integers. The function should handle lists with at least one element, negative numbers, and duplicates. The code should start with: ```python from typing import List def find_minimum(lst: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def find_minimum(lst: List[int]) -> int: """ Find the minimum element in a given list of integers. Args: lst (List[int]): The list of integers from which to find the minimum element. ...
python_sharegpt_23k
5,918
Write a Python function to combine the elements of two lists of equal length into a dictionary. The dictionary should only include elements from the first list (`list1`) that have a corresponding element in the second list (`list2`) that is divisible by 2. If there is a repeating element in `list1`, it should be stored...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def combine_lists(list1: List[str], list2: List[int]) -> Dict[str, List[int]]: """ Combines elements of two lists into a dictionary based on the condition that the corresponding element in list2 is...
python_sharegpt_23k
5,919
Write a Python function to reverse a given string without using any built-in string reversal functions or methods. The function should iterate through the string and construct the reversed string manually. The code should start with: ```python def reverse_string(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(string: str) -> str: """ Reverses a given string without using any built-in string reversal functions or methods. Args: string (str): The input string to be reversed. Returns: str: Th...
python_sharegpt_23k
5,925
Write a Python function to calculate the average of an array of integers. The function should handle arrays with any number of elements, including empty arrays. If the array is empty, the function should return 0. The code should start with: ```python from typing import List def calculate_average(array: List[int]) -> ...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def calculate_average(array: List[int]) -> float: """ Calculate the average of an array of integers. Args: array (List[int]): The array of integers for which to calculate the average. ...
python_sharegpt_23k
5,926
Write a Python function to sort a given array in ascending order using the Gnome sort algorithm. The function should use a constant amount of extra space and have a time complexity of O(n^2), where n is the size of the array. The function should start with: ```python from typing import List def gnome_sort(array: List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def gnome_sort(array: List[int]) -> List[int]: """ Sorts the given array in ascending order using the Gnome sort algorithm. Args: array (List[int]): The array to be sorted. Returns: ...
python_sharegpt_23k
5,931
Write a Python function to subtract two positive integers and return the result. The input numbers are guaranteed to be positive integers and will not exceed \(10^9\). The function should handle the subtraction operation efficiently and return the correct result. The code should start with: ```python def subtract_numb...
Here is the Python code to solve the given problem in the markdown block: ```python def subtract_numbers(a: int, b: int) -> int: """ Subtracts the second integer from the first integer and returns the result. Args: a (int): The first positive integer. b (int): The second positive integer. ...
python_sharegpt_23k
5,933
Write a Python function to calculate the sum of the absolute values of two integers. The function should take two integers as input and return their sum of absolute values. The code should start with: ```python def sum_of_absolute_values(num1: int, num2: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_absolute_values(num1: int, num2: int) -> int: """ Calculate the sum of the absolute values of two integers. Args: num1 (int): The first integer. num2 (int): The second integer. Returns: ...
python_sharegpt_23k
5,935
Write a Python function to calculate the sum of all numerical elements in a given list, which may contain nested lists. The function should handle lists of arbitrary depth and should ignore non-numeric elements. The code should start with: ```python from typing import List, Union def sum_nested_list(lst: List[Union[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def sum_nested_list(lst: List[Union[int, float, List]]) -> Union[int, float]: """ Calculate the sum of all numerical elements in a given list, which may contain nested lists. Args: ls...
python_sharegpt_23k
5,936
Write a Python function to reverse a given string without using any built-in string reversal functions or methods. The function should iterate through the string and construct the reversed string manually. The code should start with: ```python def reverse_string(input_str: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(input_str: str) -> str: """ Reverses the given string without using any built-in string reversal functions or methods. Args: input_str (str): The string to be reversed. Returns: str: ...
python_sharegpt_23k
5,937
Write a Python function to count the occurrences of each character in a given string. The function should return a dictionary where the keys are characters and the values are the counts of those characters in the string. The function should handle any string input, including strings with special characters, spaces, and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_character_occurrences(input_string: str) -> Dict[str, int]: """ Counts the occurrences of each character in the given string. Args: input_string (str): The string to analyze. ...
python_sharegpt_23k
5,939
Write a Python function to implement a custom sorting algorithm that sorts a list of integers in ascending order. The algorithm should have a time complexity of O(nlogn) and should not use any built-in sorting functions or data structures. The input list will contain up to 100,000 integers ranging from -1,000,000 to 1,...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def custom_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the Merge Sort algorithm. Args: arr (List[int]): The list of integers to be sorted. R...
python_sharegpt_23k
5,941
Write a Python function to calculate the area of a triangle given its base and height. The function should handle the input as integers or floats and return the area as a float. The code should start with: ```python def calculate_triangle_area(base: float, height: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def calculate_triangle_area(base: float, height: float) -> float: """ Calculate the area of a triangle given its base and height. Args: base (float): The base of the triangle. height (float): The height of...
python_sharegpt_23k
5,942
Write a Python function to generate a list of prime numbers within a given range [start, end]. The function should return a list of all prime numbers in that range. The code should start with: ```python from typing import List def generate_primes_in_range(start: int, end: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def is_prime(num: int) -> bool: """ Helper function to check if a number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the number is pri...
python_sharegpt_23k
5,943
Write a Python function to sort an array of integers in descending order and return the sorted array. The array can contain both positive and negative numbers. The function should handle any size of input array. The code should start with: ```python from typing import List def sort_descending(arr: List[int]) -> List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_descending(arr: List[int]) -> List[int]: """ Sorts the given array of integers in descending order and returns the sorted array. Args: arr (List[int]): The array of integers to be s...
python_sharegpt_23k
5,945
Write a Python function to search for the first occurrence of a target element in a given array and return its index. If the target is not found, return -1. The array may contain duplicate elements. The code should start with: ```python from typing import List def search_first_occurrence(arr: List[int], target: int) ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def search_first_occurrence(arr: List[int], target: int) -> int: """ Searches for the first occurrence of a target element in the given array and returns its index. If the target is not found, return...
python_sharegpt_23k
5,947
Write a Python function to rotate a given square matrix by 90 degrees in a counterclockwise direction. The matrix is represented as a list of lists, where each inner list represents a row of the matrix. The function should modify the matrix in place and return the rotated matrix. The code should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def rotate_matrix_counterclockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotate a given square matrix by 90 degrees in a counterclockwise direction. Args: matrix (List[List[int]])...
python_sharegpt_23k
5,948
Write a Python function to find the maximum number in an array without using the built-in `max()` function, ensuring that the solution has a time complexity of O(n). The function should start with: ```python from typing import List def find_max_in_array(array: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_in_array(array: List[int]) -> int: """ Find the maximum number in an array without using the built-in max() function. Args: array (List[int]): The array of integers from which t...
python_sharegpt_23k
5,950
Write a Python function to calculate the square root of a given number using the `math` module. The function should handle both positive and negative numbers, returning `None` for negative inputs since the square root of a negative number is not a real number. The code should start with: ```python import math def calc...
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_square_root(number: float) -> float: """ Calculate the square root of a given number. Args: number (float): The number for which to calculate the square root. Returns: float: ...
python_sharegpt_23k
5,952
Write a Python function to calculate the sum of all positive numbers in a given list of integers. The function should ignore any negative numbers and return the sum of only the positive numbers. The code should start with: ```python from typing import List def sum_of_positive_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_positive_numbers(numbers: List[int]) -> int: """ Calculate the sum of all positive numbers in the given list. Args: numbers (List[int]): A list of integers. Returns: ...
python_sharegpt_23k
5,954
Write a Python function to determine if a given string is in lowercase. The function should return `True` if all characters in the string are lowercase letters, and `False` otherwise. Non-alphabetic characters should be ignored in the check. The code should start with: ```python def is_lowercase(string: str) -> bool: ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_lowercase(string: str) -> bool: """ Determines if all alphabetic characters in the given string are lowercase. Args: string (str): The input string to be checked. Returns: bool: True if all alpha...