source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
python_sharegpt_23k
418
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. Additionally, ensure that the time complexity of your s...
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 of uniq...
python_sharegpt_23k
421
Write a Python function to calculate the greatest common divisor (GCD) of two integers using a recursive approach. The function should handle negative integers by converting them to positive values. The algorithm should have a time complexity of O(log min(n1, n2)) and should not use any built-in functions or libraries ...
Here is the Python code to solve the given problem in the markdown block: ```python def gcd_recursive(n1: int, n2: int) -> int: """ Calculate the greatest common divisor (GCD) of two integers using a recursive approach. Args: n1 (int): The first integer. n2 (int): The second integer. R...
python_sharegpt_23k
426
Write a Python function to determine if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. The function should return `True` if the string is a palindrome and `False` otherwise. The function should be case-insensitive and sho...
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_palindrome(string: str) -> bool: """ Determine if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. This ...
python_sharegpt_23k
428
Write a Python function that takes a list of numbers and a specified number of decimal places as arguments, and returns a dictionary where each key is a number from the list and the corresponding value is its square root rounded to the specified number of decimal places. The function should handle the following constra...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import math def square_root_dict(numbers: List[float], decimal_places: int) -> Dict[float, float]: """ Calculate the square root of each number in the list and return a dictionary where each ke...
python_sharegpt_23k
429
Write a Python function named `group_students` that takes in a list of student dictionaries and returns a dictionary where the keys are the major names and the values are lists of student names belonging to that major. The student names should be sorted in alphabetical order. The function should ignore any students who...
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]) -> Dict[str, List[str]]: """ Groups students by their major and returns a dictionary where the keys are the major names and the values are lists of ...
python_sharegpt_23k
431
Write a Python function to reverse a given string without using any built-in string manipulation functions or methods and without using any additional data structures. The function should have a complexity of O(n), where n is the length of the string. The function should be implemented using only constant space complex...
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 manipulation functions or methods and without using any additional data structures. Args: string (str): The input...
python_sharegpt_23k
435
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', are above 18 years old, and have an odd age. The dictionary will have the following structure: ```python dictionary = { 'name': ['John', 'Jane', 'Jake', 'Jared', 'Jill'], 'age': [25, ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def sum_of_ages_with_conditions(dictionary: Dict[str, List[str]]) -> int: """ Calculate the sum of the ages of all people in the given dictionary whose names start with 'J', are above 18 years ...
python_sharegpt_23k
438
Write a Python function to remove duplicate elements from a given array while preserving the original order of elements. The function should not use any built-in functions or libraries for removing duplicates or any additional data structures such as dictionaries or sets. The function should have a time complexity of O...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(arr: List[int]) -> List[int]: """ Removes duplicate elements from the given array while preserving the original order. Args: arr (List[int]): The array from which dupli...
python_sharegpt_23k
439
Write a Python function to calculate the mean of a given list of numbers using a for loop. The list may contain up to \(10^6\) numbers, including negative numbers, decimal numbers, and numbers greater than 1000. Ensure that the final mean is rounded to two decimal places. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_mean(numbers: List[float]) -> float: """ Calculate the mean of a list of numbers and round it to two decimal places. Args: numbers (List[float]): A list of numbers (can include...
python_sharegpt_23k
450
Write a Python function to print out each item in a given array that is divisible by 2, along with its index. The function should not use any built-in functions or libraries that directly solve the problem. The code should start with: ```python from typing import List def print_divisible_by_two(array: List[int]) -> No...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def print_divisible_by_two(array: List[int]) -> None: """ Prints out each item in the given array that is divisible by 2, along with its index. Args: array (List[int]): The array of integers...
python_sharegpt_23k
451
Write a Python function to sort a given list in increasing order without using any built-in sorting functions or methods. Additionally, you are not allowed to use any additional data structures or create any helper functions. The list may contain duplicate elements. The solution should have a time complexity of O(n^2)....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_list(my_list: List[int]) -> None: """ Sorts the given list in increasing order using the Bubble Sort algorithm. Args: my_list (List[int]): The list of integers to be sorted. Re...
python_sharegpt_23k
455
Write a Python function to calculate the Fibonacci series from 0 to n using an iterative approach. The function should not use recursion, built-in functions, or libraries to solve the problem. The solution should have a time complexity of O(n) and a space complexity of O(1). The code should start with: ```python from ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def fibonacci_iterative(n: int) -> List[int]: """ Calculate the Fibonacci series from 0 to n using an iterative approach. Args: n (int): The upper limit of the Fibonacci series to calculate....
python_sharegpt_23k
464
Write a Python function to encode a given string in Base64 and then decode it back to its original form. The input string may contain any printable ASCII characters, including non-printable ASCII characters. Ensure that your solution has a time complexity of O(n) and a space complexity of O(1). The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python def encode_and_decode_base64(input_string: str) -> str: """ Encodes a given string in Base64 and then decodes it back to its original form. Args: input_string (str): The string to be encoded and then decoded. R...
python_sharegpt_23k
469
Write a Python function to determine if a given integer `n` is a power of two. A number is considered a power of two if it can be expressed as \(2^k\) where \(k\) is a non-negative integer. The function should return `True` if `n` is a power of two, and `False` otherwise. The code should start with: ```python def is_po...
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_two(n: int) -> bool: """ Determine if a given integer n is a power of two. Args: n (int): The integer to check. Returns: bool: True if n is a power of two, False otherwise. """ #...
python_sharegpt_23k
471
Write a Python function to sort a list of positive integers in ascending order using the Bubble Sort algorithm. The function should not use any built-in sorting functions or libraries, and the time complexity should be O(n^2). The function should start with: ```python from typing import List def bubble_sort(myList: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(myList: List[int]) -> List[int]: """ Sorts a list of positive integers in ascending order using the Bubble Sort algorithm. Args: myList (List[int]): The list of positive inte...
python_sharegpt_23k
472
Write a Python function to search for a word in a given string, considering the following constraints: 1. The search should be case-insensitive. 2. The function should handle multiple occurrences of the word and return a list of all the index positions where the word is found. 3. The function should handle partial matc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def search_word_in_string(word: str, string: str) -> List[int]: """ Search for a word in a given string and return a list of all index positions where the word is found. Args: word...
python_sharegpt_23k
487
Write a Python function that takes two parameters, a list of integers and a target integer. The function should return a new list containing only the elements from the original list that are greater than the target integer. Additionally, the function should sort the new list in ascending order. The original list should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_and_sort_greater_than_target(lst: List[int], target: int) -> List[int]: """ Filters and sorts the elements of a list that are greater than a given target integer. Args: lst (List[...
python_sharegpt_23k
491
Write a Python function to sort an array in descending order using the bubble sort algorithm. The function should correctly handle the provided array and ensure that the sorting is done efficiently. The code should start with: ```python from typing import List def sort_array_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 sort_array_descending(arr: List[int]) -> List[int]: """ Sorts the given array in descending order using the bubble sort algorithm. Args: arr (List[int]): The array to be sorted. Ret...
python_sharegpt_23k
492
Write a Python function to find the minimum and maximum values from a list along with the indices of all occurrences of these values. The function should ensure a time complexity of O(n log n) and a space complexity of O(1). The function should handle lists with duplicate values and return the indices of all occurrence...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_min_max_indices(lst: List[int]) -> Tuple[int, List[int], int, List[int]]: """ Find the minimum and maximum values from a list along with the indices of all occurrences of these values. ...
python_sharegpt_23k
514
Write a Python function to find the second largest number in an unsorted list. The function should handle the following edge cases: 1. If the list contains less than 2 elements, raise an exception indicating that there is no second largest number. 2. If the list contains negative numbers, handle them appropriately to f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_second_largest(lst: List[int]) -> int: """ Find the second largest number in an unsorted list of numeric values. Args: lst (List[int]): The list of numeric values. Returns: ...
python_sharegpt_23k
517
Write a Python function to calculate the product of all elements in a given matrix of integers. If any element in the matrix is zero or negative, the function should return -1. The function should handle matrices with up to 1000 rows and 1000 columns. 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 product_of_matrix(matrix: List[List[int]]) -> int: """ Calculate the product of all elements in a given matrix of integers. If any element in the matrix is zero or negative, return -1. Args:...
python_sharegpt_23k
520
Write a Python function to create a dictionary with ten unique key-value pairs, where the keys are alphanumeric characters and the values are strings with a minimum length of 10 characters. The dictionary should be sorted in ascending order based on the keys. The function should return the sorted dictionary. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def create_sorted_dictionary() -> Dict[str, str]: """ Creates a dictionary with ten unique key-value pairs, where the keys are alphanumeric characters and the values are strings with a minimum length...
python_sharegpt_23k
525
Write a Python function to check if a given number is a palindrome. The function should meet the following requirements: 1. The function should have a time complexity of O(log n), where n is the number of digits in the input number. 2. The function should use only constant space complexity. 3. The function should not c...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(num: int) -> bool: """ Check if a given number is a palindrome. The function uses a constant space complexity and a time complexity of O(log n), where n is the number of digits in the input number. It ...
python_sharegpt_23k
526
Write a Python function to calculate the sum of all prime numbers in a given list. The function should take a list of integers as input and return the sum of all prime numbers in the list. The function should start with: ```python from typing import List def sum_of_primes(numbers: List[int]) -> int: ```
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 given number is prime. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise...
python_sharegpt_23k
530
Write a Python function that retrieves the first value from a dictionary that starts with a given letter and is greater than a specified number. The dictionary must have at least 10 key-value pairs. The function should also return the key associated with the retrieved value. Additionally, the function should handle cas...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Optional, Tuple def retrieve_first_value(dictionary: Dict[str, int], starting_letter: str, minimum_value: int) -> Optional[Tuple[int, str]]: """ Retrieves the first value from a dictionary that starts w...
python_sharegpt_23k
534
Write a Python function to count the occurrences of each unique word in a given string, ignoring punctuation and case sensitivity, and excluding specified stop words. The function should return a dictionary where each key is a unique word and each value is the number of times that word appears in the string. The functi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import re def count_words_excluding_stop_words(string: str, stop_words: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique word in a given string, ignoring punctuation and case...
python_sharegpt_23k
538
Write a Python function to calculate the sum of all prime numbers from 1 to a given number `n` (inclusive). The function should have a time complexity of O(n^2) and a space complexity of O(n). The code should start with: ```python def sum_of_primes(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_primes(n: int) -> int: """ Calculate the sum of all prime numbers from 1 to a given number n (inclusive). Args: n (int): The upper limit of the range to calculate the sum of primes. Returns: ...
python_sharegpt_23k
542
Write a Python function to implement an Insertion Sort algorithm that sorts the elements of the input array `arr` in non-decreasing order. The array `arr` may contain duplicate elements. The modified code should have a time complexity of O(n^2) and should not use any built-in sorting functions or libraries. Additionall...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def insertion_sort_large_array(arr: List[float]) -> List[float]: """ Sorts a large array using Insertion Sort in chunks and merges the sorted chunks. Args: arr (List[float]): The...
python_sharegpt_23k
549
Write a Python function to merge two given arrays and remove duplicates. The merged array should be sorted in ascending order. The function should implement the merge sort algorithm to merge the two arrays in O(n log n) time complexity and an efficient algorithm to remove duplicates from the merged array in O(n) time c...
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 arrays and remove duplicates. The merged array is sorted in ascending order. Args: arr1 (List[in...
python_sharegpt_23k
550
Write a Python function to find the highest common factor (HCF) of two numbers without using the modulus operator (%) or any built-in Python functions that directly calculate the HCF. The function should use the subtraction-based approach to iteratively reduce the numbers until the HCF is found. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python def find_hcf(a: int, b: int) -> int: """ Calculate the highest common factor (HCF) of two numbers using an iterative subtraction-based approach. Args: a (int): The first number. b (int): The second number. ...
python_sharegpt_23k
551
Write a Python function to compute the sum of corresponding elements from two lists of integers, `a` and `b`, and return the result as a list. The function should have a time complexity of O(n), where n is the length of the input lists, and a space complexity of O(1), meaning it should not use any additional space to s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_lists(a: List[int], b: List[int]) -> List[int]: """ Computes the sum of corresponding elements from two lists of integers and returns the result as a list. Args: a (List[int]): The f...
python_sharegpt_23k
552
Write a Python function to sort a given list of integers in descending order using a custom merge sort algorithm. The function should not use any built-in sorting functions or data structures, and it should only use a constant amount of extra space. The time complexity of the function should be O(n log n), where n is t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def custom_merge_sort_descending(arr: List[int]) -> List[int]: """ Sorts the given list of integers in descending order using a custom merge sort algorithm. Args: arr (List[int]): The list o...
python_sharegpt_23k
555
Write a Python function to calculate the sum of two integers, ensuring that the sum is always positive and within the range of 1 to 100. The function should handle potential errors and follow PEP-8 guidelines. The code should start with: ```python def calculate_sum(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_sum(a: int, b: int) -> int: """ Calculate the sum of two integers, ensuring the result is always positive and within the range of 1 to 100. Args: a (int): The first integer. b (int): The second...
python_sharegpt_23k
563
Write a Python function to find the longest common prefix of two strings, ignoring case, special characters, spaces, and punctuation marks. The strings should have a length of at least 5 characters. The function should return the longest common prefix as a string. The code should start with: ```python import re def l...
Here is the Python code to solve the given problem in the markdown block: ```python import re def longest_common_prefix_ignore_case_and_special_chars(str1: str, str2: str) -> str: """ Finds the longest common prefix of two strings, ignoring case, special characters, spaces, and punctuation marks. Args: ...
python_sharegpt_23k
579
Write a Python function to concatenate two input strings and return the resulting string. Additionally, the function should print the length of the resulting string. The function must adhere to the following constraints: - The input strings can have a maximum length of 1000 characters each. - The function should have a...
Here is the Python code to solve the given problem in the markdown block: ```python def concatenate_and_print_length(string1: str, string2: str) -> str: """ Concatenates two input strings and returns the resulting string. Additionally, prints the length of the resulting string. Args: string1 (s...
python_sharegpt_23k
582
Write a Python function to determine whether a given number is a triangle number. A triangle number is a number that can be represented as the sum of consecutive positive integers starting from 1. The function should return `True` if the number is a triangle number and `False` otherwise. The input number will be an int...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_triangle_number(num: int) -> bool: """ Determine whether the given number is a triangle number. A triangle number is a number that can be represented as the sum of consecutive positive integers start...
python_sharegpt_23k
591
Write a Python function to implement a binary search algorithm that accounts for duplicates in the list while maintaining a time complexity of O(log n) and a space complexity of O(1). The function should return `True` if the target element is found in the list, otherwise `False`. 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 binary_search_with_duplicates(arr: List[int], target: int) -> bool: """ Implements a binary search algorithm that accounts for duplicates in the list. Args: arr (List[int]): The sorted l...
python_sharegpt_23k
592
Write a Python function to sort an array in-place using the Bubble Sort algorithm in descending order. 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 def bubble_sort_descending(arr: List[int]) -> None: ```
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]) -> None: """ Sorts the given array in-place using the Bubble Sort algorithm in descending order. Args: arr (List[int]): The array to be sorted. ...
python_sharegpt_23k
593
Write a Python function to determine if a given string is a palindrome. The function should ignore spaces, punctuation, and capitalization, and handle Unicode characters, including emojis. The function should have a time complexity of O(n) and should not use any built-in library or function for reversing the string. T...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(s: str) -> bool: """ Determine if a given string is a palindrome, ignoring spaces, punctuation, and capitalization. Handles Unicode characters, including emojis. Args: s (str): The input string...
python_sharegpt_23k
603
Write a Python function to implement the insertion sort algorithm correctly. The function should sort a list of integers in ascending order. The code should start with: ```python from typing import List def insertion_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def insertion_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the insertion sort algorithm. Args: arr (List[int]): The list of integers to be sorted....
python_sharegpt_23k
612
Write a Python function to combine the elements of two lists of equal length into a dictionary. The dictionary should only include elements from `list1` that have a corresponding element in `list2` that is divisible by 3. If there is a repeating element in `list1`, it should be stored as a list of corresponding divisib...
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 specific conditions. The dictionary includes elemen...
python_sharegpt_23k
614
Write a Python function to add two matrices represented as lists of lists of integers. The function should return a new matrix that is the sum of the two input matrices. The matrices will have the same number of rows and columns. The code should start with: ```python from typing import List def add_matrices(a: List[L...
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
618
Write a Python function to check if a given string is a palindrome. The function should be case-insensitive and ignore any non-alphanumeric characters. A palindrome is a sequence of characters that reads the same forward and backward. The function should return `True` if the input string is a palindrome and `False` oth...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(s: str) -> bool: """ Check if the given string is a palindrome, ignoring case and non-alphanumeric characters. Args: s (str): The input string to check. Returns: bool: True if the stri...
python_sharegpt_23k
623
Write a Python function to calculate the nth Fibonacci number using matrix exponentiation. The function should have a time complexity of O(log n) and a space complexity of O(log n). You are not allowed to use any iterative loops or recursive functions in your implementation. The code should start with: ```python def f...
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci_matrix_exponentiation(n: int) -> int: """ Calculate the nth Fibonacci number using matrix exponentiation. Args: n (int): The position in the Fibonacci sequence to calculate. Returns: int: ...
python_sharegpt_23k
626
Write a Python function to calculate the sum of two given positive integers, with additional constraints. The function should validate that the input numbers are positive integers, raise an error if they are not. If the sum of the two numbers exceeds a given maximum value (which must also be a positive integer), the fu...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_with_constraints(num1: int, num2: int, max_value: int, divisor: int) -> int: """ Calculate the sum of two positive integers with additional constraints. Args: num1 (int): The first positive integer. ...
python_sharegpt_23k
627
Write a Python function to generate and print all even numbers from 1 to 1000 in ascending order, but the loop should exit immediately upon encountering the first prime number. The function should not use any conditional statements (if-else) inside the loop. The time complexity should be less than O(n^2). The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime(num: int) -> bool: """ Check if a given number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. ""...
python_sharegpt_23k
628
Write a Python function to calculate the product of two numbers, which may be positive or negative integers. The input numbers are guaranteed to not exceed 10^9 in absolute value. The function should correctly handle the sign of the product based on the signs of the input numbers. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_product(num1: int, num2: int) -> int: """ Calculate the product of two integers, correctly handling the sign based on the input numbers. Args: num1 (int): The first integer. num2 (int): The sec...
python_sharegpt_23k
629
Write a Python function that processes a list of strings according to the following rules: 1. Capitalize each string. 2. Remove any string that contains special characters (i.e., any character that is not alphanumeric or whitespace). The function should have a time complexity of O(n), where n is the total number of ch...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def process_strings(strings: List[str]) -> List[str]: """ Processes a list of strings by capitalizing each string and removing any strings that contain special characters. Args: st...
python_sharegpt_23k
630
Implement the Gnome sort algorithm with the following additional steps: 1. Before starting the sorting process, check if the array is already sorted. If it is, return the sorted array immediately without performing any further steps. The array will be considered sorted if it is in descending order. 2. During each swap ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def gnome_sort_descending(arr: List[int]) -> List[int]: """ Sorts the given array in descending order using the Gnome sort algorithm with additional optimizations. Args: arr (List[int]): The...
python_sharegpt_23k
635
Write a Python function to reverse a given string without using any built-in string reversal functions or methods. The function should have a time complexity of O(n) and a space complexity of O(1). The function 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
638
Write a Python function to find all prime numbers between two given integers, `start` and `end` (inclusive), with a time complexity of O((end-start+1)*log(log(end))). The function should use an optimized algorithm to achieve this time complexity. The code should start with: ```python from typing import List import mat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def find_primes_in_range(start: int, end: int) -> List[int]: """ Find all prime numbers between start and end (inclusive) using an optimized algorithm. Args: start (int): The sta...
python_sharegpt_23k
642
Write a Python function to perform a binary search on a sorted array to find the index of the first occurrence of a target element. If the target is not found, return -1. The function should handle arrays with duplicate elements and should have a time complexity of O(log n), where n is the length of the array. The func...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search_first_occurrence(arr: List[int], target: int) -> int: """ Perform a binary search to find the index of the first occurrence of the target element in a sorted array. If the target is...
python_sharegpt_23k
644
Write a Python function to rotate a given square matrix by 90 degrees in a clockwise direction. The matrix is represented as a two-dimensional list, where each inner list represents a row of the matrix. The function should modify the matrix in-place and return the modified 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_90_clockwise(matrix: List[List[int]]) -> List[List[int]]: """ Rotates a given square matrix by 90 degrees in a clockwise direction. Args: matrix (List[List[int]]): The inpu...
python_sharegpt_23k
649
Write a Python function to find the maximum sum subarray within a given array using the divide and conquer algorithm. The function should return the maximum sum of the subarray. The code should start with: ```python from typing import List def max_subarray_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 max_subarray_sum(arr: List[int]) -> int: """ Find the maximum sum of a subarray within the given array using the divide and conquer algorithm. Args: arr (List[int]): The input array of i...
python_sharegpt_23k
651
Write a Python function to calculate the average of positive even numbers from a given list of numbers. The function should handle errors and ensure the input list contains at least one number. Additionally, the function should raise appropriate exceptions if the input list is empty, contains non-numeric values, or doe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average_positive_even(numbers: List[float]) -> float: """ Calculate the average of positive even numbers from a given list of numbers. Args: numbers (List[float]): A list of nu...
python_sharegpt_23k
653
Write a Python function to generate a 5 x 5 matrix filled with prime numbers ranging from 1 to 25. Additionally, implement a function to check if a given number is prime using a probabilistic primality test algorithm such as Miller-Rabin. The matrix generation function should use this primality test to ensure that each...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def is_prime(n: int, k: int = 5) -> bool: """ Check if a number is prime using the Miller-Rabin primality test. Args: n (int): The number to check for primality. k (int...
python_sharegpt_23k
660
Write a Python function to remove all occurrences of a given item from a list without using the built-in `remove` function, `del` keyword, or any other built-in function specifically designed for removing elements from a list. The function should have a time complexity of O(n) and should be able to handle lists with a ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_items(lst: List[int], item: int) -> List[int]: """ Removes all occurrences of a given item from a list without using built-in removal functions. Args: lst (List[int]): The list fr...
python_sharegpt_23k
662
Write a Python function to generate and print a multiplication table for a given number, but with specific constraints. The table should only include multiples of 3, end at the 100th multiple, and only display the multiples of 3 that are also divisible by 2 and have a digit sum greater than 10. The function should stop...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_multiplication_table(number: int): """ Generates and prints a multiplication table for the given number, but with specific constraints. The table only includes multiples of 3, ends at the 100th multiple, and onl...
python_sharegpt_23k
663
Write a Python function to find the greatest common factor (GCF) of three prime numbers. The function should have a time complexity of O(n), where n is the largest prime number among the three. The function should not use any built-in Python functions or libraries for calculating the GCF. The code should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def find_gcf_of_primes(prime1: int, prime2: int, prime3: int) -> int: """ Find the greatest common factor (GCF) of three prime numbers. Args: prime1 (int): The first prime number. prime2 (int): The second pr...
python_sharegpt_23k
664
Write a Python function to find all prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm. The function should return a list of the prime numbers. The code should start with: ```python from typing import List def find_primes_up_to(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_primes_up_to(n: int) -> List[int]: """ Find all prime numbers up to a given number n using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit up to which prime numb...
python_sharegpt_23k
665
Write a Python function to remove the first element from an array and shift all the remaining elements to fill the empty space. The function should be implemented manually without using any built-in array functions or additional data structures. The time complexity of the solution should be O(n), where n is the size of...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_and_shift(arr: List[int]) -> List[int]: """ Removes the first element from the array and shifts all the remaining elements to fill the empty space. Args: arr (List[int]): The inpu...
python_sharegpt_23k
667
Write a Python function to calculate the total number of unique digits in a given number. The number can be positive or negative. If the number is negative, consider the negative sign as a digit as well. The function should have a time complexity of O(n), where n is the number of digits in the input number. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python def count_unique_digits(num: int) -> int: """ Calculate the total number of unique digits in a given number. Args: num (int): The input number, which can be positive or negative. Returns: int: The total...
python_sharegpt_23k
670
Write a Python function to count the number of items in a given hashmap (dictionary) using a recursive function that employs a backtracking algorithm. You are not allowed to use any built-in functions or methods for counting the items, nor are you allowed to use any loops, recursion, or any other form of iteration to i...
Here is the Python code to solve the given problem in the markdown block: ```python def count_items(hashmap: dict) -> int: """ Counts the number of items in a given hashmap using a recursive function with backtracking. Args: hashmap (dict): The hashmap (dictionary) to count the items from. Ret...
python_sharegpt_23k
677
Write a Python function to extract the first 3 unique elements from a given list without using built-in slicing functionality. The function should manually iterate through the list and extract the elements one by one. The function should handle cases where the list may contain duplicate elements and should return a lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def extract_first_three_unique(lst: List[int]) -> List[int]: """ Extracts the first 3 unique elements from the given list. Args: lst (List[int]): The list from which to extract the first 3 u...
python_sharegpt_23k
679
Write a Python function to find the common elements between two lists and return them in a new list. The function should have a time complexity of O(n^2), where n is the length of the longer list. The function should not use any built-in functions or libraries that directly solve the problem. Handle edge cases such as ...
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 and return a list of elements that are common to both input lists. Args: list1 (List[int]): The first list...
python_sharegpt_23k
680
Write a Python function to reverse a string in place without using any built-in string reversal methods or functions. The function should only use a single loop and should not create any new variables or data structures. The function should handle special characters, whitespace, and uppercase/lowercase letters correctl...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string_in_place(string: str) -> str: """ Reverses a string in place without using any built-in string reversal methods or functions. Args: string (str): The input string to be reversed. Returns: ...
python_sharegpt_23k
681
Write a Python function that performs a series of operations which may raise different types of exceptions. The function should handle these exceptions using multiple `except` statements, each tailored to handle a specific type of exception. Additionally, include a final `except` statement to catch any other exceptions...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def handle_exceptions() -> List[str]: """ Perform a series of operations that may raise different types of exceptions and handle them using multiple `except` statements. Additionally, include a neste...
python_sharegpt_23k
683
Write a Python function to generate a random string of 20 lowercase letters, ensuring that the string contains at least two vowels and three consonants. The function should start with: ```python from typing import List def generate_random_string() -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random import string def generate_random_string() -> str: """ Generates a random string of 20 lowercase letters, ensuring it contains at least two vowels and three consonants. Returns: ...
python_sharegpt_23k
691
Write a Python function to determine if a given string is a palindrome. The function should ignore any non-alphanumeric characters, be case-insensitive, and handle strings with leading or trailing spaces. The function should be implemented without using any built-in string manipulation functions such as `reverse()` or ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(s: str) -> bool: """ Determine if a given string is a palindrome, ignoring non-alphanumeric characters, case, and leading or trailing spaces. Args: s (str): The input string to check. Retu...
python_sharegpt_23k
698
Write a Python function to generate a list of `n` unique random integers within a specified range `[min_val, max_val]` and sort them in ascending order using a custom merge sort algorithm. The function should not use any built-in sorting functions or libraries. The code should start with: ```python from typing import L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_and_sort_unique_numbers(n: int, min_val: int, max_val: int) -> List[int]: """ Generate a list of n unique random integers within the range [min_val, max_val] and sort them in a...
python_sharegpt_23k
699
Write a Python function to sort a list of integers in descending order, remove duplicates, and append the string "Prime" after each prime number in the output list. The function should adhere to the following constraints: - The length of the list should not exceed 1000 elements. - The numbers in the list should be inte...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_descending_primes(nums: List[int]) -> List[int]: """ Sorts a list of integers in descending order, removes duplicates, and appends the string "Prime" after each prime number. Args: ...
python_sharegpt_23k
702
Write a Python function to calculate the `n`th number in the Fibonacci sequence using a purely mathematical formula or expression. The function must adhere to the following constraints: 1. No recursion, iteration, or any built-in mathematical functions (such as `pow`, `sqrt`, etc.) can be used. 2. No loops or condition...
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using a purely mathematical formula. Args: n (int): The position in the Fibonacci sequence to calculate. Returns: int: The nth Fibona...
python_sharegpt_23k
709
Write a Python function to find the intersection of two given arrays while maintaining the order of elements from the first array. The function should meet the following requirements: 1. The function should have a time complexity of O(n), where n is the total number of elements in both arrays. 2. The function should ha...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_intersection(arr_1: List[int], arr_2: List[int]) -> List[int]: """ Find the intersection of two arrays while maintaining the order of elements from the first array. Args: arr_1 (Lis...
python_sharegpt_23k
712
Write a Python function to sort a list of integers using the insertion sort algorithm. The function should take a list of integers as input and return the sorted list in ascending order. The insertion sort algorithm should be implemented as described in the given code snippet. The code should start with: ```python fro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def insertion_sort(nums: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the insertion sort algorithm. Args: nums (List[int]): The list of integers to be sorte...
python_sharegpt_23k
714
Write a Python function to calculate the sum of the cubes of all the even numbers in a given list of integers. If any of the numbers in the list is a negative integer, the function should raise a `ValueError` with the message "Negative integers are not allowed". Additionally, if the input list is empty, the function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_even_cubes(numbers: List[int]) -> int: """ Calculate the sum of the cubes of all even numbers in the given list. Args: numbers (List[int]): A list of integers. Returns: ...
python_sharegpt_23k
718
Write a Python function to increment a given counter by a specified positive integer without using the addition operator (`+`), multiplication operator (`*`), or any bitwise operations. The function should ensure the time complexity of the solution is O(1). The code should start with: ```python def increment_counter(c...
Here is the Python code to solve the given problem in the markdown block: ```python def increment_counter(counter: int, increment_value: int) -> int: """ Increments the given counter by the specified positive integer without using the addition operator (+), multiplication operator (*), or any bitwise operat...
python_sharegpt_23k
720
Write a Python function to evaluate a given Python expression dynamically, ensuring that it does not exceed a certain length limit, returns a specific data type, and handles errors and exceptions appropriately. The solution should be optimized to have a time complexity of O(n) and a space complexity of O(1), where n is...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_expression(expression: str, length_limit: int, return_type: type) -> any: """ Evaluates a given Python expression dynamically, ensuring it does not exceed a certain length limit, returns a specific data type, an...
python_sharegpt_23k
721
Write a Python function to reverse a given list without using the built-in `reverse()` method, slicing syntax, or any other built-in function or method to reverse the list. Additionally, you are not allowed to use any additional data structures or create any helper functions. The function should directly modify the inp...
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 given list in place without using built-in reverse methods, slicing, or additional data structures. Args: lst (List[int]): The...
python_sharegpt_23k
727
Write a Python function to generate an array of 1 million unique random integers between -1 million and 1 million, and then sort the array in ascending order using a quicksort algorithm. The quicksort algorithm should be optimized to have an average time complexity of O(n log n) and a worst-case time complexity of O(n^...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_and_sort_array() -> List[int]: """ Generates an array of 1 million unique random integers between -1 million and 1 million, and sorts the array in ascending order using a q...
python_sharegpt_23k
732
Write a Python function to count the number of elements in a list of strings without using the `len()` function or any other built-in function that counts the number of elements. The function should iterate over the elements of the list and return the total number of elements. The code should start with: ```python fro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_elements(mylist: List[str]) -> int: """ Counts the number of elements in a list of strings without using the len() function or any other built-in function that counts the number of elements. ...
python_sharegpt_23k
739
Write a Python function to print the words "hello world" five times, but each occurrence must be capitalized and separated by a comma. The function must use a loop to print the words instead of repeating the print statement five times. You are not allowed to use any string manipulation functions or methods to capitaliz...
Here is the Python code to solve the given problem in the markdown block: ```python def print_capitalized_hello_world(): """ Prints the words "hello world" five times, each occurrence capitalized and separated by a comma. This function uses basic control structures and operations to achieve the desired res...
python_sharegpt_23k
741
Write a Python function to merge two sorted arrays into one sorted array without any duplicate elements. The function should have a time complexity of O(n log n) and should not use any built-in sorting functions or data structures. The merged array should be stored in a new array, and the original arrays should remain ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_arrays(array1: List[int], array2: List[int]) -> List[int]: """ Merge two sorted arrays into one sorted array without any duplicate elements. Args: array1 (List[int]): The fi...
python_sharegpt_23k
745
Write a Python function to calculate the factorial of a given non-negative integer using a recursive approach. The function should not use any loop constructs (such as `for` or `while` loops) or the built-in factorial function. The code should start with: ```python def factorial_recursive(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_recursive(n: int) -> int: """ Calculate the factorial of a given non-negative integer using a recursive approach. Args: n (int): The non-negative integer for which to calculate the factorial. Retu...
python_sharegpt_23k
746
Write a Python function to calculate the sum of all even numbers in a given list of integers. Additionally, the function should return the count of even numbers and the average of all even numbers rounded to two decimal places. The function must use a while loop and should not use any built-in functions or methods that...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_even_stats(lst: list) -> tuple: """ Calculate the sum, count, and average of all even numbers in the given list. Args: lst (list): A list of integers. Returns: tuple: A tuple containing th...
python_sharegpt_23k
755
Write a Python function to generate a random string of a specified length, composed of numbers, lowercase letters, uppercase letters, and special characters. The function should ensure that the generated string contains at least one character from each of the four categories. The code should start with: ```python impor...
Here is the Python code to solve the given problem in the markdown block: ```python import random import string def generate_secure_random_string(length: int) -> str: """ Generate a random string of the specified length, ensuring it contains at least one character from each of the following categories: - N...
python_sharegpt_23k
762
Write a Python function to calculate the sum and product of three given integers using only bitwise operations. The function should print the values of the integers in a specific order and then print the calculated sum and product. The code should start with: ```python def calculate_sum_and_product(num1: int, num2: int...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_sum_and_product(num1: int, num2: int, num3: int) -> None: """ Calculate and print the sum and product of three integers using only bitwise operations. Args: num1 (int): The first integer. num2 ...
python_sharegpt_23k
764
Write a Python function to transpose a given matrix. The matrix is represented as a list of lists, where each inner list represents a row of the matrix. The function should return the transposed matrix, where the rows of the original matrix become the columns of the transposed matrix. The code should start with: ```py...
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 the given matrix. Args: matrix (List[List[int]]): The original matrix to be transposed. Returns: ...
python_sharegpt_23k
765
Write a Python function to find the longest common prefix string among an array of strings, where the prefix must be at least 10 characters long. The input array can contain up to 500 strings, and each string can have a maximum length of 200 characters. The strings in the input array can contain uppercase and lowercase...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_prefix_at_least_10(strings: List[str]) -> str: """ Find the longest common prefix string among an array of strings, where the prefix must be at least 10 characters long. Args: ...
python_sharegpt_23k
777
Write a Python function to generate and return the Fibonacci sequence up to the nth number. The function should take an integer `n` as input and return a list containing the first `n` Fibonacci numbers. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two. The code shou...
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 Fibonacci sequence up to the nth number. Args: n (int): The number of Fibonacci numbers to generate. Returns: List[...
python_sharegpt_23k
782
Write a Python function to extract and print all prime numbers from a given array in ascending order, and then remove those prime numbers from the array. The function should adhere to the following constraints: - The time complexity of the function should be O(n * sqrt(max)), where n is the size of the array and max is...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def extract_and_remove_primes(arr: List[int]) -> List[int]: """ Extracts and prints all prime numbers from the given array in ascending order, and then removes those prime numbers from th...
python_sharegpt_23k
784
Write a Python function to search for a given item in a sorted list and return the indices of all occurrences of the item in the list. If the item is not found, the function should return an empty list. Additionally, the function should also return the number of occurrences of the item in the list. The function should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def search_item(list_items: List[int], item_to_search: int) -> Tuple[List[int], int]: """ Searches for a given item in a sorted list and returns the indices of all occurrences of the item. If ...
python_sharegpt_23k
792
Write a Python function to determine if a given number is a power of two using bitwise operations. The function should have a time complexity of O(1) and a space complexity of O(1). The number should be represented in binary and have exactly one '1' bit set. The code should start with: ```python def is_power_of_two(n:...
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_two(n: int) -> bool: """ Determines if a given number is a power of two using bitwise operations. Args: n (int): The number to check. Returns: bool: True if the number is a power of two,...
python_sharegpt_23k
793
Write a Python function to sort a given list of numbers using the Merge Sort algorithm. The function should ensure that the time complexity of the merge function is O(n), where n is the length of the list, and the space complexity of the merge_sort function is O(n), where n is the length of the list. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the Merge Sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: List...
python_sharegpt_23k
801
Write a Python function to filter out positive numbers greater than 10 from a given array and sort the resulting array in ascending order. The solution should not use any built-in Python functions or libraries for sorting and should have a time complexity of O(n log n). The code should start with: ```python from typing...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts the input array using the Merge Sort algorithm. Args: arr (List[int]): The array to be sorted. Returns: List[int]: The sor...
python_sharegpt_23k
819
Write a Python function to perform a binary search on a sorted array that may contain duplicate elements. The function should return the index of the first occurrence of the target element if it exists, otherwise return -1. The function should be implemented using a recursive approach and should have a runtime complexi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search_first_occurrence(arr: List[int], low: int, high: int, target: int) -> int: """ Perform a binary search to find the first occurrence of the target element in a sorted array. Args: ...
python_sharegpt_23k
824
Write a Python function to convert all lowercase characters in a list of strings to uppercase. The function should handle the following scenarios: 1. If the input list is empty, the function should return an empty list. 2. If any of the strings in the input list contain non-alphabetic characters, the function should ra...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def convert_to_uppercase(strings: List[str]) -> List[str]: """ Converts all lowercase characters in a list of strings to uppercase. Args: strings (List[str]): A list of strings to be convert...
python_sharegpt_23k
825
Write a Python function to convert a decimal number to a binary number without using any built-in functions or libraries for conversion, and also without using any loops or recursion. Additionally, you are not allowed to use any bitwise operators or string manipulation methods. The function should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python def decimal_to_binary(decimal: int) -> int: """ Converts a decimal number to its binary representation without using any built-in functions, loops, recursion, bitwise operators, or string manipulation methods. Args: ...
python_sharegpt_23k
830
Write a Python function to convert a given string to its hexadecimal representation. The input string will consist of only lowercase letters, numbers, and special characters, and will not exceed 1000 characters in length. The function should handle empty strings as well. The function should use an iterative approach, h...
Here is the Python code to solve the given problem in the markdown block: ```python def string_to_hexadecimal(string: str) -> str: """ Converts a given string to its hexadecimal representation. Args: string (str): The input string to be converted. It consists of only lowercase letters, numbers, and...
python_sharegpt_23k
838
Write a Python function that takes a list of integers and returns a list containing only the odd numbers from the original list. The resulting list should be sorted in descending order and should not contain any duplicates. Implement the solution without using any built-in functions or methods for sorting or removing d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_sort_remove_duplicates(nums: List[int]) -> List[int]: """ Filters out the odd numbers from the input list, sorts them in descending order, and removes any duplicates. Args: nu...
python_sharegpt_23k
840
Write a Python function that demonstrates the concept of lexical closure. The outer function should accept two parameters and return a closure function. The closure function should accept one parameter and return a value that is computed using the values of all three parameters. The closure function should contain at l...
Here is the Python code to solve the given problem in the markdown block: ```python def create_closure(a: int, b: int): """ Creates a closure function that accepts one parameter and returns a computed value. Args: a (int): The first parameter for the outer function. b (int): The second para...