source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
python_sharegpt_23k | 3,768 | Write a Python function to filter out the odd numbers from a given list of integers, sort them in descending order, and remove any duplicates. The function should handle cases where the input list is empty or contains only even numbers. The function should have a time complexity of O(nlogn) or better and should not use... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(arr: List[int], reverse: bool = False) -> List[int]:
"""
Sorts the input list using the merge sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
... |
python_sharegpt_23k | 3,776 | Write a Python function to calculate the sum of all unique prime numbers in a given list of integers. The function should have a time complexity of O(n^2) and a space complexity of O(1). Additionally, the function should handle large input sizes efficiently and should not use any built-in functions or libraries for pri... | 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:
"""
Helper function to check if a number is prime.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, Fa... |
python_sharegpt_23k | 3,784 | Write a Python function to determine if two binary search trees (BSTs) are identical, considering the following additional constraints:
- The BSTs can have duplicate values.
- Each node in the BSTs can have an additional attribute called "color", which can take values of "red" or "black".
- Each node can also have an a... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_identical(tree1, tree2):
"""
Determines if two binary search trees are identical considering their structure, values, "color" attribute, and "weight" attribute.
Args:
tree1: The root node of the first binary ... |
python_sharegpt_23k | 3,787 | Implement the merge sort algorithm to sort a given array of integers in ascending order. The array will contain at least 10 million elements and can have duplicate numbers. Additionally, you are not allowed to use any built-in sorting functions or libraries. Your implementation should have a time complexity of O(n log ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a given array of integers in ascending order using the merge sort algorithm.
Args:
arr (List[int]): The array of integers to be sorted.... |
python_sharegpt_23k | 3,791 | Write a Python function to sort the unique characters of a given string of lowercase alphabets in descending order. The function should have a time complexity of O(n log n) and a space complexity of O(n), where n is the length of the input string.
The code should start with:
```python
from typing import List
def sort... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_unique_elements(input_string: str) -> List[str]:
"""
Sorts the unique characters of a given string of lowercase alphabets in descending order.
Args:
input_string (str): The input st... |
python_sharegpt_23k | 3,792 | Write a Python function to reverse the order of elements in a given array without using any built-in functions or methods, and without creating any additional arrays or data structures. Ensure that the time complexity of the solution is O(n) and the space complexity is O(1).
The code should start with:
```python
from ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_array_in_place(arr: List[int]) -> List[int]:
"""
Reverses the order of elements in a given array in place.
Args:
arr (List[int]): The array to be reversed.
Returns:
... |
python_sharegpt_23k | 3,800 | Write a Python function to determine if a given integer `y` is a power of another integer `x`. The function should also validate that both `x` and `y` are positive integers and handle cases where `x` is a negative number or a decimal number by returning `False`. The function should start with:
```python
def is_power_of... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_power_of(x: int, y: int) -> bool:
"""
Determine if y is a power of x, given that both x and y are positive integers.
Args:
x (int): The base number.
y (int): The number to check if it is a power of x.... |
python_sharegpt_23k | 3,804 | Write a Python function to transform a list of integers such that each even number is replaced by its square and each odd number is replaced by its cube. Additionally, each transformed number should be rounded to the nearest whole number. The function should have a time complexity of O(n), where n is the number of elem... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transform_list(arr: List[int]) -> List[int]:
"""
Transforms a list of integers such that each even number is replaced by its square
and each odd number is replaced by its cube. Each transformed n... |
python_sharegpt_23k | 3,806 | Write a Python function that processes a given string containing only lowercase letters. The function should print each character of the string on a single line, followed by a space. Additionally, the function should return a tuple containing the number of vowels and the number of consonants in the string.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def analyze_string(string: str) -> tuple:
"""
Processes a given string containing only lowercase letters. Prints each character on a single line, followed by a space.
Returns a tuple containing the number of vowels and the n... |
python_sharegpt_23k | 3,807 | Write a Python function to replace each element in a given 2D array of non-negative integers with the greatest element found on its row. The function should modify the input array in-place and run in O(n) time complexity, where n is the total number of elements in the input array. Additionally, the function should mini... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def replace_with_greatest(arr: List[List[int]]) -> List[List[int]]:
"""
Replace each element in a given 2D array with the greatest element found on its row.
Args:
arr (List[List[int]]): The ... |
python_sharegpt_23k | 3,808 | Write a Python function to compute the nth Fibonacci number efficiently with a time complexity of O(n) and a space complexity of O(1). The function should take an integer parameter `n` and return the nth Fibonacci number. You can assume that `n` will always be a positive integer.
The code should start with:
```python
... | Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci(n: int) -> int:
"""
Compute the nth Fibonacci number efficiently with O(n) time complexity and O(1) space complexity.
Args:
n (int): The position in the Fibonacci sequence to compute.
Returns:
... |
python_sharegpt_23k | 3,810 | Write a Python function to check whether a given number is within a specified inclusive range, is positive, and has at most 3 decimal places. The function should return a boolean indicating whether all conditions are met.
The code should start with:
```python
def is_number_valid(number: float, min_range: float, max_ra... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_number_valid(number: float, min_range: float, max_range: float) -> bool:
"""
Check if a given number is within a specified inclusive range, is positive, and has at most 3 decimal places.
Args:
number (float):... |
python_sharegpt_23k | 3,817 | Write a Python function that takes in a list of unique integers and returns a random value from the list that is greater than 10 and divisible by 2. The function should also remove the selected value from the list before returning it. The input list will contain at least 10 integers and at most 100 integers. The functi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_random_divisible_by_2_and_greater_than_10(nums: List[int]) -> int:
"""
Selects a random value from the list that is greater than 10 and divisible by 2,
and removes it from the list before ret... |
python_sharegpt_23k | 3,826 | Write a Python function to create a copy of a given list while excluding any duplicate elements. The solution should have a space complexity of O(1) and a time complexity less than O(n^2). Additionally, the solution should not use any built-in Python functions or methods related to duplicate removal or list manipulatio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_duplicates(lst: List[int]) -> List[int]:
"""
Creates a copy of the given list, excluding any duplicate elements.
The solution has a space complexity of O(1) and a time complexity less than... |
python_sharegpt_23k | 3,827 | Write a Python function to modify the font size of all `<p>` elements in a given HTML string to a specified font size value. The function should handle the following requirements:
1. If the font size value is less than or equal to 0, raise a `ValueError` with the message "Invalid font size value".
2. If the font size v... | Here is the Python code to solve the given problem in the markdown block:
```python
def change_font_size(html_code: str, font_size: int) -> str:
"""
Modify the font size of all <p> elements in the given HTML code to the specified font size value.
Args:
html_code (str): The HTML code string to be mo... |
python_sharegpt_23k | 3,828 | Write a Python function to calculate the sum of all integer values in a given dictionary. The dictionary may contain nested dictionaries and lists as values. The function should recursively calculate the sum of all integers in the dictionary, including those within nested dictionaries and lists. Non-integer values shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union, List, Dict
def sum_of_integers_in_dict(dictionary: Dict[str, Union[int, List[int], Dict]]) -> int:
"""
Calculate the sum of all integer values in a given dictionary.
The dictionary may contain nes... |
python_sharegpt_23k | 3,830 | Write a Python function to determine if a given target element is present in a sorted array using a custom binary search algorithm. The array is guaranteed to be sorted in ascending order. The time complexity of the solution should be O(log n), where n is the size of the array. You are not allowed to use the built-in b... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_element_present(arr: List[int], target: int) -> bool:
"""
Determines if a given target element is present in a sorted array using a custom binary search algorithm.
Args:
arr (List[int... |
python_sharegpt_23k | 3,841 | Write a Python function to find the maximum of four numbers using only ternary operators. The function should handle cases where two or more numbers are equal. The code should start with:
```python
def find_maximum(a: int, b: int, c: int, d: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def find_maximum(a: int, b: int, c: int, d: int) -> int:
"""
Find the maximum of four numbers using only ternary operators.
Args:
a (int): The first number.
b (int): The second number.
c (int): The t... |
python_sharegpt_23k | 3,846 | Write a Python function to find all the common elements between two given lists of integers and return them in sorted order. The input lists can contain duplicate elements, but the common elements should not include any duplicates. The solution should not use any built-in sorting functions or data structures, and it sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_common_elements(list1: List[int], list2: List[int]) -> List[int]:
"""
Find all the common elements between two lists of integers and return them in sorted order.
The input lists can contain ... |
python_sharegpt_23k | 3,853 | Write a Python function that processes a list of integers and returns a list of integers that are not divisible by a given divisor. The function should use the `continue` statement to skip processing of elements that are divisible by the divisor. The code should start with:
```python
from typing import List
def filte... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_non_divisible(numbers: List[int], divisor: int) -> List[int]:
"""
Filters out numbers from the given list that are divisible by the specified divisor.
Args:
numbers (List[int]): T... |
python_sharegpt_23k | 3,854 | Write a Python function that processes an array of strings and returns a sorted dictionary. The function should follow these steps:
1. Remove any duplicate strings from the input array.
2. Filter out strings that have a length of less than 3 characters.
3. Create a dictionary where the keys are the strings and the valu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_array(arr: List[str]) -> Dict[str, int]:
"""
Processes an array of strings and returns a sorted dictionary.
Args:
arr (List[str]): The input array of strings.
Returns:... |
python_sharegpt_23k | 3,856 | Write a Python function to calculate the discounted price based on a given price and discount percentage. The function should only accept prices that are greater than or equal to 100. If the price is less than 100, the function should raise a `ValueError` with the message "Invalid price: price must be greater than or e... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_discount(price: float, discount_percentage: float) -> int:
"""
Calculate the discounted price based on the given price and discount percentage.
Args:
price (float): The original price to be discounted.... |
python_sharegpt_23k | 3,858 | Write a Python function to process an array of positive integers and return a new array containing the squared values of all odd elements from the input array, sorted in descending order. The input array must contain at least 20 elements and must not contain any negative integers. If these conditions are not met, the f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def square_odd_elements(arr: List[int]) -> List[int]:
"""
Process an array of positive integers and return a new array containing the squared values of all odd elements, sorted in descending order.
... |
python_sharegpt_23k | 3,859 | Write a Python function to determine if a given string is a palindrome. The function should ignore spaces, punctuation, and capitalization when determining if a string is a palindrome. It should only consider alphanumeric characters. The function should have a time complexity of O(n) and a space complexity of O(1), whe... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def is_palindrome(s: str) -> bool:
"""
Determine if a given string is a palindrome, ignoring spaces, punctuation, and capitalization.
Args:
s (str): The input string to check.
Returns:
bool: ... |
python_sharegpt_23k | 3,867 | Write a Python function to classify and print the data types of a list of given pieces of data. The function should handle various data types including strings, floats, lists, dictionaries, tuples, booleans, and None. The function should start with:
```python
from typing import List, Any
def print_data_types(data: Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def print_data_types(data: List[Any]) -> None:
"""
Classify and print the data types of a list of given pieces of data.
Args:
data (List[Any]): A list containing various pieces of data.... |
python_sharegpt_23k | 3,872 | Write a Python function to filter out integers from a given list that meet the following criteria:
1. The integer is divisible by 6.
2. The integer is a prime number.
3. The sum of the digits of the integer is greater than 10.
The function should return the sum of all the filtered integers.
The code should start with... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_prime(n: int) -> bool:
"""
Check if a number is a prime number.
Args:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
"""
... |
python_sharegpt_23k | 3,876 | Write a Python function to validate whether a given string is a valid IPv4 address. The function should adhere to the following requirements:
1. The function should have a time complexity of O(1) and a space complexity of O(1).
2. The function should validate that the IP address has exactly four decimal numbers separat... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_IPv4(IP: str) -> bool:
"""
Validates whether the given string is a valid IPv4 address.
Args:
IP (str): The string to be validated as an IPv4 address.
Returns:
bool: True if the string is a ... |
python_sharegpt_23k | 3,881 | Write a Python function to determine if two given strings are anagrams of each other, considering only alphabetic characters and ignoring case, spaces, punctuation marks, and special characters. The function should have a time complexity of O(n log n), where n is the length of the strings.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def are_anagrams(str1: str, str2: str) -> bool:
"""
Determines if two strings are anagrams of each other, ignoring case, spaces, punctuation marks, and special characters.
Args:
str1 (str): The first stri... |
python_sharegpt_23k | 3,891 | Write a Python function to find all common elements between two lists, ensuring that duplicates are removed from both lists before finding the common elements. The final list of common elements should be sorted in ascending order. The function should have a time complexity of O(n) and should not use any built-in functi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_common_elements(list1: List[int], list2: List[int]) -> List[int]:
"""
Find all common elements between two lists after removing duplicates from both lists.
The final list of common elements ... |
python_sharegpt_23k | 3,893 | Write a Python function to implement the insertion sort algorithm on a given list of positive integers. The list may contain duplicates, and the sorting should preserve the original order of these duplicates. The function should be efficient and capable of handling large inputs up to a maximum length of 100,000 element... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def insertion_sort(lst: List[int]) -> List[int]:
"""
Sorts a list of positive integers using the insertion sort algorithm.
Args:
lst (List[int]): The list of positive integers to be sorted.
... |
python_sharegpt_23k | 3,897 | Write a Python function to sort a two-dimensional array (matrix) using the bubble sort algorithm. The matrix will contain a mix of positive and negative integers, and each row in the matrix may have a different number of elements. The function should also allow sorting the matrix in descending order instead of the defa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def bubble_sort_matrix(matrix: List[List[int]], ascending: bool = True) -> List[List[int]]:
"""
Sorts a two-dimensional array (matrix) using the bubble sort algorithm.
Args:
matrix (List[Lis... |
python_sharegpt_23k | 3,899 | Write a Python function to find and return the duplicate items in a given array of integers in ascending order. If there are no duplicates, the function should return the string "No duplicates found." The array size is limited to 1000, and the elements are in the range of -1000 to 1000. The original array should not be... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_duplicate_numbers(nums: List[int]) -> List[int] or str:
"""
Find and return the duplicate items in a given array of integers in ascending order.
If there are no duplicates, return "No duplic... |
python_sharegpt_23k | 3,903 | Write a Python function to extract all unique words from a given paragraph while maintaining the order of their first occurrence. The function should ignore punctuation marks, whitespace, and special characters, and only consider alphanumeric characters as part of a word. Additionally, the function should be case-insen... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_unique_words(paragraph: str) -> List[str]:
"""
Extracts all unique words from a given paragraph while maintaining the order of their first occurrence.
The function ignores punct... |
python_sharegpt_23k | 3,918 | Write a Python function to count the number of digits in an integer without using any built-in string or mathematical functions, and with a time complexity of O(log n), where n is the value of the input integer. The function should handle negative integers and return an error message if the input is not a valid integer... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_digits(num: int) -> int:
"""
Counts the number of digits in an integer without using any built-in string or mathematical functions,
and with a time complexity of O(log n), where n is the value of the input integer.... |
python_sharegpt_23k | 3,928 | Write a Python function that takes in an array (list) and an object (dictionary) as parameters. The function should iterate through each element in the array and check if the corresponding key exists in the object. If the key exists and its corresponding value is a number (integer or float), the function should add the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def find_matching_values(array: List[int], obj: Dict[int, int]) -> List[int]:
"""
Finds matching values in the dictionary and returns a list of their squares.
Args:
array (List[int]): ... |
python_sharegpt_23k | 3,933 | Write a Python function to randomly swap two elements in an array of unique integers, ensuring that the array has a length of at least 10 and the swapped elements are at least 5 positions apart. Additionally, the function should ensure that the swapped elements are not adjacent to each other in the modified array. The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def swap_elements(arr: List[int]) -> List[int]:
"""
Randomly swaps two elements in an array of unique integers, ensuring that the array has a length of at least 10 and the swapped elements ... |
python_sharegpt_23k | 3,954 | Write a Python function to calculate the perimeter of a triangle given its three side lengths. The function should validate if the given side lengths form a valid triangle. A valid triangle is one where the sum of any two side lengths is greater than the third side length. If the side lengths do not form a valid triang... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_triangle_perimeter(side1: float, side2: float, side3: float) -> tuple:
"""
Calculate the perimeter of a triangle and determine its type based on the given side lengths.
Args:
side1 (float): The length ... |
python_sharegpt_23k | 3,956 | Write a Python function to filter prime numbers from a given list and return a new list containing only the prime numbers. The function should exclude any negative numbers and raise a `ValueError` if the list is empty or contains any non-integer values. The output list should be sorted in descending order. The function... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_prime_numbers(numbers: List[int]) -> List[int]:
"""
Filters prime numbers from a given list and returns a new list containing only the prime numbers.
The output list is sorted in descendin... |
python_sharegpt_23k | 3,958 | Write a Python function called `set_result` that takes in a boolean value `bool1` and returns an integer value `result`. The function should follow these steps:
1. Initialize a variable `result` to 0.
2. Check if `bool1` is `False`.
3. If `bool1` is `False`, set `result` to 0.
4. If `bool1` is `True`, set `result` to 1... | Here is the Python code to solve the given problem in the markdown block:
```python
def set_result(bool1: bool) -> int:
"""
Returns an integer based on the value of the input boolean.
Args:
bool1 (bool): A boolean value that determines the output.
Returns:
int: 0 if bool1 is False, 1 i... |
python_sharegpt_23k | 3,964 | Write a Python function to swap the case of each character in a given string `x` without using any built-in string manipulation functions or methods (e.g., `lower()`, `upper()`, `swapcase()`). The function should have a time complexity of O(n), where n is the length of the string `x`. The input string `x` will contain ... | Here is the Python code to solve the given problem in the markdown block:
```python
def swap_case(x: str) -> str:
"""
Swaps the case of each character in the given string `x`.
Args:
x (str): The input string containing only alphabetic characters.
Returns:
str: A new string with the cas... |
python_sharegpt_23k | 3,972 | Write a Python function to determine if a given number is an Armstrong number and return the decomposition of the number as a list of its digits raised to the power of the number of digits. The function should handle negative numbers and non-integer inputs, and it should return `False` for any number outside the range ... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_armstrong_number(num: int) -> bool:
"""
Determine if a given number is an Armstrong number and return the decomposition of the number.
An Armstrong number is a number that is equal to the sum of its digits raised to ... |
python_sharegpt_23k | 3,976 | Write a Python function that takes an array of strings and returns an array of tuples containing the first and last word of each string. The function should handle various edge cases, such as strings with leading or trailing whitespace, multiple consecutive spaces, punctuation marks, and strings with only one word. The... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import re
def get_first_last_words(strings: List[str]) -> List[Tuple[str, str]]:
"""
Extracts the first and last words from each string in the input array and returns them as a list of tuples.
... |
python_sharegpt_23k | 3,989 | Write a Python function to count the occurrences of each character in a given string and return a dictionary where the keys are the unique characters in the string and the values are the counts of each character. The input string will consist only of lowercase letters, numbers, and special characters. The input string ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def count_characters(string: str) -> Dict[str, int]:
"""
Count the occurrences of each character in the given string and return a dictionary
where the keys are the unique characters and the values ar... |
python_sharegpt_23k | 3,990 | Write a Python function to find and return a list of tuples, where each tuple contains a prime number from a given list of numbers and the sum of all its divisors. The function should start with:
```python
from typing import List, Tuple
def find_prime_numbers_and_divisor_sums(numbers: List[int]) -> List[Tuple[int, int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
Args:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
"""
... |
python_sharegpt_23k | 3,991 | Write a Python function to print all odd numbers from 1 to a given positive integer `n` using a single line of code and without using any conditional statements or arithmetic operators. The function should have a time complexity of O(n/2) and a space complexity of O(1).
The code should start with:
```python
def print_... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_odd_numbers(n: int) -> None:
"""
Prints all odd numbers from 1 to the given positive integer `n` using a single line of code.
Args:
n (int): The upper limit of the range (inclusive) to print odd numbers.
... |
python_sharegpt_23k | 3,996 | Write a Python function to group elements of a given array into pairs, sort each pair in descending order, and print each pair. If the array has an odd number of elements, the last element should be ignored. Implement the solution using a recursive function.
The code should start with:
```python
from typing import Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def group_pairs_recursive(arr: List[int]) -> List[Tuple[int, int]]:
"""
Groups elements of the given array into pairs, sorts each pair in descending order,
and returns a list of these sorted p... |
python_sharegpt_23k | 3,997 | Write a Python function to find all the students who scored above 80 and have a grade level of 10 or above from a given list of student records. Each student record contains the student's name, score, and grade level. The grade level should be a positive integer between 1 and 12. If a student record does not have a val... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_high_scoring_students(records: List[Tuple[str, int, int, int]]) -> List[str]:
"""
Find all students who scored above 80 and have a grade level of 10 or above.
Args:
records (... |
python_sharegpt_23k | 4,000 | Write a Python function to check if an input string is a palindrome, considering only alphanumeric characters and ignoring case, special characters, numbers, and spaces. The function should not use any built-in string reversal or palindrome-checking functions and should have a time complexity of O(n), where n is the le... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome(s: str) -> bool:
"""
Check if the input string is a palindrome, considering only alphanumeric characters and ignoring case, special characters, numbers, and spaces.
Args:
s (str): The input string ... |
python_sharegpt_23k | 4,003 | Write a Python function to count the number of distinct characters in a given string. The function should handle both uppercase and lowercase characters as distinct. The code should start with:
```python
def count_distinct_characters(string: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
def count_distinct_characters(string: str) -> int:
"""
Counts the number of distinct characters in a given string.
Args:
string (str): The input string to count distinct characters from.
Returns:
int:... |
python_sharegpt_23k | 4,006 | Write a Python function to generate all possible unique permutations of a given list of integers, including handling duplicates, and return them in lexicographic order. The function should use an iterative approach and avoid using built-in functions or libraries for generating permutations. The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_unique_permutations(nums: List[int]) -> List[List[int]]:
"""
Generate all possible unique permutations of a given list of integers in lexicographic order.
Args:
nums (List[int])... |
python_sharegpt_23k | 4,018 | Write a Python function to generate the first n prime numbers using a recursive function to check for primality. The function should be named `get_prime_numbers` and should take an integer `n` as input. The function should return a list of the first n prime numbers. The primality check should be performed by a recursiv... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def is_prime(num):
"""
Recursively checks if a number is prime using the trial division method.
Args:
num (int): The number to check for primality.
Returns:
bool: True if the number is prim... |
python_sharegpt_23k | 4,019 | Write a Python function to determine if a given number is both a prime number and a palindrome. The function should have a time complexity of O(sqrt(n)) for checking primality and O(d) for checking palindromicity, where d is the number of digits in the number. The input number should be between 2 and 10^9, inclusive. T... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def is_prime_and_palindrome(n: int) -> bool:
"""
Determine if a given number is both a prime number and a palindrome.
Args:
n (int): The number to check. Must be between 2 and 10^9, inclusive.
Retu... |
python_sharegpt_23k | 4,023 | Write a Python function to calculate the greatest common divisor (GCD) of two numbers without using any built-in mathematical functions or libraries. The function should use the Euclidean algorithm, which is a more efficient method for finding the GCD.
The code should start with:
```python
def gcd_euclidean(a: int, b:... | Here is the Python code to solve the given problem in the markdown block:
```python
def gcd_euclidean(a: int, b: int) -> int:
"""
Calculate the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.
Args:
a (int): The first number.
b (int): The second number.
Retur... |
python_sharegpt_23k | 4,037 | Write a Python function to find the largest prime number in an array of integers without using any built-in sorting or max functions. The function should have a time complexity of O(n), where n is the length of the array.
The code should start with:
```python
from typing import List
def largest_prime_number(arr: List... | 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 | 4,040 | Write a Python function to categorize a list of phrases into their corresponding categories. Each phrase can only belong to one category, and each category must contain at least one phrase. The function should return a dictionary mapping each phrase to its category. The function should have a time complexity of O(n) or... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def categorize_phrases(phrases: List[str], categories: List[str]) -> Dict[str, str]:
"""
Categorizes a list of phrases into their corresponding categories.
Args:
phrases (List[str]): A... |
python_sharegpt_23k | 4,041 | Write a Python function to find the minimum value from a given array without using any built-in functions or methods for finding the minimum value (e.g., `min()`, sorting the array, etc.). The function must implement its own algorithm to solve the problem. The array may contain both positive and negative numbers, and t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_minimum_value(arr: List[int]) -> int:
"""
Find the minimum value in a given array without using built-in functions or methods.
Args:
arr (List[int]): The array of integers from whic... |
python_sharegpt_23k | 4,048 | Write a Python function to sort an array of integers in descending order using a stable sorting algorithm with a time complexity of O(n log n). The function should not use any built-in sorting functions or libraries, and it should not modify the original array. Additionally, the function should not use any extra memory... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def stable_descending_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in descending order using a stable sorting algorithm with a time complexity of O(n log n).
The function does no... |
python_sharegpt_23k | 4,051 | Write a Python function to encrypt and decrypt text using a Caesar cipher. The cipher should wrap around the alphabet if the shift value exceeds the number of characters in the alphabet. Additionally, implement a decryption function to reverse the encryption process. The code should handle both uppercase and lowercase ... | Here is the Python code to solve the given problem in the markdown block:
```python
def caesar_encrypt(text: str, shift: int) -> str:
"""
Encrypts the given text using a Caesar cipher with the specified shift.
Args:
text (str): The text to be encrypted.
shift (int): The number of positions ... |
python_sharegpt_23k | 4,053 | Write a Python function to generate a multi-dimensional array with the following properties:
1. Each element is a randomly generated integer between 1 and 100.
2. The array has dimensions of at least 10x10.
3. No two elements in the same row, column, or diagonal have the same value.
4. The array is sorted in descending... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import List
def generate_unique_array(dim: int) -> np.ndarray:
"""
Generates a multi-dimensional array with the following properties:
1. Each element is a randomly generated integer between 1 ... |
python_sharegpt_23k | 4,054 | Write a Python function to find the maximum and minimum values in a list of integers using a recursive function. The function should have a time complexity of O(n) where n is the number of elements in the list. The function should be able to handle lists with at least one element.
The code should start with:
```python... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_min_max(nums: List[int]) -> Tuple[int, int]:
"""
Find the maximum and minimum values in a list of integers using a recursive function.
Args:
nums (List[int]): The list of int... |
python_sharegpt_23k | 4,055 | Write a Python function to find the closest number to a given target value in a sorted array using a binary search algorithm. If the target value is present in the array, return it as the closest number. If there are two numbers equally close to the target value, return the larger number. The array can have duplicate v... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_closest_number(arr: List[int], target: int) -> int:
"""
Find the closest number to a given target value in a sorted array using binary search.
If the target value is present in the array, re... |
python_sharegpt_23k | 4,060 | Write a Python function to implement the bottom-up cut rod algorithm. The function should take an integer `n` representing the length of the rod and a list `prices` where `prices[i]` represents the price of a rod of length `i`. The goal is to find the maximum revenue that can be obtained by cutting and selling the rod.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def cut_rod(n: int, prices: List[int]) -> int:
"""
Calculate the maximum revenue that can be obtained by cutting a rod of length n
with given prices for each possible length of a cut.
Args:
... |
python_sharegpt_23k | 4,063 | Write a Python function that takes in a string and returns a new string with all uppercase letters converted to lowercase, and vice versa, without using the built-in `swapcase()` function. The function should preserve the original case of any non-alphabetic characters in the input string. Additionally, the function sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def swap_case_custom(string: str) -> str:
"""
Swaps the case of each alphabetic character in the input string without using the built-in `swapcase()` function.
Non-alphabetic characters remain unchanged.
Args:
s... |
python_sharegpt_23k | 4,067 | Write a Python function to calculate the total price of all the selected dishes from multiple tables that contain a specific ingredient. Each table is represented as a dictionary where each key-value pair represents a menu entry. Each menu entry is a dictionary containing the dish name, its price, and a list of ingredi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def calculate_total_price(tables: List[Dict], ingredient: str) -> float:
"""
Calculate the total price of all dishes from multiple tables that contain a specific ingredient.
Args:
tabl... |
python_sharegpt_23k | 4,073 | Write a Python function to traverse through an array and print only the even elements while keeping track of the number of even elements encountered. The function should meet the following requirements:
1. The time complexity of the solution should be O(n), where n is the size of the array.
2. You are not allowed to us... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_and_print_even_elements(arr: List[float]) -> int:
"""
Traverse through the array and print only the even elements while keeping track of the number of even elements encountered.
Args:
... |
python_sharegpt_23k | 4,074 | Write a Python function to calculate the sum of all even numbers in a given list without using the built-in `sum()` function. The function should have a time complexity of O(n), where n is the length of the list, and a space complexity of O(1), meaning it should not use any additional data structures to store intermedi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_evens(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list.
Args:
numbers (List[int]): The list of integers from which to calculate the sum of e... |
python_sharegpt_23k | 4,079 | Write a Python function to replace all occurrences of a specified element in a given list with another specified element. The function should handle cases where the specified element to be replaced is a nested list or a dictionary. In such cases, the function should replace the nested list or dictionary with the specif... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any, Dict
def replace_element(lst: List[Any], target: Any, replacement: Any) -> List[Any]:
"""
Replace all occurrences of a specified element in a given list with another specified element.
Handles ... |
python_sharegpt_23k | 4,085 | Write a Python function to calculate the sum of three numbers, `X`, `Y`, and 5, and print the sum along with a message based on the value of the sum. The function should print "Sum is greater than 15" if the sum is greater than 15, "Sum is between 11 and 15" if the sum is less than or equal to 15 but greater than 10, a... | Here is the Python code to solve the given problem in the markdown block:
```python
def sum_and_message(X: int, Y: int) -> None:
"""
Calculate the sum of three numbers, X, Y, and 5, and print the sum along with a message based on the value of the sum.
Args:
X (int): The first number.
Y (int... |
python_sharegpt_23k | 4,087 | Write a Python function to sort an array of integers in ascending order using the Merge Sort algorithm. The function should be implemented without using any built-in sorting functions or libraries. The sorting algorithm must have a time complexity of O(nlogn) or better and should be optimized to handle large input size... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers in ascending order using the Merge Sort algorithm.
Args:
arr (List[int]): The unsorted array of integers.
Ret... |
python_sharegpt_23k | 4,091 | Write a Python function to determine if a given sentence is a palindrome or not. The function should ignore punctuation, white spaces, and case sensitivity, but exclude any numbers and special characters. The function should return `True` if the sentence is a palindrome and `False` otherwise.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome(sentence: str) -> bool:
"""
Determine if a given sentence is a palindrome, ignoring punctuation, white spaces, and case sensitivity, but excluding any numbers and special characters.
Args:
sentence... |
python_sharegpt_23k | 4,096 | Write a Python function to create an array of student dictionaries, where each dictionary contains the keys `name`, `age`, and `grade`. The `name` values should be provided as a list of strings, the `age` values should be randomly generated integers between 18 and 25 (inclusive), and the `grade` values should be random... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import random
def create_and_sort_students(names: List[str]) -> List[Dict[str, object]]:
"""
Create an array of student dictionaries, each containing 'name', 'age', and 'grade' keys.
The 'age' ... |
python_sharegpt_23k | 4,097 | Write a Python function to reverse a singly linked list without using any extra space or creating a new list. The function should only rearrange the links between the nodes and should not modify the values stored in each node. The reversed linked list should have its nodes arranged in ascending order based on the origi... | 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 without using any extra spac... |
python_sharegpt_23k | 4,106 | Write a Python function to calculate the nth Fibonacci number efficiently using dynamic programming and matrix exponentiation. The function should handle input validation and optimize the algorithm to have a time complexity of O(log n). The function should also use a caching mechanism to store and retrieve previously c... | Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using dynamic programming and matrix exponentiation.
Args:
n (int): The position of the Fibonacci number to calculate.
Returns:
int: ... |
python_sharegpt_23k | 4,107 | Write a Python function to sort a list of integers in descending order using a recursive merge sort algorithm. You are not allowed to use any built-in sorting functions or libraries. The function should start with:
```python
from typing import List
def recursive_merge_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 recursive_merge_sort_descending(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in descending order using a recursive merge sort algorithm.
Args:
arr (List[int]): The list of ... |
python_sharegpt_23k | 4,113 | Write a Python function to find all the prime factors of a given number, where the number can be as large as \(10^9\). The function should return a list of these prime factors in ascending order. The code should start with:
```python
from typing import List
import math
def find_prime_factors(num: int) -> List[int]:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def find_prime_factors(num: int) -> List[int]:
"""
Find all the prime factors of a given number.
Args:
num (int): The number for which to find the prime factors.
Returns:
... |
python_sharegpt_23k | 4,121 | Write a Python function to find the maximum value in a list of integers without using any built-in functions or libraries. The function should have a time complexity of O(n), where n is the number of elements in the list. Additionally, the function should return the maximum value that occurs first in the list if there ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_max_value(lst: List[int]) -> Optional[int]:
"""
Find the maximum value in a list of integers without using built-in functions or libraries.
Args:
lst (List[int]): The list... |
python_sharegpt_23k | 4,132 | Write a Python function to calculate the sum of all integer elements in a given array. The function should skip any non-integer elements and should not use any built-in functions or libraries to calculate the sum. The function should be efficient and work correctly for large arrays.
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 sum_array(arr: List[int]) -> int:
"""
Calculate the sum of all integer elements in the given array.
Args:
arr (List[int]): The array containing elements to be summed.
Returns:
... |
python_sharegpt_23k | 4,133 | Write a Python function to implement the insertion sort algorithm correctly. The function should sort a list of integers in ascending order. Additionally, analyze the time complexity of the insertion sort algorithm and provide a brief explanation of why the given code snippet is incorrect.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in ascending order using the insertion sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.... |
python_sharegpt_23k | 4,135 | Write a Python function to count the number of bits that are set to 1 in the bitwise AND result of two given integers. The function should not use any built-in functions or libraries. The code should start with:
```python
def count_set_bits_in_and(num1: int, num2: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_set_bits_in_and(num1: int, num2: int) -> int:
"""
Counts the number of bits that are set to 1 in the bitwise AND result of two integers.
Args:
num1 (int): The first integer.
num2 (int): The second ... |
python_sharegpt_23k | 4,142 | Write a Python function to remove all duplicate elements from a given list of integers, sort the list in ascending order, and return the new list. The time complexity of your solution should be O(n log n), where n is the length of the list.
The code should start with:
```python
from typing import List
def remove_dupl... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_duplicates_and_sort(arr: List[int]) -> List[int]:
"""
Removes all duplicate elements from the given list of integers and returns a new list sorted in ascending order.
Args:
arr (L... |
python_sharegpt_23k | 4,144 | Write a Python function to find the largest common divisor (GCD) of two positive integers, A and B, without using any built-in functions or libraries for calculating the GCD. The function should have a time complexity of O(N), where N is the number of prime factors in the smaller of the two input numbers. The function ... | Here is the Python code to solve the given problem in the markdown block:
```python
def largest_common_divisor(A: int, B: int) -> int:
"""
Calculate the largest common divisor (GCD) of two positive integers, A and B,
without using any built-in functions or libraries for calculating the GCD.
Args:
... |
python_sharegpt_23k | 4,146 | Write a Python function that prints all the lowercase alphabets in reverse order, excluding the letter 'a'. The function should have a time complexity of O(1) and a space complexity of O(1). The code should start with:
```python
def print_alphabets_reverse_exclude_a():
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
def print_alphabets_reverse_exclude_a():
"""
Prints all the lowercase alphabets in reverse order, excluding the letter 'a'.
This function iterates from 'z' to 'b' (inclusive) and prints each character.
The time comple... |
python_sharegpt_23k | 4,148 | Write a Python function to calculate the sum of all even numbers in a given array of positive integers. The function should use a single loop to iterate through the array and should not use any built-in array manipulation functions or libraries (e.g., `filter`, `map`, `reduce`). The function should have a time complexi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_evens(arr: List[int]) -> int:
"""
Calculate the sum of all even numbers in a given array of positive integers.
Args:
arr (List[int]): The array of positive integers.
Returns:... |
python_sharegpt_23k | 4,150 | Write a Python function to create an array of elements that are the cubes of the prime numbers between 1 and 1000. The function should handle potential errors, such as when the cube of a prime number exceeds the maximum value that can be stored in the array. Additionally, optimize the program to calculate the cubes usi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
Args:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
""... |
python_sharegpt_23k | 4,154 | Write a Python function to convert a binary string to its equivalent integer value, considering the following additional requirements:
1. Validate the binary string to ensure it only consists of '0' and '1' characters and is not empty.
2. Handle negative binary numbers by allowing the binary string to start with a '-' ... | Here is the Python code to solve the given problem in the markdown block:
```python
def binary_to_integer(binary_num: str) -> int:
"""
Convert a binary string to its equivalent integer value.
Args:
binary_num (str): The binary string to convert.
Returns:
int: The integer value of the b... |
python_sharegpt_23k | 4,162 | Write a Python function to implement a binary search algorithm that searches for a specific element in a given sorted list of numbers. The function should return the index of the target number if it is found in the list, and -1 if it is not. The list will always be sorted in ascending order and will contain at most 1,0... | 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:
"""
Implements a binary search algorithm to find the index of a target number in a sorted list.
Args:
arr (List[int]): A sorted list of... |
python_sharegpt_23k | 4,164 | Write a Python function to determine if a given positive integer greater than 1 is a prime number. The function should not use any built-in functions or libraries that directly check for prime numbers. The algorithm must have a time complexity of O(sqrt(n)), where n is the input number.
The code should start with:
```... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(n: int) -> bool:
"""
Determines if a given positive integer greater than 1 is a prime number.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, F... |
python_sharegpt_23k | 4,174 | Write a Python function to implement the Bubble Sort algorithm, which sorts a list of integers in ascending order. The function should have a time complexity of O(n^2) in the worst and average cases, and O(n) in the best case. The space complexity should be O(1). Additionally, the function should include an optimizatio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def bubble_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in ascending order using the Bubble Sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
... |
python_sharegpt_23k | 4,176 | Write a Python function to calculate the sum of all prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm. The function should not use any built-in Python functions or libraries that directly calculate prime numbers and should have a time complexity of O(n log log n) or better.
The code shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_primes(n: int) -> int:
"""
Calculate the sum of all prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm.
Args:
n (int): The upper limit up to which to calculate the sum of pri... |
python_sharegpt_23k | 4,180 | Write a Python function to compute the sum of squares of all even numbers from 0 up to a given positive integer `n`. The function should use a single loop to identify the even numbers and calculate their sum of squares. The code should start with:
```python
def sum_of_squares_of_evens(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_squares_of_evens(n: int) -> int:
"""
Computes the sum of squares of all even numbers from 0 up to a given positive integer n.
Args:
n (int): The upper limit (inclusive) for the range of numbers to conside... |
python_sharegpt_23k | 4,182 | Write a Python function to determine if a given number is a perfect square without using any built-in math functions or operators for calculating the square root. The function should return a boolean value indicating whether the number is a perfect square or not. The input number should be an integer greater than or eq... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_perfect_square(num: int) -> bool:
"""
Determines if a given number is a perfect square without using built-in math functions or operators for calculating the square root.
Args:
num (int): The number to check ... |
python_sharegpt_23k | 4,184 | Write a Python function to calculate the sum of `True` and `False` values in a given list, where each `True` value contributes 2 to the sum and each `False` value contributes 2 to the sum. The list can contain elements of type `bool` or `int`. The function should return a tuple of two integers, where the first integer ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Union
def true_false_sum(x: List[Union[bool, int]]) -> Tuple[int, int]:
"""
Calculate the sum of `True` and `False` values in a given list, where each `True` value contributes 2 to the sum and ea... |
python_sharegpt_23k | 4,188 | Write a Python function to find and return a list of prime numbers between 1 and a given upper limit `n`, excluding those that are divisible by 5. The function should use nested loops to determine if a number is prime and should print each prime number as it is found.
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 find_primes_excluding_divisible_by_5(n: int) -> List[int]:
"""
Find and return a list of prime numbers between 1 and n, excluding those divisible by 5.
Args:
n (int): The upper limit for... |
python_sharegpt_23k | 4,190 | Implement the Shell Sort algorithm in Python, ensuring it is stable, optimized with a dynamically chosen gap sequence, and capable of sorting in both ascending and descending order. The function should accept a list of integers and a sorting order (either 'asc' for ascending or 'desc' for descending). The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def shell_sort(arr: List[int], order: str = 'asc') -> List[int]:
"""
Sorts the input list using the Shell Sort algorithm with a dynamically chosen gap sequence.
The algorithm can sort in both ascendi... |
python_sharegpt_23k | 4,193 | Write a Python function to determine whether a given integer `n` is a prime number or not using a recursive solution. The function must satisfy the following conditions:
- It must use a recursive solution.
- It must use constant space complexity, i.e., it cannot use any additional data structures besides a few variable... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime_recursive(n: int, i: int = 2) -> bool:
"""
Determine whether a given integer `n` is a prime number using a recursive solution.
Args:
n (int): The integer to check for primality.
i (int, optional... |
python_sharegpt_23k | 4,198 | Write a Python function to clean a given string by removing all punctuation marks, converting all letters to uppercase, and counting the occurrences of each letter in the string. The function should return a dictionary where the keys are the letters and the values are their respective counts.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import string
def clean_and_count_letters(input_str: str) -> Dict[str, int]:
"""
Cleans the input string by removing all punctuation marks, converting all letters to uppercase,
and counting the occur... |
python_sharegpt_23k | 4,199 | Write a Python function to sort an array of numbers in ascending order using the bubble sort algorithm. The function should not use any built-in sorting functions or external 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 an array of numbers in ascending order using the bubble sort algorithm.
Args:
arr (List[int]): The array of numbers to be sorted.
... |
python_sharegpt_23k | 4,210 | Write a Python function to compute the maximum depth of a binary tree from a given list of numbers. The list may contain invalid inputs such as strings, negative integers, numbers larger than 1000, or floating-point numbers. The function should handle these cases and return an appropriate error message. The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def max_depth_of_binary_tree(nums: List[Union[int, None]]) -> Union[int, str]:
"""
Compute the maximum depth of a binary tree from a given list of numbers.
The list may contain invalid inputs ... |
python_sharegpt_23k | 4,211 | Write a Python function to calculate the duration in seconds between two given times in 24-hour format. The times will be provided as strings in the format "HH:MM:SS", where HH represents hours (00-23), MM represents minutes (00-59), and SS represents seconds (00-59). The input will always be a list containing exactly ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_duration_in_seconds(times: List[str]) -> int:
"""
Calculate the duration in seconds between two given times in 24-hour format.
Args:
times (List[str]): A list containing exactly two ... |
python_sharegpt_23k | 4,214 | Write a Python function to print an upside-down triangle pattern where each row contains numbers in descending order, and each number in a row is the sum of all the previous numbers in that row. The function should take the number of rows as input and print the pattern accordingly.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_upside_down_triangle(rows: int):
"""
Prints an upside-down triangle pattern where each row contains numbers in descending order,
and each number in a row is the sum of all the previous numbers in that row.
Arg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.