source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
python_sharegpt_23k
7,853
Write a Python function to generate an array of a specified number of random integers within a given range, and return the array sorted in descending order. The function should handle the input validation to ensure the number of integers and the range are valid. The code should start with: ```python from typing import...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_and_sort_random_integers(num_integers: int, lower_bound: int, upper_bound: int) -> List[int]: """ Generates an array of a specified number of random integers within a given ran...
python_sharegpt_23k
7,854
Write a Python function to find the length of the longest run of consecutive characters in a given string. A run is defined as a sequence of consecutive characters that are the same. The function should start with: ```python def longest_run_of_consecutive_characters(string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_run_of_consecutive_characters(string: str) -> int: """ Find the length of the longest run of consecutive characters in a given string. Args: string (str): The input string to analyze. Returns: ...
python_sharegpt_23k
7,860
Write a Python function to delete all prime numbers from an array of integers containing the first `n` natural numbers. The function should return the modified array with all prime numbers removed. The code should start with: ```python from typing import List import math def delete_prime_numbers(arr: List[int], n: in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def is_prime(number: int) -> bool: """ Check if a given number is prime. Args: number (int): The number to check for primality. Returns: bool: True if the number is ...
python_sharegpt_23k
7,866
Write a Python function to count the number of times a given string appears in a list of strings. If the list is empty or the given string is empty, return -1. The function should be case-sensitive. The code should start with: ```python from typing import List def count_string_appearances(strings: List[str], string: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_string_appearances(strings: List[str], string: str) -> int: """ Counts the number of times a given string appears in a list of strings. Args: strings (List[str]): The list of strin...
python_sharegpt_23k
7,870
Write a Python function to generate a list of a specified length with random integers between a given range, ensuring that the list does not contain any duplicate values. The function should take three parameters: the desired length of the list, the lower bound of the range (inclusive), and the upper bound of the range...
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(length: int, lower_bound: int, upper_bound: int) -> List[int]: """ Generates a list of unique random integers within a specified range. Args: le...
python_sharegpt_23k
7,872
Write a Python function to reverse a given string. The function should handle both normal strings and empty strings. The code should start with: ```python def reverse_string(input_string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(input_string: str) -> str: """ Reverses the given input string. Args: input_string (str): The string to be reversed. Returns: str: The reversed string. """ # Ensure the input ...
python_sharegpt_23k
7,873
Write a Python function to calculate the result of the expression `3 * 5 + 7` for each iteration of a loop that runs from 1 to 10. The function should return a list of results for each iteration. The code should start with: ```python from typing import List def calculate_expression_results(start: int, end: int) -> Lis...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def calculate_expression_results(start: int, end: int) -> List[int]: """ Calculate the result of the expression 3 * 5 + 7 for each iteration from start to end (inclusive). Args: start (int...
python_sharegpt_23k
7,874
Write a Python function to round a given floating-point number to the nearest hundredth. The function should handle both positive and negative numbers, and should return the result as a float. The code should start with: ```python def round_to_nearest_hundredth(num: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def round_to_nearest_hundredth(num: float) -> float: """ Rounds a given floating-point number to the nearest hundredth. Args: num (float): The number to be rounded. Returns: float: The number rounded to...
python_sharegpt_23k
7,879
Write a Python function to calculate the Levenshtein distance between two strings. The Levenshtein distance is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. The function should take two strings as input and return an integ...
Here is the Python code to solve the given problem in the markdown block: ```python def levenshtein_distance(str1: str, str2: str) -> int: """ Calculate the Levenshtein distance between two strings. The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or subs...
python_sharegpt_23k
7,880
Write a Python function to find the union of two sets. The function should take two sets as input and return a new set that contains all the elements from both sets without any duplicates. The function should be able to handle sets of different lengths, empty sets, and sets containing any type of elements (numbers, str...
Here is the Python code to solve the given problem in the markdown block: ```python def find_union(set1: set, set2: set) -> set: """ Find the union of two sets. Args: set1 (set): The first set. set2 (set): The second set. Returns: set: A new set containing all elements from bot...
python_sharegpt_23k
7,881
Write a Python function to concatenate two strings `s1` and `s2` and repeat the resulting string `n` times. The function should return the final repeated string. The code should start with: ```python def repeat_concatenated_strings(s1: str, s2: str, n: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def repeat_concatenated_strings(s1: str, s2: str, n: int) -> str: """ Concatenates two strings `s1` and `s2`, and repeats the resulting string `n` times. Args: s1 (str): The first string to concatenate. s2 (...
python_sharegpt_23k
7,882
Write a Python function to get the next element of a list, given the following constraints: - The function should have a time complexity of O(1). - The function should not modify the original list. - The function should be able to handle lists of any data type, not just integers. - If the list is empty or contains only...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def get_next_element(lst: List[Any]) -> Any: """ Returns the next element of the list, or None if the list is empty or contains only one element. Args: lst (List[Any]): The list from wh...
python_sharegpt_23k
7,883
Write a Python function to remove all occurrences of a given number `num` from a list `array` and return the modified list. The function should iterate through the list and construct a new list that excludes the specified number. The code should start with: ```python from typing import List def remove_all_occurrences(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_all_occurrences(array: List[int], num: int) -> List[int]: """ Removes all occurrences of the given number `num` from the input list `array` and returns the modified list. Args: ar...
python_sharegpt_23k
7,886
Write a Python function to flatten a two-dimensional array of integers and return the sum of all its elements. The input array may contain positive and negative integers, varying lengths for its inner arrays, and an arbitrary number of inner arrays. The input array may also be empty. The output should be an integer. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flatten_and_sum(arr: List[List[int]]) -> int: """ Flattens a two-dimensional array of integers and returns the sum of all its elements. Args: arr (List[List[int]]): A two-dimensional arr...
python_sharegpt_23k
7,888
Write a Python function to calculate the sum of the first N-1 elements of a given list, where N is the length of the list. If N is not a prime number, the function should return an error message. The function should start with: ```python from typing import List def sum_of_first_n_minus_1_elements(X: List[int]) -> str:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_prime(n: int) -> bool: """ Check if a given number is prime. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise...
python_sharegpt_23k
7,889
Write a Python function to find the first occurrence of a specified character in a given string. If the character is not found, the function should return -1. The string will not contain any leading or trailing whitespace, and the character will always be a lowercase alphabet. The string can have a maximum length of 10...
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_index(string: str, character: str) -> int: """ Find the first occurrence of a specified character in a given string. Args: string (str): The string to search within. character (str): The chara...
python_sharegpt_23k
7,893
Write a Python function to implement the Comb Sort algorithm, which is an improvement over the Bubble Sort algorithm. The Comb Sort algorithm works by comparing elements that are a certain gap apart and then reducing this gap over multiple passes until the gap is 1, which is equivalent to a Bubble Sort pass. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def comb_sort(arr: List[int]) -> List[int]: """ Sorts the input list using the Comb Sort algorithm. Comb Sort is an improvement over Bubble Sort that works by comparing elements that are a certa...
python_sharegpt_23k
7,898
Write a Python function to print the message "Hello!" a random number of times between 5 and 10 (inclusive) using a while loop. The function should not return any value; it should only print the message. The code should start with: ```python import random def print_hello_random_times(): ```
Here is the Python code to solve the given problem in the markdown block: ```python import random def print_hello_random_times(): """ Prints the message "Hello!" a random number of times between 5 and 10 (inclusive). This function does not return any value; it only prints the message. """ # Genera...
python_sharegpt_23k
7,902
Write a Python function to perform Bubble Sort on an array of integers in descending order. The function should modify the input array in place and return the sorted array. The code should start with: ```python from typing import List def bubble_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 bubble_sort_descending(arr: List[int]) -> List[int]: """ Sorts an array of integers in descending order using the Bubble Sort algorithm. Args: arr (List[int]): The array of integers to b...
python_sharegpt_23k
7,903
Write a Python function to identify the type of a given variable and, if the variable is a list, return the number of elements in the list. The function should handle various types of variables, including integers, strings, lists, and other data types. The code should start with: ```python from typing import Any, Union...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, Union def variable_info(var: Any) -> Union[str, int]: """ Identify the type of a given variable and, if the variable is a list, return the number of elements in the list. Args: var (Any): Th...
python_sharegpt_23k
7,905
Write a Python function to find the most frequent element in a list that appears at least twice. If no such element exists, return `None`. The input list will contain at most \(10^6\) elements, and each element will be an integer between 0 and \(10^9\). The code should start with: ```python from typing import List, Op...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def most_frequent_element(lst: List[int]) -> Optional[int]: """ Find the most frequent element in a list that appears at least twice. Args: lst (List[int]): The input list of integ...
python_sharegpt_23k
7,909
Write a Python function to generate a list of `n` random integers between a specified lower bound `low` and upper bound `high`, inclusive. The function should return the list of random integers. The code should start with: ```python from typing import List import random def generate_random_integers(n: int, low: int, h...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_integers(n: int, low: int, high: int) -> List[int]: """ Generates a list of `n` random integers between `low` and `high`, inclusive. Args: n (int): The numb...
python_sharegpt_23k
7,910
Write a Python function to count the occurrences of each character in a given string, excluding any whitespace characters, and handle cases in a case-insensitive manner. The function should return a dictionary where the keys are characters and the values are their respective counts. The code should start with: ```pyth...
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]: """ Counts the occurrences of each character in the given string, excluding whitespace characters, and handles cases in a case-insensitive manner. ...
python_sharegpt_23k
7,913
Write a Python function to move all zeros in a given list to the end while maintaining the relative order of the non-zero elements. The function should not use any additional data structures; it should modify the list in place. The code should start with: ```python from typing import List def move_zeros_to_end(arr: L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def move_zeros_to_end(arr: List[int]) -> None: """ Moves all zeros in the given list to the end while maintaining the relative order of the non-zero elements. Args: arr (List[int]): The list...
python_sharegpt_23k
7,914
Write a Python function to sort a list of integers in ascending order using the bubble sort algorithm. The function should modify the input list in place and return the sorted list. 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
7,915
Write a Python function to compare two unsorted arrays of integers and find the number of mismatches. The arrays can contain duplicate values. Additionally, the function should return the indices at which the mismatches occur in both arrays. The code should start with: ```python from typing import List, Tuple def com...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def compare_arrays(arr1: List[int], arr2: List[int]) -> Tuple[int, List[int], List[int]]: """ Compare two unsorted arrays of integers and find the number of mismatches. Additionally, return th...
python_sharegpt_23k
7,916
Write a Python function to determine if a given number is divisible by 4 and greater than 100. The function should return a boolean value (`True` if the number meets both conditions, `False` otherwise). The code should start with: ```python def is_divisible_by_4_and_greater_than_100(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_divisible_by_4_and_greater_than_100(num: int) -> bool: """ Determine if a given number is divisible by 4 and greater than 100. Args: num (int): The number to be checked. Returns: bool: True if th...
python_sharegpt_23k
7,918
Write a Python function to transpose a given 2D array of integers. The function should return a new 2D array that is the transposed version of the input array. The input array will contain integers ranging from -10^9 to 10^9. The function should handle arrays of any size, including empty arrays. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transpose_2d_array(arr: List[List[int]]) -> List[List[int]]: """ Transposes a given 2D array of integers. Args: arr (List[List[int]]): The input 2D array to be transposed. Returns: ...
python_sharegpt_23k
7,920
Write a Python function to determine if two numbers have the same frequency of digits without converting the numbers to strings or using any built-in functions for counting the frequency of digits. The function should use integer arithmetic to count the digits and compare the frequencies. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python def same_frequency(num1: int, num2: int) -> bool: """ Determines if two numbers have the same frequency of digits without converting them to strings. Args: num1 (int): The first number to compare. num2 (int)...
python_sharegpt_23k
7,923
Write a Python function to calculate the factorial of a given non-negative integer using an iterative approach. The function should handle edge cases such as negative numbers and non-integer inputs by returning a specific error message. The code should start with: ```python def factorial_iterative(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_iterative(n: int) -> int: """ Calculate the factorial of a given non-negative integer using an iterative approach. Args: n (int): The non-negative integer for which to calculate the factorial. Ret...
python_sharegpt_23k
7,929
Write a Python function to determine if the elements of a given array are in strictly increasing order. The array may contain both positive and negative integers. The function should return `True` if the elements are in increasing order and `False` otherwise. 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 is_strictly_increasing(arr: List[int]) -> bool: """ Determines if the elements of the given array are in strictly increasing order. Args: arr (List[int]): The array of integers to check....
python_sharegpt_23k
7,934
Write a Python function to reverse an array of size `n` in place, where `n` is a positive integer not exceeding 10^6. The array elements are integers between 1 and 10^9 (inclusive). Implement an efficient algorithm with a time complexity of O(n) and a space complexity of O(1). 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 reverse_array_in_place(arr: List[int]) -> List[int]: """ Reverses the given array in place with a time complexity of O(n) and space complexity of O(1). Args: arr (List[int]): The array o...
python_sharegpt_23k
7,935
Write a Python function to convert a given positive integer less than or equal to 3999 to its corresponding Roman numeral representation. The function should handle the conversion by iterating through predefined decimal values and their corresponding Roman numeral symbols, appending the symbols to a result string until...
Here is the Python code to solve the given problem in the markdown block: ```python def integer_to_roman(num: int) -> str: """ Convert a given positive integer less than or equal to 3999 to its corresponding Roman numeral representation. Args: num (int): The positive integer to be converted, must b...
python_sharegpt_23k
7,936
Write a Python function to iterate over a list in reverse order and return a list of tuples where each tuple contains the index position and the corresponding element from the original list. The function should handle lists of any length and any type of elements. 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, Tuple def reverse_enumerate(lst: List) -> List[Tuple[int, any]]: """ Iterates over a list in reverse order and returns a list of tuples where each tuple contains the index position and the corresponding...
python_sharegpt_23k
7,937
Write a Python function to reverse a list of integers in place without using any built-in functions or additional data structures. The function should have a time complexity of O(n), where n is the length of the list. The code should start with: ```python from typing import List def reverse_list_in_place(lst: List[int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list_in_place(lst: List[int]) -> None: """ Reverses the given list of integers in place without using any built-in functions or additional data structures. Args: lst (List[int]):...
python_sharegpt_23k
7,938
Write a Python function to reverse a given string without using any built-in string manipulation functions or libraries. The function should iterate through the string and construct the reversed string manually. The code should start with: ```python def reverse_string(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(string: str) -> str: """ Reverses a given string without using any built-in string manipulation functions or libraries. Args: string (str): The input string to be reversed. Returns: s...
python_sharegpt_23k
7,939
Write a Python function to extract and return the names of all font styles available within an HTML document. The function should consider the following font style tags: `<b>`, `<i>`, `<u>`, `<s>`, `<strong>`, `<em>`, `<ins>`, `<del>`. The function should correctly handle nested font style tags, meaning if a font style...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Set import re def find_font_styles(html: str) -> Set[str]: """ Extracts and returns the names of all font styles available within an HTML document. The function considers the following font style tags: <...
python_sharegpt_23k
7,943
Write a Python function to calculate the factorial of a given positive integer `n` using a recursive approach. The function should also validate that `n` is a positive integer and raise a `ValueError` if it is not. The code should start with: ```python def factorial(n: int) -> int: ```
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 positive integer n using a recursive approach. Args: n (int): The positive integer for which to calculate the factorial. Returns: int...
python_sharegpt_23k
7,947
Write a Python function to determine if two given lists contain the same elements in the same order. The function should return `True` if the lists are identical in both elements and order, and `False` otherwise. The code should start with: ```python from typing import List def are_lists_identical(list1: List[int], li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def are_lists_identical(list1: List[int], list2: List[int]) -> bool: """ Determines if two lists contain the same elements in the same order. Args: list1 (List[int]): The first list to compa...
python_sharegpt_23k
7,948
Write a Python function to calculate the total number of unique paths from the top-left corner to the bottom-right corner of an N x M matrix, where N and M are positive integers. You can only move down or right in each step. The function should have a time complexity of O(N*M) or better. The code should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def unique_paths(n: int, m: int) -> int: """ Calculate the total number of unique paths from the top-left corner to the bottom-right corner of an N x M matrix. Args: n (int): The number of rows in the matrix. ...
python_sharegpt_23k
7,952
Write a Python function that removes the first element from a given list and returns the modified list. The function should not modify the original list (i.e., it should eliminate passing by reference) and should have a time complexity of O(n^2). The code should start with: ```python from typing import List def remove...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_first_element(arr: List[int]) -> List[int]: """ Removes the first element from the given list and returns the modified list. The original list is not modified, and the function has a time ...
python_sharegpt_23k
7,953
Write a Python function to generate an array of the first n prime numbers. The function should return a list of integers 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 oth...
python_sharegpt_23k
7,956
Write a Python function to convert a date string in the format 'YYYY-MM-DD' to a more readable format "Month Day, Year". The function should handle the conversion of month numbers to month names and add appropriate suffixes to the day values (e.g., 'st', 'nd', 'rd', 'th'). The code should start with: ```python def form...
Here is the Python code to solve the given problem in the markdown block: ```python def format_date(date: str) -> str: """ Converts a date string in the format 'YYYY-MM-DD' to a more readable format "Month Day, Year". Args: date (str): The input date string in the format 'YYYY-MM-DD'. Returns:...
python_sharegpt_23k
7,957
Write a Python function to generate a list containing only the odd numbers from 1 to `n`, excluding multiples of 3. The function should take an integer `n` as input and return a list of integers. The code should start with: ```python from typing import List def generate_odd_numbers_excluding_multiples_of_3(n: int) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_odd_numbers_excluding_multiples_of_3(n: int) -> List[int]: """ Generate a list of odd numbers from 1 to n, excluding multiples of 3. Args: n (int): The upper limit (inclusive) f...
python_sharegpt_23k
7,960
Write a Python function to implement a quick sort algorithm that can handle a large input size of `n` (where `n > 10^6`) efficiently. The algorithm should have a time complexity of O(n log n) and should not exceed the space complexity of O(log n). The input list may contain duplicate numbers, and the algorithm should b...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def efficient_quick_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the quick sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: ...
python_sharegpt_23k
7,961
Write a Python function to find the maximum prime number in a given array. If no prime number is present in the array, return -1. The code should start with: ```python from typing import List def find_max_prime(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(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if n <...
python_sharegpt_23k
7,966
Write a Python function to generate a greeting message based on a given name. The function should ensure that the name is a non-empty string containing only alphabetic characters and has a maximum length of 20 characters. If the name does not meet these criteria, the function should return an error message. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python def greet(name: str) -> str: """ Generates a greeting message based on the given name. Args: name (str): The name to be included in the greeting. Must be a non-empty string containing only alphabetic characters and ...
python_sharegpt_23k
7,967
Write a Python function to extract a substring from a given string based on specified start and end indices. The start index should be inclusive, and the end index should be exclusive. The function should handle edge cases such as when the start index is greater than or equal to the end index, or when the indices are o...
Here is the Python code to solve the given problem in the markdown block: ```python def get_substring(string: str, start: int, end: int) -> str: """ Extracts a substring from the given string based on the specified start and end indices. Args: string (str): The input string from which to extract th...
python_sharegpt_23k
7,969
Write a Python function to reverse a singly linked list in-place. The function should modify the existing linked list instead of creating a new one. The linked list is represented by a class `Node` where each node has a `data` attribute and a `next` attribute pointing to the next node in the list. The function should b...
Here is the Python code to solve the given problem in the markdown block: ```python class Node: def __init__(self, data): self.data = data self.next = None def reverse_list(self): """ Reverses the linked list in-place and returns the new head of the reversed list. Retur...
python_sharegpt_23k
7,970
Write a Python function to sort a list of strings in alphabetical order using a divide-and-conquer approach. The function should handle a large number of strings (up to 10^6) efficiently and remove any duplicates from the input list. The input list may contain special characters. The function should return the sorted l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_unique_strings(list_of_strings: List[str]) -> List[str]: """ Sorts a list of strings in alphabetical order using a divide-and-conquer approach. Removes any duplicates from the input list and...
python_sharegpt_23k
7,971
Write a Python function to compare two strings using only bitwise operations. The function should return `True` if the two strings are identical, and `False` otherwise. The comparison should be case-sensitive and should not use any built-in string comparison functions or methods. The code should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python def bitwise_compare(str1: str, str2: str) -> bool: """ Compare two strings using only bitwise operations. Args: str1 (str): The first string to compare. str2 (str): The second string to compare. Returns...
python_sharegpt_23k
7,972
Write a Python function to generate the Fibonacci series up to 'n' terms, where n is a positive integer less than or equal to 50. The function should handle input validation and raise a `ValueError` if n is not within the specified range. The function should return the Fibonacci series as a list of integers. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_fibonacci_series(n: int) -> List[int]: """ Generate the Fibonacci series up to 'n' terms. Args: n (int): The number of terms in the Fibonacci series to generate. Must be a posit...
python_sharegpt_23k
7,974
Write a Python function to find the square root of a given number using the Newton-Raphson method. The function should take a number and an optional precision parameter, and return the square root of the number to the specified precision. If the precision parameter is not provided, the function should return the square...
Here is the Python code to solve the given problem in the markdown block: ```python def newton_raphson_sqrt(number: float, precision: float = 1e-6) -> float: """ Calculate the square root of a given number using the Newton-Raphson method. Args: number (float): The number for which to calculate the ...
python_sharegpt_23k
7,976
Write a Python function to perform matrix addition for two given sparse matrices. The matrices are represented as two-dimensional arrays, where each array represents a row of the matrix. The function should return the result matrix. The matrices can have varying sizes, but are guaranteed to have the same number of rows...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sparse_matrix_addition(matrix1: List[List[int]], matrix2: List[List[int]]) -> List[List[int]]: """ Perform matrix addition for two given sparse matrices. Args: matrix1 (List[List[int]]):...
python_sharegpt_23k
7,977
Write a Python function to determine if a given integer is a prime palindrome number. A prime palindrome number is a number that is both prime and a palindrome. The function should return `True` if the number is a prime palindrome, and `False` otherwise. The code should start with: ```python def is_prime_palindrome(num...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_palindrome(num: int) -> bool: """ Determine if a given integer is a prime palindrome number. Args: num (int): The integer to be checked. Returns: bool: True if the number is both prime and ...
python_sharegpt_23k
7,983
Write a Python function to find the maximum element in a given array of numbers, which may contain negative numbers. The function should handle arrays of any length, including empty arrays. The code should start with: ```python from typing import List def find_max_element(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_element(arr: List[int]) -> int: """ Find the maximum element in a given array of numbers. Args: arr (List[int]): The array of numbers to search for the maximum element. Ret...
python_sharegpt_23k
7,984
Write a Python function to compute the product of elements in a given array that meet specific criteria. The function should only consider elements that are multiples of 3 and ignore any element that is equal to 4. The function should also handle negative numbers correctly. 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 compute_product_with_constraints(arr: List[int]) -> int: """ Computes the product of elements in the given array that are multiples of 3 and not equal to 4. Args: arr (List[int]): The ar...
python_sharegpt_23k
7,985
Write a Python function to find the intersection of two lists and return a list containing the common elements, including duplicates. The function should handle duplicates correctly by including each common element the number of times it appears in both lists. 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 from collections import Counter def find_intersection_with_duplicates(list1: List[int], list2: List[int]) -> List[int]: """ Finds the intersection of two lists and returns a list containing the common el...
python_sharegpt_23k
7,988
Write a Python function to determine if a given integer is a prime number. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as negative numbers, 0, and 1, which are not prime numbers. The code should start with: ```python def is_prime(num: int) -...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Determine if a given integer is a prime number. Args: num (int): The integer to check for primality. Returns: bool: True if the number is prime, False otherwise. ...
python_sharegpt_23k
7,989
Write a Python function to determine if the second string is a rotation of the first string. A rotation is defined as shifting all the characters of a string by a certain number of positions and wrapping around to the beginning. The function should take two strings and their respective lengths as inputs and return a bo...
Here is the Python code to solve the given problem in the markdown block: ```python def is_rotation(string1: str, string2: str, length1: int, length2: int) -> bool: """ Determines if the second string is a rotation of the first string. Args: string1 (str): The first string. string2 (str): T...
python_sharegpt_23k
7,990
Write a Python function to calculate the sum of the positions of all alphabetic characters in a given string, where 'a' or 'A' is 1, 'b' or 'B' is 2, and so on. Non-alphabetic characters should be ignored. The code should start with: ```python def sum_of_alphabet_positions(s: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def sum_of_alphabet_positions(s: str) -> int: """ Calculate the sum of the positions of all alphabetic characters in the given string. The position of 'a' or 'A' is 1, 'b' or 'B' is 2, and so on. Non-alphabetic characters ...
python_sharegpt_23k
7,995
Write a Python function to evaluate a given mathematical expression in string format. The function should handle basic arithmetic operations including addition, subtraction, multiplication, and division. The expression will not contain parentheses or other complex operations. The code should start with: ```python def e...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_expression(expression: str) -> float: """ Evaluate a given mathematical expression in string format. Args: expression (str): The mathematical expression to evaluate. Returns: float: The res...
python_sharegpt_23k
7,997
Write a Python function to calculate the mean average of a list of integers. The function should handle cases where the list is empty by returning a meaningful error message. The code should start with: ```python from typing import List, Union def calculate_mean(numbers: List[int]) -> Union[float, str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def calculate_mean(numbers: List[int]) -> Union[float, str]: """ Calculate the mean average of a list of integers. Args: numbers (List[int]): A list of integers for which the mean ave...
python_sharegpt_23k
7,999
Write a Python function to calculate the sum of all even elements in a given list. The list may contain up to 100 elements. The function should return the total sum of the even elements. The code should start with: ```python from typing import List def sum_of_even_elements(my_list: 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_elements(my_list: List[int]) -> int: """ Calculate the sum of all even elements in the given list. Args: my_list (List[int]): The list of integers from which to calculate the...
python_sharegpt_23k
8,001
Write a Python function to calculate the sum of all positive numbers in a given list. The function should skip any negative numbers using the `continue` keyword. The code should start with: ```python from typing import List def sum_of_positive_numbers(numbers: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_positive_numbers(numbers: List[int]) -> int: """ Calculate the sum of all positive numbers in the given list, skipping any negative numbers. Args: numbers (List[int]): A list of i...
python_sharegpt_23k
8,005
Write a Python function to check whether all elements in a given list are equal and return a tuple containing a boolean indicating whether all elements are equal and the count of unique elements in the list. The code should start with: ```python from typing import List, Tuple def check_elements_equality(arr: List[int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def check_elements_equality(arr: List[int]) -> Tuple[bool, int]: """ Check whether all elements in the given list are equal and return a tuple containing: - A boolean indicating whether all el...
python_sharegpt_23k
8,008
Write a Python function to create a dictionary from two given lists, where the keys are the elements from the first list converted to uppercase, and the values are the elements from the second list converted to lowercase. If the lengths of the two lists are not equal, the function should return an empty dictionary. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def create_dictionary_from_lists(list1: List[str], list2: List[int]) -> Dict[str, str]: """ Creates a dictionary from two lists where the keys are the elements from the first list converted to uppe...
python_sharegpt_23k
8,012
Write a Python function to safely divide two numbers and handle different types of errors using `try...except` blocks. The function should return a specific message for each type of error and a default message for any other unexpected errors. The function should also return the result of the division if no errors occur...
Here is the Python code to solve the given problem in the markdown block: ```python def safe_division(numerator: float, denominator: float) -> str: """ Safely divides two numbers and handles different types of errors. Args: numerator (float): The numerator in the division. denominator (floa...
python_sharegpt_23k
8,020
Write a Python function to determine if a given string contains only uppercase letters and numbers that are divisible by 3. The function should return `True` if the string meets these criteria, otherwise `False`. The code should start with: ```python def check_string_divisible_by_3(string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def check_string_divisible_by_3(string: str) -> bool: """ Check if the given string contains only uppercase letters and numbers that are divisible by 3. Args: string (str): The input string to be checked. Retur...
python_sharegpt_23k
8,021
Write a Python function to change the case of each character in a given string. The function should have a time complexity of O(n), where n is the length of the string. The function should be implemented without using any built-in functions or methods specifically designed for changing the case of strings. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python def change_case(string: str) -> str: """ Changes the case of each character in the given string. Args: string (str): The input string whose case needs to be changed. Returns: str: A new string with the ...
python_sharegpt_23k
8,028
Write a Python function to encrypt a given string using the Caesar Cipher with a specified shift value. The function should adhere to the following constraints: 1. The shift value should be an integer between 1 and 25, inclusive. 2. The function should handle both uppercase and lowercase letters in the input string. 3....
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_cipher(string: str, shift: int) -> str: """ Encrypts a string using the Caesar Cipher with a given shift value. Args: string (str): The input string to be encrypted. shift (int): The shift value f...
python_sharegpt_23k
8,036
Write a Python function to find the maximum, minimum, second maximum, and second minimum values from a given list of integers. The function should return these four values in a tuple. The code should start with: ```python from typing import List, Tuple def find_extremes(lst: List[int]) -> Tuple[int, int, int, int]: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_extremes(lst: List[int]) -> Tuple[int, int, int, int]: """ Find the maximum, minimum, second maximum, and second minimum values from a given list of integers. Args: lst (List...
python_sharegpt_23k
8,037
Write a Python function to generate a list of prime numbers within a given range [start, end]. The function should return the list of prime numbers. The code should start with: ```python from typing import List def generate_primes_in_range(start: int, end: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_prime(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if n <...
python_sharegpt_23k
8,039
Write a Python function to find the length of the longest contiguous substring without repeating characters in a given string. The function should return the length of this substring. The code should start with: ```python def longest_substring_length(s: str) -> int: ```
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 contiguous substring without repeating characters in the given string. Args: s (str): The input string to analyze. Returns: ...
python_sharegpt_23k
8,044
Write a Python function to calculate the average of all the even numbers in a given array. The function should adhere to the following constraints: - The input array can have up to \(10^6\) elements. - The elements of the array can be positive or negative integers. - The elements of the array can be in any order. - You...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def average_of_even_numbers(arr: List[int]) -> float: """ Calculate the average of all even numbers in the given array. Args: arr (List[int]): The input array of integers. Returns: ...
python_sharegpt_23k
8,047
Write a Python function to calculate the sum of all prime numbers up to and including a given number `n`. The function should return the sum of these prime numbers. The code should start with: ```python def sum_of_primes_up_to(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_primes_up_to(n: int) -> int: """ Calculate the sum of all prime numbers up to and including a given number n. Args: n (int): The upper limit (inclusive) for the prime numbers to be summed. Returns: ...
python_sharegpt_23k
8,048
Write a Python function to remove all the vowels from a given string. The function should handle both uppercase and lowercase vowels. The code should start with: ```python def remove_vowels(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def remove_vowels(string: str) -> str: """ Removes all vowels (both uppercase and lowercase) from the given string. Args: string (str): The input string from which vowels are to be removed. Returns: s...
python_sharegpt_23k
8,050
Write a Python function to access the first element of a nested list inside a dictionary. The dictionary is stored in a variable called `data`. The list should remain unchanged. The function should return the first element of the list. The code should start with: ```python def get_first_element(data: dict) -> int: ```...
Here is the Python code to solve the given problem in the markdown block: ```python def get_first_element(data: dict) -> int: """ Accesses and returns the first element of a list nested inside a dictionary. Args: data (dict): A dictionary containing a key 'list' whose value is a list. Returns:...
python_sharegpt_23k
8,052
Write a Python function to format a string without using the `str.format()` method or f-strings. The function should take three parameters: `name`, `age`, and `city`, and return a formatted string that says: "Hello, my name is [name]. I am [age] years old, and I live in [city]." The code should start with: ```python d...
Here is the Python code to solve the given problem in the markdown block: ```python def custom_format_string(name: str, age: int, city: str) -> str: """ Formats a string without using the str.format() method or f-strings. Args: name (str): The name of the person. age (int): The age of the p...
python_sharegpt_23k
8,055
Write a Python function to create a dictionary from a list where the list contains alternating key-value pairs. The list can contain both strings and integers. The function should correctly handle cases where the list length is odd by ignoring the last element if it does not have a corresponding value. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def create_dict_from_list(lst: List[Union[str, int]]) -> dict: """ Creates a dictionary from a list containing alternating key-value pairs. Args: lst (List[Union[str, int]]): A list c...
python_sharegpt_23k
8,056
Write a Python function to generate and return a list of the first `n` prime numbers. The function should efficiently determine if a number is prime and collect the required number of primes into a list. 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 is_prime(n: int) -> bool: """ Check if a given number is prime. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise...
python_sharegpt_23k
8,059
Write a Python function to format a given list of numbers such that each element at the i'th index is the product of all elements in the list except the i'th element. The input list will not contain any zeros. The function should be efficient and avoid using division. 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 product_except_self(nums: List[int]) -> List[int]: """ Calculate the product of all elements in the list except the i'th element. Args: nums (List[int]): The input list of integers. ...
python_sharegpt_23k
8,064
Write a Python function to convert a list of strings representing numbers to a list of integers, and then sort the list in descending order. The function should handle lists of varying lengths and ensure that the conversion and sorting are performed correctly. 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 convert_and_sort_descending(str_list: List[str]) -> List[int]: """ Converts a list of string representations of numbers to a list of integers and sorts it in descending order. Args: str_...
python_sharegpt_23k
8,068
Write a Python function to delete all occurrences of a given key from a dictionary. The dictionary may contain multiple values with the same key. The function should have a time complexity of O(n) or better, where n is the number of key-value pairs in the dictionary. The code should start with: ```python from typing i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def delete_key(dictionary: Dict[str, int], key: str) -> Dict[str, int]: """ Deletes all occurrences of the given key from the dictionary. Args: dictionary (Dict[str, int]): The dictionary fr...
python_sharegpt_23k
8,069
Write a Python function to solve a 9x9 Sudoku puzzle using a backtracking algorithm. The function should take a partially filled Sudoku grid as input and return the solved grid. The grid is represented as a list of lists, where each inner list represents a row in the grid. Empty cells are represented by the number 0. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_valid(board: List[List[int]], row: int, col: int, num: int) -> bool: """ Check if placing 'num' at position (row, col) in the Sudoku board is valid. Args: board (List[List[int]]): The...
python_sharegpt_23k
8,075
Write a Python function to find all prime numbers less than a given positive integer `n` using the Sieve of Eratosthenes algorithm. The function should return a list of all prime numbers less than `n`. The code should start with: ```python from typing import List def find_prime_numbers(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_numbers(n: int) -> List[int]: """ Find all prime numbers less than a given positive integer n using the Sieve of Eratosthenes algorithm. Args: n (int): A positive integer grea...
python_sharegpt_23k
8,080
Write a Python function to split a given list into two parts: one containing all the odd numbers and the other containing all the even numbers. The function should maintain the relative order of the odd and even numbers in their respective parts. If there are no odd or even numbers in the list, the corresponding part s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def split_list_by_parity(mylist: List[int]) -> Tuple[List[int], List[int]]: """ Splits a list into two parts: one containing all the odd numbers and the other containing all the even numbers. ...
python_sharegpt_23k
8,081
Write a Python function to print a right-aligned triangle of asterisks with a given length. The function should take an integer `length` as input and print the triangle with the specified number of rows. Each row `i` should contain `i` asterisks, right-aligned. The code should start with: ```python def print_right_ali...
Here is the Python code to solve the given problem in the markdown block: ```python def print_right_aligned_triangle(length: int) -> None: """ Prints a right-aligned triangle of asterisks with the given length. Args: length (int): The number of rows in the triangle. Must be a positive integer. ...
python_sharegpt_23k
8,082
Write a Python function to remove all consecutive duplicated characters from a given string and return the modified string. If a character appears multiple times in a row, only the first occurrence should be kept. If the string is empty or contains no duplicated characters, return the original string. The code should ...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_consecutive_duplicates(string: str) -> str: """ Remove all consecutive duplicated characters from the given string and return the modified string. Args: string (str): The input string from which conse...
python_sharegpt_23k
8,083
Write a Python function to convert an adjacency matrix into an adjacency list while considering weighted edges. The function should take two matrices as input: one representing the adjacency matrix and the other representing the weights of each edge. The weights matrix should have the same dimensions as the adjacency m...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple def adjacency_matrix_to_list(adj_matrix: List[List[int]], weights_matrix: List[List[int]]) -> Dict[int, List[Tuple[int, int]]]: """ Converts an adjacency matrix into an adjacency list with w...
python_sharegpt_23k
8,085
Write a Python function to find the minimum, maximum, and average of a list of numbers without using any built-in functions or methods such as `min()`, `max()`, or `sum()`. The function should return a tuple containing the minimum, maximum, and average values. 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, Tuple def find_min_max_avg(numbers: List[int]) -> Tuple[int, int, float]: """ Find the minimum, maximum, and average of a list of numbers without using built-in functions. Args: numbers (Li...
python_sharegpt_23k
8,091
Write a Python function to count the number of occurrences of a given element in a sorted array using a single loop and achieving a time complexity of O(log n), where n is the size of the array. The array will contain at most 10^6 elements, and the element to search for will be a positive integer between 1 and 10^9 inc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_occurrences(arr: List[int], element: int) -> int: """ Counts the number of occurrences of a given element in a sorted array using binary search. Args: arr (List[int]): The sorted a...
python_sharegpt_23k
8,095
Write a Python function to determine the largest prime number in an unordered array of integers. The function should return `None` if no prime numbers are present in the array. The code should start with: ```python from typing import List, Optional def largest_prime_number(array: List[int]) -> Optional[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional 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, F...
python_sharegpt_23k
8,097
Write a Python function to generate a list (vector) of a specified size filled with random integers within a given range. The function should take two parameters: the size of the vector and the range of the random integers (inclusive). The code should start with: ```python from typing import List import random def gen...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_vector(size: int, lower_bound: int, upper_bound: int) -> List[int]: """ Generates a list of random integers of a specified size within a given range. Args: ...
python_sharegpt_23k
8,098
Write a Python function to calculate the frequency of alphabetic characters in a given input string, ignoring spaces, special characters, and numbers. The function should be case-insensitive, meaning 'a' and 'A' should be considered the same character. The function should return a dictionary where the keys are the uniq...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_alphabet_frequency(input_string: str) -> Dict[str, int]: """ Calculate the frequency of alphabetic characters in a given input string, ignoring spaces, special characters, and numbers. Arg...
python_sharegpt_23k
8,100
Write a Python function to calculate the sum of each row in a given 2-dimensional array and return a new array containing these sums. The function should handle any rectangular 2-dimensional array of integers. The code should start with: ```python from typing import List def row_sums(arr: 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 row_sums(arr: List[List[int]]) -> List[int]: """ Calculate the sum of each row in a given 2-dimensional array and return a new array containing these sums. Args: arr (List[List[int]]): A...
python_sharegpt_23k
8,101
Write a Python function to remove duplicate values from a given list without using any built-in methods or data structures (such as sets or dictionaries) to store unique values. The function should iterate through the list and maintain a separate list to store unique elements. The code should start with: ```python from...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(arr: List[int]) -> List[int]: """ Removes duplicate values from a given list without using any built-in methods or data structures. Args: arr (List[int]): The input lis...
python_sharegpt_23k
8,102
Write a Python function to determine whether a given number is a prime number or not. The function should return a boolean value (`True` if the number is prime, `False` otherwise). The code should start with: ```python def is_prime(number: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(number: int) -> bool: """ Determine whether a given number is a prime number. Args: number (int): The number to check for primality. Returns: bool: True if the number is prime, False otherw...
python_sharegpt_23k
8,103
Write a Python function to find the smallest positive integer that is not present in a given list of integers. The function should have a time complexity of O(n), where n is the length of the input list. The input list can contain up to 100,000 integers, including both positive and negative integers. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_smallest_missing_positive_integer(nums: List[int]) -> int: """ Finds the smallest positive integer that is not present in the given list of integers. Args: nums (List[int]): A list ...
python_sharegpt_23k
8,104
Write a Python function to create a 2D array with `n` columns and `m` rows filled with random integers between 1 and 100. Additionally, write a function that calculates the average of each row in the array and returns the row index and the average value of the row with the highest average. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import random def create_random_matrix(m: int, n: int) -> List[List[int]]: """ Create a 2D array with m rows and n columns filled with random integers between 1 and 100. Args: m (int)...