source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
python_sharegpt_23k
4,702
Write a Python function to find the maximum element in an array while adhering to specific constraints. The function should iterate through the array and update a variable to store the maximum element found. The function should handle edge cases such as an empty array, an array with all elements being the same, and arr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def findMax(arr: List[int]) -> Optional[int]: """ Find the maximum element in an array with the given constraints. Args: arr (List[int]): The input array of integers. Returns:...
python_sharegpt_23k
4,708
Write a Python function to find all occurrences of words in a given string `s` that are present in a list of words `words`, while ignoring any occurrences that are part of a larger word. Additionally, the function should return the frequency of each word in the string `s`. The string `s` will only contain lowercase let...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def find_word_occurrences(s: str, words: List[str]) -> Dict[str, int]: """ Find all occurrences of words in a given string `s` that are present in a list of words `words`, while ignoring any oc...
python_sharegpt_23k
4,713
Write a Python function to find the largest prime number within a given range [start, end]. The function should return the largest prime number found within the specified range. If no prime numbers are found, the function should return `None`. The code should start with: ```python def find_largest_prime_in_range(start...
Here is the Python code to solve the given problem in the markdown block: ```python def find_largest_prime_in_range(start: int, end: int) -> int: """ Find the largest prime number within the given range [start, end]. Args: start (int): The starting number of the range (inclusive). end (int)...
python_sharegpt_23k
4,714
Write a Python function to remove all prime numbers from a given list of integers. The function should return the modified list without any prime numbers. The input list may contain duplicate elements, and the function should delete all occurrences of prime numbers from the list. You should not use any built-in functio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def is_prime(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. ""...
python_sharegpt_23k
4,730
Write a Python function to implement the FizzBuzz game for numbers from 1 to 100. The function should replace numbers divisible by 3 with "Fizz", numbers divisible by 5 with "Buzz", and numbers divisible by both 3 and 5 with "FizzBuzz". Instead of using the modulo operator to determine divisibility, implement a custom ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_divisible_bitwise(numerator: int, divisor: int) -> bool: """ Check if a number is divisible by another number using only bitwise operators. Args: numerator (int): The number to check ...
python_sharegpt_23k
4,731
Write a Python function to process a list by removing all duplicate numbers, filtering out non-numeric elements, and sorting the remaining numbers in descending order. The function should handle large input lists efficiently, up to 10,000,000 elements. The code should start with: ```python from typing import List, Unio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def process_list(lst: List[Union[int, float, str]]) -> List[float]: """ Processes a list by removing duplicates, filtering out non-numeric elements, and sorting the remaining numbers in descen...
python_sharegpt_23k
4,734
Write a Python function to search for a target element in a sorted array with a time complexity of O(log n) and without using any built-in search functions or libraries. The function should be able to handle duplicates in the array and return the index of the first occurrence of the target element if it exists, otherwi...
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 a sorted array with duplicates. Args: arr (List[int]): The sorte...
python_sharegpt_23k
4,740
Write a Python function to filter out prime numbers from a given list of integers. The function should have a time complexity of O(n^2), where n is the length of the input list. Additionally, the function should not use any built-in Python functions or libraries for determining prime numbers. The code should start wit...
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 prime...
python_sharegpt_23k
4,744
Write a Python function to create a dictionary from a given list, where the keys are the elements of the list that are divisible by 2, and the values are the squares of these keys. The function should ensure that no duplicate keys are included in the dictionary, and the time complexity should be O(n^2), where n is the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def create_dict_with_squared_values(lst: List[int]) -> Dict[int, int]: """ Create a dictionary from a list where the keys are the elements of the list that are divisible by 2, and the values ar...
python_sharegpt_23k
4,747
Write a Python function to manipulate a given list where every element in the list has to be doubled. The resulting list should be sorted in ascending order. The original list should not be modified, and the manipulation should be done using list comprehension. Additionally, implement your own sorting algorithm instead...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def manipulate_list(lst: List[int]) -> List[int]: """ Manipulate a given list by doubling each element and then sorting the resulting list in ascending order. Args: lst (List[int]): The inpu...
python_sharegpt_23k
4,748
Write a Python function to determine whether all elements in a given list are equal. The list can contain positive integers, negative integers, or both. The function should have a time complexity of O(n) and a space complexity of O(1), where n is the length of the list. The function 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 def are_all_elements_equal(lst: List[int]) -> bool: """ Determine whether all elements in the given list are equal. Args: lst (List[int]): The list of integers to check. Returns: ...
python_sharegpt_23k
4,749
Write a Python function to find the index of a given string from a list of strings. If the string is not present in the list, return -1. The function should be case-sensitive, meaning that "apple" and "Apple" should be treated as different strings. Additionally, the function should only return the index of the first oc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_string_index(strings: List[str], target: str) -> int: """ Find the index of the first occurrence of a given string in a list of strings. Args: strings (List[str]): A list of strings...
python_sharegpt_23k
4,750
Write a Python function to calculate the sum of the first n terms of a mathematical series, adhering to the following requirements: 1. Validate the input: Ensure n is a positive integer greater than 1. If not, return an error message. 2. Handle large numbers: The function should efficiently handle large values of n wit...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_series_sum(n: int) -> int: """ Calculate the sum of the first n terms of the mathematical series. Args: n (int): The number of terms in the series. Must be a positive integer greater than 1. Retur...
python_sharegpt_23k
4,755
Write a Python function to calculate the floor value of the square root of a positive integer using only integer operations. The function should have a time complexity of O(log n) and should not use any built-in square root functions or external libraries. The code should start with: ```python def floor_sqrt(n: int) ->...
Here is the Python code to solve the given problem in the markdown block: ```python def floor_sqrt(n: int) -> int: """ Calculate the floor value of the square root of a positive integer using only integer operations. Args: n (int): The positive integer for which to find the floor value of the squar...
python_sharegpt_23k
4,768
Write a Python function to calculate the power of a base raised to an exponent using a binary exponentiation algorithm. The function should have a time complexity of O(log(n)) where n is the value of the exponent. Additionally, the function should handle cases where the exponent is negative by returning the reciprocal ...
Here is the Python code to solve the given problem in the markdown block: ```python def power(base: int, exponent: int) -> float: """ Calculate the power of a base raised to an exponent using binary exponentiation. Args: base (int): The base number, a positive integer greater than 1. expone...
python_sharegpt_23k
4,771
Write a Python function to transpose a 4x4 2D array recursively without using any built-in functions or libraries for matrix transposition. The function should correctly transpose the entire matrix, not just the first row. The code should start with: ```python from typing import List def transpose_matrix(matrix: List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Transposes a 4x4 2D array recursively. Args: matrix (List[List[int]]): A 4x4 2D array to be transposed. Returns: ...
python_sharegpt_23k
4,772
Write a Python function to merge two given lists into a single sorted list in ascending order. The function must ensure that the time complexity is O(n log n), where n is the total number of elements in both lists. Additionally, the function should handle duplicates in the input lists and maintain their order in the ou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_and_sort(list1: List[int], list2: List[int]) -> List[int]: """ Merges two lists into a single sorted list in ascending order. Args: list1 (List[int]): The first list of integers. ...
python_sharegpt_23k
4,778
Write a Python function to reverse a given array in-place using a recursive approach. The function should not use any built-in array reversing functions or methods, and it should not use loops or iteration. The original array should be modified directly. The function should handle arrays with duplicate elements and neg...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array_recursive(nums: List[int]) -> List[int]: """ Reverses the given array in-place using a recursive approach. Args: nums (List[int]): The array to be reversed. Returns: ...
python_sharegpt_23k
4,779
Write a Python function to print the 16-bit binary representation of a given number, count the number of ones and zeros in the binary representation, and return the number of zeros. If the given number is negative, return an error message stating that negative numbers are not allowed. The input number will always be be...
Here is the Python code to solve the given problem in the markdown block: ```python def count_binary_ones_zeros(num: int) -> str: """ Returns the 16-bit binary representation of a given number, counts the number of ones and zeros, and returns the number of zeros. If the number is negative, returns an error ...
python_sharegpt_23k
4,784
Write a Python function to calculate the column-wise sum of a given 2D array. The input array will contain `n` rows and `m` columns, where `1 <= n, m <= 10^6`. The elements of the array will be integers between `-10^6` and `10^6`. The function should be optimized to run efficiently for large input arrays with a time co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def column_sum(arr: List[List[int]]) -> List[int]: """ Calculate the column-wise sum of a given 2D array. Args: arr (List[List[int]]): A 2D array containing integers. Returns: L...
python_sharegpt_23k
4,791
Write a Python function to convert a given decimal value to its binary equivalent without using any built-in conversion functions or operators. The function should have a time complexity of O(log^2 n), where n is the decimal value. The function should start with: ```python def decimal_to_binary(decimal: int) -> str: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def decimal_to_binary(decimal: int) -> str: """ Converts a given decimal value to its binary equivalent without using built-in conversion functions or operators. Args: decimal (int): The decimal value to be converte...
python_sharegpt_23k
4,796
Write a Python function to determine if a given number is a prime number. The function should handle the following cases: 1. If the input number is a decimal, return `False`. 2. If the input number is negative, return `False`. 3. If the input number is a positive integer, determine if it is a prime number. A prime numb...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_number(n: float) -> bool: """ Determines if a given number is a prime number. Args: n (float): The number to check for primality. Returns: bool: True if the number is a prime number, False ...
python_sharegpt_23k
4,799
Write a Python function called `find_common_elements` that takes in two lists of integers as input. The function should return a new list containing only the elements that are common to both input lists. The solution should meet the following requirements: 1. The solution should not use any built-in sorting functions o...
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]) -> List[int]: """ Finds the common elements between two lists of integers and returns them in ascending order. Args: list1 (List[...
python_sharegpt_23k
4,805
Write a Python function to count the number of times a given character appears in an input string, but only count the occurrences of the character if it is surrounded by a pair of parentheses and the parentheses are not nested within another pair of parentheses. Ignore any occurrences of the character that are not surr...
Here is the Python code to solve the given problem in the markdown block: ```python def count_char_in_parentheses(input_string: str, char: str) -> int: """ Counts the number of times a given character appears in an input string, but only counts the occurrences if the character is surrounded by a pair of...
python_sharegpt_23k
4,806
Write a Python function to process a list of characters from the Lord of the Rings and return an array of their corresponding nicknames. The function should meet the following requirements: 1. The function should have a time complexity of O(n), where n is the number of characters in the input list. 2. The nicknames sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_nicknames(characters: List[str]) -> List[str]: """ Processes a list of characters from the Lord of the Rings and returns an array of their corresponding nicknames. Args: characters (...
python_sharegpt_23k
4,821
Write a Python function to shift an array to the right by a specified number of positions without using built-in functions. The array should be modified in-place without creating a new array. The array should contain both positive and negative integers, and the length of the array should be at least 1. The function sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def shift_array_right(arr: List[int], num_positions: int) -> None: """ Shifts the given array to the right by the specified number of positions. The array is modified in-place without creating a new ...
python_sharegpt_23k
4,829
Write a Python function to remove all occurrences of a specified element from a list while maintaining the original order of the remaining elements. The function should have a time complexity of O(n), where n is the length of the list. Additionally, if the element is not present in the list, the function should display...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_element(lst: List[int], element: int) -> List[int]: """ Removes all occurrences of the specified element from the list while maintaining the original order of the remaining elements. Args...
python_sharegpt_23k
4,830
Write a Python function to generate all possible permutations of a given input string with duplicate characters. The function should use recursion instead of iteration to generate the permutations. The time complexity of the function should be O(n!) in the worst case, where n is the length of the input string. The func...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_unique_permutations(string: str) -> List[str]: """ Generate all unique permutations of a given input string with duplicate characters. Args: string (str): The input string for w...
python_sharegpt_23k
4,832
Write a Python function to determine if a target integer occurs more than twice in a given list of integers. The function should have a time complexity of O(n) and should not use any built-in functions or libraries that provide direct solutions to the problem. The function 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 check_occurrence(nums: List[int], target: int) -> bool: """ Determines if the target integer occurs more than twice in the given list of integers. Args: nums (List[int]): The list of int...
python_sharegpt_23k
4,839
Write a Python function to generate a histogram from a given list of integers. The function should return a dictionary where the keys are the unique positive integers from the input list and the values are the frequencies of those integers in the input list. If the input list contains negative integers, the function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_histogram(data: List[int]) -> Dict[int, int]: """ Generates a histogram from a given list of integers. Args: data (List[int]): A list of integers from which to generate th...
python_sharegpt_23k
4,843
Write a Python function to transform a list of positive integers such that each odd number is multiplied by 7 and each even number is replaced by its cube. The function should maintain the order of the original list and should have a time complexity of O(n) and a space complexity of O(1), where n is the length of the i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transform_list(nums: List[int]) -> List[int]: """ Transforms a list of positive integers such that each odd number is multiplied by 7 and each even number is replaced by its cube. The transformat...
python_sharegpt_23k
4,846
Write a Python function to filter a list of strings based on specific criteria. The function should return only strings that start with an uppercase letter, contain at least one lowercase letter, are at least 5 characters long, and contain at least one digit (0-9). If the input list is empty, the function should return...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_strings(lst: List[str]) -> List[str]: """ Filters a list of strings based on specific criteria. Args: lst (List[str]): A list of strings to be filtered. Returns: List...
python_sharegpt_23k
4,850
Write a Python function to count the number of times a specified prime number appears in an array, considering only the numbers that are greater than or equal to zero. The function should have a time complexity of O(n), where n is the length of the array. 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 is_prime(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if n <...
python_sharegpt_23k
4,851
Write a Python function to search for a given string element in a list of strings. The function should return the index of the first occurrence of the element if it is found, and -1 otherwise. The search should be case-insensitive, and the function should handle edge cases such as an empty list or a list with a single ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def search_element(lst: List[str], element: str) -> int: """ Searches for a given string element in a list of strings and returns the index of the first occurrence. The search is case-insensitive. If...
python_sharegpt_23k
4,852
Write a Python function to remove duplicates from a given list while maintaining the original order of elements. The function should use only a single loop and should not use any built-in functions or libraries. The time complexity of the function should be O(n^2), where n is the length of the list. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_in_order(original_list: List[int]) -> List[int]: """ Removes duplicates from the given list while maintaining the original order of elements. The function uses a single loop and...
python_sharegpt_23k
4,857
Write a Python function to determine if a given number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should return `True` if the number is prime and `False` otherwise. The code should start with: ```python def is_prime(number: in...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(number: int) -> bool: """ Determine if a given number is a prime number. Args: number (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. ...
python_sharegpt_23k
4,858
Write a Python function to multiply two large integers represented as lists of digits. Each integer can have up to \(10^5\) digits. The function should have a time complexity of \(O(n^2)\), where \(n\) is the number of digits in the larger integer. The function should not use any built-in multiplication or division ope...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_large_integers(num1: List[int], num2: List[int]) -> List[int]: """ Multiplies two large integers represented as lists of digits. Args: num1 (List[int]): The first integer repres...
python_sharegpt_23k
4,862
Write a Python function to sort a given list of integers in ascending order using the bubble sort algorithm. The bubble sort algorithm should have a time complexity of O(n^2) and a space complexity of O(1), where n is the length of the array. The function should handle any edge cases, such as an empty list or a list wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the bubble sort algorithm. Args: arr (List[int]): The list of integers to be sorted. ...
python_sharegpt_23k
4,863
Write a Python function to determine whether one string is a substring of another, without using built-in string search methods like `str.find()` or `str.index()`. The function should handle case-insensitive substring matching and have a time complexity of O(n), where n is the length of the main string. The function s...
Here is the Python code to solve the given problem in the markdown block: ```python def is_substring(string_1: str, string_2: str) -> bool: """ Determine whether string_2 is a substring of string_1, handling case-insensitive matching. Args: string_1 (str): The main string to search within. ...
python_sharegpt_23k
4,864
Implement an efficient sorting algorithm with a time complexity of O(n log n) to sort the given array in ascending order. You are not allowed to use any built-in sorting functions or libraries. The code should start with: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts the given array in ascending order using the Merge Sort algorithm. Args: arr (List[int]): The array to be sorted. Returns: ...
python_sharegpt_23k
4,869
Write a Python function to remove duplicates from a given list of integers without using any additional data structures and without modifying the order of the elements. The function should have a time complexity of O(n^2) and a space complexity of O(1). The code should start with: ```python from typing import List de...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(nums: List[int]) -> List[int]: """ Removes duplicates from a list of integers without using additional data structures and without modifying the order of the elements. The funct...
python_sharegpt_23k
4,876
Write a Python function to convert a given English sentence into Pig Latin following the specified rules. The function should handle capitalization and punctuation correctly. The code should start with: ```python def convert_to_pig_latin(sentence: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_pig_latin(sentence: str) -> str: """ Converts a given English sentence into Pig Latin following specified rules. Args: sentence (str): The English sentence to be converted. Returns: str: ...
python_sharegpt_23k
4,885
Write a Python function to find the second maximum value from a given list of numbers without using any built-in functions or methods that directly find the maximum value or sort the array. The function should handle cases where the list contains duplicate values and should return `None` if the list has fewer than two ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_second_max(numbers: List[int]) -> Optional[int]: """ Find the second maximum value from a given list of numbers without using built-in functions or methods that directly find the maxim...
python_sharegpt_23k
4,888
Write a Python function to sort an array of integers in descending order using the insertion sort algorithm. The array can contain duplicate elements. The algorithm should have a time complexity of O(n^2). Additionally, the implementation should not use any built-in sorting functions or libraries. The code should star...
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 an array of integers in descending order using the insertion sort algorithm. Args: arr (List[int]): The array of integer...
python_sharegpt_23k
4,892
Write a Python function to sort an array of integers from largest to smallest using a divide and conquer approach. The sorting algorithm should have a time complexity of O(n log n) or better and should handle duplicate integers correctly, preserving their relative order in the sorted array. The algorithm should not use...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort_descending(arr: List[int]) -> List[int]: """ Sorts an array of integers from largest to smallest using a merge sort algorithm. Args: arr (List[int]): The array of integers to ...
python_sharegpt_23k
4,895
Write a Python function to remove an element at a specified index from a given array and return the updated array. If the index is out of bounds or the array is empty, return the original array unchanged. The function should modify the array in place without using any built-in functions or methods that directly remove ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_element_at_index(arr: List[int], index: int) -> List[int]: """ Removes the element at the specified index from the array and returns the updated array. If the index is out of bounds or the...
python_sharegpt_23k
4,901
Write a Python function that demonstrates the concept of immutability in functional programming by performing a complex task such as sorting a large dataset in ascending order while maintaining the original dataset's integrity. The function should be pure, meaning it should not modify the input data and should always r...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_and_maintain_original(dataset: List[int]) -> List[int]: """ Sorts a large dataset in ascending order while maintaining the original dataset's integrity. Args: dataset (List[int]): T...
python_sharegpt_23k
4,906
Write a Python function to search for the index of a given element in a list without using the built-in `index` function or any built-in searching functions. The function should return -1 if the element is not found in the list. Additionally, the function should handle edge cases such as empty lists, lists with duplica...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def search_index(lst: List[int], target: int) -> int: """ Searches for the index of a given element in a list without using built-in searching functions. Returns -1 if the element is not found. ...
python_sharegpt_23k
4,908
Write a Python function to merge two sorted arrays into a single sorted array without modifying the original arrays. The merged array should not contain any duplicate elements and should be in non-decreasing order. The function should achieve this with a time complexity of O(n log n), where n is the total number of ele...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_arrays_unique(arr1: List[int], arr2: List[int]) -> List[int]: """ Merge two sorted arrays into a single sorted array without duplicates. Args: arr1 (List[int]): The first so...
python_sharegpt_23k
4,914
Write a Python function to multiply each number in a given list by three, ensuring that the function modifies the list in place and returns the modified list. Additionally, provide a reference to an erroneous code that tries to multiply each number by five instead. The function should have a time complexity of O(n) and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_by_three(numbers: List[int]) -> List[int]: """ Multiplies each number in the given list by three and returns the modified list. Args: numbers (List[int]): The list of integers t...
python_sharegpt_23k
4,915
Write a Python function to replace all consecutive whitespaces in a given string with a single space, while ignoring any whitespaces at the beginning or end of the string. The function should also handle cases where the input string contains non-alphanumeric characters. The function should have a time complexity of O(n...
Here is the Python code to solve the given problem in the markdown block: ```python import re def remove_consecutive_whitespaces(string: str) -> str: """ Replaces all consecutive whitespaces in a given string with a single space, while ignoring any whitespaces at the beginning or end of the string. The...
python_sharegpt_23k
4,918
Write a Python function to sort a list of user dictionaries by their name in alphabetical order and then by their age in descending order. Each user dictionary contains the following attributes: `name` (a string), `age` (an integer), and `country` (a string). The function should ensure that the time complexity does not...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def sort_users(users: List[Dict[str, str]]) -> List[Dict[str, str]]: """ Sorts a list of user dictionaries by their name in alphabetical order and then by their age in descending order. Args: ...
python_sharegpt_23k
4,928
Write a Python function to find the index of the first occurrence of a target integer in a given list of integers. If the target integer does not exist in the list, return -1. The function should have a time complexity of O(n) and should not use any built-in search functions or libraries. Additionally, the function sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_first_occurrence(nums: List[int], target: int) -> int: """ Find the index of the first occurrence of a target integer in a list. If the target integer does not exist in the list, return -1. ...
python_sharegpt_23k
4,934
Write a Python function that takes in a list of dictionaries and returns a new list of dictionaries. Each dictionary in the new list should only include key-value pairs where the key starts with a vowel (a, e, i, o, u) and the value is a list of integers. Additionally, the function should sort the dictionaries in the n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def filter_and_sort_dictionaries(list_of_dicts: List[Dict[str, List[int]]]) -> List[Dict[str, List[int]]]: """ Filters and sorts a list of dictionaries based on specific criteria. Args: ...
python_sharegpt_23k
4,936
Write a Python function to find the index of the first occurrence of a given integer in an array with a time complexity requirement of O(n^2), where n is the length of the array. The function should handle arrays with duplicate values and negative integers. If the given integer is not found in the array, the function s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_index_with_duplicates(arr: List[int], target: int) -> int: """ Find the index of the first occurrence of a given integer in an array with a time complexity of O(n^2). Args: arr (Lis...
python_sharegpt_23k
4,939
Write a Python function to calculate the hypotenuse of a right-angled triangle given the lengths of the two sides. The function should also round the result to the nearest whole number. The code should start with: ```python import math def calculate_hypotenuse(side1: float, side2: float) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_hypotenuse(side1: float, side2: float) -> int: """ Calculate the hypotenuse of a right-angled triangle given the lengths of the two sides. The result is rounded to the nearest whole number. Ar...
python_sharegpt_23k
4,947
Write a Python function called `reverse_array` that takes in an array of integers and returns a string with each number in reverse order, separated by a comma. The function should have a time complexity of O(n) and a space complexity of O(1), where n is the length of the input array. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array(arr: List[int]) -> str: """ Reverses the order of the input array of integers and returns a string with each number separated by a comma. Args: arr (List[int]): The input a...
python_sharegpt_23k
4,948
Write a Python function to sort a given input array of integers in ascending order and return the sorted array as a string. The input array may contain negative numbers. The output string should contain the numbers separated by commas and enclosed in square brackets. The length of the input array should be at least 10....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_array_to_string(arr: List[int]) -> str: """ Sorts the given input array of integers in ascending order and returns it as a string. The output string contains the numbers separated by commas ...
python_sharegpt_23k
4,949
Write a Python function to compute a vector of length M+1 from a given MxN matrix of integers. The vector should contain the sum of each row in the matrix, followed by the sum of all the elements in the matrix as the last element. Each element in the matrix must be a positive integer not exceeding 1000. The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def row_sums(matrix: List[List[int]]) -> List[int]: """ Computes a vector of length M+1 from a given MxN matrix of integers. The vector contains the sum of each row in the matrix, followed by the sum...
python_sharegpt_23k
4,954
Write a Python function to determine if a given number is a prime number using a boolean variable. The function should use a loop to check for factors of the number and update the boolean variable accordingly. The function should return the boolean value indicating whether the number is prime or not. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_number(number: int) -> bool: """ Determine if a given number is a prime number. Args: number (int): The number to check for primality. Returns: bool: True if the number is prime, False othe...
python_sharegpt_23k
4,955
Write a Python function to find the common elements between two lists, considering the elements may have duplicates. The function should return a list containing only the elements common to both lists, preserving the order of their first appearance in the second list. The solution should adhere to the following constra...
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]) -> List[int]: """ Find the common elements between two lists, considering duplicates. Args: list1 (List[int]): The first list of ...
python_sharegpt_23k
4,958
Write a Python function to find the second largest element in a given array of at least 2 unique integers. The function should not use any built-in sorting functions or methods and should have a time complexity of O(n), where n is the length of the array. 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, Optional def find_second_largest(numbers: List[int]) -> Optional[int]: """ Find the second largest element in a given array of at least 2 unique integers. Args: numbers (List[int]): The arr...
python_sharegpt_23k
4,960
Write a Python function to reverse a list of integers in place without using the `reverse()` function or any built-in methods, and without using any additional data structures. The function should have a time complexity of O(n) and a space complexity of O(1). The code should start with: ```python from typing import Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list_in_place(lst: List[int]) -> List[int]: """ Reverses a list of integers in place without using the reverse() function or any built-in methods. Args: lst (List[int]): The list...
python_sharegpt_23k
4,961
Write a Python function to implement the Bubble Sort algorithm with a time complexity of O(n^2) and a space complexity of O(1). The function should sort an array of integers in ascending order. The input array will contain at most 1000 elements. Additionally, the function should handle duplicate elements in the array a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers in ascending order using the Bubble Sort algorithm. Args: arr (List[int]): The array of integers to be sorted. ...
python_sharegpt_23k
4,969
Write a Python function to generate a list of N unique, randomly generated numbers between 0 and 100, sorted in ascending order, without using any external libraries or built-in sorting functions. The function should have a time complexity of O(N). Additionally, handle the cases where N is greater than 100 or a negativ...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_unique_sorted_numbers(N: int) -> list: """ Generates a list of N unique, randomly generated numbers between 0 and 100, sorted in ascending order. Args: N (int): The number of unique random numbers to ge...
python_sharegpt_23k
4,976
Write a Python function to perform a binary search on a sorted array to find the index of a target value. If the target value is found, return its index; otherwise, return -1. The function should be efficient and should handle edge cases such as an empty array or a target value that is not present in the array. The co...
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 array to find the index of a target value. Args: arr (List[int]): A sorted list of integers. ...
python_sharegpt_23k
4,978
Write a Python function to search for the index of the first occurrence of a given integer `item` in a sorted list of distinct integers `items`. If the `item` is not found, the function should return -1. The function should have a time complexity of O(log n) and a space complexity of O(1). The code should start with: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def search(items: List[int], item: int) -> int: """ Searches for the index of the first occurrence of a given integer `item` in a sorted list of distinct integers `items`. If the `item` is not found,...
python_sharegpt_23k
4,981
Write a Python function to determine if a list of HTML tags is structured correctly based on their hierarchical relationships. The function should optimize both time complexity and space complexity. The hierarchical relationships of the HTML tags are defined as follows: - An opening tag must be closed by a correspondi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_html_tags_correct(tags: List[str]) -> bool: """ Determines if a list of HTML tags is structured correctly based on their hierarchical relationships. Args: tags (List[str]): A list of ...
python_sharegpt_23k
4,984
Write a Python function to modify an array such that the element at index 4 is multiplied by two if it is a prime number, otherwise, it is incremented by one. The function should use a recursive approach to check for prime numbers. The array should have at least 6 elements. 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 is_prime_recursive(n: int, divisor: int = 2) -> bool: """ Recursively checks if a number is prime. Args: n (int): The number to check for primality. divisor (int): The current di...
python_sharegpt_23k
4,987
Write a Python function to remove all repeated elements from a list and return a new list containing only the unique prime elements. The function should take in a list of positive integers as input and iterate through each element in the list. For each element, it should check if it has already been encountered in the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def is_prime(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. ""...
python_sharegpt_23k
4,988
Write a Python function to filter and print only the valid names and numeric values from a given list. Valid elements are strings and numeric values (integers and floats). If an element is not a string or a numeric value, it should be skipped. The function should start with: ```python from typing import List, Union de...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def print_valid_elements(names: List[Union[str, int, float]]) -> None: """ Prints only the valid names and numeric values from the given list. Valid elements are strings and numeric values (i...
python_sharegpt_23k
4,995
Write a Python function that takes in a string, a substring, and a replacement string as inputs. The function should search for all occurrences of the substring in the string and replace them with the replacement string. The function should be case-sensitive and should return the modified string. The function should ha...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_substring(string: str, substring: str, replacement: str) -> str: """ Replace all occurrences of a substring in a string with a replacement string. Args: string (str): The input string to be modified. ...
python_sharegpt_23k
5,007
Write a Python function to find all pairs of words in a given array that are anagrams of each other. The function should return a list of these pairs. The time complexity of the solution should be O(n^2), where n is the length of the input array. Additionally, the space complexity of the solution should be O(1), meanin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_anagram_pairs(words: List[str]) -> List[Tuple[str, str]]: """ Find all pairs of words in the given array that are anagrams of each other. Args: words (List[str]): The array o...
python_sharegpt_23k
5,009
Write a Python function to reverse the elements of an array of integers in place, without using any built-in methods or functions that directly reverse the array. The time complexity of your solution should be O(n), where n is the length of the array. The function should start with: ```python from typing import List d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array_in_place(arr: List[int]) -> None: """ Reverses the elements of an array of integers in place. Args: arr (List[int]): The array of integers to be reversed. Returns: ...
python_sharegpt_23k
5,016
Write a Python function to generate all prime numbers between 1 and a given upper limit `n` (inclusive). The function should use an efficient algorithm to determine if a number is prime and return a list of all prime numbers within the specified range. The code should start with: ```python from typing import List def...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_primes(n: int) -> List[int]: """ Generate all prime numbers between 1 and the given upper limit n (inclusive). Args: n (int): The upper limit of the range to search for prime nu...
python_sharegpt_23k
5,018
Write a Python function to find all starting indices of a given pattern within a text string. The function should return a list of all such indices where the pattern appears as a substring in the text. If the pattern is not found, the function should return an empty list. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_indices(text: str, pattern: str) -> List[int]: """ Finds all starting indices of a given pattern within a text string. Args: text (str): The text string in which to search for t...
python_sharegpt_23k
5,020
Write a Python function to find the common elements between two arrays of integers. The arrays may contain duplicate elements, and the common elements should be returned in ascending order without any duplicates. The time complexity of the solution should be less than O(n), where n is the length of the longer array. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_common_elements(arr1: List[int], arr2: List[int]) -> List[int]: """ Find the common elements between two arrays of integers and return them in ascending order without duplicates. Args: ...
python_sharegpt_23k
5,021
Write a Python function to classify elements of an integer array as even or odd using a bitwise solution. The function should not use the modulus operator (%) or any other arithmetic operation to determine the parity of each element. The time complexity of the solution should be O(n), where n is the length of the input...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def classify_elements(arr: List[int]) -> Tuple[List[int], List[int]]: """ Classify elements of an integer array as even or odd using a bitwise solution. Args: arr (List[int]): The inp...
python_sharegpt_23k
5,023
Write a Python function to determine whether each number in a given list is a perfect square or not. Return a new list with the corresponding boolean results. The function should adhere to the following constraints: - The input list can contain up to 10^6 integers. - Each integer in the list will be between 1 and 10^12...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_perfect_square(num: int) -> bool: """ Determines if a given number is a perfect square. Args: num (int): The number to check. Returns: bool: True if the number is a perfe...
python_sharegpt_23k
5,031
Write a Python function to calculate the area of a parallelogram given its base and height. The function should correctly handle the multiplication of the base and height to compute the area. The code should start with: ```python def calculate_parallelogram_area(base: float, height: float) -> float: ```
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 base of the parallelogram. he...
python_sharegpt_23k
5,035
Write a Python function to find and return a list of strings that occur exactly once in a given list of strings. If a string occurs more than once, it should not be included in the output list. The function should be efficient and handle various edge cases, such as an empty input list or a list with all strings being d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_unique_strings(input_list: List[str]) -> List[str]: """ Returns a list of strings that occur exactly once in the given input list. Args: input_list (List[str]): The list of strings ...
python_sharegpt_23k
5,037
Write a Python function to count the occurrences of each unique word in a given string. The string may contain multiple words, separated by spaces, and may also contain punctuation marks, special characters, and numbers. The function should be case-insensitive and should treat numbers as separate words. The function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import re from collections import defaultdict def count_word_occurrences(string: str) -> Dict[str, int]: """ Count the occurrences of each unique word in the given string. Args: string (str)...
python_sharegpt_23k
5,039
Write a Python function to determine if a given string is a palindrome using a stack data structure. The function should only accept strings that contain alphabetic characters and have at least one character. The function should return `True` if the string is a palindrome and `False` otherwise. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(string: str) -> bool: """ Determine if a given string is a palindrome using a stack data structure. Args: string (str): The input string to check. Must contain only alphabetic characters and have a...
python_sharegpt_23k
5,040
Write a Python function to tokenize a given sentence and count the number of occurrences for each word in the sentence. The function should handle punctuation marks and special characters, such as commas, periods, exclamation marks, question marks, and quotation marks. Additionally, the function must handle cases where...
Here is the Python code to solve the given problem in the markdown block: ```python def tokenize_and_count(sentence: str) -> dict: """ Tokenizes a given sentence and counts the number of occurrences for each word. Handles punctuation marks and special characters, and multiple spaces or newlines. Args: ...
python_sharegpt_23k
5,043
Write a Python function to determine if a given string is a palindrome, considering only lowercase alphabetic characters and ignoring any non-alphabetic characters and whitespace. The function should return `True` if the string is a palindrome and `False` otherwise. 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(string: str) -> bool: """ Determine if a given string is a palindrome, considering only lowercase alphabetic characters and ignoring non-alphabetic characters and whitespace. Args: string (str): Th...
python_sharegpt_23k
5,045
Write a Python function to parse a list of JSON objects and return a dictionary. The parsed dictionary should include only the "name", "age", and "hobbies" fields. The "name" field should be converted to uppercase letters. The "age" field should be validated to ensure it is a positive integer, and the "hobbies" field s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any def parse_json_objects(json_objects: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: """ Parses a list of JSON objects and returns a dictionary with specific fields. Args: jso...
python_sharegpt_23k
5,046
Write a Python function to generate a random sentence based on given sets of nouns, pronouns, verbs, and objects. The sentence should be grammatically correct and make sense. Additionally, implement a function that can generate a sentence of a specific length. The sentence should still follow the given grammar rules an...
Here is the Python code to solve the given problem in the markdown block: ```python import random def generate_sentence(nouns, pronouns, verbs, objects): """ Generate a random sentence based on the given sets of nouns, pronouns, verbs, and objects. Args: nouns (list): A list of nouns. pron...
python_sharegpt_23k
5,047
Write a Python function to sort a given list in descending order without using any built-in sorting functions. Additionally, the function should remove any duplicates from the sorted list. The sorting algorithm should minimize the number of comparisons and swaps performed. 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 def sort_and_remove_duplicates(unsorted_list: List[int]) -> List[int]: """ Sorts the given list in descending order and removes any duplicates without using built-in sorting functions. Args: ...
python_sharegpt_23k
5,052
Write a Python function to generate the first n elements of the Fibonacci sequence efficiently, ensuring that the solution is optimized for both time complexity and space complexity. The Fibonacci sequence is defined by the rule \( F(n) = F(n-1) + F(n-2) \), where \( F(0) = 0 \) and \( F(1) = 1 \). The function should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_fibonacci(n: int) -> List[int]: """ Generate the first n elements of the Fibonacci sequence. The Fibonacci sequence is defined by the rule F(n) = F(n-1) + F(n-2), where F(0) = 0 and...
python_sharegpt_23k
5,053
Write a Python function to calculate the sum of the elements in a given 2D array. The function should handle any potential runtime errors, such as a null array, an array with mismatched dimensions, or an array containing non-numeric values. Additionally, the function should be implemented using only a single loop or re...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def sum_2d_array(arr: Union[List[List[Union[int, float]]], None]) -> float: """ Calculate the sum of the numeric elements in a given 2D array. Args: arr: A 2D list of integers and flo...
python_sharegpt_23k
5,061
Write a Python function to find the second highest value in a given list of integers without using any built-in functions or libraries. The function should handle cases where the list contains duplicate values and should return `None` if the list has fewer than two unique elements. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_second_highest(arr: List[int]) -> Optional[int]: """ Find the second highest value in a given list of integers without using any built-in functions or libraries. Args: arr...
python_sharegpt_23k
5,069
Write a Python function to calculate the factorial of a positive integer using recursion with memoization. The function should handle edge cases such as negative integers and 0, and should output an error message if the input is invalid. The implementation should optimize performance using memoization. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_with_memoization(n: int, memo: dict = None) -> int or str: """ Calculate the factorial of a positive integer using recursion with memoization. Args: n (int): The positive integer for which to calculate...
python_sharegpt_23k
5,077
Write a Python function to generate a random sample of a specified size from a given range, ensuring that all numbers in the sample are unique, and compute the mean of the sample. The function should handle the case where the sample size exceeds the range size by returning `None`. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import Optional def generate_unique_sample_mean(range_size: int, sample_size: int) -> Optional[float]: """ Generate a random sample of unique numbers from a given range and compute its mean. ...
python_sharegpt_23k
5,082
Write a Python function to determine the maximum sum of a subarray within a given array, with the constraint that the subarray must contain at least three elements. The array may contain negative numbers. The function should achieve this in O(n) time complexity. The code should start with: ```python from typing import...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum_with_constraint(arr: List[int]) -> int: """ Determine the maximum sum of a subarray within the given array, with the constraint that the subarray must contain at least three elements...
python_sharegpt_23k
5,087
Write a Python function to determine if a target string is a substring of a main string. The function should be case-insensitive and should not use any built-in string manipulation functions or methods (e.g., `substring`, `contains`). The time complexity of the solution should be O(n + m), where n is the length of the ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_substring(main_string: str, target_string: str) -> bool: """ Determines if the target string is a substring of the main string. Args: main_string (str): The main string to search within. target_string...
python_sharegpt_23k
5,106
Write a Python function to extract unique odd numbers from a given list of integers and return them in descending order. The function should not use any built-in functions or libraries, and the time complexity should be O(n^2) or less. The code should start with: ```python from typing import List def get_unique_odd_n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_unique_odd_numbers(nums: List[int]) -> List[int]: """ Extracts unique odd numbers from a given list of integers and returns them in descending order. Args: nums (List[int]): The list...
python_sharegpt_23k
5,110
Write a Python function to find the median of a given integer array using a recursive approach. The function should handle the following cases: 1. The array is empty. 2. The array contains an even number of elements. 3. The array contains an odd number of elements. 4. The array contains duplicate values. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_median_recursive(arr: List[int]) -> Optional[float]: """ Find the median of a given integer array using a recursive approach. Args: arr (List[int]): The integer array for ...
python_sharegpt_23k
5,114
Write a Python function to modify an array of integers based on the following rules: - If the array has less than 3 elements, return the array unchanged. - If the array has 3 or more elements, delete the third element (index 2) and shift all the remaining elements to the left to fill the empty space. - The resulting ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def modify_array(arr: List[int]) -> List[int]: """ Modifies the input array by deleting the third element (index 2) and shifting all remaining elements to the left. Args: arr (List[int])...
python_sharegpt_23k
5,115
Write a Python function to sort a given array in descending order using a custom implementation of the merge sort algorithm. The function should not use any built-in sorting functions or methods, and it must have a time complexity of O(n log n). Additionally, the function should not use any additional data structures o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort_descending(arr: List[int]) -> List[int]: """ Sorts the given array in descending order using a custom implementation of the merge sort algorithm. Args: arr (List[int]): The ar...
python_sharegpt_23k
5,116
Implement a depth-first search (DFS) algorithm to search for a specific value in a given tree structure. The tree can have any number of child nodes for each parent node, and each node can have any number of attributes associated with it. The attribute name that stores the value to be searched for may be different from...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, List def depth_first_search(node: Any, target_value: Any, value_attribute: str) -> bool: """ Perform a depth-first search to find a specific value in a tree structure. Args: node (Any): The ...