source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
python_sharegpt_23k
13,978
Write a Python function to remove all occurrences of a specified element from a given list and return the modified list. The function should handle the following scenarios: 1. **Empty List**: If the input list is empty, return an empty list. 2. **No Occurrences**: If the input list does not contain any occurrences of t...
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]: """ Remove all occurrences of a specified element from a given list and return the modified list. Args: lst (List[int]): The li...
python_sharegpt_23k
13,989
Write a Python function to encode a text string using the Caesar cipher with a variable shift. The shift value should be provided as an argument to the function. The function should handle special characters, including punctuation marks, and maintain their original positions in the encoded string. Both uppercase and lo...
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_cipher_encode(text: str, shift: int) -> str: """ Encodes a text string using the Caesar cipher with a variable shift. Args: text (str): The text string to be encoded. shift (int): The shift value ...
python_sharegpt_23k
13,990
Write a Python function to sort a given list of numbers in descending order using the Merge Sort algorithm, which has a time complexity of O(nlogn). The function should recursively divide the input list into two halves, sort each half, and then merge the two sorted halves back together into a single sorted list in desc...
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 a given list of numbers in descending order using the Merge Sort algorithm. Args: arr (List[int]): The list of numbers to be...
python_sharegpt_23k
13,994
Write a Python function to calculate the sum of all numbers in a given list without using the `+` operator or any built-in functions or libraries. 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 List def calculate_sum_without_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum_without_plus(numbers: List[int]) -> int: """ Calculate the sum of all numbers in a given list without using the '+' operator or any built-in functions. Args: numbers (List[...
python_sharegpt_23k
13,999
Write a Python function to remove all even elements and duplicates from a given list while preserving the original order of the elements. The input list should contain at least 20 elements. The function should start with: ```python from typing import List def remove_even_duplicates(lst: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_even_duplicates(lst: List[int]) -> List[int]: """ Removes all even elements and duplicates from the given list while preserving the original order of the elements. Args: lst (List...
python_sharegpt_23k
14,004
Write a Python function to filter out all even numbers from a given list of integers using a lambda function with the `filter()` method. The function should return a new list containing only the odd numbers from the original list. The code should start with: ```python from typing import List def filter_odd_numbers(nu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_odd_numbers(numbers: List[int]) -> List[int]: """ Filters out all even numbers from the given list of integers and returns a new list containing only the odd numbers. Args: number...
python_sharegpt_23k
14,005
Write a Python function to print the value of a variable `num` if it is within the range of 1 to 100 (inclusive). If `num` is not within this range, print an error message instead. Additionally, after printing each valid value of `num`, increment its value by 2 until it reaches or exceeds 100. The function should start...
Here is the Python code to solve the given problem in the markdown block: ```python def print_num_within_range(num: int) -> None: """ Prints the value of num if it is within the range of 1 to 100 (inclusive). If num is not within this range, prints an error message. After printing each valid value of nu...
python_sharegpt_23k
14,009
Write a Python function to determine if a given positive integer is a prime number. Additionally, create a function to generate the first n prime numbers and calculate their product. The code should start with: ```python def is_prime(num: int) -> bool: ``` and ```python def generate_first_n_primes_and_product(n: int) ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Determines if a given positive integer is a prime number. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False otherw...
python_sharegpt_23k
14,011
Write a Python function to remove all duplicate elements from a given list and return the result. The function should not use any built-in Python functions or libraries, except for basic data structures like lists and sets. The function should have a time complexity of O(n), where n is the length of the list. The code...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_duplicates(lst): """ Removes all duplicate elements from the given list and returns the result. Args: lst (list): The list from which to remove duplicates. Returns: list: A list containing on...
python_sharegpt_23k
14,012
Write a Python function that takes a string, a keyword, and a replacement word. The function should delete all occurrences of the keyword in the given string and replace them with the replacement word. The function should be case-sensitive and should also count and return the total number of occurrences of the keyword ...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_keyword(string: str, keyword: str, replacement: str) -> (int, str): """ Replace all occurrences of the keyword in the given string with the replacement word, while counting the total number of occurrences of the ...
python_sharegpt_23k
14,014
Write a Python function to generate and return a list of the first n Fibonacci numbers. The function should handle the edge case where n is 0 by returning an empty list. The code should start with: ```python from typing import List def generate_fibonacci(n: int) -> List[int]: ```
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 a list of the first n Fibonacci numbers. Args: n (int): The number of Fibonacci numbers to generate. Returns: List[int]...
python_sharegpt_23k
14,016
Write a Python function to traverse a given matrix in a spiral order and calculate the sum of all positive elements while skipping any negative numbers. The function should start from the top-left corner and move right, down, left, and up in a spiral manner until all elements have been visited. The code should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def spiral_sum_of_positive_elements(matrix: List[List[int]]) -> int: """ Traverse a given matrix in a spiral order and calculate the sum of all positive elements. Args: matrix (List[List[int...
python_sharegpt_23k
14,017
Write a Python function to merge overlapping intervals in a list of intervals. Each interval is represented as a list of two integers, where the first integer is the start time and the second integer is the end time. The function should return a list of merged intervals. 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 merge_intervals(intervals: List[List[int]]) -> List[List[int]]: """ Merge overlapping intervals in a list of intervals. Args: intervals (List[List[int]]): A list of intervals, where each...
python_sharegpt_23k
14,020
Write a Python function to calculate the sum of elements in an array where each element is added to the total sum only if it is larger than the previous element. The array will only contain positive integers. The function should return the total sum of all the valid items in the array. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_increasing_elements(arr: List[int]) -> int: """ Calculate the sum of elements in an array where each element is added to the total sum only if it is larger than the previous element. ...
python_sharegpt_23k
14,027
Write a Python function to generate a unique ID for each element in a given array. The unique ID should be a combination of a randomly generated alphanumeric string, a timestamp, and a checksum. The alphanumeric string should be at least 20 characters long and should contain a combination of uppercase letters, lowercas...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random import string import hashlib import datetime def generate_alphanumeric(length: int) -> str: """ Generate a random alphanumeric string of the specified length. Args: length (int...
python_sharegpt_23k
14,029
Write a Python function to calculate the number of valid permutations of length `n` with respect to a given set of `n` distinct elements, where each element can only appear once in a permutation and there are certain constraints on the order of elements. The constraints are: 1. The first element in the permutation can ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_valid_permutations(n: int, elements: List[int]) -> int: """ Calculate the number of valid permutations of length n with respect to a given set of n distinct elements. Each element can only ...
python_sharegpt_23k
14,033
Write a Python function that converts a time string in the format `hh:mm:ss` to the total number of seconds. The function should handle time strings with leading zeroes for the hour, minute, and second components. The time string will always be valid and represent a time within a 24-hour period. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python def time_to_seconds(time_string: str) -> int: """ Converts a time string in the format 'hh:mm:ss' to the total number of seconds. Args: time_string (str): A string representing time in the format 'hh:mm:ss'. Re...
python_sharegpt_23k
14,035
Write a Python function to find the largest number in a given array without using any built-in functions or methods. You are only allowed to use basic arithmetic operations and control structures. The array can contain both positive and negative integers. Additionally, the time complexity of your solution should be O(n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_number(arr: List[int]) -> int: """ Find the largest number in a given array without using any built-in functions or methods. Args: arr (List[int]): The array of integers fro...
python_sharegpt_23k
14,038
Write a Python function to find the longest common substring between two given strings. The function should have a time complexity of O(n^3), where n is the length of the longer string. The function should handle cases where the strings can contain special characters and are case-sensitive. Additionally, the function s...
Here is the Python code to solve the given problem in the markdown block: ```python def find_longest_common_substring(str1: str, str2: str) -> str: """ Find the longest common substring between two given strings. Args: str1 (str): The first string to compare. str2 (str): The second string t...
python_sharegpt_23k
14,047
Write a Python function that takes an array of integers as input and randomly swaps two elements in the array. The function should return the modified array. The array should contain unique elements, have a length of at least 5, and the swapped elements should be at least 3 positions apart. The code should start with:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def random_swap_elements(array: List[int]) -> List[int]: """ Randomly swaps two elements in the given array. The array must contain unique elements and have a length of at least 5. The ...
python_sharegpt_23k
14,054
Write a Python function to count the number of unique words in a given string, ignoring case sensitivity. The function should handle leading and trailing spaces and should not modify the input string. The function should start with: ```python def count_unique_words(string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_unique_words(string: str) -> int: """ Counts the number of unique words in a given string, ignoring case sensitivity. Args: string (str): The input string containing words to be counted. Returns: ...
python_sharegpt_23k
14,055
Write a Python function `access_tuple_element(T, k)` that takes in a tuple `T` and an index `k` as parameters, and returns the element at index `k`. The function should not use any built-in Python functions like `tuple.index()` or `tuple.__getitem__()` to access the element. Instead, implement the logic yourself using ...
Here is the Python code to solve the given problem in the markdown block: ```python def access_tuple_element(T, k): """ Accesses the element at index k in the tuple T without using built-in functions. Args: T (tuple): The tuple from which to access the element. k (int): The 1-based index of...
python_sharegpt_23k
14,056
Write a Python function to determine if a given string contains only prime digits (i.e., digits that are prime numbers). The function should return `True` if all characters in the string are prime digits, and `False` otherwise. The code should start with: ```python def contains_only_prime_digits(string: str) -> bool: `...
Here is the Python code to solve the given problem in the markdown block: ```python def contains_only_prime_digits(string: str) -> bool: """ Determines if a given string contains only prime digits. Args: string (str): The input string to be checked. Returns: bool: True if all character...
python_sharegpt_23k
14,058
Write a Python function that takes an array of strings and returns an array of tuples containing the first and last word of each string, after removing any leading or trailing whitespace and punctuation marks. The function should handle cases where strings contain multiple consecutive spaces or only one word, and shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def extract_first_and_last_words(strings: List[str]) -> List[Tuple[str, str]]: """ Extracts the first and last words from each string in the input list, after removing any leading or trailing whit...
python_sharegpt_23k
14,060
Write a Python function to multiply two matrices and raise an exception if the matrices cannot be multiplied due to incompatible dimensions. The function should return the resulting matrix if the multiplication is valid. The code should start with: ```python from typing import List def multiply_matrices(A: List[List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_matrices(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: """ Multiplies two matrices A and B. Raises a ValueError if the matrices cannot be multiplied due to incompatible dimensi...
python_sharegpt_23k
14,074
Write a Python function to replace each character in a given string with the next character in the alphabet, wrapping around from 'z' to 'a' and 'Z' to 'A'. The input string will only consist of alphabetic characters (both uppercase and lowercase), and it can be empty. The output string should have the same length as t...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_characters(input_str: str) -> str: """ Replace each character in the input string with the next character in the alphabet, wrapping around from 'z' to 'a' and 'Z' to 'A'. Args: input_str (str): The input...
python_sharegpt_23k
14,076
Write a Python function to find the nth prime number efficiently without using any pre-calculated lists or libraries. Additionally, create an array of length 1000 populated with the first 1000 prime numbers using this function. The code should start with: ```python from typing import List def nth_prime(n: int) -> int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def nth_prime(n: int) -> int: """ Calculate the nth prime number efficiently. Args: n (int): The position of the prime number to find. Returns: int: The nth prime number. ""...
python_sharegpt_23k
14,079
Write a Python function to swap the case of each character in a given string `x` containing only alphabetic characters. The function should be efficient and should not use any built-in string manipulation functions or methods (e.g., `lower()`, `upper()`, `swapcase()`). The input string `x` will have at most a length of...
Here is the Python code to solve the given problem in the markdown block: ```python def swap_case(x: str) -> str: """ Swaps the case of each alphabetic character in the input string `x`. Args: x (str): The input string containing only alphabetic characters. Returns: str: A new string w...
python_sharegpt_23k
14,081
Write a Python function to reverse the order of words in a given string, while excluding any consecutive duplicate words and removing any non-alphabet characters from the string before processing. The function should start with: ```python from typing import List def reverse_words_and_remove_duplicates(string: str) -> ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def reverse_words_and_remove_duplicates(string: str) -> str: """ Reverses the order of words in a given string, removes consecutive duplicate words, and removes any non-alphabet characters ...
python_sharegpt_23k
14,086
Write a Python function to reverse a given string without using any built-in string reversal functions or methods, and without creating any new strings or using any additional data structures. The function should modify the input string in place. The code should start with: ```python def reverse_string(s: str) -> str:...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(s: str) -> str: """ Reverses the input string in place without using any built-in string reversal functions or methods, and without creating any new strings or using any additional data structures. Ar...
python_sharegpt_23k
14,088
Write a Python function to find the first occurrence of a target element in a sorted array using binary search. The function should return the index of the first occurrence of the target element. If the target element is not found, the function should return -1. The function should handle arrays with duplicates and ens...
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: """ Find the first occurrence of a target element in a sorted array using binary search. Args: arr (List[int]): A sort...
python_sharegpt_23k
14,089
Write a Python function to reverse a list of numbers without using any built-in functions or methods. The function should use a single loop and a constant amount of extra space, ensuring that the time complexity is O(n), where n is the length of the input list. Additionally, the function should handle cases where the i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list(nums: List[int]) -> List[int]: """ Reverses a list of numbers without using any built-in functions or methods. The function uses a single loop and a constant amount of extra space, e...
python_sharegpt_23k
14,092
Write a Python function to determine if a given positive integer `n` is both a prime number and a perfect square. The function should return `True` if both conditions are met, and `False` otherwise. The function should have a time complexity of O(sqrt(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 import math def is_prime_and_perfect_square(n: int) -> bool: """ Determines if a given positive integer `n` is both a prime number and a perfect square. Args: n (int): The positive integer to check. Returns: ...
python_sharegpt_23k
14,096
Write a Python function to filter an array of strings based on a given character. The function should return an array containing only the strings that start with the given character, ignoring any leading whitespace characters before checking the first character of each string. 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 filter_strings_by_char(arr: List[str], char: str) -> List[str]: """ Filters an array of strings to return only those that start with a given character, ignoring any leading whitespace. Args:...
python_sharegpt_23k
14,097
Write a Python function to create an array of size 100 filled with unique random integer numbers between -100 and 100, ensuring that the array contains an equal number of positive and negative integers. The function should not use any loops and should leverage Numpy for efficient array operations. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_unique_random_array() -> np.ndarray: """ Create an array of size 100 filled with unique random integer numbers between -100 and 100, ensuring that the array contains an equal number of positive...
python_sharegpt_23k
14,103
Write a Python function to count the occurrences of each character in a given string and return a dictionary where the keys are the unique characters in the string and the values are the counts of each character. The input string will consist only of lowercase letters, numbers, and special characters. The input string ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_characters(string: str) -> Dict[str, int]: """ Count the occurrences of each character in a given string and return a dictionary where the keys are the unique characters and the values are ...
python_sharegpt_23k
14,108
Write a Python function to calculate the total number of unique positive integers in a nested array of sub-arrays, where each sub-array contains exactly two elements. The elements in each sub-array are restricted to be positive integers greater than zero. The array can also contain sub-arrays with negative integers or ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flatten_array(arr: List) -> List: """ Recursively flattens a nested array into a single list of elements. Args: arr (List): The nested array to be flattened. Returns: List: ...
python_sharegpt_23k
14,111
Write a Python function to flatten a deeply nested list into a single list. The function should handle lists of arbitrary depth and structure, including lists within lists, and return a single list containing all the elements in a flat structure. The code should start with: ```python from typing import List, Any def ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def flatten_nested_list(nested_list: List[Any]) -> List[Any]: """ Flattens a deeply nested list into a single list. Args: nested_list (List[Any]): The nested list to be flattened. ...
python_sharegpt_23k
14,115
Write a Python function to calculate the sum of all elements in a given list that are greater than zero and less than or equal to 100. The list can have up to 1 million elements. The function should be efficient and handle large datasets. The code should start with: ```python from typing import List def sum_elements_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_elements_in_range(elements: List[int]) -> int: """ Calculate the sum of all elements in the list that are greater than zero and less than or equal to 100. Args: elements (List[int]):...
python_sharegpt_23k
14,117
Write a Python function to sort a list of numbers in increasing order without using any built-in sorting functions or libraries. Additionally, you are not allowed to use any additional data structures or modify the original list in any way. The function should start with: ```python from typing import List def sort_lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_list_in_place(lst: List[int]) -> None: """ Sorts the given list of integers in increasing order using the bubble sort algorithm. The sorting is done in-place without using any built-in sorti...
python_sharegpt_23k
14,124
Write a Python function to calculate the sum, maximum, minimum, and average of the elements within a given range. The function should take two integers, `start` and `end`, representing the range (inclusive), and return a tuple containing the sum, maximum, minimum, and average of the elements in that range. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_range_stats(start: int, end: int) -> tuple: """ Calculate the sum, maximum, minimum, and average of the elements within a given range. Args: start (int): The starting number of the range (inclusive). ...
python_sharegpt_23k
14,125
Write a Python function to determine if a given number is a prime number without using the modulo operator (`%`). The function should efficiently check for primality by leveraging mathematical properties and operations such as division and square roots. The code should start with: ```python import math def is_prime_w...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime_without_modulo(number: int) -> bool: """ Determine if a given number is a prime number without using the modulo operator. Args: number (int): The number to check for primality. Returns...
python_sharegpt_23k
14,128
Write a Python function named `get_prime_numbers` that takes an integer `n` as input and returns a list containing the first `n` prime numbers. The function should use a recursive helper function named `is_prime` to check if a number is prime. The `is_prime` function should use the trial division method to determine if...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime(num): """ Recursively checks if a number is prime using the trial division method. Args: num (int): The number to check for primality. Returns: bool: True if the number is prim...
python_sharegpt_23k
14,129
Write a Python function that squares each element of a given list of positive integers using a one-line lambda function and the `map()` function. Ensure that the function only processes the list if all elements are positive integers. The function should return `None` if any element in the list is not a positive integer...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def square_positive_integers(nums: List[int]) -> Optional[List[int]]: """ Squares each element of a given list of positive integers using a one-line lambda function and the map() function. ...
python_sharegpt_23k
14,130
Write a Python function to determine if a given number is a prime number. The function should have a time complexity of O(sqrt(n)) and should handle numbers between 2 and 10^9, inclusive. The function should return `True` if the number is prime and `False` otherwise. The code should start with: ```python import math ...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime(n: int) -> bool: """ Determine if a given number is a prime number. Args: n (int): The number to check for primality. Must be between 2 and 10^9, inclusive. Returns: bool: True...
python_sharegpt_23k
14,134
Write a Python function to calculate the sum of all elements in a given list of integers without using any built-in sum() or reduce() functions. The function should have a time complexity of O(n), where n is the length of the input list. The code should start with: ```python from typing import List def calculate_sum(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum(arr: List[int]) -> int: """ Calculate the sum of all elements in a given list of integers without using built-in sum() or reduce() functions. Args: arr (List[int]): The lis...
python_sharegpt_23k
14,136
Write a Python function to reverse a given string without using any additional data structures and with a time complexity of O(n), where n is the length of the string. You are not allowed to use any built-in string manipulation functions or methods, such as `reverse()`. The function should directly modify the input str...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string_in_place(string: str) -> str: """ Reverses the given string in place without using any additional data structures and with a time complexity of O(n). Args: string (str): The input string to be rev...
python_sharegpt_23k
14,141
Write a Python function to find the second smallest number in a given list of numbers. If the list contains duplicate numbers, consider only unique values for comparison. The function should return `None` if there are fewer than two unique numbers in the list. 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, Optional def find_second_smallest(numbers: List[int]) -> Optional[int]: """ Find the second smallest number in a list of numbers, considering only unique values. Args: numbers (List[int]): ...
python_sharegpt_23k
14,142
Write a Python function to iterate through a given list of numbers and return a list of the squares of each number, but only if the number is prime. The function should start with: ```python from typing import List def get_squares_of_primes(numbers: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_prime(num: int) -> bool: """ Check if a number is prime. Args: num (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if...
python_sharegpt_23k
14,146
Write a Python function to reverse a given string without using any built-in string reversal functions or methods, ensuring that the time complexity of the solution is O(n). 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
14,151
Write a Python function to find the minimum value from a given array without using any built-in functions or methods for finding the minimum value (e.g., `min()`, `sort()`, etc.). The function should have a time complexity of O(n), where n is the number of elements in the array, and should minimize space complexity as ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_minimum_value(arr: List[int]) -> int: """ Find the minimum value in a given array without using built-in functions or methods. Args: arr (List[int]): The array of integers from whic...
python_sharegpt_23k
14,155
Write a Python function to calculate the Nth term of the Fibonacci sequence using dynamic programming. The function should be efficient in terms of both time and space complexity. The function should handle edge cases such as negative values and non-integer values of `n` gracefully. The code should start with: ```pyth...
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci(n: int) -> int: """ Calculate the Nth term of the Fibonacci sequence using dynamic programming. Args: n (int): The position in the Fibonacci sequence to calculate. Returns: int: The Nth te...
python_sharegpt_23k
14,157
Write a Python function to calculate the factorial of a given number using a recursive approach. The function should handle large inputs efficiently, such as calculating the factorial of a number up to 1000. 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 import sys def factorial_recursive(n: int) -> int: """ Calculate the factorial of a given number using a recursive approach. Args: n (int): The number for which to calculate the factorial. Returns: i...
python_sharegpt_23k
14,158
Write a Python function to filter out numbers divisible by 2 from a given list and return the filtered list in a readable format. The function should follow these steps: 1. Create an empty list called `filtered_list`. 2. Iterate through each number in the original list. 3. Check if the current number is divisible by 2....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_odd_numbers(numbers: List[int]) -> List[int]: """ Filters out numbers divisible by 2 from the given list and returns the filtered list. Args: numbers (List[int]): The list of inte...
python_sharegpt_23k
14,159
Write a Python function to remove duplicates from a given list while preserving the order of the elements. The function should return a new list with unique elements in the order they first appeared in the original list. The code should start with: ```python from typing import List def remove_duplicates(lst: List[int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(lst: List[int]) -> List[int]: """ Removes duplicates from the given list while preserving the order of the elements. Args: lst (List[int]): The input list from which du...
python_sharegpt_23k
14,162
Write a Python function to encrypt a given text using a Caesar cipher with a specified shift value. The function should handle both uppercase and lowercase letters, preserving their case, and should leave non-alphabetic characters unchanged. Additionally, the function should ensure that the shift value is within the va...
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_cipher(text: str, shift: int) -> str: """ Encrypts the given text using a Caesar cipher with the specified shift value. Args: text (str): The text to be encrypted. shift (int): The number of posit...
python_sharegpt_23k
14,163
Write a Python function to create a multi-dimensional array with dimensions of at least 10x10, where each element is a randomly generated integer between 1 and 100. The array should be populated in such a way that no two elements in the same row, column, or diagonal have the same value. Additionally, the array should b...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np import random def create_unique_sorted_array(rows: int, cols: int) -> np.ndarray: """ Create a multi-dimensional array with unique values in each row, column, and diagonal, and then sort it in descending ...
python_sharegpt_23k
14,165
Write a Python function to calculate the nth Fibonacci number using a recursive approach with memoization to improve efficiency. The function should handle edge cases where the input is not a positive integer. The code should start with: ```python def fibonacci_memoized(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def fibonacci_memoized(n: int) -> int: """ Calculate the nth Fibonacci number using a recursive approach with memoization. Args: n (int): The position in the Fibonacci sequence to calculate. Returns: ...
python_sharegpt_23k
14,167
Write a Python function to find the closest number to a given value in a sorted array using a binary search algorithm. If the given value is present in the array, return it as the closest number. If there are two numbers equally close to the given value, return the larger number. 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 find_closest_number(arr: List[int], val: int) -> int: """ Find the closest number to a given value in a sorted array using binary search. If the given value is present in the array, return it as ...
python_sharegpt_23k
14,173
Write a Python function that takes in a string and returns a new string with all uppercase letters converted to lowercase, and vice versa, without using the built-in `swapcase()` function. The function should preserve the original case of any non-alphabetic characters in the input string. The code should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def swap_case(input_string: str) -> str: """ Swaps the case of each alphabetic character in the input string without using the built-in `swapcase()` function. Non-alphabetic characters remain unchanged. Args: in...
python_sharegpt_23k
14,184
Write a Python function to traverse through an array and print only the even elements while keeping track of the number of even elements encountered. The function should adhere to the following constraints: 1. The time complexity of the solution should be O(n), where n is the size of the array. 2. You are not allowed t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_and_print_even_elements(arr: List[int]) -> int: """ Traverse through the array and print only the even elements while keeping track of the number of even elements encountered. Args: ...
python_sharegpt_23k
14,185
Write a Python function to calculate the sum of all even numbers in a given list without using the built-in `sum()` function. The function should have a time complexity of O(n), where n is the length of the list, and a space complexity of O(1), meaning it should not use any additional data structures to store intermedi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_evens(numbers: List[int]) -> int: """ Calculate the sum of all even numbers in the given list. Args: numbers (List[int]): The list of integers from which to calculate the sum of e...
python_sharegpt_23k
14,194
Write a Python function to generate a dictionary that contains all the unique words in a given string of text, along with the number of times each word occurs. The function should be case-insensitive and should ignore special characters such as punctuation marks. The solution should optimize for space complexity. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import re def word_frequency(text: str) -> Dict[str, int]: """ Generate a dictionary that contains all the unique words in a given string of text, along with the number of times each word occurs. The...
python_sharegpt_23k
14,198
Write a Python function to find the overlapping elements between two lists, considering that one of the lists may contain nested lists. The function should handle duplicates and nested lists appropriately. The code should start with: ```python from typing import List, Any def get_overlapping_elements(list1: List[Any]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def get_overlapping_elements(list1: List[Any], list2: List[Any]) -> List[Any]: """ Find the overlapping elements between two lists, including nested lists. Args: list1 (List[Any]): The ...
python_sharegpt_23k
14,201
Write a Python function to compare two strings and count the number of characters that are different. The function should handle strings of different lengths and any printable ASCII characters, including spaces, punctuation marks, and non-alphanumeric characters. The function should be optimized to have a time complexi...
Here is the Python code to solve the given problem in the markdown block: ```python def count_different_characters(str1: str, str2: str) -> int: """ Count the number of characters that are different between two strings. Args: str1 (str): The first string to compare. str2 (str): The second s...
python_sharegpt_23k
14,207
Write a Python function to create and sort an array of student dictionaries. Each student dictionary should contain keys for `name`, `age`, and `grade`. The `name` values should be predefined, the `age` values should be randomly generated integers between 18 and 25 (inclusive), and the `grade` values should be randomly...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import random def create_and_sort_students() -> List[Dict[str, object]]: """ Creates an array of student dictionaries, each containing keys for 'name', 'age', and 'grade'. The 'name' values are...
python_sharegpt_23k
14,218
Write a Python function to sort a given list of integers in descending order using the Bubble Sort algorithm. You are not allowed to use any built-in sorting functions or libraries. The function should start with: ```python from typing import List def sort_descending(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def sort_descending(arr: List[int]) -> List[int]: """ Sorts the given list of integers in descending order using the Bubble Sort algorithm. Args: arr (List[int]): The list of integers to b...
python_sharegpt_23k
14,219
Write a Python function to find and return the first `n` prime numbers that are also palindromes. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A palindrome is a number that reads the same backward as forward. The function should start with: ```python def find...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Check if a number is prime. Args: num (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if num < 2: return ...
python_sharegpt_23k
14,225
Write a Python function to find all the prime factors of a given positive integer. The function should return a list of prime factors, including their multiplicities. The code should start with: ```python from typing import List def find_prime_factors(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_prime_factors(n: int) -> List[int]: """ Returns a list of all the prime factors of a given positive integer, including their multiplicities. Args: n (int): The positive integer for ...
python_sharegpt_23k
14,227
Write a Python function to perform a linear search on a given array and return the index of the first occurrence of the target element. If the target element is not found in the array, the function should return -1. The array can contain duplicate elements, and the function should correctly return the index of the firs...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def linear_search(arr: List[Union[int, str]], target: Union[int, str]) -> int: """ Perform a linear search on the given array to find the index of the first occurrence of the target element. ...
python_sharegpt_23k
14,231
Write a Python function to reverse the order of each string in a given list of strings without using any built-in string reverse functions or methods, loops, or recursion. The reversed strings should still be stored in the original list. The code should start with: ```python from typing import List def reverse_strings...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_strings_in_list(lst: List[str]) -> None: """ Reverses the order of each string in the given list without using any built-in string reverse functions, loops, or recursion. The reversed str...
python_sharegpt_23k
14,232
Write a Python function to find and return a list of elements that appear in the first list (`a`) but not in the second list (`b`). The output list should be sorted in ascending order. The function should handle lists with duplicate elements and should be efficient given the constraints that each list can have a maximu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def elements_in_a_not_in_b(a: List[int], b: List[int]) -> List[int]: """ Returns a list of elements that appear in the first list `a` but not in the second list `b`, sorted in ascending order. Args:...
python_sharegpt_23k
14,233
Write a Python function to find the maximum value in a list of integers without using any built-in functions or libraries. The function should have a time complexity of O(n), where n is the number of elements in the list. The list can contain any number of elements, including both positive and negative integers. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_value(lst: List[int]) -> int: """ Find the maximum value in a list of integers without using built-in functions or libraries. Args: lst (List[int]): The list of integers from wh...
python_sharegpt_23k
14,234
Write a Python function to capitalize the first letter of each word in a given string, including after special characters. The function should handle strings of any length and should not use any built-in string manipulation functions. The function should have a time complexity of O(n). The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python def capitalize_string(string: str) -> str: """ Capitalizes the first letter of each word in the given string, including after special characters. Args: string (str): The input string to be capitalized. Returns:...
python_sharegpt_23k
14,237
Write a Python function to calculate the length of a given string without using any built-in functions, count the number of unique characters in the string, and return a dictionary with the frequency of each unique character. The function should handle strings with special characters and spaces. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python def analyze_string(string: str) -> tuple[int, int, dict[str, int]]: """ Analyze the given string to calculate its length, count the number of unique characters, and return a dictionary with the frequency of each unique chara...
python_sharegpt_23k
14,239
Write a Python function to calculate the least common multiple (LCM) of four positive integers. The function should be efficient and use a helper function to compute the LCM of two numbers. The code should start with: ```python def lcm_of_four(a: int, b: int, c: int, d: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def lcm_of_four(a: int, b: int, c: int, d: int) -> int: """ Calculate the least common multiple (LCM) of four positive integers. Args: a (int): The first positive integer. b (int): The second positive intege...
python_sharegpt_23k
14,242
Write a Python function to implement the selection sort algorithm correctly. The function should sort a list of integers in ascending order. Additionally, analyze the time complexity of the selection sort algorithm and provide a brief explanation of why the provided erroneous code is incorrect. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def selection_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the selection sort algorithm. Args: arr (List[int]): The list of integers to be sorted....
python_sharegpt_23k
14,243
Write a Python function to merge two sorted lists of integers into a new list without using any built-in sorting functions in Python. The new list should be sorted in descending order. The function should adhere to the following constraints: - The time complexity of the solution should be O(n), where n is the total num...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_lists(list_1: List[int], list_2: List[int]) -> List[int]: """ Merge two sorted lists of integers into a new list sorted in descending order. Args: list_1 (List[int]): The fi...
python_sharegpt_23k
14,248
Write a Python function to remove all duplicate elements from a given list of integers and return the new list sorted in ascending order. 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 def remove_duplicates_and_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_and_sort(arr: List[int]) -> List[int]: """ Removes all duplicate elements from the given list and returns a new list sorted in ascending order. Args: arr (List[int]): T...
python_sharegpt_23k
14,250
Write a Python function to create a dictionary where the keys are integers from 1 to 1000 and the values are the squares of the keys. The dictionary should be sorted in descending order based on the square values. The function should have a time complexity of O(n log n) or better. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def create_sorted_squares_dict() -> Dict[int, int]: """ Creates a dictionary where the keys are integers from 1 to 1000 and the values are the squares of the keys. The dictionary is sorted in descend...
python_sharegpt_23k
14,258
Write a Python function to remove duplicates from a sorted list of integers in O(N) time complexity and constant space complexity using a recursive approach. The function should handle cases where the input list may contain duplicate elements, and the final output should not have any duplicates. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_recursive(nums: List[int]) -> List[int]: """ Remove duplicates from a sorted list of integers using a recursive approach. The function runs in O(N) time complexity and uses cons...
python_sharegpt_23k
14,259
Write a Python function to convert an angle from degrees to radians. The function should ensure that the input angle is within the range of -360 degrees to 360 degrees. If the input angle is outside this range, the function should raise an exception with an appropriate error message. The function should have a time com...
Here is the Python code to solve the given problem in the markdown block: ```python import math def convert_to_radians(angle: float) -> float: """ Converts an angle from degrees to radians. Args: angle (float): The angle in degrees to be converted. Must be within the range of -360 to 360 degrees. ...
python_sharegpt_23k
14,262
Write a Python function to convert a binary string to an integer without using any built-in functions or libraries. The function should validate the input to ensure it is a valid binary string (i.e., it contains only '0' and '1' characters). If the input is invalid, the function should return `None`. The function shoul...
Here is the Python code to solve the given problem in the markdown block: ```python def binary_to_integer(binary_str: str) -> int: """ Converts a binary string to an integer without using any built-in functions or libraries. Args: binary_str (str): The binary string to be converted. Returns: ...
python_sharegpt_23k
14,274
Write a Python function to determine if a given positive integer greater than 1 is a prime number. The function should return `True` if the number is prime and `False` otherwise. The code should start with: ```python def is_prime(n: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n: int) -> bool: """ Determines if a given positive integer greater than 1 is a prime number. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, F...
python_sharegpt_23k
14,279
Write a Python function to find the highest prime number in a given array using a recursive approach. If no prime numbers are found, the function should return -1. The function should start with: ```python from typing import List def find_highest_prime_recursive(arr: 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(num: int, div: int = 2) -> bool: """ Recursively checks if a number is prime. Args: num (int): The number to check for primality. div (int): The current divisor to check...
python_sharegpt_23k
14,282
Write a Python function to calculate the sum of all prime numbers up to a given number `n` using an optimized algorithm. The function should return the sum as the output. 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 up to a given number `n` using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit up to which to sum prime numbers. ...
python_sharegpt_23k
14,284
Write a Python function to perform a linear search in a list of integers and return the index of the first occurrence of the target element. If the target element is not found, return -1. The list may contain duplicates. The time complexity of the solution should be O(n), where n is the number of elements in the list. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def linear_search(arr: List[int], target: int) -> int: """ Perform a linear search in a list of integers and return the index of the first occurrence of the target element. If the target element is n...
python_sharegpt_23k
14,285
Write a Python function to calculate the nth Fibonacci number efficiently with a time complexity of O(log n) and a space complexity of O(1). The function should not use recursion or any built-in functions for calculating exponents. The code should start with: ```python def fibonacci(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using matrix exponentiation. Args: n (int): The position of the Fibonacci number to calculate. Returns: int: The nth Fibonacci number...
python_sharegpt_23k
14,286
Write a Python function to find the mode(s) in an array of numbers. The mode is the number(s) that appear most frequently in the array. If there are multiple numbers that appear the same maximum number of times, the function should return a list of all the modes in ascending order. 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 def find_modes(nums: List[int]) -> List[int]: """ Finds the mode(s) in an array of numbers. The mode is the number(s) that appear most frequently in the array. If there are multiple numbers that appe...
python_sharegpt_23k
14,288
Write a Python function to calculate the sum of boolean values in a list, where `True` values are counted as 2 and `False` values are counted as 2. The function should ignore any non-boolean values in the list. The function should return a tuple containing the sum of `True` values and the sum of `False` values. The co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Union def true_false_sum(x: List[Union[bool, int]]) -> Tuple[int, int]: """ Calculate the sum of boolean values in a list, where `True` values are counted as 2 and `False` values are counted as 2...
python_sharegpt_23k
14,292
Implement the Shell Sort algorithm in Python and test it with a sample input. Provide a detailed explanation of how the algorithm works and discuss its time and space complexity. The code should start with: ```python from typing import List def shell_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 shell_sort(arr: List[int]) -> List[int]: """ Sorts the input list using the Shell Sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: List[int...
python_sharegpt_23k
14,294
Write a Python function to generate a list of prime numbers within a given range `[start, end]`, excluding numbers that are divisible by a specified divisor. The function should return the list of filtered prime numbers. The code should start with: ```python from typing import List def filtered_primes(start: int, end...
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
14,297
Write a Python function to generate a list of unique random integers of a given length, sorted in ascending order. The function should adhere to the following constraints: 1. The generated list should contain unique elements. 2. The list should be returned in ascending order. 3. The time complexity of the function shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_unique_random_list(val1: int) -> List[int]: """ Generates a list of unique random integers of a given length, sorted in ascending order. Args: val1 (int): The leng...
python_sharegpt_23k
14,298
Write a Python function to determine whether a given integer `n` is a prime number or not. The function must satisfy the following conditions: - It must use an iterative solution. - It must use constant space complexity, i.e., it cannot use any additional data structures besides a few variables. - The time complexity s...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n: int) -> bool: """ Determine whether a given integer `n` is a prime number. Args: n (int): The integer to check for primality. Returns: bool: True if `n` is a prime number, False otherwis...
python_sharegpt_23k
14,304
Write a Python function to process a list of tuples and create a dictionary with specific rules. Each tuple contains a key and a value. The function should: 1. Create an empty dictionary named `dict1`. 2. Iterate over each tuple in the input list. 3. Extract the first element of the tuple as the key and the second elem...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict import math def process_tuples(list1: List[Tuple[str, int]]) -> Dict[str, List[int]]: """ Process a list of tuples to create a dictionary with specific rules. Args: list1 (List[...
python_sharegpt_23k
14,319
Write a Python function to count the number of prime numbers from 1 to n (inclusive) where n is a positive integer greater than or equal to 2. The function should not use any built-in prime number libraries or functions. The code should start with: ```python def count_primes(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_primes(n: int) -> int: """ Count the number of prime numbers from 1 to n (inclusive) using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit of the range to count primes. Returns: ...
python_sharegpt_23k
14,326
Write a Python function that takes an hour (ranging from 0 to 23) as input and returns a corresponding greeting based on the time. The function should have a time complexity of O(1) and should not use any if-else statements or switch statements. The function should start with: ```python def get_greeting(hour: int) -> s...
Here is the Python code to solve the given problem in the markdown block: ```python def get_greeting(hour: int) -> str: """ Returns a greeting based on the given hour of the day. Args: hour (int): The hour of the day (0 to 23). Returns: str: The corresponding greeting based on the hour...
python_sharegpt_23k
14,329
Write a Python function to compare two arrays and return a Boolean result. The comparison should ignore duplicate elements and consider only the order of the remaining elements. Additionally, the comparison should only consider elements that are multiples of a given number (e.g., 3). The arrays should be of equal lengt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def compare_arrays_with_multiples(arr1: List[int], arr2: List[int], multiple: int) -> bool: """ Compare two arrays while ignoring duplicates and considering only the order of the remaining elements. ...
python_sharegpt_23k
14,333
Write a Python function to retrieve the nth element from a given set. Since sets in Python are unordered collections, the function should first convert the set to a list and then retrieve the nth element from the list. The function should handle cases where the index is out of bounds by returning `None`. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Set, Union def get_nth_element(my_set: Set[int], n: int) -> Union[int, None]: """ Retrieves the nth element from a given set. Args: my_set (Set[int]): The set from which to retrieve the element. ...
python_sharegpt_23k
14,335
Write a Python function to convert a given hexadecimal color code to its RGB format without using any built-in functions or libraries. The input will always be a valid 6-digit hexadecimal color code without any leading "#" symbol. The output should be a string in the format "RGB(x, y, z)" where x, y, and z are integers...
Here is the Python code to solve the given problem in the markdown block: ```python def hex_to_rgb(hex_code: str) -> str: """ Converts a given hexadecimal color code to its RGB format. Args: hex_code (str): A 6-digit hexadecimal color code without any leading "#". Returns: str: A strin...