source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
python_sharegpt_23k
10,003
Write a Python function to perform a linear search in an array of integers and return the indices of all occurrences of the target element. If the target element is not found, return an empty list. The code should start with: ```python from typing import List def find_all_indices(array: List[int], target: int) -> List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_indices(array: List[int], target: int) -> List[int]: """ Perform a linear search in an array of integers and return the indices of all occurrences of the target element. Args: a...
python_sharegpt_23k
10,008
Write a Python function to repeat each character in a given string a specified number of times. The function should take a string and an integer as input and return a new string where each character from the original string is repeated the specified number of times. The code should start with: ```python def repeat_cha...
Here is the Python code to solve the given problem in the markdown block: ```python def repeat_characters(string: str, n: int) -> str: """ Repeats each character in the input string `n` times and returns the resulting string. Args: string (str): The input string where each character will be repeate...
python_sharegpt_23k
10,011
Write a Python function to generate a sequence of numbers between a given `start` and `end` value, with each number incremented or decremented by a specified `step`. The function should handle both positive and negative steps and ensure the sequence includes the `end` value if it fits within the step increments. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def number_sequence(start: int, end: int, step: int) -> List[int]: """ Generate a sequence of numbers between `start` and `end` with a specified `step`. Args: start (int): The starting numbe...
python_sharegpt_23k
10,014
Write a Python function to calculate the sum of all even numbers in a given list using a while loop. The function should iterate through the list and sum only the even numbers. The code should start with: ```python from typing import List def sum_of_even_numbers(numbers: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_even_numbers(numbers: List[int]) -> int: """ Calculate the sum of all even numbers in the given list using a while loop. Args: numbers (List[int]): The list of integers to process...
python_sharegpt_23k
10,017
Write a Python function to find and return the first three distinct positions in a given array. The array can contain duplicates and negative numbers. The function should return a list of these positions. The code should start with: ```python from typing import List def first_three_distinct_positions(array: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def first_three_distinct_positions(array: List[int]) -> List[int]: """ Finds and returns the first three distinct positions in a given array. Args: array (List[int]): The array to search for...
python_sharegpt_23k
10,019
Write a Python function to concatenate two arrays without using any built-in array concatenation methods or functions. The function should take two lists as input and return a new list that contains all elements from both input lists in the order they appear. The code should start with: ```python from typing import Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_arrays(arr1: List[int], arr2: List[int]) -> List[int]: """ Concatenates two arrays without using any built-in array concatenation methods or functions. Args: arr1 (List[int])...
python_sharegpt_23k
10,023
Write a Python function to generate a list of the first `n` prime numbers. The function should take an integer `n` as input and return a list containing the first `n` prime numbers. The code should start with: ```python from typing import List def generate_first_n_primes(n: 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 given number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False other...
python_sharegpt_23k
10,024
Write a Python function to filter out all even numbers from a given list of integers ranging from -1000 to 1000. The function should not use any built-in functions or libraries. The code should start with: ```python def filter_odd_numbers(numbers: list) -> list: ```
Here is the Python code to solve the given problem in the markdown block: ```python def filter_odd_numbers(numbers: list) -> list: """ Filters out all even numbers from a given list of integers. Args: numbers (list): A list of integers ranging from -1000 to 1000. Returns: list: A list ...
python_sharegpt_23k
10,029
Write a Python function to sort a given list of numbers from lowest to highest using the **Selection Sort** algorithm. You are not allowed to use any built-in sorting functions or methods such as `sort()` or `sorted()`. Ensure that your algorithm has a time complexity of O(n^2). The code should start with: ```python f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def selection_sort(arr: List[int]) -> List[int]: """ Sorts a given list of numbers from lowest to highest using the Selection Sort algorithm. Args: arr (List[int]): The list of numbers to be...
python_sharegpt_23k
10,030
Write a Python function to check if a given string contains all the alphabets in a specific order. The alphabets must appear consecutively and in the same order as they do in the English alphabet. The function should be case-insensitive. The code should start with: ```python def check_alphabet_order(s: str) -> bool: `...
Here is the Python code to solve the given problem in the markdown block: ```python def check_alphabet_order(s: str) -> bool: """ Check if a given string contains all the alphabets in a specific order. Args: s (str): The input string to check. Returns: bool: True if the string contains...
python_sharegpt_23k
10,032
Write a Python function to sort a list of integers in descending order using a time complexity of O(n^2), where n is the length of the input list. The function should perform an in-place sort, meaning it should modify the original list without creating a new one. The code should start with: ```python from typing impor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def descending_sort(lst: List[int]) -> List[int]: """ Sorts a list of integers in descending order using the selection sort algorithm. Args: lst (List[int]): The list of integers to be sorte...
python_sharegpt_23k
10,039
Write a Python function to reverse each word in a given string without using any built-in string manipulation methods or libraries. The function should handle multiple spaces between words and should not reverse the order of the words themselves, only the characters within each word. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_each_word(string: str) -> str: """ Reverses each word in the given string without using any built-in string manipulation methods. Args: string (str): The input string containing words to be reversed. ...
python_sharegpt_23k
10,045
Write a Python function that simulates a loop running for a specified number of iterations, starting from a given initial value and incrementing by a specified step at each iteration. The function should return a list of the values of the counter at each iteration. The code should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def simulate_loop(iterations: int, start: int, step: int) -> List[int]: """ Simulates a loop running for a specified number of iterations, starting from a given initial value, and incrementing by a s...
python_sharegpt_23k
10,046
Write a Python function to iterate over a list and return a new list containing the elements that satisfy a given condition. The condition is defined by a lambda function that takes an element as input and returns a boolean value. The function should start with: ```python from typing import List, Callable def filter_l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable def filter_list(lst: List[int], condition: Callable[[int], bool]) -> List[int]: """ Filters elements from the given list based on the provided condition. Args: lst (List[int]): The...
python_sharegpt_23k
10,047
Write a Python function to concatenate two input values after converting them to strings. If either of the inputs is not a string, it should be converted to a string before concatenation. The function should return the concatenated result. The code should start with: ```python def concatenate_strings(value1, value2): ...
Here is the Python code to solve the given problem in the markdown block: ```python def concatenate_strings(value1, value2): """ Concatenates two input values after converting them to strings. Args: value1: The first input value to be concatenated. value2: The second input value to be conca...
python_sharegpt_23k
10,050
Write a Python function to merge two dictionaries `d1` and `d2` such that the values of `d1` are updated with the corresponding values from `d2` based on the keys in `d1`. If a key in `d1` does not exist in `d2`, the value in `d1` should remain unchanged. The function should return a new dictionary with the updated val...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def merge_dicts(d1: Dict[str, int], d2: Dict[str, int]) -> Dict[str, int]: """ Merge two dictionaries `d1` and `d2` such that the values of `d1` are updated with the corresponding values from `d2` based ...
python_sharegpt_23k
10,053
Write a Python function to iterate over a given sequence and perform a specified operation on each element. The function should support both `for` and `while` loops, and the operation should be customizable. The function should return a list of results after performing the operation on each element. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable def iterate_and_operate(sequence: List, operation: Callable, use_while: bool = False) -> List: """ Iterates over a given sequence and performs a specified operation on each element. The fun...
python_sharegpt_23k
10,054
Write a Python function to reverse a singly linked list in-place without using any additional data structures or recursion. The time complexity of the function should be O(n), where n is the number of nodes in the linked list. The function should start with: ```python class ListNode: def __init__(self, value=0, nex...
Here is the Python code to solve the given problem in the markdown block: ```python class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def reverse_linked_list(head: ListNode) -> ListNode: """ Reverses a singly linked list in-place without using addit...
python_sharegpt_23k
10,055
Write a Python function to calculate the sum of two integers and return the result. Additionally, ensure that the function handles cases where the input values are not integers by returning `None`. The function should also print the sum of the two integers if they are valid. The code should start with: ```python def s...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_two_integers(a: int, b: int) -> int: """ Calculate the sum of two integers and return the result. If either input is not an integer, return None. Args: a (int): The first integer. b (int): The sec...
python_sharegpt_23k
10,056
Write a Python function to calculate the cumulative sum of positive numbers in a given list. The function should ignore any negative numbers and return a list containing the cumulative sums of the positive numbers. The code should start with: ```python from typing import List def cumulative_sum_of_positive_numbers(nu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def cumulative_sum_of_positive_numbers(numbers: List[int]) -> List[int]: """ Calculate the cumulative sum of positive numbers in the given list. Args: numbers (List[int]): The list of intege...
python_sharegpt_23k
10,057
Write a Python function to perform a binary search on a sorted array to find the index of a target element using a recursive approach. The function should return the index of the target element if it is present in the array, or -1 if it is not found. The input array is guaranteed to be sorted in ascending order and doe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search(arr: List[int], target: int) -> int: """ Perform a binary search on a sorted array to find the index of a target element. Args: arr (List[int]): A sorted list of integers i...
python_sharegpt_23k
10,059
Write a Python function to compress a given string by counting the consecutive occurrences of each character and storing it as a tuple with the character and its count. The function should return a list of tuples where each tuple contains a character and its consecutive count. 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, Tuple def compress_string(string: str) -> List[Tuple[str, int]]: """ Compresses a given string by counting the consecutive occurrences of each character and storing it as a tuple with the character ...
python_sharegpt_23k
10,063
Write a Python function to find the index of the first occurrence of a given string in a list of strings. If the string is not found in the list, return -1. The list may contain duplicates, and the input string may appear multiple times. The function should start with: ```python from typing import List def find_first_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_first_occurrence(strings: List[str], target: str) -> int: """ Find the index of the first occurrence of a given string in a list of strings. Args: strings (List[str]): The list of s...
python_sharegpt_23k
10,065
Write a Python function to remove duplicate items from a given list and return the list with unique elements. The function should maintain the order of the first occurrence of each element. The code should start with: ```python from typing import List def remove_duplicates(input_list: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(input_list: List[int]) -> List[int]: """ Removes duplicate items from the given list while maintaining the order of the first occurrence of each element. Args: input_li...
python_sharegpt_23k
10,066
Write a Python function to solve the 0/1 Knapsack problem using a Bottom-Up Dynamic Programming approach. The function should determine the maximum value that can be obtained without exceeding the weight capacity of the knapsack, given a list of items with their respective weights and values. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def knapsack_max_value(n: int, W: int, values: List[int], weights: List[int]) -> int: """ Solves the 0/1 Knapsack problem using a Bottom-Up Dynamic Programming approach. Args: n (int): The n...
python_sharegpt_23k
10,073
Write a Python function to determine if a given string contains all unique characters. The function should return `True` if all characters in the string are unique, and `False` otherwise. The input string will only contain lowercase alphabets and can have a maximum length of \(10^6\) characters. The function should hav...
Here is the Python code to solve the given problem in the markdown block: ```python def is_unique_string(s: str) -> bool: """ Determines if a given string contains all unique characters. Args: s (str): The input string containing only lowercase alphabets. Returns: bool: True if all cha...
python_sharegpt_23k
10,074
Write a Python function to remove all key-value pairs from a dictionary where the value is an odd number. The function should return a new dictionary containing only the key-value pairs where the value is an even number. The code should start with: ```python from typing import Dict def remove_odd_elements(my_dict: Di...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def remove_odd_elements(my_dict: Dict[str, int]) -> Dict[str, int]: """ Removes all key-value pairs from the dictionary where the value is an odd number. Args: my_dict (Dict[str, int]): The ...
python_sharegpt_23k
10,090
Write a Python function to calculate the product of all the numbers in a given list of integers using the `reduce()` function. The function should not use any loops or the built-in `prod()` function. The code should start with: ```python from functools import reduce from typing import List def calculate_product(numbe...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import reduce from typing import List def calculate_product(numbers: List[int]) -> int: """ Calculate the product of all numbers in the given list using the reduce() function. Args: numbers (List[int...
python_sharegpt_23k
10,092
Write a Python function to find the first occurrence of a given substring in a string, ignoring case differences. The function should return the index of the first occurrence of the substring. If the substring is not found, the function should return -1. The code should start with: ```python def find_first_occurrence(...
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_occurrence(string: str, substring: str) -> int: """ Find the first occurrence of a substring in a string, ignoring case differences. Args: string (str): The string in which to search for the substring...
python_sharegpt_23k
10,093
Write a Python function to pack a string of characters into an array of length 8 while ensuring that each character is unique and preserving their original order. The function should handle strings with a variable length between 8 and 20 characters. If the input string contains fewer than 8 unique characters, the funct...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def pack_string(input_string: str) -> List[str]: """ Packs a string of characters into an array of length 8 with unique characters, preserving their original order. Args: input_string (str):...
python_sharegpt_23k
10,099
Write a Python function to trim a given string by removing leading and trailing whitespace characters, and also remove any consecutive whitespace characters within the string. The function should return the trimmed string. The code should start with: ```python import re def trim_string(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def trim_string(s: str) -> str: """ Trims a given string by removing leading and trailing whitespace characters, and also removes any consecutive whitespace characters within the string. Args: s (str)...
python_sharegpt_23k
10,103
Write a Python function to count the number of prime numbers within a given range `[2, n]` efficiently, considering both time and space complexity. The function should use the Sieve of Eratosthenes algorithm to achieve this. The code should start with: ```python import math def count_primes_in_range(n: int) -> int: `...
Here is the Python code to solve the given problem in the markdown block: ```python import math def count_primes_in_range(n: int) -> int: """ Counts the number of prime numbers within the range [2, n] using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit of the range to count p...
python_sharegpt_23k
10,109
Write a Python function to calculate the least common multiple (LCM) of a given array of positive integers efficiently. The function should not use any built-in LCM function. The code should start with: ```python from typing import List def least_common_multiple(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def least_common_multiple(nums: List[int]) -> int: """ Calculate the least common multiple (LCM) of a given array of positive integers. Args: nums (List[int]): A list of positive integers....
python_sharegpt_23k
10,118
Write a Python function to determine if a given number is an integer within the specified range. The function should return `True` if the number is an integer and falls within the range of -10^9 to 10^9, inclusive. Otherwise, it should return `False`. The code should start with: ```python def check_integer(number) -> ...
Here is the Python code to solve the given problem in the markdown block: ```python def check_integer(number) -> bool: """ Determines if the given number is an integer within the range of -10^9 to 10^9, inclusive. Args: number: The number to be checked. Returns: bool: True if the numbe...
python_sharegpt_23k
10,119
Write a Python function to check if a given string contains only prime numbers. The string is expected to contain space-separated integers. The function should return `True` if all integers in the string are prime numbers, otherwise `False`. The code should start with: ```python def contains_only_primes(string: str) -...
Here is the Python code to solve the given problem in the markdown block: ```python def contains_only_primes(string: str) -> bool: """ Check if the given string contains only prime numbers. Args: string (str): A string containing space-separated integers. Returns: bool: True if all int...
python_sharegpt_23k
10,122
Write a Python function to check if a list contains exactly two of the same elements that are adjacent to each other. The function should return `True` if the condition is met, and `False` otherwise. The list can contain integers, floats, or strings. The function should start with: ```python from typing import List, Un...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def has_adjacent_repeats(lst: List[Union[int, float, str]]) -> bool: """ Checks if a list contains exactly two of the same elements that are adjacent to each other. Args: lst (List[Un...
python_sharegpt_23k
10,123
Write a Python function to swap the values of two variables `x` and `y` using only bitwise operators. The function should take two integers as input and return a tuple containing the swapped values. The code should start with: ```python def swap_using_bitwise(x: int, y: int) -> tuple: ```
Here is the Python code to solve the given problem in the markdown block: ```python def swap_using_bitwise(x: int, y: int) -> tuple: """ Swaps the values of two integers using only bitwise operators. Args: x (int): The first integer. y (int): The second integer. Returns: tuple:...
python_sharegpt_23k
10,125
Write a Python function to calculate the sum of all numbers in a given list, excluding any numbers that are divisible by 3. The function should take a list of integers as input and return the sum of the numbers that are not divisible by 3. The code should start with: ```python from typing import List def sum_excludin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_excluding_divisible_by_three(numbers: List[int]) -> int: """ Calculate the sum of all numbers in the given list, excluding any numbers that are divisible by 3. Args: numbers (List[in...
python_sharegpt_23k
10,129
Write a Python function to remove all empty spaces and punctuation from a given string. The string may contain any printable ASCII characters including alphanumeric characters, special characters, and punctuation. The function should handle multiple occurrences of empty spaces and punctuation within the string. The fun...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_empty_spaces_and_punctuation(string: str) -> str: """ Removes all empty spaces and punctuation from the given string. Args: string (str): The input string containing any printable ASCII characters. R...
python_sharegpt_23k
10,131
Write a Python function to determine if the first integer is greater than the second integer. The function should take two integers as input and return a boolean value indicating whether the first integer is greater than the second integer. The code should start with: ```python def is_greater(num1: int, num2: int) -> ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_greater(num1: int, num2: int) -> bool: """ Determines if the first integer is greater than the second integer. Args: num1 (int): The first integer to compare. num2 (int): The second integer to compare...
python_sharegpt_23k
10,133
Write a Python function to compare two strings and return the number of character positions at which the strings differ from each other. The function should be case-insensitive, ignore any leading or trailing whitespaces, and handle Unicode characters properly. The code should start with: ```python def compare_strings...
Here is the Python code to solve the given problem in the markdown block: ```python def compare_strings(str1: str, str2: str) -> int: """ Compare two strings and return the number of character positions at which the strings differ. The comparison is case-insensitive and ignores leading or trailing whitespac...
python_sharegpt_23k
10,134
Write a Python function to calculate the sum of the cubes of the digits of a given number. The function should take an integer as input and return the sum of the cubes of its digits. The code should start with: ```python def sum_of_cubes_of_digits(num: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_cubes_of_digits(num: int) -> int: """ Calculate the sum of the cubes of the digits of a given number. Args: num (int): The number whose digits' cubes are to be summed. Returns: int: The sum o...
python_sharegpt_23k
10,138
Write a Python function to convert a list of integers to a string, where each integer in the list represents a Unicode character code point. The function should handle lists of varying lengths and ensure that each integer is valid for conversion to a Unicode character. 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 convert_list_to_string(code_points: List[int]) -> str: """ Converts a list of integers to a string, where each integer represents a Unicode character code point. Args: code_points (List[...
python_sharegpt_23k
10,140
Write a Python function that takes an array of integers and returns an array of the same length with each element multiplied by 2, ensuring that the resulting array contains only even numbers. Additionally, the function should ignore any negative numbers in the input array. The code should start with: ```python from ty...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_and_filter_even(arr: List[int]) -> List[int]: """ Returns a list of even numbers obtained by doubling each non-negative number in the input list. Args: arr (List[int]): The inpu...
python_sharegpt_23k
10,141
Write a Python function to convert a given list of integers into a dictionary where each integer in the list becomes both the key and the value in the dictionary. Ensure that all keys are unique and values are of type integer. The code should start with: ```python from typing import List, Dict def list_to_dict(my_list...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def list_to_dict(my_list: List[int]) -> Dict[int, int]: """ Converts a list of integers into a dictionary where each integer in the list becomes both the key and the value. Args: my_li...
python_sharegpt_23k
10,142
Write a Python function that takes a string as input and returns its reverse while ignoring any leading or trailing whitespace characters. The function should be case-insensitive, meaning it should treat uppercase and lowercase characters as equal when reversing the string. Additionally, the function should handle stri...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string_ignore_whitespace(string: str) -> str: """ Reverses the input string while ignoring leading and trailing whitespace and treating uppercase and lowercase characters as equal. Args: string (str): Th...
python_sharegpt_23k
10,144
Write a Python function to compare two strings for equality without using any built-in string comparison functions or operators (such as `==`, `!=`, or `strcmp`). The function should compare the strings character by character and return `True` if the strings are equal and `False` otherwise. The function should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python def custom_string_compare(str1: str, str2: str) -> bool: """ Compares two strings for equality without using built-in comparison functions or operators. Args: str1 (str): The first string to compare. str2 (s...
python_sharegpt_23k
10,145
Write a Python function to remove all duplicate words from a given string while maintaining the order of the first occurrence of each word. The input string will contain only lowercase alphabets and spaces, and its length will not exceed 10000 characters. The solution should have a time complexity of O(n), where n is t...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_duplicates(input_string: str) -> str: """ Removes all duplicate words from the input string while maintaining the order of the first occurrence of each word. Args: input_string (str): The input string con...
python_sharegpt_23k
10,149
Write a Python function to sort a list of integers in ascending order using the Bubble Sort algorithm. The function should not use any built-in sorting functions or libraries. The code should start with: ```python from typing import List def bubble_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 bubble_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the Bubble Sort algorithm. Args: arr (List[int]): The list of integers to be sorted. ...
python_sharegpt_23k
10,152
Write a Python function to calculate the factorial of a given non-negative integer `n`. The factorial of a number `n` is defined as the product of all positive integers from 1 to `n`. The function should handle edge cases such as `n` being 0 or negative. The function should have a time complexity of O(n). The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python def factorial(n: int) -> int: """ Calculate the factorial of a given non-negative integer n. The factorial of a number n is the product of all positive integers from 1 to n. Args: n (int): The non-negative inte...
python_sharegpt_23k
10,153
Write a Python function to determine if a given string is a palindrome, considering only alphanumeric characters and ignoring case sensitivity. The function should return `True` if the string is a palindrome and `False` otherwise. The code should start with: ```python def is_palindrome(s: str) -> bool: ```
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, considering only alphanumeric characters and ignoring case sensitivity. Args: s (str): The input string to check. Returns: ...
python_sharegpt_23k
10,155
Write a Python function to classify a large dataset of text as either "opinionated" or "objective" while maintaining a time complexity of O(n) and space complexity of O(1). The function should take a list of sentences as input and return a list of classifications. The code should start with: ```python from typing impo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def classify_text(sentences: List[str]) -> List[str]: """ Classify a large dataset of text as either "opinionated" or "objective". Args: sentences (List[str]): A list of sentences to classif...
python_sharegpt_23k
10,159
Write a Python function to process a given list and return the size of the resulting list after performing the following operations: 1. Create an empty list called `list_b`. 2. Iterate through each element in the input list `list_a`. 3. If the element is even, append it to `list_b`. 4. If the element is odd, multiply i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_list_and_get_size(list_a: List[int]) -> int: """ Processes the input list and returns the size of the resulting list after performing the following operations: 1. Create an empty list cal...
python_sharegpt_23k
10,160
Write a Python function to create a new dictionary from a given dictionary where each value is squared. The function should use dictionary comprehension to achieve this. The code should start with: ```python from typing import Dict def square_values(data: Dict[str, int]) -> Dict[str, int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def square_values(data: Dict[str, int]) -> Dict[str, int]: """ Creates a new dictionary where each value from the input dictionary is squared. Args: data (Dict[str, int]): The input dictiona...
python_sharegpt_23k
10,161
Write a Python function to iterate over the items in a dictionary and return a list of tuples containing the key-value pairs in reverse order. Each tuple should contain a key and its corresponding value from the dictionary. The function should handle any dictionary with string keys and integer values. The code should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple def reverse_dict_items(dictionary: Dict[str, int]) -> List[Tuple[str, int]]: """ Returns a list of tuples containing the key-value pairs of the dictionary in reverse order. Args: ...
python_sharegpt_23k
10,162
Write a Python function to find the length of the longest substring without repeating characters in a given string. The function should have a time complexity of O(n), where n is the length of the input string. The input string can contain any printable ASCII characters. The code should start with: ```python def longe...
Here is the Python code to solve the given problem in the markdown block: ```python def longest_substring_length(s: str) -> int: """ Find the length of the longest substring without repeating characters in the given string. Args: s (str): The input string containing any printable ASCII characters. ...
python_sharegpt_23k
10,163
Write a Python function to find and return the two largest distinct numbers in a given array of integers. If there are multiple occurrences of the largest number, consider only one occurrence in the result. The input array can have both positive and negative numbers. The output should be in descending order. If there a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_two_largest_distinct(numbers: List[int]) -> List[int]: """ Find and return the two largest distinct numbers in the given array of integers. Args: numbers (List[int]): The input arra...
python_sharegpt_23k
10,164
Write a Python function to replace the value at a given key in a dictionary and return the dictionary with its key-value pairs sorted in ascending order based on the keys. The function should have a time complexity of O(log n) for the search and replacement operation, where n is the number of key-value pairs in the dic...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any import bisect def replace_value_in_sorted_dict(dictionary: Dict[str, Any], key: str, value: Any) -> Dict[str, Any]: """ Replaces the value at a given key in the dictionary and returns the dictionary...
python_sharegpt_23k
10,166
Write a Python function to calculate the sum of all prime numbers less than or equal to a given integer. The function should be efficient and handle edge cases such as negative numbers and zero. The code should start with: ```python def sum_of_primes_up_to(num: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_primes_up_to(num: int) -> int: """ Calculate the sum of all prime numbers less than or equal to a given integer. Args: num (int): The upper limit for prime numbers. Returns: int: The sum of a...
python_sharegpt_23k
10,171
Write a Python function to find the value of a variable in a given environment, considering multiple levels of nested dictionaries and handling potential errors. The function should: 1. Check if the variable exists in the environment. If not, handle the error gracefully by returning a default value. 2. Handle nested di...
Here is the Python code to solve the given problem in the markdown block: ```python def find_value_in_env(env: dict, variable: str) -> int: """ Find the value of a variable in a given environment, considering multiple levels of nested dictionaries and handling potential errors. Args: env (dict): Th...
python_sharegpt_23k
10,174
Write a Python function to reverse the order of words in a given string. The function should split the input string into individual words, reverse the order of these words, and then join them back into a single string. The function should handle any whitespace characters (spaces, tabs, newlines) and should return the r...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words_in_string(input_string: str) -> str: """ Reverses the order of words in a given string. Args: input_string (str): The input string containing words to be reversed. Returns: str: A new ...
python_sharegpt_23k
10,175
Write a Python function to reverse the words in a given string containing only alphabetic characters and spaces. The function should ignore any leading or trailing spaces and should also handle multiple consecutive spaces between words. The code should start with: ```python def reverse_words(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words(string: str) -> str: """ Reverses the words in a given string containing only alphabetic characters and spaces. Leading and trailing spaces are ignored, and multiple consecutive spaces between words are han...
python_sharegpt_23k
10,179
Write a Python function to sort an array of positive integers using the bubble sort algorithm. The function should use a single for loop and must have a time complexity of O(n^2). The input array should contain positive integers only and have a length between 5 and 1000 (inclusive). The code should start with: ```pyth...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort_single_loop(arr: List[int]) -> List[int]: """ Sorts an array of positive integers using the bubble sort algorithm with a single for loop. Args: arr (List[int]): The array of ...
python_sharegpt_23k
10,180
Write a Python function to reverse a list of integers without using the built-in `reverse()` method or the `[::-1]` slicing syntax. The function should take a list of integers as input and return the reversed list. The code should start with: ```python from typing import List def reverse_list(lst: List[int]) -> List[i...
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 a list of integers without using the built-in `reverse()` method or the `[::-1]` slicing syntax. Args: lst (List[int]): The list o...
python_sharegpt_23k
10,181
Write a Python function to check if any element in a given matrix is zero and return the positions of all zero elements as a list of tuples. If no zero element is found, return an empty list. The code should start with: ```python from typing import List, Tuple def find_zero_elements(matrix: List[List[int]]) -> List[T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_zero_elements(matrix: List[List[int]]) -> List[Tuple[int, int]]: """ Find the positions of all zero elements in a given matrix. Args: matrix (List[List[int]]): The matrix to ...
python_sharegpt_23k
10,183
Write a Python function to convert a given sentence to title case, where each word starts with a capital letter. The sentence will only contain alphabetic characters and spaces. The function should handle edge cases such as empty strings and single-word sentences. The code should start with: ```python def to_title_cas...
Here is the Python code to solve the given problem in the markdown block: ```python def to_title_case(sentence: str) -> str: """ Converts a given sentence to title case, where each word starts with a capital letter. Args: sentence (str): The input sentence to be converted to title case. Return...
python_sharegpt_23k
10,184
Write a Python function to transpose a given square matrix. The matrix is represented as a list of lists, where each inner list represents a row of the matrix. The transpose of a matrix is obtained by swapping its rows with columns. The function should handle square matrices of sizes ranging from 1x1 to 10x10, with ele...
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[float]]) -> List[List[float]]: """ Transposes a given square matrix. Args: matrix (List[List[float]]): A square matrix represented as a list of lists. ...
python_sharegpt_23k
10,185
Write a Python function to reverse the order of elements in a given array of strings. The function should return a new array with the elements in the reversed order. The original array should not be modified. The code should start with: ```python from typing import List def reverse_array(arr: List[str]) -> List[str]:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array(arr: List[str]) -> List[str]: """ Reverses the order of elements in a given array of strings. Args: arr (List[str]): The array of strings to be reversed. Returns: ...
python_sharegpt_23k
10,187
Write a Python function to flatten a bi-dimensional array into a single array while maintaining the order of the elements. The function should handle cases where the input array can have up to 100 sub-arrays, and each sub-array can contain up to 1000 elements. The elements in the sub-arrays can be of any valid data typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def flatten_bi_dimensional_array(bi_array: List[List[Any]]) -> List[Any]: """ Flattens a bi-dimensional array into a single array while maintaining the order of the elements. Args: bi_a...
python_sharegpt_23k
10,196
Write a Python function to delete the last three elements from a given list of integers and return the remaining elements. If the list has fewer than three elements, return an empty list. The code should start with: ```python from typing import List def delete_last_three_elements(my_list: List[int]) -> List[int]: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def delete_last_three_elements(my_list: List[int]) -> List[int]: """ Deletes the last three elements from the given list of integers and returns the remaining elements. If the list has fewer than thr...
python_sharegpt_23k
10,199
Write a Python function to sort a list of integers in ascending order using the bubble sort algorithm. The function should take a list of integers as input and return the sorted list. The code should start with: ```python from typing import List def bubble_sort(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 bubble_sort(lst: List[int]) -> List[int]: """ Sorts a list of integers in ascending order using the bubble sort algorithm. Args: lst (List[int]): The list of integers to be sorted. ...
python_sharegpt_23k
10,208
Write a Python function to calculate the sum of the squares of the elements in a given list. The function should iterate through each element in the list, compute the square of each element, and then sum these squares. The code should start with: ```python from typing import List def sum_of_squares(numbers: List[int])...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def sum_of_squares(numbers: List[int]) -> int: """ Calculate the sum of the squares of the elements in a given list. Args: numbers (List[int]): A list of integers for which the sum of squa...
python_sharegpt_23k
10,211
Write a Python function to filter out even numbers from a given list and return them as a new list. The function should use a functional programming style, leveraging higher-order functions and lambda expressions. The code should start with: ```python from typing import List def filter_even_numbers(numbers: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_even_numbers(numbers: List[int]) -> List[int]: """ Filters out even numbers from the given list and returns them as a new list. Args: numbers (List[int]): The list of integers fro...
python_sharegpt_23k
10,214
Write a Python function to calculate the sum of the squares of the digits of a given number. The function should handle both positive and negative integers. The code should start with: ```python def sum_of_squared_digits(number: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def sum_of_squared_digits(number: int) -> int: """ Calculate the sum of the squares of the digits of a given number. Args: number (int): The input number whose digits' squares are to be summed. Returns: ...
python_sharegpt_23k
10,215
Write a Python function to multiply two integers without using the multiplication operator (`*`). The function should handle both positive and negative integers. The code should start with: ```python def multiply_without_operator(num_1: int, num_2: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def multiply_without_operator(num_1: int, num_2: int) -> int: """ Multiplies two integers without using the multiplication operator (*). Args: num_1 (int): The first integer. num_2 (int): The second integer....
python_sharegpt_23k
10,216
Write a Python function to compute the sum of two non-negative integers without using the addition operator (`+`) or any built-in functions that directly perform addition. Instead, implement your own algorithm using bitwise operations. The code should start with: ```python def add_without_plus(a: int, b: int) -> int: ...
Here is the Python code to solve the given problem in the markdown block: ```python def add_without_plus(a: int, b: int) -> int: """ Computes the sum of two non-negative integers using bitwise operations. Args: a (int): The first non-negative integer. b (int): The second non-negative intege...
python_sharegpt_23k
10,217
Write a Python function to sort an array containing only 0s, 1s, and 2s in-place with a time complexity of O(n) and space complexity of O(1). The function should use a three-pointer approach to achieve the sorting efficiently. The code should start with: ```python from typing import List def sort_array(arr: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_array(arr: List[int]) -> List[int]: """ Sorts an array containing only 0s, 1s, and 2s in-place with O(n) time complexity and O(1) space complexity. Args: arr (List[int]): The array ...
python_sharegpt_23k
10,219
Write a Python function to remove all occurrences of a specified element from a given list while maintaining the relative order of the remaining elements. The function should take two parameters: the list from which to remove elements and the element to be removed. The function should return the modified list. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_all_occurrences(lst: List[int], element: int) -> List[int]: """ Removes all occurrences of the specified element from the given list while maintaining the relative order of the remaining eleme...
python_sharegpt_23k
10,222
Write a Python function to generate all prime numbers between 1 and a given upper limit `n` using the Sieve of Eratosthenes algorithm. The function should return a list of all prime numbers up to `n`. The code should start with: ```python from typing import List def generate_primes(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_primes(n: int) -> List[int]: """ Generate all prime numbers between 1 and a given upper limit `n` using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit up to...
python_sharegpt_23k
10,224
Write a Python function to remove all occurrences of a specified element from a given list of integers. The function should return a new list with all instances of the specified element removed. The original list should not be modified. The code should start with: ```python from typing import List def remove_all_occu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_all_occurrences(arr: List[int], element: int) -> List[int]: """ Removes all occurrences of a specified element from a given list of integers. Args: arr (List[int]): The list of in...
python_sharegpt_23k
10,226
Write a Python function to calculate the Jaccard similarity between two sets. The Jaccard similarity is defined as the size of the intersection of the two sets divided by the size of their union. The function should handle sets of any size and return a float representing the similarity. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python def jaccard_similarity(set1: set, set2: set) -> float: """ Calculate the Jaccard similarity between two sets. The Jaccard similarity is defined as the size of the intersection of the two sets divided by the size of thei...
python_sharegpt_23k
10,231
Write a Python function to convert a decimal number to its octal equivalent without using any built-in functions or libraries for the conversion. The function should handle both positive and negative numbers. The code should start with: ```python def decimal_to_octal(number: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def decimal_to_octal(number: int) -> str: """ Convert a decimal number to its octal equivalent without using built-in functions or libraries. Args: number (int): The decimal number to be converted. Returns: ...
python_sharegpt_23k
10,232
Write a Python function to filter out and return only the positive integers from a given list of integers, maintaining their original order. If there are no positive integers in the input list, the function should return an empty list. The code should start with: ```python from typing import List def get_positive_int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_positive_integers(input_list: List[int]) -> List[int]: """ Filters out and returns only the positive integers from the given list of integers, maintaining their original order. Args: ...
python_sharegpt_23k
10,234
Write a Python function to convert a given amount from USD to INR and another function to convert a given amount from INR to USD using a fixed conversion ratio. The conversion ratio is 1 USD = 73.20 INR. The code should start with: ```python def convert_usd_to_inr(amount_usd: float) -> float: def convert_inr_to_usd(amo...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_usd_to_inr(amount_usd: float) -> float: """ Convert a given amount from USD to INR using a fixed conversion ratio. Args: amount_usd (float): The amount in USD to be converted. Returns: float...
python_sharegpt_23k
10,235
Implement a custom sorting algorithm using a modified version of the quicksort algorithm that sorts a list of integers in descending order. The algorithm should have a time complexity of O(n log n) and 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 def custom_quicksort_descending(arr: List[int]) -> List[int]: """ Sorts a list of integers in descending order using a modified quicksort algorithm. Args: arr (List[int]): The list of intege...
python_sharegpt_23k
10,236
Write a Python function to validate a string based on the following criteria: 1. The string must start with a letter. 2. The string must contain only letters and numbers. 3. The string must be at least 8 characters in length. 4. The string must not contain any repeated characters. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_string(s: str) -> bool: """ Validate a string based on the following criteria: 1. The string must start with a letter. 2. The string must contain only letters and numbers. 3. The string must b...
python_sharegpt_23k
10,239
Write a Python function to update the values of an array elements with their cube. The input array will contain `n` elements, where `n` is a positive integer not exceeding 1000. The output should be an array containing the updated values. The function should update the array in place, without creating a new array, and ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def update_array_with_cube(arr: List[int]) -> List[int]: """ Updates each element of the input array with its cube. Args: arr (List[int]): The input array of integers to be updated. Ret...
python_sharegpt_23k
10,243
Write a Python function to generate and print all unique combinations of two digits between 0 and 9, excluding any combination that contains the digit 5 and any combination that contains repeating digits. The function should start with: ```python def print_unique_combinations(): ```
Here is the Python code to solve the given problem in the markdown block: ```python def print_unique_combinations(): """ Generates and prints all unique combinations of two digits between 0 and 9, excluding any combination that contains the digit 5 and any combination that contains repeating digits. ...
python_sharegpt_23k
10,245
Write a Python function to count the number of distinct states in a given matrix. Each state in the matrix is represented by a string formed by concatenating the characters of a row. The matrix can have up to \(10^6\) rows and columns. The function should efficiently handle large matrices and return the number of uniqu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_distinct_states(matrix: List[List[str]]) -> int: """ Count the number of distinct states in a given matrix. Each state is represented by a string formed by concatenating the characters of a row...
python_sharegpt_23k
10,250
Write a Python function to find a duplicate element in a given list of integers. The function should handle the case where the list contains duplicate elements and should not use any additional data structures. The time complexity of the solution should be O(n) and the space complexity should be O(1). The function shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_duplicate_in_list(nums: List[int]) -> int: """ Find a duplicate element in a given list of integers. The function uses a cyclic sort approach to place each number at its correct index. ...
python_sharegpt_23k
10,251
Write a Python function to generate a list of all even numbers between 1 and a given upper limit `n`, excluding numbers that are divisible by 3. The function should return the list of these numbers. The code should start with: ```python from typing import List def generate_even_numbers_excluding_divisible_by_3(n: int)...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_even_numbers_excluding_divisible_by_3(n: int) -> List[int]: """ Generate a list of all even numbers between 1 and n (inclusive) that are not divisible by 3. Args: n (int): The u...
python_sharegpt_23k
10,252
Write a Python function to convert a given string to lowercase and remove any punctuation marks, but preserve any whitespace characters. The function should handle various types of punctuation and whitespace characters. The code should start with: ```python from typing import List import string def clean_string(input...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import string def clean_string(input_string: str) -> str: """ Converts the given string to lowercase and removes any punctuation marks, while preserving whitespace characters. Args: input_st...
python_sharegpt_23k
10,255
Write a Python function to calculate the square of a given number without using the multiplication operator (`*`). The function should use an alternative method to compute the square. Additionally, create a loop that counts from 0 to 9 and displays both the number and its square using the provided function. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_square(num: int) -> int: """ Calculate the square of a given number without using the multiplication operator (*). Args: num (int): The number for which the square is to be calculated. Returns: ...
python_sharegpt_23k
10,256
Write a Python function to calculate the product of two numbers without using the multiplication operator or any built-in functions or methods that directly calculate the product. The function should have a time complexity of O(log n), where n is the larger of the two input numbers. The function should use basic arithm...
Here is the Python code to solve the given problem in the markdown block: ```python def multiply_without_operator(a: int, b: int) -> int: """ Calculate the product of two numbers without using the multiplication operator. Args: a (int): The first number. b (int): The second number. Ret...
python_sharegpt_23k
10,257
Write a Python function to generate a random number between 0 and 10 (inclusively) using only bitwise operations. The function should not use any built-in random number generation functions or arithmetic operations. The code should start with: ```python def generate_random_number() -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import time def generate_random_number() -> int: """ Generate a random number between 0 and 10 (inclusively) using only bitwise operations. Returns: int: A random number between 0 and 10. """ # Initialize t...
python_sharegpt_23k
10,267
Write a Python function to calculate the sum of all numbers in a given list that are multiples of a specified divisor. If there are no numbers that are multiples of the divisor, the function should return 0. The code should start with: ```python from typing import List def sum_multiples(numbers: List[int], divisor: in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_multiples(numbers: List[int], divisor: int) -> int: """ Calculate the sum of all numbers in the given list that are multiples of the specified divisor. Args: numbers (List[int]): The...
python_sharegpt_23k
10,268
Write a Python function to find the longest string in a given list of strings without using any built-in string manipulation functions or sorting algorithms. The algorithm should have a time complexity of O(n^2), where n is the total number of characters in all the strings combined, and should use constant space comple...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_longest_string(strings: List[str]) -> str: """ Finds the longest string in a given list of strings without using any built-in string manipulation functions or sorting algorithms. Args: ...
python_sharegpt_23k
10,270
Write a Python function that takes two lists of equal length and creates a dictionary where each key is the index of the elements in the lists, and the value is a tuple containing the elements from both lists at that index. If the elements at a particular index are nested lists or dictionaries, the function should crea...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any, Tuple def create_index_dictionary(list_one: List[Any], list_two: List[Any]) -> Dict[int, Any]: """ Creates a dictionary from two lists of equal length where each key is the index of the eleme...
python_sharegpt_23k
10,280
Write a Python function to extract all prime numbers from a given list of integers. The function should have a time complexity of O(n*sqrt(k)), where n is the length of the input list and k is the maximum value in the input list. The space complexity should be O(1), excluding the space required for the output list. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def is_prime(num: int) -> bool: """ Check if a number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False...
python_sharegpt_23k
10,282
Write a Python function to find the difference between the largest and smallest prime numbers in a given list of numbers. The list should be sorted in descending order before finding the prime numbers. If no prime numbers are found, return `None`. The code should start with: ```python from typing import List, Optional...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def is_prime(number: int) -> bool: """ Check if a given number is a prime number. Args: number (int): The number to check for primality. Returns: bool: True if the num...